Documentation · v0.4

The whole language
on one page.

Lith's docs are its language card: one page a model reads once before writing working Lith. Recipes for the tasks it does not cover are in the guide, and every rule and diagnostic is in the specification.

2,680tokens: the card
7,079tokens: 24 recipes
82 / 83QA checks in the v0.4 replays

Give it to your agent

Paste the card into the context, or point the agent at /llms.txt. It links the guide (/llms-guide.txt) and the full specification (/llms-full.txt, 60k tokens, with a contents line that gives each section's start line).

GuideMCP and agents
// example prompt Read https://lith.codes/llms.txt, then build the app in Lith.

Design systems are enforced, not explained. The card's Styling section is short because the compiler carries the rules: give your agent a W3C or Figma token file, and raw colours, sizes, primitives and invented tokens fail to compile, in pages and in server code, each with a patch to the right semantic token.

Recipes for common tasks: https://lith.codes/llms-guide.txt; full specification: https://lith.codes/llms-full.txt

Lith = TypeScript (strict) + JSX + Prisma-style queries + the line-start declarations table page api crud layout and state/effect/auth. All .lith files share one namespace: never import your own files or Lith names; npm imports work. Queries need no await.

Tables

table Post {
  title: string(1..200)            // length 1..200, checked on every write
  body: string                     // any text, "" allowed
  slug: string(1..80) unique       // modifiers (unique, index, renamedFrom("old")) go anywhere after the type
  views: int(0..) = 0              // value range; also number(a..b)
  pinned: boolean = false
  status: "Draft" | "Live" = "Draft"
  due: day | null                  // "YYYY-MM-DD" (from <input type="date">); compare with today()
  author: User | null              // reference: field authorId; include: { author: true } loads it
  tags: Tag[]                      // many-to-many (join table is automatic)
  created: Date = now()
}
table Like { post: Post, user: User, unique(post, user) }   // one Like per pair
  • id: int is automatic (or declare id: string: a generated UUID). T | null = optional; unique allows many nulls. A new column with a default or | null needs no migration. Rename keeping data: unitPriceCents: int(0..) renamedFrom("priceCents").
  • table Note own { ... } adds owner: User, fills it on create and limits every query, update and delete to the logged-in user's rows (others act as missing; login required). Only for private data: shared rows get owner: User plus checks in code. seed { }, migrate and dev api code runs unscoped and may set owner. system(() => ...) returns the callback's value unscoped, only there, in test and in auth(...) code.
  • User exists (email: email unique, name: string, passwordHash, never sent to the browser or JSON; email = text "@" text "." text). Add columns with table User { role: "Admin" | "Member" = "Member" }. Table names may be any word (Image, Event).

Queries (Prisma Client)

db.post.findMany findFirst findUnique findUniqueOrThrow count create update delete updateMany deleteMany aggregate groupBy with where data orderBy skip take include ({ in: ids }, OR: [...]; contains and string sorting ignore case). Nulls: orderBy: [{ done: "asc" }, { due: { sort: "asc", nulls: "last" } }]. Many-to-many: data: { tags: [tagA, tagB] } sets the list, where: { tags: { some: { name } } } filters, include: { tags: true }.

Pages and layout

auth page "/posts/:id/:slug" (id: int, slug: string, q: string = "") {   // path params typed and URL-decoded;
  const post = db.post.findUniqueOrThrow({ where: { id } })            // other params come from the query string
  return <main><title>{post.title}</title><h1>{post.title}</h1><p>{post.created}</p></main>
}
page "/posts/new" { ... }               // no params: no (); a literal segment wins over `:id`
layout {                                // optional; wraps every page; `children`, `me`, `path`, `error` are in scope
  return <html data-theme="system">     // tokens follow the OS mode; or force a token-file mode: "dark"
    <nav><a href="/" class={path === "/" ? "font-bold" : ""}>Home</a></nav>
    {children}
  </html>
}

auth page requires login; auth(me.role === "Admin") page also answers 403. me is the logged-in User or null (User under auth). A bad typed path param gives 404. A Date renders as 2026-10-16 14:05. <title> and <meta> anywhere go into <head>. error is { status, message } on error pages (else null), so the layout can replace children. Pages, apis and layout read request (a web Request: headers, raw body); pages and layout set response.status, response.headers.

Server functions and forms

A top-level function that uses db, me, an Auth helper (below) or process.env runs on the server; the browser calls it automatically. auth function requires login. Parameters are typed and validated.

<form action={addComment}><input type="hidden" name="postId" value={post.id} /><textarea name="body" /><button>Send</button></form>
auth function addComment(postId: int, body: string(1..1000)) {
  if (body.includes("http")) fail({ body: "No links" })      // field message; fail("Closed", 409) = form message
  db.comment.create({ data: { postId, body, authorId: me.id } })
}
<button onClick={() => deleteComment(c.id)}>Delete</button>    // in a page a handler is one server-function call;
                                                               // anything else needs a component with `state`
auth function deleteComment(id: int) { db.comment.delete({ where: { id, authorId: me.id } }) }  // args come from the browser: check ownership
  • Inputs, textareas, selects and hidden inputs fill parameters by name, converted to the parameter type (int, number, checkbox → boolean, type="date" → day, a repeated name → T[] without empty entries). An empty field is "" for string and null for T | null.
  • All parameter checks run first, all at once. email: User.email reuses a column's type; email: User.email unique also checks it is not taken. For your own message, type the param loosely (url: string; unknown in an api) and fail in the body.
  • Auth helpers: loginWithPassword(email, pw) → User | null and starts the session; login(user), logout(), hashPassword(pw).

Failure and refresh (pages, functions, apis)

redirect(path, status = 303), notFound(), forbidden(), unauthorized() and fail(msg | { field: msg }, status = 400) stop anywhere. Also: bad params → 400; a missing row in findUniqueOrThrow/update/delete → 404; a write that breaks a unique → 409 "already exists"; auth without login → 401 (pages go to /login). After notFound/forbidden a form shows the error page; otherwise it re-shows itself (field messages after their inputs, the rest at the end, values kept except passwords); an api answers JSON {"error":msg,"field":f}; in a component the awaited call throws (e.status, e.message). After a server function succeeds, the page re-renders from the server and the form resets: props update, state initialised from props is re-seeded if they changed, other state is kept. redirect navigates; redirect(path, { flash: "Saved" }) sets a one-time message flash for the next page.

Components and client state

function Search(placeholder: string) {             // props are parameters: <Search placeholder="Find" />
  state q = ""
  state hits: Person[] | null = null                // typed state
  const empty = hits !== null && hits.length === 0  // recomputes
  effect(() => {                                    // runs after render and whenever q changes
    if (q === "") { hits = null; return }
    let stale = false
    const timer = setTimeout(async () => {
      const res = await fetch(`/api/people?q=${encodeURIComponent(q)}`)
      if (!stale) hits = await res.json()
    }, 300)
    return () => { stale = true; clearTimeout(timer) }   // cleanup before the next run
  })
  return <div><input value={q} onInput={e => q = e.target.value} placeholder={placeholder} />{empty && <p>No matches</p>}</div>
}

No React hooks. A component with state also runs in the browser: it cannot read db or me (pass rows as props: an included row is still a Post, p.author.name; a Date stays a Date; every column reaches the browser) and may fetch the app's own routes. Assigning updates state, in place too (xs.push(x), o[k] = v). Server functions called from it are async: await them in try/catch. A component without state renders on the server and may read db and me. children: Html receives nested JSX. In handlers, e.target is the element.

APIs

crud "/api/products" Product         // GET list, GET /:id, POST 201, PATCH /:id, DELETE /:id 204
crud "/api/notes" Note: list, get    // only some operations
auth api GET "/api/orders.csv" (from: day | null) {   // params from path, query string, JSON or form body
  return new Response(csv, { headers: { "Content-Type": "text/csv" } })   // or return a value → JSON 200
}

Default action={fn}; when the URL is given, <form method="post" action="/x/1/delete"> may post to api POST "/x/:id/delete": fields fill params as in functions, fail re-shows the form; success returns to it unless it redirects. Scripts sending cookies on a non-GET add Origin.

Styling

Plain HTML already looks good: centered main, form as a column, li as a row, no ul bullets, styled controls, tables, links and <progress value={n} max={total}> bars. Tailwind class (not className, no style) is only for extras: flex gap-space (a row; flex-row makes a form a row), grid grid-cols-3 gap-space, font-bold text-danger bg-raised whitespace-pre-wrap. Class strings may be combined (ok ? "a" : "b", p-space ${x} ) if each class name appears whole somewhere, never "bg-" + c.

  • A token JSON file in the project replaces the default design system (with several, name it: design "tokens.json"). Colours, spacing, radii and font sizes take only its semantic tokens, as <utility>-<end of the token's path> (longer if two share it): semantic.color.text-muted → text-text-muted, fg/muted → text-muted, type/caption → text-caption. Raw values (#hex, px, […], p-4, text-red-600) and primitives are errors with a fix.

Tests

test("name", () => { ... }) in any file: fresh database per test, vitest expect, asUser(user, () => ...).