toiljs 0.0.128 → 0.0.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,13 @@
1
1
  export const TOIL_DOCS = {
2
2
  "README.md": "# toiljs\n\ntoiljs is a full-stack web framework. You write your **frontend in React** and your **backend in\nTypeScript**, and toiljs turns the backend into a tiny, fast **WebAssembly** program that runs at the edge\n(on servers close to your users, all over the world). One language, one project, one deploy.\n\nIf you have used Next.js, this will feel familiar: file-based routes, server code next to client code, a dev\nserver with hot reload. The difference is what happens underneath. Your server code is compiled by\n**toilscript** (a TypeScript-to-WebAssembly compiler) into a sandboxed `.wasm` module, and it runs on the\n**Dacely edge** with a built-in worldwide database (**ToilDB**), streaming, background jobs, and auth all\nincluded.\n\n## The mental model\n\n```mermaid\nflowchart LR\n A[\"Your project<br/>(TypeScript + React)\"] -->|toiljs build| B[\"client bundle<br/>(React, runs in the browser)\"]\n A -->|toilscript compile| C[\"server.wasm<br/>(your backend, sandboxed)\"]\n B --> U[\"User's browser\"]\n C --> E[\"Dacely edge<br/>(worldwide)\"]\n E --> D[(\"ToilDB<br/>global database\")]\n U <-->|HTTP / WebTransport| E\n```\n\n- **client/** is your React app (pages, components, styles). It runs in the browser.\n- **server/** is your backend (routes, database, auth). It compiles to WebAssembly and runs on the edge.\n- **shared/** is the typed bridge: toiljs generates a client here so the browser calls your server with full\n type safety.\n\n## Hello, toiljs\n\n```ts\n// server/routes/Hello.ts (a backend HTTP route)\nimport { Response } from 'toiljs/server/runtime';\n\n@rest('hello')\nclass Hello {\n @get('/')\n public hi(): Response {\n return Response.text('Hello from the edge!\\n');\n }\n}\n```\n\n```tsx\n// client/routes/index.tsx (a frontend page)\nexport default function Home() {\n return <main><h1>Welcome</h1></main>;\n}\n```\n\nRun `toiljs dev`, open the browser, and both are live with hot reload. That is the whole loop.\n\n## Learn toiljs\n\n**Understand toil first**\n- [Understanding toil](./introduction/README.md): what toil is and the one big idea, then\n [why toil and who it is for](./introduction/why-toil.md),\n [the modern stack you get](./introduction/modern-stack.md),\n [how it works](./introduction/how-it-works.md),\n [what makes it hyper-scalable](./introduction/hyperscale.md),\n [how it is distributed](./introduction/distributed.md),\n [toil versus other frameworks](./introduction/vs-other-frameworks.md), and\n [why it is built this way](./introduction/design-principles.md).\n\n**Start here**\n- [Getting started](./getting-started/README.md): install, create a project, project structure, your first\n app, and migrating an existing React app.\n- [The CLI](./cli/README.md): `dev`, `build`, `create`, `doctor`, and every flag.\n- [Deploy](./getting-started/deploy.md): build for production, self-host it, and how the managed edge fits in.\n\n**Build the frontend**\n- [Frontend overview](./frontend/README.md), [Routing](./frontend/routing.md),\n [Navigation](./frontend/navigation.md), [Components](./frontend/components.md),\n [Rendering and SSR](./frontend/rendering.md), [Styling](./frontend/styling.md),\n [Images](./frontend/images.md), [Metadata and SEO](./frontend/metadata.md),\n [Fetching data](./frontend/data-fetching.md), [Scripts](./frontend/scripts.md),\n [Testing and coverage](./frontend/testing.md), [Search](./frontend/search.md), [The Toil global (reference)](./frontend/toil-global.md).\n\n**Build the backend**\n- [Backend overview](./backend/README.md), [HTTP routes (`@rest`)](./backend/rest.md),\n [Typed RPC (`@service`/`@remote`)](./backend/rpc.md), [Data types (`@data`)](./backend/data.md),\n [Server image processing](./backend/images.md), [Native staging](./backend/native-staging.md).\n\n**The database (ToilDB)**\n- [Database overview and choosing a family](./database/README.md), [Setup (`@database`)](./database/setup.md),\n [Documents](./database/documents.md), [Unique](./database/unique.md), [Counters](./database/counters.md),\n [Events](./database/events.md), [Views and `@derive`](./database/views.md),\n [Membership](./database/membership.md), [Capacity](./database/capacity.md),\n [Atomic batches](./database/atomic.md), [Blobs](./database/blobs.md).\n\n**Auth**: [the full auth guide](./auth/README.md) covers post-quantum login, sessions, and `ToilUserId`;\n[customizing the auth emails](./auth/emails.md) shows how to brand the verification, reset, and 2FA mail.\n\n**Realtime and background**\n- [Streams](./realtime/README.md) and [channels](./realtime/channels.md), [Daemons and scheduled\n jobs](./background/daemons.md), [Derived views (`@derive`)](./background/derive.md).\n\n**Platform services**\n- [Caching](./services/caching.md), [Rate limiting](./services/ratelimit.md),\n [Environment and secrets](./services/environment.md), [Email and 2FA](./services/email.md),\n [Analytics](./services/analytics.md), [Crypto](./services/crypto.md), [Cookies](./services/cookies.md),\n [Time](./services/time.md).\n\n**Concepts and reference**\n- [Writing toiljs correctly (AI + human quick rules)](./concepts/ai-guide.md),\n [Compute tiers (L1 to L4)](./concepts/tiers.md), [Types (u64, u256, and friends)](./concepts/types.md),\n [Every decorator](./concepts/decorators.md), [Configuration](./concepts/config.md),\n [Security: CSP, COOP, Trusted Types, and SRI](./concepts/security.md).\n",
3
- "auth/configuration.md": "# Configuring auth for production\n\nBuilt-in auth runs locally with **zero configuration**, it falls back to published, insecure DEV secrets\nso `toiljs dev` Just Works. **A deployment MUST replace all three secrets and pin its KEM key.** This page\nis the checklist.\n\n## The secrets\n\nAuth reads these from the tenant environment store (locally, `.env.secrets`; on the edge, the per-host\nsecure env). They resolve **lazily** the first time auth runs, so no startup wiring is needed.\n\n| Key | What it is | Dev fallback |\n| --- | --- | --- |\n| `AUTH_SESSION_SECRET` | HMAC-SHA256 key that signs the session cookie. Must be identical on every edge instance (a cookie minted anywhere must verify everywhere). | a public constant, **anyone can forge a session** |\n| `AUTH_OPRF_SEED` | Master seed for the per-user OPRF salt key. Rotating it invalidates every password (users must re-register). | a hashed public constant |\n| `AUTH_KEM_SK` | The server's ML-KEM-768 **secret** key (hex). Its public half is what the client encapsulates to. | a pinned dev key pair |\n\n```bash\n# .env.secrets (gitignored; mode 0600 on the edge, NEVER under hosts/, NEVER in the .wasm)\nAUTH_SESSION_SECRET=…64 hex chars (32 bytes)…\nAUTH_OPRF_SEED=…64 hex chars (32 bytes)…\nAUTH_KEM_SK=…hex of an ML-KEM-768 secret key…\n```\n\n### Generating them\n\nRun this from your project root (or pass `--root <dir>`):\n\n```bash\ntoiljs generate auth\n```\n\nThe command saves `AUTH_SESSION_SECRET`, `AUTH_OPRF_SEED`, and `AUTH_KEM_SK` in\n`.env.secrets` with mode `0600`, and the matching `VITE_AUTH_KEM_PUBLIC_KEY` in `.env`.\nIt adds both files to `.gitignore`, preserves unrelated settings, and does not print credentials.\nRerunning preserves existing keys and restores a missing public key from `AUTH_KEM_SK`.\nInvalid, empty, or mismatched existing credentials cause an error without changing the env files.\nThere is no automatic rotation: changing the OPRF seed invalidates passwords, and changing the\nsession secret invalidates sessions. Back up the private file securely.\n\nFor toil-backend, merge the private settings into `/run/toil/env/<host>.env.secrets`\n(or the directory selected by `TOIL_ENV_DIR`). If using database-backed env settings, run\n`toil env sync <host>` with the production configuration after editing the files.\nThe **public** key must also be present in the project `.env` on the machine running the frontend\nbuild. Backend runtime env files do not supply Vite's build-time variables. Rebuild and deploy\nthe client with its matching key; the command does not edit your client code or deploy anything.\n\nTo generate keys manually instead:\n\n`AUTH_SESSION_SECRET` and `AUTH_OPRF_SEED` are just 32 random bytes each:\n\n```bash\nnode -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n```\n\n`AUTH_KEM_SK` is an ML-KEM-768 key pair. Generate it and keep BOTH halves, the secret goes in the env, the\npublic half is pinned in the client (next section):\n\n```ts\nimport { ml_kem768 } from '@dacely/noble-post-quantum/ml-kem';\nconst { secretKey, publicKey } = ml_kem768.keygen();\nconsole.log('AUTH_KEM_SK =', Buffer.from(secretKey).toString('hex'));\nconsole.log('client serverKemPublicKey =', Buffer.from(publicKey).toString('hex'));\n```\n\n## Pin the client's KEM public key\n\nThe browser must know the server's genuine KEM public key to run the mutual-auth handshake, this is the\nanti-phishing anchor. The `toiljs/client` `Auth` helper ships with the **dev** key pinned, so a deployment\nMUST pass its own:\n\n```ts\nimport { Auth } from 'toiljs/client';\n\n// Set by `toiljs generate auth` in the project .env, embedded during the client build.\nconst hex = import.meta.env.VITE_AUTH_KEM_PUBLIC_KEY;\nif (!hex || !/^[0-9a-f]{2368}$/.test(hex)) throw new Error('Missing auth public key');\nconst SERVER_KEM_PUBLIC_KEY = Uint8Array.from(hex.match(/../g)!, byte => parseInt(byte, 16));\n\nawait Auth.login(username, password, { serverKemPublicKey: SERVER_KEM_PUBLIC_KEY });\nawait Auth.register(username, password, { serverKemPublicKey: SERVER_KEM_PUBLIC_KEY });\n```\n\nShip the public key with your client bundle (it's public, safe to embed). If it doesn't match the server's\n`AUTH_KEM_SK`, login's `serverConfirm` check fails and the client aborts.\n\n## Optional: audience & domain\n\nBoth are optional and have sensible defaults; set them for stability across host aliases:\n\n| Key | Meaning | Default |\n| --- | --- | --- |\n| `TOIL_AUTH_AUDIENCE` | The service audience bound into the signed login message. | `\"toil\"` |\n| `TOIL_AUTH_DOMAIN` | The `domain` input of the stable `ToilUserId` (`sha256(pubkey ‖ username ‖ domain)`). | the request `Host` header, else `localhost` |\n\nSet `TOIL_AUTH_DOMAIN` explicitly if your site answers on multiple hostnames, otherwise the same user could\nget different `ToilUserId`s from different aliases. Once users exist, changing it changes everyone's id, so\npick it before launch.\n\n## Email confirmation\n\nTwo plain env vars (tenant-readable, like `PUBLIC_BASE_URL`) control the built-in email-verification flow. They are separate on purpose: sending a verify email at registration is one decision, blocking login until confirmed is another.\n\n| Key | What it does |\n| --- | --- |\n| `AUTH_EMAIL_CONFIRMATION` | Registration emails a one-time confirm link (`/confirm#token=…`) and stores the account **unconfirmed**. Login is **not** blocked: the user can sign in, and you nudge them to verify. Use this for \"verify at signup, but let people in\". |\n| `AUTH_REQUIRE_EMAIL_CONFIRMATION` | The stricter form: does everything above AND **refuses login** until the email is confirmed (a distinguishable status the client surfaces as `EmailNotConfirmedError`, so the UI can prompt \"confirm your email / resend\"). Implies `AUTH_EMAIL_CONFIRMATION`. On the managed edge this is force-set from the per-domain Dacely setting. |\n\nWith neither set, accounts are auto-confirmed at registration and no confirm email is sent. The one-time link is delivered by email; in `toiljs dev` it is drawn in the console (no mailer needed). Both use the standard non-enumerating responses (a generic 200 that never reveals whether an address exists).\n\n## Argon2id strength (known limitation)\n\nThe built-in controller currently uses **demo-light** Argon2id params (32 MiB, 2 iterations, 1 lane) so it\nstays responsive in a browser tab. These are baked into the shipped controller today; **config-driven\ntuning is a planned follow-up.** For a high-value production deployment you should either wait for the\nconfig knob or hand-write your own controller with `≥ 256 MiB / ≥ 3 iterations`. The OPRF still provides the\nprimary offline-attack resistance regardless, but raise these before protecting anything sensitive.\n\nThe client always derives against whatever params the server returns in `/login/start`, so when the config\nknob lands you can raise them server-side with **no client change**.\n\n## Deploy checklist\n\n- [ ] `AUTH_SESSION_SECRET` set (32 random bytes), identical on every edge instance.\n- [ ] `AUTH_OPRF_SEED` set (32 random bytes).\n- [ ] `AUTH_KEM_SK` set (an ML-KEM-768 secret key), and its **public** half pinned in the client via\n `serverKemPublicKey`.\n- [ ] `TOIL_AUTH_DOMAIN` set if you serve multiple hostnames (stable `ToilUserId`).\n- [ ] (Recommended) Argon2id params reviewed for your threat model.\n\nThe CLI doctor warns when `server.auth` is on and the secrets are missing, run it before you ship.\n\n## Upgrading to 0.0.118\n\nLogin now requires `AuthOptions.serverKemPublicKey`, the 1184-byte public key matching\n`AUTH_KEM_SK`. There is no implicit fallback to the published development key. Keep\nexisting OPRF and KEM secrets when upgrading; replacing the OPRF seed invalidates\nexisting password credentials. Project-root `VITE_*` variables are loaded by default.\n\nSessions use a versioned signed payload with a random session identifier and a user\nrevocation generation. Pre-upgrade session cookies and pending login challenges are\nrejected, so users must sign in again. Single-session logout revokes the signed session;\n`POST /auth/logout-all`, password reset, and confirmed two-factor changes revoke all\nsessions. Two-factor changes require a fresh login after success. Existing account IDs\nremain stable after password reset. The compiler includes the new revocation and factor\nsettings database declarations automatically.\n\nAuthenticated factor operations accept `headers` and `onRequestFailed(status)` options\nfor application account guards. HTTP failures include their status in the client error.\n\n## Session lifetime\n\nSuccessful password and two-factor sign-ins issue sessions valid for seven days\n(604800 seconds). The signed expiry and both session/display cookie lifetimes\nmatch. This is a fixed lifetime from sign-in, not an idle timeout. Logout, password\nreset, and account revocation can end a session earlier. Existing cookies retain\nthe expiry they were issued with; sign in again to receive the longer lifetime.\n\n## Account deletion\n\n`await Auth.deleteAccount(options)` calls authenticated `POST /auth/delete`.\nIt releases the sign-in account's username and email, revokes all its sessions,\nand clears both browser cookies. Clean application-owned records and projections\nbefore calling it. The endpoint operates only on the authenticated user's account.\n\nDeletion marks the old account before cleanup and frees the username last.\nIf cleanup is interrupted, retry with the existing session. Registration also\nfinishes an interrupted deletion before claiming the username. Conditional\nwrites prevent an overlapping request from removing or modifying a replacement\naccount. Confirm/reset links and pending logins bind to an account incarnation;\nlinks issued before this upgrade are rejected and can be requested again.\nA re-registered account starts with fresh factor settings. Revocation epochs and opaque deletion-incarnation guards\nremain to reject copied cookies and delayed replays of old account rows; random login challenges expire and cannot\nbe redeemed against a replacement account.\n\nFor cleanup that spans background runs, finish deleting application-owned data,\nthen call `AuthService.deleteUser(id)` from a `@job`, passing a `ToilUserId`.\nIt uses the same account cleanup and session revocation as `/auth/delete`,\nwithout a signed-in request. Request Actions, Queries, and Derives are rejected.\nIt returns `true` after removing the account, or `false` if the ID is absent,\nits index is stale, or its account incarnation no longer owns that ID. Concurrent\nupdates and storage failures throw; retry them to resume deletion. A marked account\ncannot sign in while cleanup is incomplete. Permanent incarnation guards and\nsession epochs remain after deletion. The ID index removes the deleted account's\nusername/realm pointer after the account is removed, using a conditional update\nthat preserves pointers for replacement accounts.\n\nRegistration stores the ID index before activating the account; sign-in repairs\nmissing entries. Existing deployments should backfill their accounts from a Job\nbefore relying on ID deletion. `AuthService.indexUsers(limit = 8, cursor = null)`\nindexes at most eight accounts per invocation and returns the next cursor, or\n`null` at completion. Persist the cursor after a successful invocation and keep\ncalling even when a page indexes no accounts. Retry the same cursor on failure.\nThe scan requires a [complete local collection copy](../database/documents.md#background-collection-scans)\nand, for existing native data, the record-directory migration described there.\nAccounts predating stored stable IDs require the original `TOIL_AUTH_DOMAIN`\nvalue; the Job refuses to guess a historic request hostname or port. Accounts\nwith stored IDs do not require that setting.\n\nNormally an ID identifies one realm. If a deployment intentionally assigns the\nsame ID to accounts in multiple realms, pass the normalized realm as the second\nargument: `AuthService.deleteUser(id, 'example.com')`. Ambiguous lookups throw.\nThe index supports up to sixteen realms per ID. Account pointers include an\nincarnation so a delayed cleanup cannot remove a replacement with another ID.\nRe-registering with identical credentials and identity-domain inputs can reuse\nthe same stable ID; applications requiring a distinction between those lifetimes\nshould retain their own deletion generation.\n",
3
+ "auth/configuration.md": "# Configuring auth for production\n\nBuilt-in auth runs locally with **zero configuration**, it falls back to published, insecure DEV secrets\nso `toiljs dev` Just Works. **A deployment MUST replace all three secrets and pin its KEM key.** This page\nis the checklist.\n\n## The secrets\n\nAuth reads these from the tenant environment store (locally, `.env.secrets`; on the edge, the per-host\nsecure env). They resolve **lazily** the first time auth runs, so no startup wiring is needed.\n\n| Key | What it is | Dev fallback |\n| --- | --- | --- |\n| `AUTH_SESSION_SECRET` | HMAC-SHA256 key that signs the session cookie. Must be identical on every edge instance (a cookie minted anywhere must verify everywhere). | a public constant, **anyone can forge a session** |\n| `AUTH_OPRF_SEED` | Master seed for the per-user OPRF salt key. Rotating it invalidates every password (users must re-register). | a hashed public constant |\n| `AUTH_KEM_SK` | The server's ML-KEM-768 **secret** key (hex). Its public half is what the client encapsulates to. | a pinned dev key pair |\n\n```bash\n# .env.secrets (gitignored; mode 0600 on the edge, NEVER under hosts/, NEVER in the .wasm)\nAUTH_SESSION_SECRET=…64 hex chars (32 bytes)…\nAUTH_OPRF_SEED=…64 hex chars (32 bytes)…\nAUTH_KEM_SK=…hex of an ML-KEM-768 secret key…\n```\n\n### Generating them\n\nRun this from your project root (or pass `--root <dir>`):\n\n```bash\ntoiljs generate auth\n```\n\nThe command saves `AUTH_SESSION_SECRET`, `AUTH_OPRF_SEED`, and `AUTH_KEM_SK` in\n`.env.secrets` with mode `0600`, and the matching `VITE_AUTH_KEM_PUBLIC_KEY` in `.env`.\nIt adds both files to `.gitignore`, preserves unrelated settings, and does not print credentials.\nRerunning preserves existing keys and restores a missing public key from `AUTH_KEM_SK`.\nInvalid, empty, or mismatched existing credentials cause an error without changing the env files.\nThere is no automatic rotation: changing the OPRF seed invalidates passwords, and changing the\nsession secret invalidates sessions. Back up the private file securely.\n\nFor toil-backend, merge the private settings into `/run/toil/env/<host>.env.secrets`\n(or the directory selected by `TOIL_ENV_DIR`). If using database-backed env settings, run\n`toil env sync <host>` with the production configuration after editing the files.\nThe **public** key must also be present in the project `.env` on the machine running the frontend\nbuild. Backend runtime env files do not supply Vite's build-time variables. Rebuild and deploy\nthe client with its matching key; the command does not edit your client code or deploy anything.\n\nTo generate keys manually instead:\n\n`AUTH_SESSION_SECRET` and `AUTH_OPRF_SEED` are just 32 random bytes each:\n\n```bash\nnode -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n```\n\n`AUTH_KEM_SK` is an ML-KEM-768 key pair. Generate it and keep BOTH halves, the secret goes in the env, the\npublic half is pinned in the client (next section):\n\n```ts\nimport { ml_kem768 } from '@dacely/noble-post-quantum/ml-kem';\nconst { secretKey, publicKey } = ml_kem768.keygen();\nconsole.log('AUTH_KEM_SK =', Buffer.from(secretKey).toString('hex'));\nconsole.log('client serverKemPublicKey =', Buffer.from(publicKey).toString('hex'));\n```\n\n## Pin the client's KEM public key\n\nThe browser must know the server's genuine KEM public key to run the mutual-auth handshake, this is the\nanti-phishing anchor. The `toiljs/client` `Auth` helper ships with the **dev** key pinned, so a deployment\nMUST pass its own:\n\n```ts\nimport { Auth } from 'toiljs/client';\n\n// Set by `toiljs generate auth` in the project .env, embedded during the client build.\nconst hex = import.meta.env.VITE_AUTH_KEM_PUBLIC_KEY;\nif (!hex || !/^[0-9a-f]{2368}$/.test(hex)) throw new Error('Missing auth public key');\nconst SERVER_KEM_PUBLIC_KEY = Uint8Array.from(hex.match(/../g)!, byte => parseInt(byte, 16));\n\nawait Auth.login(username, password, { serverKemPublicKey: SERVER_KEM_PUBLIC_KEY });\nawait Auth.register(username, password, { serverKemPublicKey: SERVER_KEM_PUBLIC_KEY });\n```\n\nShip the public key with your client bundle (it's public, safe to embed). If it doesn't match the server's\n`AUTH_KEM_SK`, login's `serverConfirm` check fails and the client aborts.\n\n## Optional: audience & domain\n\nBoth are optional and have sensible defaults; set them for stability across host aliases:\n\n| Key | Meaning | Default |\n| --- | --- | --- |\n| `TOIL_AUTH_AUDIENCE` | The service audience bound into the signed login message. | `\"toil\"` |\n| `TOIL_AUTH_DOMAIN` | The `domain` field in the [stable `ToilUserId` derivation](./how-it-works.md#the-stable-user-identity-toiluserid): SHA-256 over the length-prefixed `toil.userid.v1` label, ML-DSA public key, username, and domain. | the request `Host` header, else `localhost` |\n\nSet `TOIL_AUTH_DOMAIN` explicitly if your site answers on multiple hostnames, otherwise the same user could\nget different `ToilUserId`s from different aliases. Once users exist, changing it changes everyone's id, so\npick it before launch.\n\n## Email confirmation\n\nTwo plain env vars (tenant-readable, like `PUBLIC_BASE_URL`) control the built-in email-verification flow. They are separate on purpose: sending a verify email at registration is one decision, blocking login until confirmed is another.\n\n| Key | What it does |\n| --- | --- |\n| `AUTH_EMAIL_CONFIRMATION` | Registration emails a one-time confirm link (`/confirm#token=…`) and stores the account **unconfirmed**. Login is **not** blocked: the user can sign in, and you nudge them to verify. Use this for \"verify at signup, but let people in\". |\n| `AUTH_REQUIRE_EMAIL_CONFIRMATION` | The stricter form: does everything above AND **refuses login** until the email is confirmed (a distinguishable status the client surfaces as `EmailNotConfirmedError`, so the UI can prompt \"confirm your email / resend\"). Implies `AUTH_EMAIL_CONFIRMATION`. On the managed edge this is force-set from the per-domain Dacely setting. |\n\nWith neither set, accounts are auto-confirmed at registration and no confirm email is sent. The one-time link is delivered by email; in `toiljs dev` it is drawn in the console (no mailer needed). Both use the standard non-enumerating responses (a generic 200 that never reveals whether an address exists).\n\n## Argon2id strength (known limitation)\n\nThe built-in controller currently uses **demo-light** Argon2id params (32 MiB, 2 iterations, 1 lane) so it\nstays responsive in a browser tab. These are baked into the shipped controller today; **config-driven\ntuning is a planned follow-up.** For a high-value production deployment you should either wait for the\nconfig knob or hand-write your own controller with `≥ 256 MiB / ≥ 3 iterations`. The OPRF still provides the\nprimary offline-attack resistance regardless, but raise these before protecting anything sensitive.\n\nThe client always derives against whatever params the server returns in `/login/start`, so when the config\nknob lands you can raise them server-side with **no client change**.\n\n## Deploy checklist\n\n- [ ] `AUTH_SESSION_SECRET` set (32 random bytes), identical on every edge instance.\n- [ ] `AUTH_OPRF_SEED` set (32 random bytes).\n- [ ] `AUTH_KEM_SK` set (an ML-KEM-768 secret key), and its **public** half pinned in the client via\n `serverKemPublicKey`.\n- [ ] `TOIL_AUTH_DOMAIN` set if you serve multiple hostnames (stable `ToilUserId`).\n- [ ] (Recommended) Argon2id params reviewed for your threat model.\n\nThe CLI doctor warns when `server.auth` is on and the secrets are missing, run it before you ship.\n\n## Upgrading to 0.0.118\n\nLogin now requires `AuthOptions.serverKemPublicKey`, the 1184-byte public key matching\n`AUTH_KEM_SK`. There is no implicit fallback to the published development key. Keep\nexisting OPRF and KEM secrets when upgrading; replacing the OPRF seed invalidates\nexisting password credentials. Project-root `VITE_*` variables are loaded by default.\n\nSessions use a versioned signed payload with a random session identifier and a user\nrevocation generation. Pre-upgrade session cookies and pending login challenges are\nrejected, so users must sign in again. Single-session logout revokes the signed session;\n`POST /auth/logout-all`, password reset, and confirmed two-factor changes revoke all\nsessions. Two-factor changes require a fresh login after success. Existing account IDs\nremain stable after password reset. The compiler includes the new revocation and factor\nsettings database declarations automatically.\n\nAuthenticated factor operations accept `headers` and `onRequestFailed(status)` options\nfor application account guards. HTTP failures include their status in the client error.\n\n## Session lifetime\n\nSuccessful password and two-factor sign-ins issue sessions valid for seven days\n(604800 seconds). The signed expiry and both session/display cookie lifetimes\nmatch. This is a fixed lifetime from sign-in, not an idle timeout. Logout, password\nreset, and account revocation can end a session earlier. Existing cookies retain\nthe expiry they were issued with; sign in again to receive the longer lifetime.\n\n## Account deletion\n\n`await Auth.deleteAccount(options)` calls authenticated `POST /auth/delete`.\nIt releases the sign-in account's username and email, revokes all its sessions,\nand clears both browser cookies. Clean application-owned records and projections\nbefore calling it. The endpoint operates only on the authenticated user's account.\n\nDeletion marks the old account before cleanup and frees the username last.\nIf cleanup is interrupted, retry with the existing session. Registration also\nfinishes an interrupted deletion before claiming the username. Conditional\nwrites prevent an overlapping request from removing or modifying a replacement\naccount. Confirm/reset links and pending logins bind to an account incarnation;\nlinks issued before this upgrade are rejected and can be requested again.\nA re-registered account starts with fresh factor settings. Revocation epochs and opaque deletion-incarnation guards\nremain to reject copied cookies and delayed replays of old account rows; random login challenges expire and cannot\nbe redeemed against a replacement account.\n\nFor cleanup that spans background runs, finish deleting application-owned data,\nthen call `AuthService.deleteUser(id)` from a `@job`, passing a `ToilUserId`.\nIt uses the same account cleanup and session revocation as `/auth/delete`,\nwithout a signed-in request. Request Actions, Queries, and Derives are rejected.\nIt returns `true` after removing the account, or `false` if the ID is absent,\nits index is stale, or its account incarnation no longer owns that ID. Concurrent\nupdates and storage failures throw; retry them to resume deletion. A marked account\ncannot sign in while cleanup is incomplete. Permanent incarnation guards and\nsession epochs remain after deletion. The ID index removes the deleted account's\nusername/realm pointer after the account is removed, using a conditional update\nthat preserves pointers for replacement accounts.\n\nRegistration stores the ID index before activating the account; sign-in repairs\nmissing entries. Existing deployments should backfill their accounts from a Job\nbefore relying on ID deletion. `AuthService.indexUsers(limit = 8, cursor = null)`\nindexes at most eight accounts per invocation and returns the next cursor, or\n`null` at completion. Persist the cursor after a successful invocation and keep\ncalling even when a page indexes no accounts. Retry the same cursor on failure.\nThe scan requires a [complete local collection copy](../database/documents.md#background-collection-scans)\nand, for existing native data, the record-directory migration described there.\nAccounts predating stored stable IDs require the original `TOIL_AUTH_DOMAIN`\nvalue; the Job refuses to guess a historic request hostname or port. Accounts\nwith stored IDs do not require that setting.\n\nNormally an ID identifies one realm. If a deployment intentionally assigns the\nsame ID to accounts in multiple realms, pass the normalized realm as the second\nargument: `AuthService.deleteUser(id, 'example.com')`. Ambiguous lookups throw.\nThe index supports up to sixteen realms per ID. Account pointers include an\nincarnation so a delayed cleanup cannot remove a replacement with another ID.\nRe-registering with identical credentials and identity-domain inputs can reuse\nthe same stable ID; applications requiring a distinction between those lifetimes\nshould retain their own deletion generation.\n",
4
4
  "auth/emails.md": "# Customizing the auth emails\n\nBuilt-in auth sends three transactional emails: the email-verification link, the password-reset link, and the two-factor code. Each ships with a plain, working default. You can replace any of them with your own branded template, and you never touch the auth code to do it.\n\n## The three emails\n\n| Email | When it sends | The value it gives your template |\n| --- | --- | --- |\n| Email verification | On register, when email confirmation is on | `link` (the confirm URL) |\n| Password reset | On `POST /auth/reset/request` | `link` (the reset URL) |\n| Two-factor code | On login or 2FA setup, for the email method | `code` (the numeric code) and `action` (the flow phrase) |\n\nThe defaults are intentionally minimal so a fresh project sends real, correct mail with no setup. To match your brand, override them.\n\n## How to override\n\nDrop a React template in your project's `emails/` folder with the reserved name for that email. If the file exists, the build uses it; if not, the default stands. This is the same `emails/*.tsx` system you use for your own mail (see [Email](../services/email.md)), so you get full markup and inline CSS.\n\n| Reserved file | Overrides | Prop it must read |\n| --- | --- | --- |\n| `emails/auth-confirm.tsx` | Email verification | `link` |\n| `emails/auth-reset.tsx` | Password reset | `link` |\n| `emails/auth-2fa.tsx` | Two-factor code | `code`, `action` |\n\nEach template is a default-exported React component. Read the one prop it is given, and it becomes a `{{token}}` hole the edge fills per send. Reading any other prop renders empty, so the build warns you.\n\n```tsx\n// emails/auth-confirm.tsx -> overrides the email-verification message.\nexport const subject = 'Verify your Acme account';\n\nexport default function AuthConfirm({ link }: { link: string }) {\n return (\n <div style={{ fontFamily: 'system-ui', padding: 24 }}>\n <h1 style={{ color: '#cb9820' }}>Welcome to Acme</h1>\n <p>Tap below to verify your email and finish signing up.</p>\n <p>\n <a\n href={link}\n style={{ background: '#cb9820', color: '#fff', padding: '10px 18px', borderRadius: 8, textDecoration: 'none' }}\n >\n Verify my email\n </a>\n </p>\n <p style={{ color: '#666', fontSize: 13 }}>Or paste this link: {link}</p>\n </div>\n );\n}\n```\n\nThe reset template works the same way with the `link` prop.\n\n## The subject line\n\nFor verification and reset, set the subject with `export const subject = '...'`. Leave it out and the default subject is used (`Confirm your account`, `Reset your password`).\n\nThe two-factor email is different. It serves three flows (signing in, enabling 2FA, and turning 2FA off), so besides the `code` it also gets an `action` prop: the framework fills it with the flow phrase, `sign in`, `enable two-factor authentication`, or `turn off two-factor authentication`. Write it into a sentence like \"Enter this code to {action}.\" and the one template reads correctly for every flow. The subject is likewise set by the framework and stays contextual, so a `subject` export in this file is ignored.\n\n```tsx\n// emails/auth-2fa.tsx -> overrides the 2FA code message (subject is contextual).\nexport default function Auth2fa({ code, action }: { code: string; action: string }) {\n return (\n <div style={{ fontFamily: 'system-ui', padding: 24, textAlign: 'center' }}>\n <p>Your Acme verification code:</p>\n <p style={{ fontSize: 32, fontWeight: 700, letterSpacing: 6 }}>{code}</p>\n <p>Enter it to {action}.</p>\n <p style={{ color: '#666' }}>It expires in a few minutes.</p>\n </div>\n );\n}\n```\n\n## What you can and cannot put in\n\nEach template is rendered once, at build time, into a static string of HTML with your styles inlined, and the prop becomes a fill hole. So a fixed layout and inline styles work, but per-send logic does not: a `{items.map(...)}` or a conditional runs at build, not per email. For these three messages that is all you need, one link or one code.\n\nThe only values auth hands each template are the ones in the table above (`link`, or `code` plus `action` for 2FA). There is no user name, no app name, no expiry value. Write those into the template text directly.\n\nStyling rules are the same as any toiljs email: write inline `style={{ ... }}`, or import a stylesheet and its rules are inlined for you. A bare CSS import with no inlining has no effect in an email client. See [Email](../services/email.md) for the details.\n\n## Delivery stays safe\n\nYou cannot weaken the security of these flows by overriding a template. Every auth email is sent detached (fire-and-forget), so the response time never reveals whether an address maps to an account. That holds whether the message is the default or your override. Overriding only changes what the email looks like, never how it is sent.\n\n## Where the templates go\n\nThere is nothing to import and nothing to register. The build reads `emails/auth-*.tsx`, bakes the effective templates into the compiled server, and the auth controller sends them. Changing a template and rebuilding (or saving under `toiljs dev`) is all it takes.\n\n## Related\n\n- [Email](../services/email.md): the full `emails/*.tsx` system, `EmailService`, and `EmailTemplate`.\n- [Configuration](./configuration.md): the auth secrets and the email provider a deployment must set.\n- [Usage](./usage.md): enabling auth, the client API, and guarding routes.\n",
5
- "auth/extending.md": "# Extending & integrating auth\n\nBuilt-in auth is deliberately opinionated so the common case is one line. This page covers the identity\nyou build ON, `ToilUserId`, and how to go beyond the defaults: keying your own data on a user, a custom\nuser shape, and hand-writing auth from the same primitives.\n\n## `ToilUserId`\n\nThe stable, tenant-scoped user identity: `sha256(mldsaPublicKey ‖ identifier ‖ domain)`, a 256-bit value.\nIt's a **global** (no import), like `crypto`.\n\n```ts\n// Read the current user's id in any handler (gate on hasSession(), see the null note below).\nconst id: ToilUserId = AuthService.userId()!;\n\n// Or derive one yourself.\nconst id2 = ToilUserId.derive(mldsaPublicKey, 'alice@example.com', 'acme.dacely.com');\n```\n\n| Member | Description |\n| --- | --- |\n| `ToilUserId.derive(pk, identifier, domain)` | Derive from an ML-DSA public key + email/username + tenant domain. Deterministic. |\n| `ToilUserId.fromBytes(b)` | Rebuild from a 32-byte digest (from `toBytes()` or storage). |\n| `toBytes(): Uint8Array` | The 32 identity bytes. |\n| `toHex(): string` | Lowercase 64-char hex, a convenient string key. |\n| `isZero(): bool` | True for the unset / anonymous id. |\n| `equals(other): bool` | Value equality. |\n| `a == b` / `a != b` | Overloaded value comparison, **O(1)** (four `u64` word compares, no byte loop, no allocation). |\n\n```ts\nconst a = ToilUserId.derive(pk, 'alice', 'acme.com');\nconst b = ToilUserId.derive(pk, 'alice', 'acme.com');\nconst c = ToilUserId.derive(pk, 'bob', 'acme.com');\na == b; // true, same inputs, same id\na != c; // true, different user\n```\n\n> **Null-check gotcha:** because `ToilUserId` overloads `==`, `AuthService.userId() == null` does NOT\n> type-check (`==` expects a `ToilUserId`). Gate with `AuthService.hasSession()` and then `userId()!`, or\n> compare with `getUser()` (a plain nullable). `===` is reference identity in AssemblyScript and is not\n> overloadable, use `==` for value equality.\n\n## Keying your own data on the user\n\n`toilUserId` is the right key for per-user data, it's stable across sessions/devices and opaque. Use the\nhex as a string key, or the bytes in a `@data` key class:\n\n```ts\n@data\nclass UserKey {\n id: Uint8Array = new Uint8Array(0); // toilUserId bytes\n constructor(id: Uint8Array = new Uint8Array(0)) { this.id = id; }\n}\n\n@data class Profile { displayName: string = ''; bio: string = ''; }\n\n@database\nclass AppDb {\n @collection static profiles: Documents<UserKey, Profile>;\n}\n\n@rest('profile')\nclass ProfileApi {\n @auth\n @post('/')\n public save(ctx: RouteContext): Response {\n const key = new UserKey(AuthService.userId()!.toBytes());\n const p = Profile.decode(ctx.request.body);\n // Save this user's profile. create is insert-only, so the first save creates\n // the record and later saves overwrite the existing one with enqueue.\n if (!AppDb.profiles.create(key, p)) {\n AppDb.profiles.enqueue(key, p);\n }\n return Response.text('saved\\n');\n }\n}\n```\n\n## Extending the user: add your own fields\n\nBuilt-in auth reserves exactly two fields on the authenticated user: `toilUserId` and `username`. To carry\nmore (a role, a display name, a tenant), just declare your OWN `@user` in your server code while\n`server.auth` is on. The build detects it and **extends** it: it injects the reserved `toilUserId` +\n`username` as the first two fields and mints sessions for your shape automatically. You do not opt out of\nanything, and there is still exactly one `@user` per program.\n\n```ts\n@user\nclass Account {\n admin: bool = false;\n displayName: string = '';\n tenant: string = '';\n // toilUserId + username are INJECTED by the build; do not declare them here.\n}\n```\n\nRules:\n\n- Do **not** declare `toilUserId` or `username` yourself. They are reserved and injected; declaring either is\n a compile error (`'username' is reserved by built-in auth`).\n- Your `@user` must be default-constructible (give every field an initializer), like any `@data` class.\n\n`AuthService.getUser()` is now typed to YOUR shape:\n\n```ts\nconst user = AuthService.getUser(); // { toilUserId, username, admin, displayName, tenant } | null\n```\n\n**Populating your fields.** Login fills `toilUserId` + `username`; your extra fields start at their declared\ndefaults (`admin = false`, and so on). The built-in controller cannot know your business fields, so you set\nthem yourself on one of your own `@auth` routes by reading the user, updating it, and re-minting the session:\n\n```ts\n@rest('account')\nclass AccountApi {\n @auth @post('/promote')\n public promote(): Response {\n const user = AuthService.getUser()!;\n user.admin = true;\n const resp = Response.text('promoted\\n');\n resp.setCookie(AuthService.mintSession(user.encode())); // re-sign the session with the new fields\n resp.setCookie(AuthService.userCookie(user.encode())); // update the readable companion cookie\n return resp;\n }\n}\n```\n\nIf you would rather hand-write the whole controller instead, you still can: do **not** enable `server.auth`,\nand build your own `@user` + routes from the [AuthService primitives](#the-authservice-primitive-reference)\nbelow. But for most apps, extending is all you need.\n\n## Adding email verification / 2FA\n\nLayer a second factor on top of the session with `TwoFactor` (stateless email codes, no DB; see\n[email](../services/email.md)). Typical flow: after login, require a verified email before granting access to\nsensitive routes.\n\n```ts\n@rest('2fa')\nclass TwoFactorApi {\n // Step 1: email a code to the logged-in user, hand back the signed token.\n @auth @post('/send')\n public send(): Response {\n const email = /* the user's email, e.g. their username, or a stored profile field */;\n const ch = TwoFactor.send(email, 'login'); // emails the code, returns { token, status }\n return Response.bytes(new DataWriter().writeString(ch.token).toBytes());\n }\n\n // Step 2: verify the code the user typed against the token.\n @auth @post('/verify')\n public verify(ctx: RouteContext): Response {\n const r = new DataReader(ctx.request.body);\n const token = r.readString(); const email = r.readString(); const code = r.readString();\n if (!TwoFactor.verify(token, email, code)) return Response.text('bad code\\n', 401);\n // Mark this session 2FA-verified: re-mint the session with a flag in your own @user, or store a\n // per-user \"verified\" record keyed on AuthService.userId().\n return Response.text('verified\\n');\n }\n}\n```\n\n`TwoFactor` gives integrity + expiry but not single-use (a code re-verifies within its TTL); keep the TTL\nshort. For a branded email, use `TwoFactor.issue(...)` (returns the code without sending) + your own\n`Emails.*` template. Call `TwoFactor.setSecret(...)` once at startup in production.\n\n## The `AuthService` primitive reference\n\nEverything the built-in controller is built from, available for hand-written auth. All are ambient globals\n(no import).\n\n**Sessions & cookies**\n- `mintSession(userData: Uint8Array, ttlSecs?: u64): Cookie`: the signed `__Host-toil_sess` cookie.\n- `userCookie(userData, ttlSecs?): Cookie`: the readable `__Secure-toil_user` companion.\n- `clearSession(): Cookie` / `clearUserCookie(): Cookie`.\n- `hasSession(): bool`: the `@auth` predicate.\n- `getSessionBytes(): Uint8Array | null`: the verified `@user` payload bytes.\n- `getUser(): <your @user> | null`: decoded, typed to your `@user`.\n- `userId(): ToilUserId | null`: the stable id (built-in `@user` layout).\n- `setSecret(secret: Uint8Array)`: override the session HMAC key programmatically.\n\n**Post-quantum login crypto**\n- `oprfEvaluate(username, blinded): Uint8Array`: server-keyed OPRF eval.\n- `buildRegisterMessage(username, pk)` / `verifyRegister(pk, msg, sig): bool`: proof-of-possession.\n- `buildLoginMessage(sub, aud, cid, nonce, iat, exp, ct, memKiB, iterations, parallelism, serverKemKeyId)`\n / `verifyLogin(pk, msg, sig): bool`.\n- `mlkemDecapsulate(ct): Uint8Array`, `serverKemKeyId(): Uint8Array`.\n- `deriveSessionKey(sharedSecret, transcriptHash)`, `serverConfirmTag(sessionKey, transcriptHash)`: the\n mutual-auth confirmation.\n- `sha256(data): Uint8Array`.\n- `setOprfSeed(seed)`, `setServerKemSecretKey(sk)`, `setServerKemPublicKey(pk)`: override the seeds/keys.\n- Sizes: `PUBLIC_KEY_LEN`, `SIGNATURE_LEN`, `OPRF_ELEMENT_LEN`, `KEM_CIPHERTEXT_LEN`, `SHARED_SECRET_LEN`, …\n\n**Related globals**, `TwoFactor` (email codes; see [email](../services/email.md)), `RateLimitService` (used by\n`@ratelimit`), `Environment` (the secret store).\n\n## Two ways in, one behavior\n\nThe config flag and the import are identical at build time, both make the build append the shipped\n`@user` + `@rest('auth')` controller to the toilscript **entry** set, where their decorators weave and the\n`@rest` class self-mounts. (A framework decorator source only weaves as an entry; that's why a plain\n`import` of the controller isn't enough on its own, the marker import is detected by the build, which does\nthe entry injection.) This is why built-in auth needs no runtime registration call.\n\n\n## Static server typings\n\nServer editor declarations ship with the package; they do not require an app\nbuild. Importing `toiljs/server/runtime` loads them. A project with no runtime\nimport can add `/// <reference types=\"toiljs/server/globals\" />` to a declaration\nfile, or include `\"toiljs/server/globals\"` in its tsconfig `types` alongside\n`\"assembly\"`. The generated `toil-server-env.d.ts` is only a reference shim;\ncreate, build and doctor share the same declaration source.\n\nA plain ToilScript compile needs the framework globals in `--lib`. Without a\ncustom `@user` entry, `AuthService.getUser()` exposes the standard signed\nidentity prefix (`toilUserId: Uint8Array` and `username: string`) without a\ngenerated application declaration. Its decoder validates the 32-byte identity.\nAn explicit `@user` source entry preserves the application's full typed codec,\nincluding additional fields. The framework auth build still appends the built-in\nuser codec when auth is enabled and no custom user exists. That codec also\nsupplies the account controller's session encoder.\n\n## Initializing application records during registration\n\nInstall `AuthService.onRegistered((id, username, email) => { ... })` from your\nserver entry point. The callback receives the reserved stable `ToilUserId` and\nvalidated account fields. It runs before the account becomes active and uses the\nsame Action budget as registration. Use conditional create/upsert logic suitable\nfor retries: the callback may run more than once.\n\nIf it traps, registration remains pending and cannot sign in. A new registration\nattempt with the same credentials and proof resumes it and reruns the initializer.\nEarlier successful database calls remain committed, so callbacks must be\nidempotent. This is appropriate for creating an initial profile or pending\neligibility record; it does not supply extra age/profile answers absent from the\nregistration protocol.\n",
6
- "auth/how-it-works.md": "# How Toil auth works\n\nToil auth is a **post-quantum, password-based, mutually-authenticated** login. The design goal: the user\ntypes a password, but the server never sees it, never stores it, and can't be phished into leaking a\nverifier, and every primitive is quantum-resistant.\n\nThis page explains the protocol. You do not need to understand it to use auth (see [Usage](./usage.md)),\nbut you should understand the guarantees before you ship.\n\n## The building blocks\n\n| Primitive | Role |\n| --- | --- |\n| **OPRF** (RFC 9497, ristretto255-SHA512) | A *server-keyed* salt. The client blinds its password, the server evaluates it under a per-user key, the client unblinds. The result can't be computed without the server, so a stolen database can't be brute-forced offline. |\n| **Argon2id** | Stretches the OPRF output into key material (memory-hard, GPU/ASIC-resistant). Runs in the browser. |\n| **ML-DSA-44** (FIPS 204) | The user's identity key pair is *derived* from the Argon2id output. The server stores only the **public** key. Login is proved by an ML-DSA signature. |\n| **ML-KEM-768** (FIPS 203) | Key encapsulation on login: the server proves it holds its KEM secret by returning a confirmation tag only derivable from the decapsulated shared secret → **mutual** auth (anti-phishing). |\n| **HMAC-SHA256** | Signs the session cookie (`AUTH_SESSION_SECRET`). |\n\n> The whole thing is sometimes called an *aPAKE* (asymmetric password-authenticated key exchange). Do not\n> call it OPAQUE, this is Toil's own OPRF + KEM + signature construction.\n\n## What the server stores\n\nPer account, in ToilDB (`@database AuthDb`):\n\n- `username`, a deterministic `salt`, the **ML-DSA public key**, and the Argon2id params.\n\nThat's it. **No password, no password hash, no verifier that can be brute-forced without the OPRF key.**\nLogin challenges are a second collection, consumed exactly once (atomic `getDelete`).\n\n## Registration\n\n```\n Browser (client) Toil edge (server)\n ───────────────── ──────────────────\n blind(password) OPRF key = f(seed, username)\n │ username, blinded │\n │ ───────── POST /auth/register/start ───────────► │\n │ │ evaluated = OPRF(blinded)\n │ ◄──── {mem,iters,par, salt, evaluated} ───────── │ (salt is deterministic per user)\n │ │\n unblind → oprfOut │\n seed = Argon2id(oprfOut, salt, params) │\n (pk, sk) = ML-DSA-44.keygen(seed) │\n proof = ML-DSA.sign(sk, \"register|username|pk\") │\n │ username, pk, proof │\n │ ───────── POST /auth/register/finish ──────────► │\n │ │ verifyRegister(pk, msg, proof) ✓ proof-of-possession\n │ ◄──────────── {status: 0 ok | 1 taken} ──────── │ store AuthAccount{username, salt, pk, params}\n```\n\nThe server never learns the password or the secret key `sk`, only the public key `pk` and a proof the\nclient holds the matching `sk`. A duplicate username returns a **distinguishable** `status = 1` (so the UI\ncan say \"taken, log in instead\"); everything else fails generically.\n\n## Login (with mutual auth)\n\n```\n Browser (client) Toil edge (server)\n ───────────────── ──────────────────\n blind(password) │\n │ username, blinded │\n │ ───────── POST /auth/login/start ──────────────► │ evaluated = OPRF(blinded) (ALWAYS, even unknown user)\n │ │ if known: store Challenge{cid, nonce, iat, exp}\n │ ◄─ {cid, aud, params, salt, nonce, iat, exp, ── │ (identical response whether the user exists or not)\n │ evaluated} │\n unblind → Argon2id → (pk, sk) = ML-DSA.keygen │\n (ct, ssС) = ML-KEM-768.encapsulate(serverKemPublicKey) │\n msg = \"login|username|aud|cid|nonce|iat|exp|ct|params|kid\" │\n sig = ML-DSA.sign(sk, msg) │\n │ cid, ct, sig │\n │ ───────── POST /auth/login/finish ─────────────► │ ch = challenges.getDelete(cid) (consume once; check exp)\n │ │ rebuild msg from OUR stored values + ct\n │ │ verifyLogin(acct.pk, msg, sig) ✓ it's really this user\n │ │ ssS = ML-KEM.decapsulate(ct) ✓ we hold the KEM key\n │ │ K = deriveSessionKey(ssS, H(msg))\n │ ◄──── {0, sessionToken, serverConfirm} ──────── │ serverConfirm = tag(K, H(msg))\n │ + Set-Cookie: __Host-toil_sess=… │ mint session cookie\n verify serverConfirm using ssC ✓ the server is genuine │\n```\n\nTwo verifications, both required:\n1. **The server verifies the client**: the ML-DSA signature over a message bound to the challenge, the\n Argon2id params, and the server's KEM key id. Replays fail (the challenge is consumed).\n2. **The client verifies the server**: the `serverConfirm` tag is derivable only from the ML-KEM shared\n secret, which only the holder of the KEM secret key can decapsulate. A phishing site can't forge it.\n\n## Anti-enumeration\n\n`/login/start` behaves identically for a known and an unknown user: it always runs the OPRF (a decoy key\nfor unknown users), returns a **deterministic** per-user salt and constant params, and a fresh challenge.\nThe challenge is persisted only for a real account, and `/login/finish` fails generically at consume for an\nunknown user. So an attacker can't probe which usernames exist. Every failure path returns the same\n`401 auth: request failed`.\n\n## Sessions & cookies\n\nOn successful login the server mints **two** cookies:\n\n- **`__Host-toil_sess`**: the authoritative session. HMAC-SHA256 signed with `AUTH_SESSION_SECRET`,\n `HttpOnly`, `Secure`, `SameSite=Lax`. It carries the `@user` codec payload. `@auth` and\n `AuthService.getUser()` open + verify this cookie server-side; a forged or tampered cookie fails.\n- **`__Secure-toil_user`**: a **readable** companion carrying the same payload, so the browser can show\n \"logged in as …\" via the client's `getUser()`. The server **never trusts it**, it is display-only.\n\nEach request runs in a fresh wasm instance. The signed payload is self-contained,\nbut verification also reads the revoked-session and user-generation collections. `AUTH_SESSION_SECRET` must be identical across every edge instance (it is, via the\nenv store) so a cookie minted anywhere verifies everywhere.\n\n## The stable user identity: `ToilUserId`\n\nAt account creation the server derives and stores a stable, tenant-scoped id; login puts that stored id in the session (the first field of the\nbuilt-in `@user`):\n\n```\ntoilUserId = SHA-256(bytes(\"toil.userid.v1\") ‖ bytes(mldsaPublicKey) ‖ bytes(username) ‖ bytes(domain))\n```\n\n- **Stable:** same login key + username on the same tenant `domain` → same id, forever, across sessions\n and devices. Key your own data on it.\n- **Opaque + one-way:** it's a hash: safe to store, log, or expose without leaking the key or the address.\n- Read it anywhere with `AuthService.userId()`. See [Extending](./extending.md#toiluserid) for the\n `ToilUserId` API (O(1) `==` / `!=`, `toHex()`, …).\n\n## Threat-model summary\n\n- **Server database stolen** → attacker gets public keys + salts, not passwords. Brute-forcing needs the\n OPRF key (server-side) *and* Argon2id work per guess.\n- **Server compromised / malicious** → still can't recover passwords (only public keys) and can't forge a\n past session without `AUTH_SESSION_SECRET`.\n- **Phishing site** → can't produce the `serverConfirm` tag (no KEM secret), so a correct client aborts.\n- **Quantum adversary** → ML-DSA + ML-KEM are post-quantum; the OPRF/Argon2id/HMAC pieces are classical but\n not the long-term identity or key-exchange.\n- **Replay** → challenges are single-use (`getDelete`) with a short TTL.\n\nResidual responsibilities are yours: set the [secrets](./configuration.md), pin your deployment's KEM\npublic key in the client, and raise the Argon2id params for production.\n\nFor native/mobile ports, see the [binary protocol and verified test vectors](./native-protocol.md).\n",
7
- "auth/native-protocol.md": "# Native client protocol and vectors\n\nA native client can implement the same protocol as `toiljs/client` without a\nWebView. The portable known-answer fixture is [vectors-v1.json](./vectors-v1.json).\nIt contains public test seeds and keys, intermediate values, complete signed\nmessages, signatures, and confirmation tags. The fixture is tested against the\nJavaScript client, compiled ToilScript server helpers, and native Rust OPRF,\nML-DSA, ML-KEM, SHA-256, and HMAC implementations.\n\nRegenerate it after building toiljs with `node scripts/gen-auth-vectors.mjs`.\nAll binary fields in the JSON are hexadecimal; timestamps are decimal strings.\nThe fixture's fixed timestamps and keys are for offline interoperability tests.\n\n## Binary framing\n\nHTTP bodies use `application/octet-stream`. All integers are unsigned,\n**little-endian**. `bytes(x)` is `u32(byteLength) || x`; `str(s)` is\n`bytes(UTF8(s))`. Strings are length-prefixed UTF-8, without a terminator.\nThese auth bodies do not have the four-byte `@data` class tag.\n\n## Password and key derivation\n\n1. Encode `NFKC(password)` as UTF-8. Do not trim, lowercase, or otherwise change it.\n2. Use RFC 9497 **OPRF mode**, `ristretto255-SHA512`, not VOPRF or POPRF mode.\n The client generates a fresh blind and sends the 32-byte blinded element.\n The server derives its per-user OPRF key with `DeriveKeyPair(oprfSeed,\n UTF8(username))` and evaluates that element.\n3. Finalize the OPRF using the normalized password bytes, saved blind, and\n evaluated element. Its 64-byte output is the **binary password input** to\n Argon2id; it is not hexadecimal text.\n4. Run Argon2id with the server-issued salt, memory size in **KiB**, iteration\n count, parallelism, and a 32-byte output. The vector records each parameter.\n5. Use those 32 output bytes as the ML-DSA-44 key-generation seed. Public keys\n are 1,312 bytes and signatures are 2,420 bytes. Do not send the password,\n OPRF output, Argon2 output, or signing secret key to the server.\n\n## Registration\n\n`POST /auth/register/start`:\n\n```\nrequest = str(username) bytes(blinded)\nresponse = u8(status) u32(memKiB) u32(iterations) u32(parallelism)\n bytes(salt) bytes(evaluated)\n```\n\nContinue only for status 0. Build the registration proof message:\n\n```\nu8(1) str(username) bytes(mldsaPublicKey)\n```\n\nSign it with ML-DSA-44 and the separate FIPS 204 context\n`qauth:register:v1`. Pass the context through the signature API; do not prepend\nit to the message yourself.\n\n`POST /auth/register/finish` sends:\n\n```\nstr(username) str(email) bytes(mldsaPublicKey) bytes(registerSignature)\n```\n\nThe response starts with a status byte. Status 0 means registration completed;\nnonzero statuses are errors. Email confirmation may still be required by the\napplication. Initialize application records through the server-side\n`AuthService.onRegistered` hook when appropriate.\n\n## Login and server authentication\n\nPin the deployment's **ML-KEM-768 public key** in the native app's trusted\nconfiguration. It is 1,184 bytes; never replace it with a key learned from an\nuntrusted login response.\n\n`POST /auth/login/start`:\n\n```\nrequest = str(username) bytes(blinded)\nresponse = bytes(cid) str(audience)\n u32(memKiB) u32(iterations) u32(parallelism) bytes(salt)\n bytes(nonce) u64(iat) u64(exp) bytes(evaluated)\n```\n\nFinish the OPRF/KDF and regenerate the signing key. Encapsulate a fresh ML-KEM-768\nsecret to the pinned server public key. The ciphertext is 1,088 bytes; the shared\nsecret is 32 bytes. Compute `serverKemKeyId = SHA256(serverKemPublicKey)`.\nBuild the exact login message:\n\n```\nu8(1) str(username) str(audience) bytes(cid) bytes(nonce)\nu64(iat) u64(exp) bytes(ciphertext)\nu32(memKiB) u32(iterations) u32(parallelism) bytes(serverKemKeyId)\n```\n\nSign with the separate context `qauth:login:v1`. Submit\n`bytes(cid) bytes(ciphertext) bytes(signature)` to `/auth/login/finish`.\nFor status 0 or 3, its response is:\n\n```\nu8(status) bytes(first) bytes(serverConfirm)\n```\n\nStatus 0 supplies the readable user codec bytes in `first`; status 3 supplies a\nsecond-factor challenge identifier and creates no session. For **both** statuses,\nverify server authentication before accepting a login or showing the 2FA prompt:\n\n```\nH = SHA256(loginMessage)\nK = HMAC_SHA256(sharedSecret, UTF8(\"toil-session-key-v1\") || H)\nexpected = HMAC_SHA256(K, UTF8(\"toil-server-confirm-v1\") || H)\n```\n\nCompare `expected` to `serverConfirm` without an early exit on differing bytes.\nOther status values represent failed credentials, confirmation requirements, or\nother errors. Challenges are expiring and single-use; obtain a new challenge for\na retry.\n\n## Sessions on native transports\n\nThe readable `first` value is **not a bearer credential**. Preserve the signed\nHttpOnly session cookie from `Set-Cookie` in the platform's cookie jar and send\nit on later requests to the same tenant. Over HTTPS its name is\n`__Host-toil_sess`; the readable companion is `__Secure-toil_user`. Honor both\nclearing cookies on logout or 401. The companion and decoded user bytes are for\ndisplay, and the server revalidates the signed cookie and revocation state.\n\n## Initial stable identity\n\nFor a newly registered account, the user ID is SHA-256 over four `bytes(...)`\nfields: UTF-8 `toil.userid.v1`, the ML-DSA public key, UTF-8 username, and the\nconfigured identity domain. The vector includes this initial ID. The account\nstores its ID so password/key changes preserve the existing identity; clients\nshould use the returned server identity rather than derive a replacement.\n",
5
+ "auth/extending.md": "# Extending & integrating auth\n\nBuilt-in auth is deliberately opinionated so the common case is one line. This page covers the identity\nyou build ON, `ToilUserId`, and how to go beyond the defaults: keying your own data on a user, a custom\nuser shape, and hand-writing auth from the same primitives.\n\n## `ToilUserId`\n\nThe stable, tenant-scoped user identity is a 256-bit SHA-256 hash of four\nlength-prefixed fields: the `toil.userid.v1` label, ML-DSA public key, identifier\n(the built-in account username), and tenant domain. See the\n[exact derivation](./how-it-works.md#the-stable-user-identity-toiluserid).\nIt's a **global** (no import), like `crypto`.\n\n```ts\n// Read the current user's id in any handler (gate on hasSession(), see the null note below).\nconst id: ToilUserId = AuthService.userId()!;\n\n// Or derive one yourself.\nconst id2 = ToilUserId.derive(mldsaPublicKey, 'alice@example.com', 'acme.dacely.com');\n```\n\n| Member | Description |\n| --- | --- |\n| `ToilUserId.derive(pk, identifier, domain)` | Derive from an ML-DSA public key + email/username + tenant domain. Deterministic. |\n| `ToilUserId.fromBytes(b)` | Rebuild from a 32-byte digest (from `toBytes()` or storage). |\n| `toBytes(): Uint8Array` | The 32 identity bytes. |\n| `toHex(): string` | Lowercase 64-char hex, a convenient string key. |\n| `isZero(): bool` | True for the unset / anonymous id. |\n| `equals(other): bool` | Value equality. |\n| `a == b` / `a != b` | Overloaded value comparison, **O(1)** (four `u64` word compares, no byte loop, no allocation). |\n\n```ts\nconst a = ToilUserId.derive(pk, 'alice', 'acme.com');\nconst b = ToilUserId.derive(pk, 'alice', 'acme.com');\nconst c = ToilUserId.derive(pk, 'bob', 'acme.com');\na == b; // true, same inputs, same id\na != c; // true, different user\n```\n\n> **Null-check gotcha:** because `ToilUserId` overloads `==`, `AuthService.userId() == null` does NOT\n> type-check (`==` expects a `ToilUserId`). Gate with `AuthService.hasSession()` and then `userId()!`, or\n> compare with `getUser()` (a plain nullable). `===` is reference identity in AssemblyScript and is not\n> overloadable, use `==` for value equality.\n\n## Keying your own data on the user\n\n`toilUserId` is the right key for per-user data, it's stable across sessions/devices and opaque. Use the\nhex as a string key, or the bytes in a `@data` key class:\n\n```ts\n@data\nclass UserKey {\n id: Uint8Array = new Uint8Array(0); // toilUserId bytes\n constructor(id: Uint8Array = new Uint8Array(0)) { this.id = id; }\n}\n\n@data class Profile { displayName: string = ''; bio: string = ''; }\n\n@database\nclass AppDb {\n @collection static profiles: Documents<UserKey, Profile>;\n}\n\n@rest('profile')\nclass ProfileApi {\n @auth\n @post('/')\n public save(ctx: RouteContext): Response {\n const key = new UserKey(AuthService.userId()!.toBytes());\n const p = Profile.decode(ctx.request.body);\n // Save this user's profile. create is insert-only, so the first save creates\n // the record and later saves overwrite the existing one with enqueue.\n if (!AppDb.profiles.create(key, p)) {\n AppDb.profiles.enqueue(key, p);\n }\n return Response.text('saved\\n');\n }\n}\n```\n\n## Extending the user: add your own fields\n\nBuilt-in auth reserves exactly two fields on the authenticated user: `toilUserId` and `username`. To carry\nmore (a role, a display name, a tenant), just declare your OWN `@user` in your server code while\n`server.auth` is on. The build detects it and **extends** it: it injects the reserved `toilUserId` +\n`username` as the first two fields and mints sessions for your shape automatically. You do not opt out of\nanything, and there is still exactly one `@user` per program.\n\n```ts\n@user\nclass Account {\n admin: bool = false;\n displayName: string = '';\n tenant: string = '';\n // toilUserId + username are INJECTED by the build; do not declare them here.\n}\n```\n\nRules:\n\n- Do **not** declare `toilUserId` or `username` yourself. They are reserved and injected; declaring either is\n a compile error (`'username' is reserved by built-in auth`).\n- Your `@user` must be default-constructible (give every field an initializer), like any `@data` class.\n\n`AuthService.getUser()` is now typed to YOUR shape:\n\n```ts\nconst user = AuthService.getUser(); // { toilUserId, username, admin, displayName, tenant } | null\n```\n\n**Populating your fields.** Login fills `toilUserId` + `username`; your extra fields start at their declared\ndefaults (`admin = false`, and so on). The built-in controller cannot know your business fields, so you set\nthem yourself on one of your own `@auth` routes by reading the user, updating it, and re-minting the session:\n\n```ts\n@rest('account')\nclass AccountApi {\n @auth @post('/promote')\n public promote(): Response {\n const user = AuthService.getUser()!;\n user.admin = true;\n const resp = Response.text('promoted\\n');\n resp.setCookie(AuthService.mintSession(user.encode())); // re-sign the session with the new fields\n resp.setCookie(AuthService.userCookie(user.encode())); // update the readable companion cookie\n return resp;\n }\n}\n```\n\nIf you would rather hand-write the whole controller instead, you still can: do **not** enable `server.auth`,\nand build your own `@user` + routes from the [AuthService primitives](#the-authservice-primitive-reference)\nbelow. But for most apps, extending is all you need.\n\n## Adding email verification / 2FA\n\nLayer a second factor on top of the session with `TwoFactor` (stateless email codes, no DB; see\n[email](../services/email.md)). Typical flow: after login, require a verified email before granting access to\nsensitive routes.\n\n```ts\n@rest('2fa')\nclass TwoFactorApi {\n // Step 1: email a code to the logged-in user, hand back the signed token.\n @auth @post('/send')\n public send(): Response {\n const email = /* the user's email, e.g. their username, or a stored profile field */;\n const ch = TwoFactor.send(email, 'login'); // emails the code, returns { token, status }\n return Response.bytes(new DataWriter().writeString(ch.token).toBytes());\n }\n\n // Step 2: verify the code the user typed against the token.\n @auth @post('/verify')\n public verify(ctx: RouteContext): Response {\n const r = new DataReader(ctx.request.body);\n const token = r.readString(); const email = r.readString(); const code = r.readString();\n if (!TwoFactor.verify(token, email, code)) return Response.text('bad code\\n', 401);\n // Mark this session 2FA-verified: re-mint the session with a flag in your own @user, or store a\n // per-user \"verified\" record keyed on AuthService.userId().\n return Response.text('verified\\n');\n }\n}\n```\n\n`TwoFactor` gives integrity + expiry but not single-use (a code re-verifies within its TTL); keep the TTL\nshort. For a branded email, use `TwoFactor.issue(...)` (returns the code without sending) + your own\n`Emails.*` template. Call `TwoFactor.setSecret(...)` once at startup in production.\n\n## The `AuthService` primitive reference\n\nEverything the built-in controller is built from, available for hand-written auth. All are ambient globals\n(no import).\n\n**Sessions & cookies**\n- `mintSession(userData: Uint8Array, ttlSecs?: u64): Cookie`: the signed `__Host-toil_sess` cookie.\n- `userCookie(userData, ttlSecs?): Cookie`: the readable `__Secure-toil_user` companion.\n- `clearSession(): Cookie` / `clearUserCookie(): Cookie`.\n- `hasSession(): bool`: the `@auth` predicate.\n- `getSessionBytes(): Uint8Array | null`: the verified `@user` payload bytes.\n- `getUser(): <your @user> | null`: decoded, typed to your `@user`.\n- `userId(): ToilUserId | null`: the stable id (built-in `@user` layout).\n- `setSecret(secret: Uint8Array)`: override the session HMAC key programmatically.\n\n**Post-quantum login crypto**\n- `oprfEvaluate(username, blinded): Uint8Array`: server-keyed OPRF eval.\n- `buildRegisterMessage(username, pk)` / `verifyRegister(pk, msg, sig): bool`: proof-of-possession.\n- `buildLoginMessage(sub, aud, cid, nonce, iat, exp, ct, memKiB, iterations, parallelism, serverKemKeyId)`\n / `verifyLogin(pk, msg, sig): bool`.\n- `mlkemDecapsulate(ct): Uint8Array`, `serverKemKeyId(): Uint8Array`.\n- `deriveSessionKey(sharedSecret, transcriptHash)`, `serverConfirmTag(sessionKey, transcriptHash)`: the\n mutual-auth confirmation.\n- `sha256(data): Uint8Array`.\n- `setOprfSeed(seed)`, `setServerKemSecretKey(sk)`, `setServerKemPublicKey(pk)`: override the seeds/keys.\n- Sizes: `PUBLIC_KEY_LEN`, `SIGNATURE_LEN`, `OPRF_ELEMENT_LEN`, `KEM_CIPHERTEXT_LEN`, `SHARED_SECRET_LEN`, …\n\n**Related globals**, `TwoFactor` (email codes; see [email](../services/email.md)), `RateLimitService` (used by\n`@ratelimit`), `Environment` (the secret store).\n\n## Two ways in, one behavior\n\nThe config flag and the import are identical at build time, both make the build append the shipped\n`@user` + `@rest('auth')` controller to the toilscript **entry** set, where their decorators weave and the\n`@rest` class self-mounts. (A framework decorator source only weaves as an entry; that's why a plain\n`import` of the controller isn't enough on its own, the marker import is detected by the build, which does\nthe entry injection.) This is why built-in auth needs no runtime registration call.\n\n\n## Static server typings\n\nServer editor declarations ship with the package; they do not require an app\nbuild. Importing `toiljs/server/runtime` loads them. A project with no runtime\nimport can add `/// <reference types=\"toiljs/server/globals\" />` to a declaration\nfile, or include `\"toiljs/server/globals\"` in its tsconfig `types` alongside\n`\"assembly\"`. The generated `toil-server-env.d.ts` is only a reference shim;\ncreate, build and doctor share the same declaration source.\n\nA plain ToilScript compile needs the framework globals in `--lib`. Without a\ncustom `@user` entry, `AuthService.getUser()` exposes the standard signed\nidentity prefix (`toilUserId: Uint8Array` and `username: string`) without a\ngenerated application declaration. Its decoder validates the 32-byte identity.\nAn explicit `@user` source entry preserves the application's full typed codec,\nincluding additional fields. The framework auth build still appends the built-in\nuser codec when auth is enabled and no custom user exists. That codec also\nsupplies the account controller's session encoder.\n\n## Initializing application records during registration\n\nInstall `AuthService.onRegistered((id, username, email) => { ... })` from your\nserver entry point. The callback receives the reserved stable `ToilUserId` and\nvalidated account fields. It runs before the account becomes active and uses the\nsame Action budget as registration. Use conditional create/upsert logic suitable\nfor retries: the callback may run more than once.\n\nIf it traps, registration remains pending and cannot sign in. A new registration\nattempt with the same credentials and proof resumes it and reruns the initializer.\nEarlier successful database calls remain committed, so callbacks must be\nidempotent. This is appropriate for creating an initial profile or pending\neligibility record; it does not supply extra age/profile answers absent from the\nregistration protocol.\n",
6
+ "auth/how-it-works.md": "# How Toil auth works\n\nToil auth is a **post-quantum, password-based, mutually-authenticated** login. The design goal: the user\ntypes a password, but the server never sees it, never stores it, and can't be phished into leaking a\nverifier, and every primitive is quantum-resistant.\n\nThis page explains the protocol. You do not need to understand it to use auth (see [Usage](./usage.md)),\nbut you should understand the guarantees before you ship.\n\n## The building blocks\n\n| Primitive | Role |\n| --- | --- |\n| **OPRF** (RFC 9497, ristretto255-SHA512) | A *server-keyed* salt. The client blinds its password, the server evaluates it under a per-user key, the client unblinds. The result can't be computed without the server, so a stolen database can't be brute-forced offline. |\n| **Argon2id** | Stretches the OPRF output into key material (memory-hard, GPU/ASIC-resistant). Runs in the browser. |\n| **ML-DSA-44** (FIPS 204) | The user's identity key pair is *derived* from the Argon2id output. The server stores only the **public** key. Login is proved by an ML-DSA signature. |\n| **ML-KEM-768** (FIPS 203) | Key encapsulation on login: the server proves it holds its KEM secret by returning a confirmation tag only derivable from the decapsulated shared secret → **mutual** auth (anti-phishing). |\n| **HMAC-SHA256** | Signs the session cookie (`AUTH_SESSION_SECRET`). |\n\n> The whole thing is sometimes called an *aPAKE* (asymmetric password-authenticated key exchange). Do not\n> call it OPAQUE, this is Toil's own OPRF + KEM + signature construction.\n\n## What the server stores\n\nPer account, in ToilDB (`@database AuthDb`):\n\n- `username`, a deterministic `salt`, the **ML-DSA public key**, and the Argon2id params.\n\nThat's it. **No password, no password hash, no verifier that can be brute-forced without the OPRF key.**\nLogin challenges are a second collection, consumed exactly once (atomic `getDelete`).\n\n## Registration\n\n```\n Browser (client) Toil edge (server)\n ───────────────── ──────────────────\n blind(password) OPRF key = f(seed, username)\n │ username, blinded │\n │ ───────── POST /auth/register/start ───────────► │\n │ │ evaluated = OPRF(blinded)\n │ ◄──── {mem,iters,par, salt, evaluated} ───────── │ (salt is deterministic per user)\n │ │\n unblind → oprfOut │\n seed = Argon2id(oprfOut, salt, params) │\n (pk, sk) = ML-DSA-44.keygen(seed) │\n proof = ML-DSA.sign(sk, \"register|username|pk\") │\n │ username, pk, proof │\n │ ───────── POST /auth/register/finish ──────────► │\n │ │ verifyRegister(pk, msg, proof) ✓ proof-of-possession\n │ ◄──────────── {status: 0 ok | 1 taken} ──────── │ store AuthAccount{username, salt, pk, params}\n```\n\nThe server never learns the password or the secret key `sk`, only the public key `pk` and a proof the\nclient holds the matching `sk`. A duplicate username returns a **distinguishable** `status = 1` (so the UI\ncan say \"taken, log in instead\"); everything else fails generically.\n\n## Login (with mutual auth)\n\n```\n Browser (client) Toil edge (server)\n ───────────────── ──────────────────\n blind(password) │\n │ username, blinded │\n │ ───────── POST /auth/login/start ──────────────► │ evaluated = OPRF(blinded) (ALWAYS, even unknown user)\n │ │ if known: store Challenge{cid, nonce, iat, exp}\n │ ◄─ {cid, aud, params, salt, nonce, iat, exp, ── │ (identical response whether the user exists or not)\n │ evaluated} │\n unblind → Argon2id → (pk, sk) = ML-DSA.keygen │\n (ct, ssС) = ML-KEM-768.encapsulate(serverKemPublicKey) │\n msg = \"login|username|aud|cid|nonce|iat|exp|ct|params|kid\" │\n sig = ML-DSA.sign(sk, msg) │\n │ cid, ct, sig │\n │ ───────── POST /auth/login/finish ─────────────► │ ch = challenges.getDelete(cid) (consume once; check exp)\n │ │ rebuild msg from OUR stored values + ct\n │ │ verifyLogin(acct.pk, msg, sig) ✓ it's really this user\n │ │ ssS = ML-KEM.decapsulate(ct) ✓ we hold the KEM key\n │ │ K = deriveSessionKey(ssS, H(msg))\n │ ◄──── {0, sessionToken, serverConfirm} ──────── │ serverConfirm = tag(K, H(msg))\n │ + Set-Cookie: __Host-toil_sess=… │ mint session cookie\n verify serverConfirm using ssC ✓ the server is genuine │\n```\n\nTwo verifications, both required:\n1. **The server verifies the client**: the ML-DSA signature over a message bound to the challenge, the\n Argon2id params, and the server's KEM key id. Replays fail (the challenge is consumed).\n2. **The client verifies the server**: the `serverConfirm` tag is derivable only from the ML-KEM shared\n secret, which only the holder of the KEM secret key can decapsulate. A phishing site can't forge it.\n\n## Anti-enumeration\n\n`/login/start` behaves identically for a known and an unknown user: it always runs the OPRF (a decoy key\nfor unknown users), returns a **deterministic** per-user salt and constant params, and a fresh challenge.\nThe challenge is persisted only for a real account, and `/login/finish` fails generically at consume for an\nunknown user. So an attacker can't probe which usernames exist. Every failure path returns the same\n`401 auth: request failed`.\n\n## Sessions & cookies\n\nOn successful login the server mints **two** cookies:\n\n- **`__Host-toil_sess`**: the authoritative session. HMAC-SHA256 signed with `AUTH_SESSION_SECRET`,\n `HttpOnly`, `Secure`, `SameSite=Lax`. It carries the `@user` codec payload. `@auth` and\n `AuthService.getUser()` open + verify this cookie server-side; a forged or tampered cookie fails.\n- **`__Secure-toil_user`**: a **readable** companion carrying the same payload, so the browser can show\n \"logged in as …\" via the client's `getUser()`. The server **never trusts it**, it is display-only.\n\nEach request runs in a fresh wasm instance. The signed payload is self-contained,\nbut verification also reads the revoked-session and user-generation collections. `AUTH_SESSION_SECRET` must be identical across every edge instance (it is, via the\nenv store) so a cookie minted anywhere verifies everywhere.\n\n## The stable user identity: `ToilUserId`\n\nAt account creation the server derives and stores a stable, tenant-scoped id; login puts that stored id in the session (the first field of the\nbuilt-in `@user`):\n\n```\ntoilUserId = SHA-256(bytes(\"toil.userid.v1\") ‖ bytes(mldsaPublicKey) ‖ bytes(username) ‖ bytes(domain))\n```\n\nEach `bytes(x)` writes a `u32` little-endian byte length followed by the bytes.\nText fields use UTF-8. The prefix is framed the same way as the other fields;\nthe preimage is not a raw concatenation of strings.\n\n- **Stable:** same login key + username on the same tenant `domain` → same id, forever, across sessions\n and devices. Key your own data on it.\n- **Opaque + one-way:** it's a hash: safe to store, log, or expose without leaking the key or the address.\n- Read it anywhere with `AuthService.userId()`. See [Extending](./extending.md#toiluserid) for the\n `ToilUserId` API (O(1) `==` / `!=`, `toHex()`, …).\n\n## Threat-model summary\n\n- **Server database stolen** → attacker gets public keys + salts, not passwords. Brute-forcing needs the\n OPRF key (server-side) *and* Argon2id work per guess.\n- **Server compromised / malicious** → still can't recover passwords (only public keys) and can't forge a\n past session without `AUTH_SESSION_SECRET`.\n- **Phishing site** → can't produce the `serverConfirm` tag (no KEM secret), so a correct client aborts.\n- **Quantum adversary** → ML-DSA + ML-KEM are post-quantum; the OPRF/Argon2id/HMAC pieces are classical but\n not the long-term identity or key-exchange.\n- **Replay** → challenges are single-use (`getDelete`) with a short TTL.\n\nResidual responsibilities are yours: set the [secrets](./configuration.md), pin your deployment's KEM\npublic key in the client, and raise the Argon2id params for production.\n\nFor native/mobile ports, see the [binary protocol and verified test vectors](./native-protocol.md).\n",
7
+ "auth/native-protocol.md": "# Native client protocol and vectors\n\nA native client can implement the same protocol as `toiljs/client` without a\nWebView. The portable known-answer fixture is [vectors-v1.json](./vectors-v1.json).\nThe package ships it as `toiljs/auth/vectors-v1.json`, and builds copy it beside\nthis guide under `.toil/docs/auth/` so the relative link works locally.\nIt contains public test seeds and keys, intermediate values, complete signed\nmessages, signatures, and confirmation tags. The fixture is tested against the\nJavaScript client, compiled ToilScript server helpers, and native Rust OPRF,\nML-DSA, ML-KEM, SHA-256, and HMAC implementations.\n\nRegenerate it after building toiljs with `node scripts/gen-auth-vectors.mjs`.\nAll binary fields in the JSON are hexadecimal; timestamps are decimal strings.\nThe fixture's fixed timestamps and keys are for offline interoperability tests.\n\n## Binary framing\n\nHTTP bodies use `application/octet-stream`. All integers are unsigned,\n**little-endian**. `bytes(x)` is `u32(byteLength) || x`; `str(s)` is\n`bytes(UTF8(s))`. Strings are length-prefixed UTF-8, without a terminator.\nThese auth bodies do not have the four-byte `@data` class tag.\n\n## Password and key derivation\n\n1. Encode `NFKC(password)` as UTF-8. Do not trim, lowercase, or otherwise change it.\n2. Use RFC 9497 **OPRF mode**, `ristretto255-SHA512`, not VOPRF or POPRF mode.\n The client generates a fresh blind and sends the 32-byte blinded element.\n The server derives its per-user OPRF key with `DeriveKeyPair(oprfSeed,\n UTF8(username))` and evaluates that element.\n3. Finalize the OPRF using the normalized password bytes, saved blind, and\n evaluated element. Its 64-byte output is the **binary password input** to\n Argon2id; it is not hexadecimal text.\n4. Run Argon2id with the server-issued salt, memory size in **KiB**, iteration\n count, parallelism, and a 32-byte output. The vector records each parameter.\n5. Use those 32 output bytes as the ML-DSA-44 key-generation seed. Public keys\n are 1,312 bytes and signatures are 2,420 bytes. Do not send the password,\n OPRF output, Argon2 output, or signing secret key to the server.\n\n## Registration\n\n`POST /auth/register/start`:\n\n```\nrequest = str(username) bytes(blinded)\nresponse = u8(status) u32(memKiB) u32(iterations) u32(parallelism)\n bytes(salt) bytes(evaluated)\n```\n\nContinue only for status 0. Build the registration proof message:\n\n```\nu8(1) str(username) bytes(mldsaPublicKey)\n```\n\nSign it with ML-DSA-44 and the separate FIPS 204 context\n`qauth:register:v1`. Pass the context through the signature API; do not prepend\nit to the message yourself.\n\n`POST /auth/register/finish` sends:\n\n```\nstr(username) str(email) bytes(mldsaPublicKey) bytes(registerSignature)\n```\n\nThe response starts with a status byte. Status 0 means registration completed;\nnonzero statuses are errors. Email confirmation may still be required by the\napplication. Initialize application records through the server-side\n`AuthService.onRegistered` hook when appropriate.\n\n## Login and server authentication\n\nPin the deployment's **ML-KEM-768 public key** in the native app's trusted\nconfiguration. It is 1,184 bytes; never replace it with a key learned from an\nuntrusted login response.\n\n`POST /auth/login/start`:\n\n```\nrequest = str(username) bytes(blinded)\nresponse = bytes(cid) str(audience)\n u32(memKiB) u32(iterations) u32(parallelism) bytes(salt)\n bytes(nonce) u64(iat) u64(exp) bytes(evaluated)\n```\n\nFinish the OPRF/KDF and regenerate the signing key. Encapsulate a fresh ML-KEM-768\nsecret to the pinned server public key. The ciphertext is 1,088 bytes; the shared\nsecret is 32 bytes. Compute `serverKemKeyId = SHA256(serverKemPublicKey)`.\nBuild the exact login message:\n\n```\nu8(1) str(username) str(audience) bytes(cid) bytes(nonce)\nu64(iat) u64(exp) bytes(ciphertext)\nu32(memKiB) u32(iterations) u32(parallelism) bytes(serverKemKeyId)\n```\n\nSign with the separate context `qauth:login:v1`. Submit\n`bytes(cid) bytes(ciphertext) bytes(signature)` to `/auth/login/finish`.\nFor status 0 or 3, its response is:\n\n```\nu8(status) bytes(first) bytes(serverConfirm)\n```\n\nStatus 0 supplies the readable user codec bytes in `first`; status 3 supplies a\nsecond-factor challenge identifier and creates no session. For **both** statuses,\nverify server authentication before accepting a login or showing the 2FA prompt:\n\n```\nH = SHA256(loginMessage)\nK = HMAC_SHA256(sharedSecret, UTF8(\"toil-session-key-v1\") || H)\nexpected = HMAC_SHA256(K, UTF8(\"toil-server-confirm-v1\") || H)\n```\n\nCompare `expected` to `serverConfirm` without an early exit on differing bytes.\nOther status values represent failed credentials, confirmation requirements, or\nother errors. Challenges are expiring and single-use; obtain a new challenge for\na retry.\n\n## Sessions on native transports\n\nThe readable `first` value is **not a bearer credential**. Preserve the signed\nHttpOnly session cookie from `Set-Cookie` in the platform's cookie jar and send\nit on later requests to the same tenant. Over HTTPS its name is\n`__Host-toil_sess`; the readable companion is `__Secure-toil_user`. Honor both\nclearing cookies on logout or 401. The companion and decoded user bytes are for\ndisplay, and the server revalidates the signed cookie and revocation state.\n\n## Initial stable identity\n\nFor a newly registered account, the user ID is SHA-256 over four `bytes(...)`\nfields: UTF-8 `toil.userid.v1`, the ML-DSA public key, UTF-8 username, and the\nconfigured identity domain. The vector includes this initial ID. The account\nstores its ID so password/key changes preserve the existing identity; clients\nshould use the returned server identity rather than derive a replacement.\n",
8
8
  "auth/README.md": "# Authentication\n\nToil ships a complete, **post-quantum password login** you turn on with one line. No passwords on your\nserver, no third-party identity provider, no hand-written crypto: enable it and you get a `/auth/*` API,\nsigned sessions, `@auth`-guarded routes, and a stable per-user identity.\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n server: { auth: true }, // ← mounts the full /auth/* API + sessions\n});\n```\n\nThat is the whole setup. The build appends the framework's auth controller to your server, so `/auth/*`\nis live and `@auth` works everywhere.\n\n## Storage and request lifetime\n\nAuthentication uses collections in two databases: `AuthDb` for accounts and\nchallenges, and `AuthStateDb` for revoked sessions, user generations, and two-factor\nsettings. Verification is cached only on the current request object. Later requests\ncheck revocation state again; local revocation and signing-secret changes invalidate\nthe cached result. Temporary failures reading revocations, generations, or\ntwo-factor state abort the request; they never mean that a restriction is absent.\n\nSession generations use immutable revocation claims and a conditional head update.\nReads probe at most eight revisions beyond the head. Writable requests repair a\nstale head without overwriting a concurrent advance; read-only queries never\nrepair it. If a chain exceeds the probe limit, verification fails closed with\n`Session state recovering; retry`. A writable sign-in or revocation attempt still\npersists its scanned progress before failing, so repeated attempts recover even\nchains longer than 64 revisions. No sessions are minted from a partial scan.\nAuthentication calls count against the same database budget as your handler;\nsee [database limits](../database/documents.md#size-limits-and-file-uploads).\n\nWhen a generated `@auth` guard returns 401, it clears both the signed session and\nreadable user cookies, using their HTTP or HTTPS names and attributes. Storage\nfailures abort verification instead of returning that 401, preserving credentials\nfor a retry.\n\nThe `AuthStateDb` layout replaces the separate session and factor database\nnamespaces. It requires a fresh store or an explicit migration of existing security\nstate; it does not read the previous namespaces. The Nerva rollout uses a database\nreset alongside the application schema change.\n\n## What you get\n\n| Endpoint | Purpose |\n| --- | --- |\n| `POST /auth/register/start`, `/register/finish` | Create an account (password never leaves the browser) |\n| `POST /auth/login/start`, `/login/finish` | Log in; sets a signed session cookie |\n| `GET /auth/me` *(`@auth`)* | The current user (`toilUserId` + `username`) |\n| `POST /auth/logout` *(`@auth`)* | Clear the session |\n\nPlus, in your own code:\n\n- **`@auth`** on any route (or a whole `@rest` class) → 401 unless there's a valid session.\n- **`AuthService.getUser()`** → the typed logged-in user.\n- **`AuthService.userId()`** → the stable [`ToilUserId`](./extending.md#toiluserid) (a 256-bit id you can\n key your data on).\n- **The client**: `import { Auth } from 'toiljs/client'`, then `Auth.register(username, password)` /\n `Auth.login(username, password)`. It does all the browser-side crypto and talks to `/auth/*` for you.\n\n## A login page in full\n\n```tsx\n// client/routes/login.tsx\nimport { useState } from 'react';\nimport { Auth } from 'toiljs/client';\n\nexport default function Login() {\n const [u, setU] = useState('');\n const [p, setP] = useState('');\n const [msg, setMsg] = useState('');\n\n const register = async () => {\n try { await Auth.register(u, p); setMsg('registered, now log in'); }\n catch (e) { setMsg(parseError(e)); }\n };\n const login = async () => {\n try { await Auth.login(u, p); setMsg('logged in'); } // sets the session cookie\n catch (e) { setMsg(parseError(e)); }\n };\n\n return (\n <main>\n <input value={u} onChange={(e) => setU(e.currentTarget.value)} placeholder=\"username\" />\n <input value={p} type=\"password\" onChange={(e) => setP(e.currentTarget.value)} placeholder=\"password\" />\n <button onClick={register}>Register</button>\n <button onClick={login}>Log in</button>\n <p>{msg}</p>\n </main>\n );\n}\n```\n\n```ts\n// server/routes/Secret.ts, a route only a logged-in user can reach\nimport { Response } from 'toiljs/server/runtime';\n\n@rest('secret')\nclass Secret {\n @auth // 401 without a valid session\n @get('/')\n public secret(): Response {\n const user = AuthService.getUser()!; // typed: { toilUserId, username }\n return Response.text('hello ' + user.username + '\\n');\n }\n}\n```\n\nThat's a real, production-grade auth system, the password is stretched with Argon2id in the browser into\nan ML-DSA-44 key pair, your server only ever stores a public key, and login is a mutually-authenticated\nML-KEM-768 challenge. You didn't write any of it.\n\n## Where to go next\n\n- **[How it works](./how-it-works.md)**: the protocol (OPRF + Argon2id + ML-DSA + ML-KEM), sessions,\n cookies, and the `ToilUserId`, with sequence diagrams.\n- **[Usage](./usage.md)**: enabling it, the client API, guarding routes, reading the user, the full wire\n contract of each endpoint.\n- **[Configuration](./configuration.md)**: the secrets a deployment MUST set, the audience/domain, tuning\n Argon2id, and the deploy checklist.\n- **[Extending & integrating](./extending.md)**: `ToilUserId`, keying your own data on a user, a custom\n user shape / opting out, and the `AuthService` primitive reference.\n- **[Customizing the auth emails](./emails.md)**: replace the verification, password-reset, and 2FA\n emails with your own branded React templates by dropping `emails/auth-*.tsx` files.\n\n> **One rule before you ship:** built-in auth runs with **insecure DEV fallback secrets** so it Just Works\n> locally. A deployment MUST set `AUTH_SESSION_SECRET`, `AUTH_OPRF_SEED`, and `AUTH_KEM_SK`. See\n> [Configuration](./configuration.md).\n",
9
9
  "auth/usage.md": "# Using auth\n\n## 1. Enable it\n\nEither the config flag (canonical) or a one-line import, both do the same thing (the build appends the\nframework's auth controller + user shape to your server as compiled entries, so `/auth/*` self-mounts):\n\n```ts\n// toil.config.ts, canonical\nexport default defineConfig({ server: { auth: true } });\n```\n\n```ts\n// server/main.ts, escape hatch (equivalent)\nimport 'toiljs/server/auth';\n```\n\nThere is also an `AuthService.enable()` no-op you can call for discoverability, but enabling is done by the\nflag/import above (it happens at build time). Turn it off by removing the flag/import, with neither, no\n`/auth` routes and no accounts collection are generated. It is strictly opt-in.\n\n## 2. The client\n\n`toiljs/client` ships the browser half, it runs the OPRF blinding, Argon2id, ML-DSA keygen, and ML-KEM\nencapsulation, and talks to `/auth/*`. You never touch the crypto.\n\n```ts\nimport { Auth } from 'toiljs/client';\n\n// Create an account. Throws on a taken username or a transport error.\nawait Auth.register(username, password);\n\n// Log in. On success the browser holds the signed session cookie; subsequent\n// requests to @auth routes are authorized automatically.\nawait Auth.login(username, password);\n```\n\nOptions (second argument, `AuthOptions`):\n\n```ts\nawait Auth.login(username, password, {\n baseUrl: '/auth', // default; change if you mount elsewhere\n serverKemPublicKey: MY_KEM_PUB, // REQUIRED in production, pin your deployment's KEM key\n});\n```\n\n> **Production:** the client ships with the DEV KEM public key pinned. A real deployment MUST pass its own\n> `serverKemPublicKey` (derived from `AUTH_KEM_SK`). See [Configuration](./configuration.md).\n\n## 2b. Client-side: who's logged in, and protecting pages\n\n`register`/`login` set the session cookies; to *render* login state on the client, use the generated\n`getUser()` (emitted from the built-in `@user`). It reads the **readable** `__Secure-toil_user` companion\ncookie and returns the typed user or `null`, instant, no network call. It is **display-only**; the server\nstill enforces access via `@auth`, so never trust it for authorization.\n\n```tsx\nimport { getUser } from 'shared/server'; // generated; typed to the built-in @user\n\nfunction Nav() {\n const user = getUser(); // { toilUserId, username } | null\n return user\n ? <span>Hi {user.username} <button onClick={logout}>Log out</button></span>\n : <a href=\"/login\">Log in</a>;\n}\n\nasync function logout() {\n await fetch('/auth/logout', { method: 'POST' });\n location.href = '/login'; // cookies are cleared; bounce to login\n}\n```\n\nGate a whole client route by redirecting when there's no session:\n\n```tsx\nexport default function Dashboard() {\n const user = getUser();\n if (user == null) { location.href = '/login'; return null; } // not logged in -> to /login\n return <main>Welcome, {user.username}</main>;\n}\n```\n\nThe authoritative check is still the server: any data this page fetches should come from an `@auth` route,\nso a user who forged/deleted the readable cookie sees the redirect OR a `401`, never real data.\n\n## 2c. Handling errors\n\n`Auth.register` / `Auth.login` reject with a message you can show. The important distinguishable cases:\n\n```ts\ntry {\n await Auth.register(username, password);\n} catch (e) {\n const m = String(e);\n if (m.includes('already registered')) setError('That username is taken, log in instead.');\n else setError('Could not register, try again.');\n}\n\ntry {\n await Auth.login(username, password);\n} catch {\n // Wrong password OR unknown user both fail generically (anti-enumeration), one message.\n setError('Incorrect username or password.');\n}\n```\n\n- **Username taken** → `register` throws `auth: username already registered (log in instead)` (a\n distinguishable case so you can guide the user).\n- **Wrong password / unknown user** → `login` throws generically (`auth: request failed`): by design,\n the two are indistinguishable, so use ONE \"incorrect username or password\" message.\n- **Rate limited** → after 5 attempts / 60s a `429` surfaces as the same generic throw; back off and tell\n the user to wait.\n\n## 3. Guard your routes: `@auth`\n\nPut `@auth` on a route method or a whole `@rest` class. The generated dispatcher checks for a valid signed\nsession **before** your handler runs and returns `401` otherwise. `@auth` is unchanged by built-in auth,\nit's the same decorator you'd use with hand-written auth.\n\n```ts\n@rest('account')\nclass AccountApi {\n @auth // this route needs a session\n @get('/settings')\n public settings(): Response { /* … */ }\n\n @get('/public') // this one is open\n public open(): Response { /* … */ }\n}\n\n@auth // …or guard the ENTIRE class\n@rest('admin')\nclass AdminApi { /* every route requires a session */ }\n```\n\n## 4. Read the current user\n\nInside any handler:\n\n```ts\n// The typed logged-in user (the built-in `@user`: toilUserId + username), or null.\nconst user = AuthService.getUser();\nif (user != null) {\n user.username; // string\n user.toilUserId; // Uint8Array(32), the stable id bytes\n}\n\n// The stable identity as a ToilUserId (gate on hasSession() first, see note).\nif (AuthService.hasSession()) {\n const id = AuthService.userId()!; // ToilUserId\n // key your own data on id (see Extending)\n}\n```\n\n> `ToilUserId` overloads `==`, so `AuthService.userId() == null` does not type-check. Gate with\n> `AuthService.hasSession()` and then use `userId()!`, or use `getUser()` and null-check that.\n\n## 5. The endpoint wire contract\n\nYou normally use the `Auth` client, but the raw endpoints are binary (`DataWriter`/`DataReader`, never\nJSON):\n\n| Route | Request body | Response |\n| --- | --- | --- |\n| `POST /auth/register/start` | `str(username) bytes(blinded)` | `u8(0) u32(mem) u32(iters) u32(par) bytes(salt) bytes(evaluated)` |\n| `POST /auth/register/finish` | `str(username) bytes(pubkey) bytes(proof)` | `u8(status)`, `0` ok, `1` username taken |\n| `POST /auth/login/start` | `str(username) bytes(blinded)` | `bytes(cid) str(aud) u32(mem) u32(iters) u32(par) bytes(salt) bytes(nonce) u64(iat) u64(exp) bytes(evaluated)` |\n| `POST /auth/login/finish` | `bytes(cid) bytes(ct) bytes(sig)` | `u8(0) bytes(sessionToken) bytes(serverConfirm)` + `Set-Cookie`, or `u8(≠0)` on failure |\n| `GET /auth/me` *(`@auth`)* | (none) | `bytes(toilUserId) str(username)` |\n| `POST /auth/logout` *(`@auth`)* | (none) | `200` + cookie-clearing `Set-Cookie` |\n\nRate limiting: every register/login POST carries `@ratelimit(SlidingWindow, 5, 60)` (5 requests / 60s per\nclient) out of the box, so brute-force is throttled before it reaches the crypto.\n\n## 6. Under `toiljs dev`\n\nEverything runs locally with **zero setup**: the dev server emulates the ToilDB account/challenge storage\nand the ML-DSA/ML-KEM/OPRF host functions in process, and the auth secrets fall back to insecure DEV\nvalues. Register and login span requests (the accounts persist for the dev session). You'll see a warning\nthat `AUTH_SESSION_SECRET` is unset, that's expected in dev; set it before you deploy (see\n[Configuration](./configuration.md)).\n\n## 7. `Server.REST.auth.*`\n\nBecause the controller is a normal `@rest('auth')` class, a typed `Server.REST.auth.*` fetch client is\ngenerated for free (`me`, `logout`, and the register/login methods). Use it for `/me` and `/logout`; but\n**drive register/login through `toiljs/client` `Auth`**, not the generated client, only the `Auth` helper\nruns the required browser-side OPRF/Argon2id/ML-DSA/ML-KEM crypto.\n",
10
+ "auth/vectors-v1.json": "{\n \"format\": \"toil-auth-protocol-v1\",\n \"description\": \"PUBLIC TEST SEEDS AND KEYS. Never use in a deployment.\",\n \"username\": \"vector-user\",\n \"email\": \"vector@example.com\",\n \"domain\": \"vectors.toil.example\",\n \"password\": \"PaKsswörd-12!\",\n \"passwordNfkcUtf8\": \"50614b737377c3b672642d313221\",\n \"memKiB\": 32768,\n \"iterations\": 2,\n \"parallelism\": 1,\n \"salt\": \"202122232425262728292a2b2c2d2e2f\",\n \"oprfSeed\": \"a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3a3\",\n \"blind\": \"b372eed50523143885dcbf65883ac7ccadbc846bb62a98ffaee4b667bc407e04\",\n \"blinded\": \"569d286c0a058b86987e5646a2c75888112a4c32fed65f65e973a6e54e1cf600\",\n \"evaluated\": \"807be09d776fb5fcb8440b988c25eb67c29c88d8f0b18eaae5de80ff13e18903\",\n \"oprfOutput\": \"801b033287fe9c5905d99b4cde02a164ebe2e70eb1a73e9abe84a2bdeb5b1b138b4a9d44868fdbe9f2223f1726e1e8b4ea18cf117f26a6abafe3819710b09943\",\n \"signingSeed\": \"3654780bdac4955df7ba4c677a563a837611b2f60de8170a5cfdb5e5cc88e3d7\",\n \"mldsaPublicKey\": \"0196dfbfa00d32dd79024cc5ef5fba8f8a855948489a20940032ae07974571ccd4ebfb4a4c95c504aeb0113a0689c0c06c4e3a43a923dfb0af06d8d71f27a017ef8547598e14ab65de873620921ca79417b39f9457208b77efac7bfa394ba85fce3c47dc1ed6bed672cca4745a6988bafd89b95117d2aca531ece00cd5681b31702e99fac8a68a1b03a727abca08bedfeaf9d47de33069ad52a5a5ad1faf102e431d1d1a9902aafaa4c03a13cbd265345d34440fcac6a9c42e1f0b4fabf4bd781cf2324fca9ba9a49328447737546197b7378ca3aec327db79500fd73a4856e31b2c7507a8168a65918197ddd139055f67a95edbe94d229b1617f3a7a177742fd4a809326ea84bc88054e0e4a9586c6f219f57ce229f3c770a64ee94bbfa5d49cc2be002b45359424da064295372270ffb6eceb4301155ef9c1358c1afa63015dac4bebbc15e510c6f7c80537c4d3047d8eec7239453f45b5ee60463c60521ad322e233c18ad20f0d0e311afc55613f638391d3714aa47c704f49df2acce9cb53bef9f5716f451071a321286401e12b5917f382a52df6ae99aad0e97fb90be9fcb0daa305836c778193161d7c15cae3e892b5ece77b32c8c7f7b25ab5bed20dd49cbfa59be54a65c1c009edffb5c2282ce0d438225bf663fa89a9f1d28562017ad31389137b25d760b3f705932f46c4583ec354057561f38554f15f3f2a6e3463a295d06f610f3dc2d104bdfea5a340ccc0007e335db83e8ce11e3ec7d8fb89ee4cad7fffadfd7c2650c9aca13c72182f0d5e431a4bc0f4136ecaa60ba1dc3a8c81f25156d0b98824e69ed764af523aa02dc70401ba6d7887d32ccb949d86f3f8d6e5ee6659067a15557f8fa760a5799b865fd0aca03686d337832363b672807e8e2fd93197eb6ccc2d73e56422386344260f9c82dcf9adb08482428b604ffe1934f4f5eb4cb977615f9aae744d335ac7e37d90b8031212e2e37ca1ef64acbe5cf3f377c1b7a98c9a9c5fe563882cfd8a31c1986d0b801d016a428d31d105e1f2b8897bd8ef48f6833d39fc3e3ea7c5d39d747351fa4fceefd5ed3aa5e016289e74db7e65c5cb2125070e3e300c0c53c63243002825751f9e9f6584aec77cb87d3001160c3c6930e7f215da3936cdbdf430c65b8ff252185e702385903dbd98fe72328e23f242e3adf474f03f81c89bb6ab3e84d082ab13864707fadade3e563af0609b918063ecff63b56bdb980b0bfe404609e25fd74cf951abfe501be137ac2cdb472133ee0bdf0cd969732acd12bf7e07c07b3e14251439f7a714250a50897354ceb68f0c0448f1d2ff989e33c289e8ee646543112135d7229135f9b972ea2219dd0d182f21c17820a7c10803634387311ebe49fb2f52a1c858f6354a2e965463ddb0d4249b321f863441270718eaef54f6cfa81bceb2237de10e26e0257ad8269f82fc4e4252a691549d438367bcffd951de644ccd0b5bd4060288bb6d160abd0e604324e900d06b9c72497180cc396d18132b8718f63e4369848ede93bc812b702daaf6247d788ebbb610cb6b08d971c122e86e5e9f4f137de0bd88abe1fb1fe0abf9823f51a25ede0d47367789c4b5acf756e671252cabedbf66c7ae7566f0cb78cf969ae0c55b52f78710cef460cd1ed7b94756f4865ed80d1ad71a5ca523edb4248cedbd7d069ff47cbbb1b8589668ce287e743e131900e16c05f30359a8a3e73386045d3094868f4f24e3bd55239c0ff5d17b28adba0636e0e69cfa52012c0c1b8a3a58e2ab6cbc082387a80f58ed05eb74f6630515d742504e39718637264a54f860b2022a755c1f5c9a4fda65d50e78dde67834206a4fb41f5db\",\n \"registerContext\": \"qauth:register:v1\",\n \"registerMessage\": \"010b000000766563746f722d75736572200500000196dfbfa00d32dd79024cc5ef5fba8f8a855948489a20940032ae07974571ccd4ebfb4a4c95c504aeb0113a0689c0c06c4e3a43a923dfb0af06d8d71f27a017ef8547598e14ab65de873620921ca79417b39f9457208b77efac7bfa394ba85fce3c47dc1ed6bed672cca4745a6988bafd89b95117d2aca531ece00cd5681b31702e99fac8a68a1b03a727abca08bedfeaf9d47de33069ad52a5a5ad1faf102e431d1d1a9902aafaa4c03a13cbd265345d34440fcac6a9c42e1f0b4fabf4bd781cf2324fca9ba9a49328447737546197b7378ca3aec327db79500fd73a4856e31b2c7507a8168a65918197ddd139055f67a95edbe94d229b1617f3a7a177742fd4a809326ea84bc88054e0e4a9586c6f219f57ce229f3c770a64ee94bbfa5d49cc2be002b45359424da064295372270ffb6eceb4301155ef9c1358c1afa63015dac4bebbc15e510c6f7c80537c4d3047d8eec7239453f45b5ee60463c60521ad322e233c18ad20f0d0e311afc55613f638391d3714aa47c704f49df2acce9cb53bef9f5716f451071a321286401e12b5917f382a52df6ae99aad0e97fb90be9fcb0daa305836c778193161d7c15cae3e892b5ece77b32c8c7f7b25ab5bed20dd49cbfa59be54a65c1c009edffb5c2282ce0d438225bf663fa89a9f1d28562017ad31389137b25d760b3f705932f46c4583ec354057561f38554f15f3f2a6e3463a295d06f610f3dc2d104bdfea5a340ccc0007e335db83e8ce11e3ec7d8fb89ee4cad7fffadfd7c2650c9aca13c72182f0d5e431a4bc0f4136ecaa60ba1dc3a8c81f25156d0b98824e69ed764af523aa02dc70401ba6d7887d32ccb949d86f3f8d6e5ee6659067a15557f8fa760a5799b865fd0aca03686d337832363b672807e8e2fd93197eb6ccc2d73e56422386344260f9c82dcf9adb08482428b604ffe1934f4f5eb4cb977615f9aae744d335ac7e37d90b8031212e2e37ca1ef64acbe5cf3f377c1b7a98c9a9c5fe563882cfd8a31c1986d0b801d016a428d31d105e1f2b8897bd8ef48f6833d39fc3e3ea7c5d39d747351fa4fceefd5ed3aa5e016289e74db7e65c5cb2125070e3e300c0c53c63243002825751f9e9f6584aec77cb87d3001160c3c6930e7f215da3936cdbdf430c65b8ff252185e702385903dbd98fe72328e23f242e3adf474f03f81c89bb6ab3e84d082ab13864707fadade3e563af0609b918063ecff63b56bdb980b0bfe404609e25fd74cf951abfe501be137ac2cdb472133ee0bdf0cd969732acd12bf7e07c07b3e14251439f7a714250a50897354ceb68f0c0448f1d2ff989e33c289e8ee646543112135d7229135f9b972ea2219dd0d182f21c17820a7c10803634387311ebe49fb2f52a1c858f6354a2e965463ddb0d4249b321f863441270718eaef54f6cfa81bceb2237de10e26e0257ad8269f82fc4e4252a691549d438367bcffd951de644ccd0b5bd4060288bb6d160abd0e604324e900d06b9c72497180cc396d18132b8718f63e4369848ede93bc812b702daaf6247d788ebbb610cb6b08d971c122e86e5e9f4f137de0bd88abe1fb1fe0abf9823f51a25ede0d47367789c4b5acf756e671252cabedbf66c7ae7566f0cb78cf969ae0c55b52f78710cef460cd1ed7b94756f4865ed80d1ad71a5ca523edb4248cedbd7d069ff47cbbb1b8589668ce287e743e131900e16c05f30359a8a3e73386045d3094868f4f24e3bd55239c0ff5d17b28adba0636e0e69cfa52012c0c1b8a3a58e2ab6cbc082387a80f58ed05eb74f6630515d742504e39718637264a54f860b2022a755c1f5c9a4fda65d50e78dde67834206a4fb41f5db\",\n \"registerSignature\": \"6c27811dfc2aa7719cd0a8b1fc9f4ec98ee140f74f989b069994a5f8d5ee7894677d983ec6b367345c9a2b34e9545e74fb41bcdb81ede55e08c202ce8c93b7545daf6a18480d2cb3199b0522d041c943aa59d351972596d13bed713deea47509db04ba2b0de43df7d06290a3844e0beacdf35a72991c480391e94d58cb010efd3e5a18e5691e4f152a5879e3200dc6700fe76740727cf6ac96a5d56995a6adc3bcf23885f5ba9c5fefb5eb0ae1602341008c569cc8f00131f2dbe776ac534e83a4061909d5aacd515689ecda1ad64ea79b4a17abcb9775a066171785914b3e3d3c95768f2d7c317c70d23eb83769e4baa58aed42fd0f108fb2c279b84d13275f2ce2bf875fea13ed0a6f1454d99f51e814c4ce088ce3013d98371d8ef91e6b11a5d235543dfc2019b89f597efabcfa834004bd9e803b0d9b2527686e531363477f064d6daaed8b1900511db59dfe0b518832f845d735817f7590b2bba936986e22b50a1d8d151ec814c264a9070c97540f29c27b1340670430c2b0d8d732bbd538bddf45eca9fe8fe714437455f433c4e634f2872ebb609e6800adf1a4c72e3b9bedbae0e865e3cc612e6b675611683857dfd83f9b87a46b583199ae21560a64c4972e73c87a03ff5389d8f70356b1f936533b5db71c9440ed581efd8c92c0d19eb91dbc92c885bd3e5714bd241c80afa16d24a0652250ace564cb8900afe3ae1abad83ccdd8b87ef9368c38fc4e6bd70d003803dc7606e97863bbeb04b7553de55f0375ee380a94cd088080b1e9c72ed8556ee8c76091057432329e2b98cc5071de8bb70cb8457a9bcf022e036ca15218abb538210c027223ae30cf5e9eea0736261b6f55e39bd8b8ff87f7fa72691541ec96f8e4aaebd48f6fb57195516cc585d2e7ff79ae8ee6f8fa91f33239af9e03ea82e77929e12f406d1cc042d08e07a12e469cea8562644600c5deaecedd2345b4696e44828f4269c0545c35dfb5c80f5c8f2674cfcc75d82134cc74124a2fb93da23f9e4c972bbfa032b34c7e8d9424fa6501970a230030e3387e30778b27412d7a0d875c94f6fb25c83249a0aac60e173c914b722ffa29dd1b949e707e1204ebeea994735e0ae23eb5a90b4dd109a944118cdd27d83b6f6b839d079227d151edeccf2a71f23583b1a335af12070ebb3accb62c3af08542a451ca97442916d027c7040ce41807b0720f1e6147fd3506ba12b3f9facc108554bb0258e71f3941baf370a2b8354a9a79fd8653d7ab39f0ee84e54ebfe1812fe9fae7d1b709a1d62585bebfdcf2bf476b62cd57f8a228551442fa864dfcf551b06b040531db2135c71266297580d3ffd9f77a2bd34739f0dd064f69db9b67f2c59149c6812453f185df10342964c9ad85d4893b0a540f002302c6f1c536f992644df64317114a40f433d4e92bc6deebef1e54b8d1311ba2cc253dc787e40a9b1ff165cde010c41bc75b111ea334005505aa0c399e8a24d2a0a07ed2afae6a8f34317d79615420ba6454f2b398f35982f44f9289f613bdbd355fd519173014bee71ca3654c553628df1b5daa1304f8bf0d57c47b9c935946a4e614e8641bc9803713ccd1d2c6ca21d38b6a1eacd2c3f9103718f16e664b0e5e993b163f1047bf3c1c9b4c8b190bcc2fbd5958c7aad02a41ccd81cf25cef48664ce6f7d2850a3f3ffef3318cbf28f33baab561e2f3a055878a39a48029e333e86f6df7b4f3a6edea221bbeca04cef965b72cfbf3be5117fa956b24f707efbf5ba4757ff2c88a699cb6d8bf1f680823171cdefd7711f414f06614ff666b46f512ed0b81d5f9be6106f029df88d21746b6e98c7f08021a1901b4fb82178c60bec557589b99a13d48891f11c1b005651d860664289bdf81e592cf47f88a1366e119d2490e5d370c23cca098d89d7921471d389b0654c49c5ccfeec02c377a5cc1c6f8a59f14337e19fcf2b62567b002199c1275f049be2fe9edacb7a095adbd8d0772b1043c8252b65f20d166d1a13c1c33e76b8d42fee8bb7e414196da7ab93095395fdbb2f8d9e8193241c87f5f398706d6bcfdc08984876861a8e3c9270ea678d32fd176e17bd81876a94e7bca8814edaae731cae1b26a03ddd9a61d8d02710f8c3f435a9c4ff2afe6255ba334588c006ef49cc752916cf6afb4d525e04b201ee50e0453bd8ae9cecc4ee66d09c23c9fa087c8a932301c9274ac2e4095c110e25eca935b924c4cd3ff3e9d78e3d19220023f412eb02941cd0d9fee332965571790811470f1cbcf3fa97b8308623fe91225c174396892137d6f1c01d76c865f6d304644f15940f3feab5c1be0984ebbf87be21c5e4b293f76fd88b7554f7db5cfa246775d007a31022c0923ac47d2b762e443b8f6170e898fa8cc82727722c5d4bdc8e41885dcb86234bdb5d33125c585a5116fd6fa000fc809599e958d2f3a716426af8b539d64f6e51d10bb2e6877dc7aa7ce41dec7ddff265989132481d143dcf5b367a3dd9f4edef333ffae39d1ca712a375376c9e3ca9f15888ceb3761f2b6519a0221dd9a0a2b1fc534042bcfc998436af71f297a53f981a5dc6649b5f3123db4f0b897b8480420db829c49362fb9b63eb1e44a272fcc30a7d0f8f5f1b80917c6fc42ea6af937faab05a808034d1cd780f9e3935c5a98d048fc09911707f3acbd4d3e3b001af6c099828235c6c821daa5380b389ff223496cdb4740ac604e7d1c0b83f30a0ace1dff2e9c8d9da31f42b58f59d23ddb8a83fe22ccd1fbf59e99ec305711d55d7b56198700d30c5c1b8dde8012fdf7686a4076529b29ecb123e3d64b59fc066f570ff0d936f9217a20fc6fc188b12c7277b94b3fcb4b45023bd6eafc4f2ffde842e7d6ee4344625359881e973e680448db627caeba3253e70fae5917177ef27b4a97096a1738adc5f256fcef120497605691b1270a8a19faabbbc8f67fd2dc6b00d32d391255a6a3245b69650fbaadb12ea677b40ac6b87b2a043f5903672992c49c879a80ffd2e3d812a2379ffd9895f25535ce189d8ff3beefeae6907e2a4f1e0089302279af453e2393f8fe8d4142e5189ec676978f8583eec0ea75aeed093f32827049604117f2bbe9eff5b473889ff89c1e33160b8b271a40df6b0d4345de0bf04bd567fe55f65305032ee68afd5c417102826d91dfbb9f7374aafa66d70413c1423b811e58a71715b0c45ae41343411318d327bdbe2a24d986b4f4c1b52b8dbeea99c6abaccc24ffdd0a2bd7a89cca0cf5487bca393ab653a161944c4b38648718461e1d62ac400343aea6ea27ffbe4e47dd92272e41557e828ba7b8c2d8e9ee245058656c6d73868f98b2c8fc040a0f122339485a5e8b9fa5caecfb001c3a49535a5fa4ccd8e4fa0000000000000000000000000000000000000000000000000000000d1a2935\",\n \"kemSeed\": \"606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f\",\n \"encapsulationSeed\": \"7777777777777777777777777777777777777777777777777777777777777777\",\n \"kemPublicKey\": \"cfc608c61500c0964798231d9552cc0091107087c0476ca810504b4909bc24f7c65d587c11e03eaa947fb76724ad7804279b4df274b7dd27c70168921f5c4b4fc74a06839ceaaa2b46d0b9e600bcde12622c411961db4d335491848526ca8495ee3c1f200556385163541540e94c3efa96c9fde23d4ea9c0629a556d1038cc72276b48bf4914c97b1638c1a129e1d059daa60cc1d5139d115fde44968cdc6112d4378e19baed39b0da7a293528ae9e3c86a846ad018a6b73a10b04f41a05a54116fc0b86a1212692690db05ccaf2610e0803c9c10a4763aefe85cc09b795b2c00fc915486bc86b7d120183b8bb0cf63704a6299163806f918d6021a24ab88d7fd1482709b359778b40115c7e5121510055597a73ed48a125a9265474bb7a16b74bfa2409a8cd4fa606b4d1afad36cd9e0c24661a69c7c60010b470a911536a53b28ab132d6a675576ab50835b24fcc3a6680848b986a6694476b09934310a5d1943f8eba21bbb3b386c223085722aadc646e5670ce2b73ae84bd53bacb8ed1b469972d88323cfae548c2971a695840c7560b56b05427042aeea13eee4815a8b22728aa586a724ddbb92d17a12180fc00ba8c7bdae3caa35cc8bfcaa23c0436339491bbd67bb44b16cb85b6eaf16c48799603b17124e49400414170fa63505814ec012279420281501bb5fc63879c44cfc952f1f2a704f3c3d72cc711d8464c898f48135fe29762c70907e6b6486cc71a832b4caffb95232190053a16c843ab9a85252ba2c866ca196d4bba50923be7a95904ac89674aca6d98541282949856cca5ba4a7018267277453f9138680a8bd8037746e242bc7c3881bc0d4f20af2f537a7d70921ae017d1e00ce1d4c2b502c8d2a73c1c4539333514d615357c2b4a9106b744132b20cb2c273296f2780609f2bac6858c36747e597722a1d34e7189af0c18bab44a1f3d0a6d3c274e104c7943c529ce882bf8783068590cac181a3ed272cbfb3405c2640940aba5a255f40b988416a483b24bea84a30bcb4d838325814724b4023af8b6401922451a1097bc92bbd65cb28c4c51ac8aceafc4296e0c6d61e4b925fa6d6e987cf9142c80d33fc4e7869c5075b533331b92204c97bbccf9ac16b992d14400e4012bba144235e0ab62288cade65692519d9bfcc2c1ac385cd3a6fcf06e8e9b12c4ca301447259f772ee2a0782776b069dbcb0e17c784e44e4ef341c38037e8aa8d5c8b80b4f6181e2753abc843035b5786e997f109ae1c3473067a301ee11576223562610cb540bcf155554787237c9318d23135c56151a0916ccb31b56a84303a9cb91273cf09420e6eb71aeed33295d726d84803aa76ce047929b2234c2dc429752072adc9926da83469a7770705244273cb96f5b5504c6b45f30d7f4620a1c17dff728dbed0281c9294b5db8c0de0649dd9aa70f660c155523447640ffc9568691ccec667c07814045244bd4697dac3c7b1ac03f57581a6c71296039999273ae226be4b74364377c6f970218c5347b4f54fd86c600fb23cb1f4be848a8e602900fe64358cf58702e656ce7c8b448427789306f63582427533e8787c99cc7aaf4926cc5785ea933d8a573f80848e7c932d1b729cf1aabd4f06a8c6793702abf4d273d93b6bf67c31b9057f1c468d6f314d495f854f4a6b\",\n \"kemSecretKey\": \"afbac9549b58d5d0b73f05375b3a5558572d91c19dcf00b8fe285fbdd03f3d48064437ab05071f99b69a99eb60b46161db0b2ca4dc25b7a0c917d5c6296c23aa401fa33123fc27a0457373cc760a1a88bd4ec0b94d0b1827d239c741762aa54bbf6a39b4a0352c92beb1a5515ac40bf5c5373e183bced003e02b63cc04c7d67638f0b8b50e338b1760782890261cd80092c6a36dec180a99c435150ea3791130a75222eb12334436ed6c410c129807053e8fcc66a6ba876aa3393432bb3171075e5cb723d2b9d7a51fd18b8ee660cef67b3aba51c56e4c045eb98eb8658dc61413dda153b49803710ac70d1b44a3554007388f60f370d0a125f3e8b95bd208037b39d823a70d3479bb3b9ce1ccc4ff49150f14666efc49f04c66f91999fb642cd338c99d63b236691e43fa7002a74ccc382635c444947490e284cdadf860cb323c627445d780c8468105fcba8cb232a620ca9f51aa61515ca1c6502df1b8aa4051660101c45ce9ced4a1bf5eaa8f1cb8c54754c9cce195af2a20cc030fc4c15f2bc06d3de23b6576c66f1c601bf509824c6312938619332f6c7a420d3b729c866e84d43cac7c70d0e964dbfc68ea7c9082d329e1227d17b490858635bf4770f96a37f8405371dab84ba43f0714c39c90c2053c4a394671fe58ca11cb3e63bb666637bfe907943af9c044c47c56676e13520e3cc0843f870dd0e1223995c34821c10ff8be7a0522df8b1dc94c34e4066f3ce79833f3c874c03b6ec29f108c8e0c3b65c4b4c3848995e66a3a18a4842de1a60eba5e4b00a0d4273b8f5260b3d75ff154cb49e5b2557cb66654703c5150acdc169f07cb0bc539494517c3b309654c043170216f113b60270a463c8a9cd0029758567087aa176b60eed2349af64beb73002c83313ba1778b2ba0f915b204eac50c994d2d337d8cf7cedb8680f3a617891ba84717435e512113d267fd73608a8b868fe826b8fc0fb526c7c31c5a611294d73137f66517c1cb6676b1974c13aab7a76efc30af6b28b92af4a57ebb9fcf420c391710e7889d67ebbd4446675b825471d6727895c8814351a4617050d9134fccbb07babb6651219f009e86514eabbab032d93568955bca83a155f278c3072ed8e1874594c9cd66be00865fb64bb9ecf116ba70198f468d414888b3981c19bc1c64639ac4c1348c13bd4e724855762725122e29bc2eea6a615a926e0a035043d9456a1a7e9f7b4670c52159782896b9933f8b638720303f13609bc030f8169597c92b85bab6592a9a2ccb0989e91f911134c2669ba22cc04c5b4ab8647c3f379d84c7783ca864bdec2a184c33bb781ada71c5b7412fd27b069e5bbced2017f1c8888102d062895fea5385e7262bd349c914100c74c661ac865432639762f698a2c7347f7c42bf05156d730cec070513b4018962bdb78990647a7fcd63606ef38f8fe29fa7b14b5c38b966403436c669d056c56aa6c2a7b15558815c8525262adc941cf84d9c0c77e2f6b232a5a0cdb2bc2a39bb72271b1ebc4323f58e64059f41674a3ba63067844a599007bad83cc8e47d8905be32e052634624c4232eea103fcaa384769a3362386da59c96eb2527b60b3849776637c594df176753414ecfc608c61500c0964798231d9552cc0091107087c0476ca810504b4909bc24f7c65d587c11e03eaa947fb76724ad7804279b4df274b7dd27c70168921f5c4b4fc74a06839ceaaa2b46d0b9e600bcde12622c411961db4d335491848526ca8495ee3c1f200556385163541540e94c3efa96c9fde23d4ea9c0629a556d1038cc72276b48bf4914c97b1638c1a129e1d059daa60cc1d5139d115fde44968cdc6112d4378e19baed39b0da7a293528ae9e3c86a846ad018a6b73a10b04f41a05a54116fc0b86a1212692690db05ccaf2610e0803c9c10a4763aefe85cc09b795b2c00fc915486bc86b7d120183b8bb0cf63704a6299163806f918d6021a24ab88d7fd1482709b359778b40115c7e5121510055597a73ed48a125a9265474bb7a16b74bfa2409a8cd4fa606b4d1afad36cd9e0c24661a69c7c60010b470a911536a53b28ab132d6a675576ab50835b24fcc3a6680848b986a6694476b09934310a5d1943f8eba21bbb3b386c223085722aadc646e5670ce2b73ae84bd53bacb8ed1b469972d88323cfae548c2971a695840c7560b56b05427042aeea13eee4815a8b22728aa586a724ddbb92d17a12180fc00ba8c7bdae3caa35cc8bfcaa23c0436339491bbd67bb44b16cb85b6eaf16c48799603b17124e49400414170fa63505814ec012279420281501bb5fc63879c44cfc952f1f2a704f3c3d72cc711d8464c898f48135fe29762c70907e6b6486cc71a832b4caffb95232190053a16c843ab9a85252ba2c866ca196d4bba50923be7a95904ac89674aca6d98541282949856cca5ba4a7018267277453f9138680a8bd8037746e242bc7c3881bc0d4f20af2f537a7d70921ae017d1e00ce1d4c2b502c8d2a73c1c4539333514d615357c2b4a9106b744132b20cb2c273296f2780609f2bac6858c36747e597722a1d34e7189af0c18bab44a1f3d0a6d3c274e104c7943c529ce882bf8783068590cac181a3ed272cbfb3405c2640940aba5a255f40b988416a483b24bea84a30bcb4d838325814724b4023af8b6401922451a1097bc92bbd65cb28c4c51ac8aceafc4296e0c6d61e4b925fa6d6e987cf9142c80d33fc4e7869c5075b533331b92204c97bbccf9ac16b992d14400e4012bba144235e0ab62288cade65692519d9bfcc2c1ac385cd3a6fcf06e8e9b12c4ca301447259f772ee2a0782776b069dbcb0e17c784e44e4ef341c38037e8aa8d5c8b80b4f6181e2753abc843035b5786e997f109ae1c3473067a301ee11576223562610cb540bcf155554787237c9318d23135c56151a0916ccb31b56a84303a9cb91273cf09420e6eb71aeed33295d726d84803aa76ce047929b2234c2dc429752072adc9926da83469a7770705244273cb96f5b5504c6b45f30d7f4620a1c17dff728dbed0281c9294b5db8c0de0649dd9aa70f660c155523447640ffc9568691ccec667c07814045244bd4697dac3c7b1ac03f57581a6c71296039999273ae226be4b74364377c6f970218c5347b4f54fd86c600fb23cb1f4be848a8e602900fe64358cf58702e656ce7c8b448427789306f63582427533e8787c99cc7aaf4926cc5785ea933d8a573f80848e7c932d1b729cf1aabd4f06a8c6793702abf4d273d93b6bf67c31b9057f1c468d6f314d495f854f4a6b0d24c71384e7dc44c7848af6f8181c782901dccafb2c4680ba1612fc7080cb61808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f\",\n \"ciphertext\": \"7fd065eb73414ba1bd219f9074433b38c007e21f2ab4632dabae4877aac911e6cca0f85eb8f78ce9c59d52aa46dfbfee337cb008e05ce2fa538f5b1aceed16a85d794481dc96cd8422b4ead175db73dcbf28a4cfb237c366be0f8ae6fa9bc8966e25a69fd45b62838f3e1cac587a8f5a3b1876dbd382e70059480b9f1be3a000ea504d149877965a857708a5a2a2ca078171f90e87b555d5e2c15a8a0131223f65a10d8305121864b65339524989ef64cdc7d98f98a704f86858faf1f80267686493eff37f9323923332b99ec051a69ef078992177cd8abde05142975e9673e732fb82c3494fc8cc2755d6a44435f6df00efa825bcd61ec0d27df1b9712e8de2bd0f3940b7c5758b2c8d2086c56966e0d8c45c9bf5534babb9a1e613db9bfaefc92818a0c7396f3f150b14d90f7479cbd9ae8fb38b08765085865b392a85eaf5a280c10ac057393ca39aab76ddd82d507f091df7782979a54f5dc19e8b134ab3499dac8bc5efc1c3ae22aa62950b8688d5f29df0e07906bd24c80ba03853081ce6e9320c4336679890cdd0734b20d3f7001c116683108bc58f1f2000176949ffbb69349823f62838c5b3170da17dec43c9a76a3e9829abd20299f0f2205e7c15b3e9486f7a047c6818366026898dcea60658db0d7c5de634875c92c9926b7e3e4e23b2307537086194055760b96525ea9ddd9ae109ddc9ccc7b2e85312e6b07476775b199128f6cac377a12f47b1ac895f9b349015cdacbcab02497cfddeabb3fccf79834cb59a8365573b3bc4013aafb4e09aad347a45a357ba328564a671bb6eda63a1ce17e207aee25368e30430531aee71ea2bc14fd94b4a61401510a6080c59cef3b91f3e58581708a284d33872f8d232f3c0b075112efd3e45d7b470be0c387f5c9b9857b879416a9ddd5b0719d97da7ecde1ed187d1f230da76e5c004a18f13f19ac2562ff69f366531a9587fafe923cff1174de7b7ee9b5fe9bea17e503760526684ba6b8b22104f04521d2207bf1ad23fbf4faf8c09749fe0db983f38bb833d7aa87e68b39be6a5c6f0f1b18579ef77a0cc9fd6ccc049f814b8e05898113bd284e388acd90ce68b765c2ac353d5beccf7b782e28a389c0765e22129e85392d3ea2c78377979118c06a0703b9a003646188a6abc5c3d8b3ed5040888e6cb21e91efa05b4583b33428b54bd7a7bfc43c31e163b034b6f50b492ce50d23479e19ad185145bae009bcd4cf29c6fb09e13f4cde4e8e1056e46f4ea07793b8c017895609f4d7bcc648c7d28ee47cc7d08674f43f6e046ed39cae0dd09cdeba551d35ddb85354b51f28004c999c45d5d9e0505e10465499ed7892392d7b180e594d6cba00e6a7731d454d23a7de4b31cc7b52a28b82a37c90c23f7acde352e393ca01217c6260c227a672b04848ef4125cc5d45748c4f41e1c6e734cf7a5d0012562211284bc2ba4c1e89f74ee48d12ed50c86fa5c1543e70f0a47a14e5e83790cddf21890c5303f68097be83d68c78237d9b843ce591d9ebf3cb1dbc7f63d\",\n \"sharedSecret\": \"d931c1f4ae9543efc8bfd3c2d1b5f1c099b4d0d93e8669dd66331ef647a03964\",\n \"serverKemKeyId\": \"2d8e7b15778d1ebafe8679ca00b6830fce21c17fdbab62f7399a1dc279e8d239\",\n \"cid\": \"101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f\",\n \"nonce\": \"404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f\",\n \"iat\": \"1700000000\",\n \"exp\": \"1700000120\",\n \"loginContext\": \"qauth:login:v1\",\n \"loginMessage\": \"010b000000766563746f722d7573657214000000766563746f72732e746f696c2e6578616d706c6520000000101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f20000000404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f00f153650000000078f1536500000000400400007fd065eb73414ba1bd219f9074433b38c007e21f2ab4632dabae4877aac911e6cca0f85eb8f78ce9c59d52aa46dfbfee337cb008e05ce2fa538f5b1aceed16a85d794481dc96cd8422b4ead175db73dcbf28a4cfb237c366be0f8ae6fa9bc8966e25a69fd45b62838f3e1cac587a8f5a3b1876dbd382e70059480b9f1be3a000ea504d149877965a857708a5a2a2ca078171f90e87b555d5e2c15a8a0131223f65a10d8305121864b65339524989ef64cdc7d98f98a704f86858faf1f80267686493eff37f9323923332b99ec051a69ef078992177cd8abde05142975e9673e732fb82c3494fc8cc2755d6a44435f6df00efa825bcd61ec0d27df1b9712e8de2bd0f3940b7c5758b2c8d2086c56966e0d8c45c9bf5534babb9a1e613db9bfaefc92818a0c7396f3f150b14d90f7479cbd9ae8fb38b08765085865b392a85eaf5a280c10ac057393ca39aab76ddd82d507f091df7782979a54f5dc19e8b134ab3499dac8bc5efc1c3ae22aa62950b8688d5f29df0e07906bd24c80ba03853081ce6e9320c4336679890cdd0734b20d3f7001c116683108bc58f1f2000176949ffbb69349823f62838c5b3170da17dec43c9a76a3e9829abd20299f0f2205e7c15b3e9486f7a047c6818366026898dcea60658db0d7c5de634875c92c9926b7e3e4e23b2307537086194055760b96525ea9ddd9ae109ddc9ccc7b2e85312e6b07476775b199128f6cac377a12f47b1ac895f9b349015cdacbcab02497cfddeabb3fccf79834cb59a8365573b3bc4013aafb4e09aad347a45a357ba328564a671bb6eda63a1ce17e207aee25368e30430531aee71ea2bc14fd94b4a61401510a6080c59cef3b91f3e58581708a284d33872f8d232f3c0b075112efd3e45d7b470be0c387f5c9b9857b879416a9ddd5b0719d97da7ecde1ed187d1f230da76e5c004a18f13f19ac2562ff69f366531a9587fafe923cff1174de7b7ee9b5fe9bea17e503760526684ba6b8b22104f04521d2207bf1ad23fbf4faf8c09749fe0db983f38bb833d7aa87e68b39be6a5c6f0f1b18579ef77a0cc9fd6ccc049f814b8e05898113bd284e388acd90ce68b765c2ac353d5beccf7b782e28a389c0765e22129e85392d3ea2c78377979118c06a0703b9a003646188a6abc5c3d8b3ed5040888e6cb21e91efa05b4583b33428b54bd7a7bfc43c31e163b034b6f50b492ce50d23479e19ad185145bae009bcd4cf29c6fb09e13f4cde4e8e1056e46f4ea07793b8c017895609f4d7bcc648c7d28ee47cc7d08674f43f6e046ed39cae0dd09cdeba551d35ddb85354b51f28004c999c45d5d9e0505e10465499ed7892392d7b180e594d6cba00e6a7731d454d23a7de4b31cc7b52a28b82a37c90c23f7acde352e393ca01217c6260c227a672b04848ef4125cc5d45748c4f41e1c6e734cf7a5d0012562211284bc2ba4c1e89f74ee48d12ed50c86fa5c1543e70f0a47a14e5e83790cddf21890c5303f68097be83d68c78237d9b843ce591d9ebf3cb1dbc7f63d008000000200000001000000200000002d8e7b15778d1ebafe8679ca00b6830fce21c17fdbab62f7399a1dc279e8d239\",\n \"loginSignature\": \"6503cf44919e53b9f1cdaec33720dd50d0713641393c904972061a21f1d9c5ed61cd9ef7e39a3a1be1dbed748936e35a1780c0bf2989c8c33316b5de264c9b3db35786adcf0f8e2b656b90fe393095385dea6e3bef30e8a0a12c77c9a9887be09ad3cf87878ebac6a2f6ef26a93d897bb4c76344b505e8e9608a6b1b74ce258664366a0ed87598308ff231c1b6ad0ce88b421872c771d9fb96938ba5d2928c68fbd28bc4fb2efdbde1183a7f4a8872120c6769dfb2ba2a675fc40e9317ab0a13539718cd7522dd10f3a13080c6ba6571c949b1daf77c93e6e8b01adf44bd577d08e9278e23d3e28fbf74270647bae0a00801d454fcab542d2b07094c0b2e776bf510209fb79633226a3ec33d33e0071c5206d2456b4a429261abcefd5f8694b24746446cc054b2c8e73e3c529d49182748073bf7d15239e4aebd8b0816e98bfa642b2ca59c9d24df9dfd5a61466e8882c6ab65025804a3c6019e16c5d25307f69573262e08a5c89d1df52c196e20fa88542b4d5580f4e149eaee49a8d9c87faa4732f0f379a6e35ec65ae7a1bdb61970c9da54cf097fba8121829d55f804966ad346ed7197f15f7e2e6f1cc30c58a7f31b9859dd67bd10cf7182874402d0ccad148ef3ada0688c2524ccbd61a259caab7a56508249c06a9c7c43e0e5d9b7cd66a12376b5b4e57199f0d09f3efaafafce1c6ed10ed5e59ab8e45106254f5c326bcb5cd1a018fa388690478d38c1995d3f362096e7711818b6fdf1abbaf315eb04d40c93b64a236eebbb4fc18a70ab40da0e5c2698ea2ccb7b393dba91fb91527565e493bc0bea5b2c28fef11e89d09003bd4dbc52dc09a7da25bc7ae495957592f444469270bc88988cc66a4202ce1041f52f62fbc4a173bf622f15f69885386ab707aceca2f778e4336fc1dce6b115dc3b20a3138fe702bd808c11f57e3078511716bd4510222b07f7a805dd76a912aad63837c29c6453f0a93e0daad59e90a033dca445d3b45158ae1906bb735b13007c1ea3b2ce89e1d079739e7c064bf238a12184f54a3232626e20271bc2d0fdc252a5a20ba0e3e983c8a2f7026cc4d357dd0149ae0f611aada234d1d0c627890b692a0bfa2e6d5ae9e716c0c518e563356d9f600b2bb095a30aea6083ce1032605d929e804974a21327df62af2950775cd6a9c33684a56132028b92340b932a8f42e11e0691d2de073ea4cdc15af91d557f65f4b4e0ac349ae981afda623fcb629ff89f11bb5cd2d7dd2ef8c456d043b2275f7deb51d25d83192ac6a3cb21b33f6d52b76aed404dfbd6164a179b21883d1e11519cfb8a52d48542e215401a26025984ecb852068551890f94fde187996d2f86a770ed82fcb34e4bba1abc5a037201b67b90bff999414424c90561bb16115319ed8726a315602cc95694b39292b7b3795e50afdf36c8d6e4feb01054a1d00bd14a21b616d19ecb66232275f64194a12bd2772ccd8cbba3e3209efea23661fd5471016f8d9003dfc2249c14f4e01164e17340eeabef475f57b2af5a1c6d2e8d8461e3667f45d18fcb712e4f1e27904e0540b0e1ed639b68bb50a5217e0e67ccac153fcd4658c1ec03d2374388a29c22b19fd8a38b534e98d2f6d3021b7f8b08a681a5b0d3103182d78ac0caed6a2ae60759fbc7f869ea0cdec59b88f7e450c1a3a103c31e60944eb0814abebd01b0752e74d8ddd3e12878b4b158ec0695b735bc6e4eb2ce0da6cd79a356d69919e40bbaa38baec45838645e8ba21d7f538fc0b8dea1f701baa8a2e537ad66bea93145d30504c9046b9d404ebc6a1be620b250170916a7c11211ad939eb8e75dc466cc70a33546f02b80e0267113ab0a466a659317d9ac3d18962df77fc738a796094cb75bf0b96039c97de0b06ad376ce0830bea513512612ed3e6b44b9d6a45d5f4abf4a6189496532bdfdb25e2f16b999d2a3b8eb6225c85e47176ba1269c6f929b4f5c00e7b2b74fb9e6aab4225eb8d26f3e165d9ec3656a7558f82521939b3e6809124c88b54a15b520511e79425c8306f2239dd95fd0f6683aa25f58f3d1ee5ed135afefe2dface3d6e154370b379fd7d7690112dd872898350835bff2c8e5fccacbb115286b983fa7e052ae80ab158c6488e4a242539f685d354b8de242d0c7f9e9b6f92219004d16f34fce6a69536e76f39bee6ddb971968bdd5b93b12715018ae9060861195f0d827cb1088106c14662b58ad206c087b1a8925cc6f4e4af621bc67f15cdbf63fe76933f07619658e92dc19f691a8c1e5dce6f59af7258a9ee02f2ee863a687768200707d723c533d604e50679b91835ffb2979dabb94f665953c03d3752af3dfe8b36c36c3f63f6f0dbe46023eba5fb14aacea0379fb35f110caa2249c077c37fd5c080a82fb18c5abc5d1ecc84c6eec8fb32d89150e077db9c6b9b7869fe35f3ac42242a9dc7825da074c9898403b7395d9b4d701cd6a04dadbac86636df58c05b07ead01f189114fb0798ff3e6736cbf354f681416e29a1295c4834899ad6338ff662ca255574cfd80cb489d47f4d43e0860fa4a334affb66f492eedff606ae685e84608177ebf6f04f1306994f12a5f8b4b534c5c1daf646aee019c4f56b6c58a993b534375905f42f7b460e71fa8cfd71834cfc9d00ce2f66abfd57d55e3917075e03e1a73640f9ee56488ee0b2889d1829fcd2167a0551c64848c584eef0e313b020c6760b1966a4180551298dde0c2297d72cd8a81b28f3ec9f60ddebe86ee053a94c90fd71372183c4c13ffab1c7e5306c147ff9731cb622c7ee9838f428b278197a58ee0aaeaa7d13c0b11a69fcff8c622decafb6d93a221afa0ffb0425ffd38b24bfe2569f0eabcd0628837e7e1c3a3b1ba05525385450cb65a507c209d40859f6ef214f240892c521fb85fe9447407bfe2e24c03405c71cbca20ee5f183d49634d261fa76a1815c3d41ea1538ac1c8eb851eaeafda2301c5aeedc6455af80ff0f0522ee5a95135e5f0df174ba2064701d4310d3c4e18390f6cd0703dbb2244c2509c6bbd57d598979815e09e0d8de53922ce272c9f19fb4aa0b79df37dedd072df71fc9c9b6dc8d18cb17ec5b977129f4e6b673f0c09f561d8a77860ec5a57c943252ffcf239bdea13cbe6d39690f050089df1cdcda8616f8d96df9e5921d9909f98dd6671188fda09d3f97ab0aaefe341ecbb36253e28033400817e5d5825ba050b1fb7e2a6b32d30a8e2cc739cf2bcf3440da5ce3ded927c0b4416cbaee75c4f01d18a78350480755705b464f6ec8671dbff89b06a257015139905768608381f5003041e2b3c3f405464697494d8e6e8fc2d324446606e8693a7b6b7b9bed0eaef00030a18374e596369757f88bbdfe4ecff060d1692b1b7dedfe1e8f300000000000000000000000000000000000000001020313c\",\n \"transcriptHash\": \"d7479af6f20ef5a9a4ea4762cbb114deede86914e2b10c3143f7b71b580dde6f\",\n \"sessionKey\": \"9dd0eda782ccb42ddcc18bbad90f6ee8fdfabac18baa509f838cdfd5bd77de46\",\n \"serverConfirm\": \"ca07bc732387c4799a64437dc3562157cd4f20ba494186e6cde53bc3fe53032f\",\n \"initialUserId\": \"5b286ac280f592bab0f14685d29c7c5b1553d064564ac330d3fede736ba08820\"\n}\n",
10
11
  "backend/data.md": "# Data types (`@data`)\n\n`@data` turns a plain class into a typed value that can travel safely between your frontend and your WASM backend, and in and out of the database, with both a binary and a JSON codec generated for you.\n\n## What `@data` is\n\nA **codec** is a pair of functions: one that turns a value into bytes (encode), and one that turns those bytes back into a value (decode). Any time data crosses a boundary (browser to server, server to database, one WASM call to another) it has to become bytes and back. Writing that by hand is tedious and easy to get wrong.\n\n`@data` writes it for you. You declare a class with typed fields, tag it `@data`, and the compiler synthesizes a deterministic binary codec and a JSON codec on the class. The exact same class is also generated into your `shared/server.ts`, so the browser and the WASM backend agree on the format down to the byte.\n\n```ts\n@data\nclass Player {\n username: string = '';\n admin: bool = false;\n score: u64 = 0;\n}\n```\n\nThat is a complete, serializable type. Note every field has a **default value**; that is required (the generated decoder and the client constructor use it).\n\n## Why and when\n\n`@data` is the backbone of almost everything that moves in a toiljs app:\n\n- **Request and response bodies** for [`@rest`](./rest.md) routes.\n- **Arguments and return values** for [`@service` / `@remote`](./rpc.md) calls.\n- **Values stored in [ToilDB](../database/README.md)**.\n- **Sessions**, [stream](../realtime/README.md) messages, and any custom payload you design.\n\nWhenever a route, an RPC method, or the database needs a structured value, that value is a `@data` class. You will define these constantly.\n\n```mermaid\nflowchart LR\n D[\"@data class<br/>(one definition)\"] --> R[\"REST route body\"]\n D --> P[\"RPC argument / result\"]\n D --> B[(\"ToilDB value\")]\n D --> S[\"Stream message\"]\n```\n\n## What the compiler generates\n\nFrom your `@data` class, the compiler adds these members:\n\n| Member | What it does |\n| --- | --- |\n| `encodedSize(): i32` | Exact binary size including the 4-byte type-id frame. It currently encodes the value to measure it. |\n| `encode(): Uint8Array` | Serialize to bytes, with a 4-byte type-id prefix. |\n| `static decode(buf): T` | Rebuild a value from bytes produced by `encode()`. |\n| `encodeInto(w: DataWriter)` | Serialize without the type-id frame, for nesting inside another value. |\n| `static decodeFrom(r: DataReader): T` | The matching read, for nested values. |\n| `toJSON()` / `static fromJSON(v)` | The JSON codec (large integers become decimal strings, so `JSON.parse` keeps them exact). |\n| `static dataId(): u32` | A stable hash (FNV-1a) of the class name, written as the type-id prefix. |\n\nYou mostly do not call these directly; routes, RPC, and the database call them for you. But they are there when you need them (for example `value.toJSON().toString()` to build a `Response.json`).\n\n## Editor support in TypeScript 7\n\n`toiljs build` and `toiljs dev` generate `toilscript.*.generated.d.ts` files\nbeside the server entry, including typed `encode()` and static `decode()`\nmethods. This supports WebStorm and TypeScript 7 without a language-service\nplugin. Keep these files included in the server `tsconfig.json`; the usual\n`\"include\": [\"./**/*.ts\"]` includes them. Run a build after upgrading, and restart\nWebStorm's TypeScript service if old errors remain cached.\n\nUse top-level named exports for module-scoped models (`@data export class ...`).\nFor a direct compiler build, pass\n`--editorTypes server/toilscript.generated.d.ts` or put that path in the\n`editorTypes` option of `toilconfig.json`. The declarations are editor-only and\nleave the runtime codec unchanged.\n\n## Supported field types\n\nA `@data` field may be:\n\n- a scalar: `u8` through `u256`, `i8` through `i256`, `f32`, `f64`, `bool`;\n- a `string`;\n- a `Uint8Array` (a raw byte buffer);\n- a nested `@data` class;\n- an array `T[]` of any of the above.\n\nFor the number types (why `u64` is a `bigint` on the client, when to reach for `u256`, and so on), see [Types](../concepts/types.md).\n\nGive every field a default. The layout is exactly the field declaration order (this matters, see [gotchas](#gotchas)).\n\n## Nested `@data`, arrays, and bytes\n\n`@data` classes compose. A field can be another `@data` class, an array, or a byte buffer, and it all encodes and decodes as one value:\n\n```ts\n@data\nclass Tag {\n label: string = '';\n weight: f32 = 0;\n}\n\n@data\nclass Document {\n id: u64 = 0;\n title: string = '';\n tags: Tag[] = []; // array of nested @data\n authors: string[] = []; // array of strings\n thumbnail: Uint8Array = new Uint8Array(0); // raw bytes\n}\n```\n\n`Document.encode()` walks the whole tree: it writes `id`, `title`, each `Tag` (via `encodeInto`), each author string, and the raw `thumbnail` bytes, in field order. `Document.decode(bytes)` reads them back in the same order. On the JSON side, a `Uint8Array` field becomes a JSON array of byte numbers, and nested `@data` fields become nested JSON objects.\n\n## Using `@data` in a route\n\nA route's body parameter and its return value are `@data` values. Which codec runs depends on the route's stream mode (see [REST bodies](./rest.md#request-and-response-bodies)):\n\n```ts\n// JSON route (the default): body from JSON.parse, result via toJSON()\n@post('/')\npublic create(input: NewPlayer): Player { /* ... */ }\n\n// Binary route: body via decode(), result via encode()\n@route({ method: Methods.POST, path: '/blob', stream: DataStream.Binary })\npublic blob(input: FileData): FileResult { /* ... */ }\n```\n\n- In a **JSON** route, the incoming body is `JSON.parse`d and revived with the type's `fromJSON`, and the returned value is serialized with `toJSON()`.\n- In a **Binary** route, the incoming body is `decode`d and the returned value is `encode`d.\n\nYou do not call the codec yourself in either case; you just declare the types.\n\n## The raw codec: `DataWriter` and `DataReader`\n\nSometimes you want to lay out bytes by hand: a custom body, a session token, a challenge message, a wire format someone else defined. For that, use the codec directly. It lives in the `data` module:\n\n```ts\nimport { DataWriter, DataReader } from 'data';\n```\n\nThis is the same codec `@data` classes are built from, and it has a byte-for-byte identical TypeScript version in `toiljs/io` (`src/io/codec.ts`), so your browser code can read and write the exact same bytes the WASM backend does.\n\n### `DataWriter`\n\nEvery write method returns the writer, so calls chain.\n\n| Method | Signature | Wire format |\n| --- | --- | --- |\n| `writeU8` / `writeI8` | `(v): DataWriter` | 1 byte |\n| `writeU16` / `writeI16` | `(v): DataWriter` | 2 bytes, little-endian |\n| `writeU32` / `writeI32` | `(v): DataWriter` | 4 bytes, LE |\n| `writeU64` / `writeI64` | `(v): DataWriter` | 8 bytes, LE |\n| `writeF32` / `writeF64` | `(v): DataWriter` | 4 / 8 bytes, IEEE-754 LE |\n| `writeBool` | `(v): DataWriter` | 1 byte (`1` / `0`) |\n| `writeBytes` | `(b: Uint8Array): DataWriter` | `u32` length (LE) + the raw bytes |\n| `writeString` | `(s: string): DataWriter` | `u32` length (LE) + UTF-8 bytes |\n| `writeU128` / `writeI128` | `(v): DataWriter` | two `u64` limbs (lo, hi) |\n| `writeU256` / `writeI256` | `(v): DataWriter` | four `u64` limbs |\n| `length` | `(): i32` | bytes written so far |\n| `toBytes` | `(): Uint8Array` | an exact-length copy of the buffer |\n\n### `DataReader`\n\nReads are **bounds-safe**: reading past the end of the buffer never crashes. Instead the read returns a zero or empty default and flips the reader's public `ok` flag to `false`. Check `ok` after a sequence of reads to catch a truncated or malformed buffer.\n\n| Method | Signature | On over-read |\n| --- | --- | --- |\n| `readU8` / `readI8` | `(): integer` | `0` |\n| `readU16`..`readU64`, `readI16`..`readI64` | `(): integer` | `0` |\n| `readF32` / `readF64` | `(): float` | `0` |\n| `readBool` | `(): bool` | `false` |\n| `readBytes` | `(): Uint8Array` | empty array |\n| `readString` | `(): string` | `\"\"` |\n| `readU128` / `readI128` / `readU256` / `readI256` | `(): bignum` | `0` |\n| `remaining` | `(): i32` | bytes left unread |\n| `ok` | `bool` (field) | `false` once any read over-ran |\n\n### Encode and decode, both directions\n\n```ts\nimport { DataWriter, DataReader } from 'data';\n\n// Encode: a version byte, a name, a score, then a blob.\nconst out = new DataWriter()\n .writeU8(1)\n .writeString('alice')\n .writeU64(1234)\n .writeBytes(payload)\n .toBytes();\n\n// Decode: read the fields back in the exact same order.\nconst r = new DataReader(out);\nconst version = r.readU8();\nconst name = r.readString();\nconst score = r.readU64();\nconst blob = r.readBytes();\nif (!r.ok) return Response.badRequest('truncated');\n```\n\nThe order of reads must match the order of writes exactly. The layout is the format.\n\n## JSON vs binary: which to use\n\nYou usually pick this at the route level (see [REST bodies](./rest.md#request-and-response-bodies)), but the trade-off is the same everywhere:\n\n- **JSON** is human-readable and understood by every tool. Pick it for endpoints a browser or a third party calls directly. Large integers ride as decimal strings so they stay exact.\n- **Binary** is smaller, faster, and lossless for big numbers. Pick it for app-to-app traffic and anything performance sensitive. RPC always uses binary under the hood.\n\n## Evolving a `@data` format: `@migrate`\n\nOnce records are stored, changing a `@data` **value** type is a problem: as the [gotchas](#gotchas) explain, the binary layout *is* the field order, so adding or changing a field means the bytes already on disk no longer match the new shape and would fail to decode. `@migrate` is how you evolve a stored type without a backfill and without downtime.\n\n**What it is.** `@migrate` marks a plain (free) function that upgrades one record written under an **old** version of a value type into the **current** shape. The compiler weaves that function into the value type's decoder as a version dispatch: every stored record carries the schema version it was written under, so when a read hits an old record, the decoder decodes it as its old shape and runs your `@migrate` forward to today's shape. This happens **lazily**, per row, only when a record is actually read (nothing rewrites your whole collection up front).\n\n**When to use it.** Any time you change a `@data` type that is already stored in ToilDB: you added a field, renamed one, changed a type. New writes use the new layout; old rows keep working because the migration upgrades them on the way out.\n\nHere is the whole story. You shipped this value type:\n\n```ts\n// server/models/GuestEntry.ts (version 1: what you shipped first)\n@data\nexport class GuestEntry {\n author: string = '';\n message: string = '';\n}\n```\n\nLater you add an `at` timestamp:\n\n```ts\n// server/models/GuestEntry.ts (version 2: gained an `at` field)\n@data\nexport class GuestEntry {\n author: string = '';\n message: string = '';\n at: u64 = 0; // NEW field\n}\n```\n\nEvery entry already stored was written without `at`, so its bytes cannot decode as the new `GuestEntry`. You add a migration file to bridge them:\n\n```ts\n// server/migrations/GuestEntry.migration.ts\nimport { GuestEntry } from '../models/GuestEntry';\n\n// Keep the ORIGINAL layout as its own class so old rows still decode.\n// One kept class per past version.\n@data\nexport class GuestEntryV1 {\n author: string = '';\n message: string = '';\n}\n\n// Upgrade a v1 row to the current GuestEntry. This is the DELTA form:\n// (old, into). The compiler pre-copies the fields the two layouts share\n// (author, message), so your body fills only what is new.\n@migrate\nexport function up(old: GuestEntryV1, into: GuestEntry): void {\n into.at = 0; // unknown for entries written before the timestamp existed\n}\n```\n\nThat is it. Old entries now surface as fully-formed `GuestEntry` values with `at = 0`; new entries carry a real timestamp; the same read path serves both.\n\nA `@migrate` function comes in two shapes, and you pick whichever reads better:\n\n- **Delta form** `up(old: OldType, into: NewType): void` (used above). The compiler copies every field the two layouts share by name and type, and your body fills only the changed or new fields. Least to write when most fields carry over.\n- **Full form** `up(old: OldType): NewType`. Your body builds and returns the whole new value itself. Use it when the transform is not a simple field-for-field copy.\n\n```ts\n// The same migration written in the full form.\n@migrate\nexport function up(old: GuestEntryV1): GuestEntry {\n const e = new GuestEntry();\n e.author = old.author;\n e.message = old.message;\n e.at = 0;\n return e;\n}\n```\n\nGotchas specific to `@migrate`:\n\n- **Location is enforced.** Every `@migrate` must live in a `migrations/<Type>.migration.ts` file (a `*.migration.ts` file under a `migrations/` folder). The build auto-discovers it (nothing imports it), and a `@migrate` placed anywhere else is a hard compile error, because it would silently never run.\n- **A migration is a pure value transform.** It may not touch the database or any host service; it only turns old fields into new ones. Trying to read or write ToilDB from inside a `@migrate` is a compile error.\n- **Migrations chain.** If you evolve a type more than once, keep one old class and one `@migrate` per step (`V0 -> V1`, `V1 -> V2`). The compiler walks the chain, so a row written under the oldest layout is carried all the way forward to the current shape, shortest path first.\n- **When it actually runs.** On any read that decodes an old row (`get`, `getMany`, a view read, events `latest`). It also runs when a [`@derive`](../background/derive.md) rebuilds a view on box load and re-reads old stored events (see [Views](../database/views.md)).\n\n## Dynamic JSON on the server: the `JSON` value tree\n\n`@data` is for shapes you know ahead of time. Sometimes you do not: a webhook whose body varies, a third-party payload with optional fields, or a response you assemble on the fly. For those, toiljs gives you a `JSON` **value tree**: an in-memory value that can be a null, a bool, a number, a string, an array, or an object, which you read and build at runtime.\n\n**What it is.** `JSON` is an ambient global class (no import needed). It represents one dynamic JSON value. `JSON.parse(text)` turns JSON text into one of these trees, and a `@data` class's `toJSON()` actually returns one too. It is the **untyped** counterpart to `@data`'s typed, fixed-shape codec: reach for `@data` when the shape is known and you want type safety, and for `JSON` when the shape is dynamic.\n\nThe statics that make a value:\n\n| Static | What it does |\n| --- | --- |\n| `JSON.parse(text: string): JSON` | Parse JSON text into a value tree (returns an error value on malformed input). |\n| `JSON.obj(): JSON` | A new empty object; fill it with `.set(key, value)`. |\n| `JSON.arr(): JSON` | A new empty array; fill it with `.push(value)`. |\n| `JSON.of<T>(value: T): JSON` | Wrap a scalar, string, bool, or array as a JSON value. |\n| `JSON.nul(): JSON` | A JSON null. |\n| `JSON.stringify<T>(value: T): string` | Serialize a scalar / string / bool / array value straight to a JSON string. |\n\nThe instance methods that read and build a value:\n\n| Method | What it does |\n| --- | --- |\n| `.isObject()` / `.isArray()` / `.isString()` / `.isNumber()` / `.isBool()` / `.isNull(): bool` | Test the value's type before you read it. |\n| `.has(key: string): bool` | Whether an object has `key`. |\n| `.get(key: string): JSON` | The value for `key` on an object. |\n| `.objectKeys(): Array<string>` | The keys of an object. |\n| `.at(index: i32): JSON` | The element at `index` of an array. |\n| `.length(): i32` | The element count of an array (0 otherwise). |\n| `.asString(): string` | Read the value as a string. |\n| `.asF64(): f64` / `.asI64(): i64` / `.asU64(): u64` | Read the value as a number. |\n| `.asBool(): bool` | Read the value as a bool. |\n| `.set(key: string, value: JSON): JSON` | Set a key on an object; returns `this`, so calls chain. |\n| `.push(value: JSON): JSON` | Append to an array; returns `this`, so calls chain. |\n| `.toString(): string` | Serialize this tree back to a JSON string. |\n\nReading an untyped body and building a reply, together:\n\n```ts\nimport { Response, RouteContext } from 'toiljs/server/runtime';\n\n@rest('echo')\nclass Echo {\n // POST /echo with an arbitrary JSON body we do not model as a @data class.\n @post('/')\n public handle(ctx: RouteContext): Response {\n const body = JSON.parse(ctx.text()); // ctx.text() is the raw body as text\n if (!body.isObject() || !body.has('name')) {\n return Response.badRequest('expected an object with a \"name\" field');\n }\n\n // Read fields out of the tree, guarding types and optional keys.\n const name = body.get('name').asString();\n const age = body.has('age') ? body.get('age').asI64() : 0;\n\n // Build a fresh JSON object to send back (chaining .set).\n const out = JSON.obj()\n .set('greeting', JSON.of<string>('hello, ' + name))\n .set('age', JSON.of<i64>(age));\n return Response.json(out.toString());\n }\n}\n```\n\nGotchas specific to `JSON`:\n\n- **Check the type before you read.** `JSON.parse` never throws; a malformed input or a wrong-typed field yields an error or default value rather than a crash. Use `.isObject()` / `.has(...)` / `.isString()` and friends to validate untrusted input before you trust it.\n- **It is a value tree, not a typed struct.** You get no compile-time field checking. When a shape is stable, prefer a `@data` class so the compiler catches typos and the client gets a typed type for free.\n- **Big-integer care still applies.** As with any JSON, integers above 2^53 are best carried as strings; read them with `.asString()` when exactness matters.\n\n## Gotchas\n\n- **Field order is the format.** The binary layout is exactly your field declaration order. Reordering fields, or changing a field's type, is a breaking change: old bytes will decode wrong. To evolve a format safely, add new fields at the **end** (and, for hand-rolled payloads, bump a leading version byte).\n- **Every field needs a default.** The generated decoder and the client constructor rely on it. A field with no default will not compile as `@data`.\n- **`encode()` carries a type id; `encodeInto` does not.** The 4-byte `dataId()` prefix lets a decoder confirm it is reading the type it expected. When nesting one `@data` inside another, `encodeInto` / `decodeFrom` skip that frame (the outer type already identifies the whole value).\n- **Endianness.** The WASM codec is little-endian. The `toiljs/io` codec defaults to little-endian too, and also accepts a per-call big-endian flag for network formats. Keep both ends on the same setting.\n- **Plain JSON numbers lose precision above 2^53.** That is why `@data` sends 64-bit-and-larger integers as decimal strings over JSON. If you hand-build JSON, do the same, or use the binary codec.\n- **`DataReader` never throws; check `ok`.** An over-read returns a default and sets `ok = false`. Always check `ok` after decoding untrusted bytes.\n\n## Related\n\n- [Types](../concepts/types.md): `u64`, `u256`, `f64`, and how each maps to `number` or `bigint`.\n- [HTTP routes (`@rest`)](./rest.md): where `@data` bodies and return values are used, and the JSON vs binary route modes.\n- [Typed RPC](./rpc.md): `@data` as RPC arguments and results, and the generated client classes.\n- [The database](../database/README.md): storing `@data` values in ToilDB.\n- [Backend overview](./README.md): where `@data` fits in the request lifecycle.\n\n\n## Checked integer arithmetic and parsing\n\n`u256.tryParse(text, radix)` returns `u256 | null`, without trapping or wrapping.\nRadix must be 10 or 16. Input must contain at least one valid digit; signs,\nwhitespace and prefixes are rejected. For example, check the pointer with\n`changetype<usize>(value) == 0` before using the result, since u256 overloads\nvalue equality. `u256.fromString` remains the throwing API and rejects overflow.\n\n`Checked.add<T>`, `Checked.subtract<T>`, and `Checked.multiply<T>` return\n`CheckedResult<T>` with `ok` and `value`. They support primitive signed/unsigned\ninteger types, including 64-bit types; a failure returns `ok == false` and a zero\nvalue. They do not rely on assertions, so `--noAssert` does not disable checking.\nFloats and big-integer specializations are compile errors.\n\nConstructing `RegExp` is a compile error until regular expressions are implemented;\nit no longer compiles into a runtime stub that traps.\n\n## Sharing pure code with TypeScript clients\n\nA pure module can be compiled unchanged by both TypeScript and ToilScript. Add\n`/// <reference types=\"toilscript/shared\" />` at its top. This shipped types-only\nentry gives the client compiler the numeric names `i8`, `u8`, `i16`, `u16`,\n`i32`, `u32`, `f64`, and `bool`; ToilScript already understands those names.\nThere is no runtime shim or global installation. Use the same relative source\nimports from the server and the phone or browser build.\n\nThe supported subset consists of explicitly typed functions, local variables,\nconditionals, indexed loops, strings, booleans, `f64` arithmetic, and bounded\n`Uint8Array` access. Use standard operations implemented by both runtimes, such\nas `length`, `charCodeAt`, `slice`, and `subarray`. Keep UI, network, database,\ncodec decorators, pointers, and asynchronous work in adapters around that code.\nUse normal value imports for shared functions; ToilScript does not parse\nTypeScript's `import type` syntax.\n\nInteger semantics need explicit conversions in shared code. JavaScript erases\ntype assertions and does not truncate an assignment to `u8` or `i32`. Write\n`value & 255`, `value | 0`, or `value >>> 0` where byte, signed 32-bit, or unsigned\n32-bit coercion is intended. Widen bytes **before** shifts: ToilScript applies\nbit operations at the operand's integer width.\n\n```ts\n/// <reference types=\"toilscript/shared\" />\nexport function readU32BE(bytes: Uint8Array, offset: i32): u32 {\n if (offset < 0 || offset > bytes.length - 4) return 0;\n const a: u32 = bytes[offset], b: u32 = bytes[offset + 1];\n const c: u32 = bytes[offset + 2], d: u32 = bytes[offset + 3];\n return ((a << 24) | (b << 16) | (c << 8) | d) >>> 0;\n}\n```\n\nCheck bounds before every indexed access and keep integer values within their\ndeclared ranges. Avoid `i64`/`u64`, integer division, implicit wrapping, `f32`,\nexceptions, dynamic objects, and runtime-specific APIs in shared modules.\nTypeScript and Wasm parity tests compile the identical source file and compare\nbyte operations and checked decimal parsing, including malformed input and\ninteger boundaries. Use the same approach for a shared photo metadata parser;\nthis subset does not supply an image decoder or resizing API.\n\n## Unicode normalization and character classes\n\nStrings support `text.normalize()` (NFC by default), plus `normalize('NFD')`,\n`normalize('NFKC')`, and `normalize('NFKD')`. An unknown form traps. Normalization\nuses pinned Unicode 17.0.0 data and preserves unpaired UTF-16 units.\n\n`Unicode.category(codePoint)` returns the two-letter General_Category, such as\n`Lu`, `Ll`, `Mn`, or `Nd`. `Unicode.isLetter`, `isMark`, `isNumber`, and\n`isWhitespace` test the Unicode L, M, N, and White_Space properties. Pass a\nUnicode code point rather than one half of a surrogate pair:\n\n```ts\nconst decomposed = text.normalize('NFKD');\nlet folded = '';\nfor (let i = 0; i < decomposed.length; i++) {\n const cp = decomposed.codePointAt(i);\n if (cp > 0xffff) i++;\n if (!Unicode.isMark(cp)) folded += String.fromCodePoint(cp);\n}\n```\n\nThis example removes marks after compatibility decomposition; decide separately\nwhether that behavior is appropriate for your language and search rules.\n`Unicode.version()` reports the table version. Values outside 0..0x10FFFF have\ncategory `Cn` and fail the property tests. The implementation follows\n[Unicode normalization](https://www.unicode.org/reports/tr15/) and is checked\nagainst all four forms in the official Unicode 17 normalization conformance\ncorpus. Long combining-mark runs use a stable merge sort. The compiler's\n`npm run gen:unicode` regenerates tables from checksum-pinned upstream data;\nthe Unicode data license ships with the generated tables.\n",
11
12
  "backend/images.md": "# Server images\n\n`Images` processes uploaded JPEG, PNG, and still WebP bytes in an Action, Job,\nor Derive. It applies EXIF orientation before resizing, then removes EXIF,\nXMP, IPTC, text, and comments. ICC profiles and PNG color descriptors remain\nso stripping metadata does not silently change the intended color space.\n\n```ts\nconst photo = Images.resize(request.body, 1600, 1600);\nif (!photo.ok) return Response.text('Image rejected', 422);\nreturn Response.bytes(photo.bytes, 200, photo.contentType);\n```\n\n`Images.stripExif(bytes, quality = 90)` retains the oriented dimensions.\n`Images.resize(bytes, width, height, quality = 90)` fits inside a box while\npreserving aspect ratio. `Images.thumbnail(bytes, width, height, quality = 90)`\ncenter crops to that aspect ratio. Both avoid enlargement; a small thumbnail\ncan therefore be smaller than the requested dimensions. All return an\n`ImageResult` with `ok`, `error`, `bytes`, `width`, `height`, `format`, and\n`contentType`. JPEG input produces a newly encoded JPEG; PNG and WebP produce\nan 8-bit PNG, preserving alpha. Quality is 1–100 and affects JPEG encoding.\n\nAnimated images and other formats are rejected. Inputs and outputs are limited\nto 8 MiB, input dimensions to 8192 per side and 16 Mi pixels, and target\ndimensions to 4096 per side. Each dispatch allows one processing attempt.\nQueries cannot process images. Check `error` for `Invalid`, `Unsupported`,\n`Limit`, `Busy`, `Timeout`, `Unavailable`, `Options`, `Kind`, or `Quota`.\nAn error has no output bytes. Processing consumes host gas for input copying,\nsource pixels, and output copying, independently of database budgets.\n\nDev runs the shared Rust codec as WASI in a disposable Node child process,\nwith a 768 MiB WebAssembly memory maximum and a five-second wall deadline.\nThe checked-in codec asset includes build hashes and dependency licenses in\n`assets/`; maintainers rebuild it with `node scripts/build-image-codec.mjs`\nfrom a sibling `toil-backend` checkout and the `wasm32-wasip1` Rust target.\n\nNative deployments must build and install `toil-image-worker` beside `toil`,\nor set `TOIL_IMAGE_WORKER_BIN` to its absolute path. The install script builds\nboth binaries. Each operation starts a disposable worker with a 768 MiB address\nspace limit, a two-second CPU limit (three-second hard limit), and a five-second\nhost deadline. The host admits at most two concurrent workers without queuing\ninput buffers. Operators may set `TOIL_IMAGE_MAX_CONCURRENT` (1–32) and\n`TOIL_IMAGE_PIXELS_PER_MINUTE` (default 256 Mi pixels per tenant host, per\nbackend process). Busy workers and exhausted quotas return explicit errors.\nThese limits apply separately on each backend process.\nThe tenant's memory, request-body, response-size, and gas limits also apply;\nworker limits do not raise those limits.\n\nUse [Blobs](../database/blobs.md) for direct streaming storage of large originals.\n`Images` accepts bounded bytes and returns bounded bytes; it does not fetch an\narbitrary URL or automatically resize `Toil.Image` URLs.\n",
12
13
  "backend/native-staging.md": "# Native staging checks\n\nThe native repository ships `toil-native-staging`, a loopback HTTP host for a\ncompiled request artifact. It uses the production Wasm validator, metered pool\nand reset logic, host imports, request/response parser, and persistent ToilDB.\nIt requires provisioned persistent storage and fails startup if it is unavailable.\n\nAn operator provisions the host with your compiled artifact and a dedicated\nstaging database. The startup report identifies the loopback URL, PID, gas\nbudget, DB deadlines, and binary capabilities. Keep its state with its database\nwhen restarting. Restart the host after rebuilding the artifact.\n\nThe default request gas budget is one billion units, host-call cap is 1024,\nand DB tier is L3 in a standalone cell. Query/Action limits and default DB wait\ndeadlines use native defaults. `TOIL_STAGE_QUERY_DEADLINE_MS` and\n`TOIL_STAGE_ACTION_DEADLINE_MS` override wait deadlines for testing; zero forces\nan immediate wait timeout. HTTP reads and writes have five-second socket\ntimeouts. The host handles one request per connection and closes it afterward.\nIt runs the request artifact's derives, but has no resident cold scheduler,\nstatic frontend, TLS, DPDK ingress, multi-cell owner routing, or production plan\nselection. Use the actual target deployment for those checks.\n\nNative acceptance tests exercise the compiled public SDK over real HTTP.\nThey prove gas exhaustion and recovery, unique-field conflicts, configured DB\nwait deadlines, status-bearing JSON responses, and decoded UTF-8 query values.\nThe test creates isolated staging databases, child hosts, and local key files and cleans\nthem up. Its checked-in Wasm has source and rebuild instructions under\n`tests/fixtures/native-staging`.\n\nA failed request can leave earlier database writes committed. Gas exhaustion\nand DB timeouts do not provide rollback. Check idempotent outcomes when retrying;\nuse [atomic partitioned documents](../database/atomic.md) for a supported\nall-or-nothing record batch.\n\n## Checking host compatibility\n\nUpdated native binaries support this read-only command, which exits before\nreading server config or initializing DPDK:\n\n```sh\ntarget/debug/toil --print-capabilities\n```\n\nThe report includes the binary SHA-256, optional `TOIL_BUILD_COMMIT` captured\nat build time, accepted daemon catalog versions, surface/catalog ABI versions,\nmetering feature, and exact host-import allowlist. `toil-native-staging` exposes\nthe same command. Collect reports for the binaries actually installed on the\nedge hosts; a local source build cannot establish the deployed fleet's versions.\nOlder binaries may lack this command, so inventory those using their release\nrecords and running executable hashes. New SDK imports require matching native\nsupport even when the daemon catalog version is accepted.\n",
@@ -14,14 +15,14 @@ export const TOIL_DOCS = {
14
15
  "backend/rest.md": "# HTTP routes (`@rest`)\n\nExpose a real HTTP API by tagging a class `@rest` and its methods with an HTTP verb; toiljs generates the router for you.\n\n## Why and when\n\nUse `@rest` when something outside your own frontend needs to call your backend over plain HTTP: a webhook from another service, a public API, a mobile app, a `curl` script, or a browser hitting a URL directly. REST endpoints are ordinary URLs with ordinary HTTP methods and status codes, so any HTTP client understands them.\n\nIf instead you are calling your own backend from your own React frontend, [typed RPC](./rpc.md) is usually nicer (you get end-to-end types and skip URL wrangling). The two live happily side by side.\n\n## The shape of a route\n\nA REST route is a method on a class. The class decorator says where the class is mounted; the method decorator says which HTTP method and path it answers.\n\n```ts\nimport { Response, RouteContext } from 'toiljs/server/runtime';\n\n@rest('players') // this controller is mounted at /players\nclass Players {\n @get('/:id') // answers GET /players/:id\n public get(ctx: RouteContext): Response {\n const id = ctx.param('id');\n return Response.json(`{\"id\":\"${id}\"}`);\n }\n}\n```\n\nSave that file, import it once (see [How routes are discovered](#how-routes-are-discovered)), and `GET /players/42` returns `{\"id\":\"42\"}`. That is a working endpoint.\n\n## `@rest`: mounting a controller\n\n`@rest` marks a class as a route **controller** (a group of related routes) and mounts it at a URL prefix.\n\n```ts\n@rest('api') // mounted at /api\n@rest('/') // or @rest('') : mounted at the root\n@rest({ stream: DataStream.Binary }) // root mount, binary body codec by default\n```\n\n- The string is the mount prefix. `\"api\"`, `\"/api\"`, and `\"api/\"` all normalize to `/api`. `\"\"` and `\"/\"` mean the root.\n- The object form sets class-wide defaults. `stream: DataStream.Binary` makes every route in the class use the binary body codec instead of JSON (more on that in [Request and response bodies](#request-and-response-bodies)).\n\nThe full URL of a route is the controller prefix joined with the method path. With `@rest('api')` and `@get('/todos/:id')`, the route is `GET /api/todos/:id`.\n\n## Verb decorators\n\nEach HTTP method has a decorator that takes the route path:\n\n```ts\n@get('/path') @post('/path') @put('/path') @patch('/path')\n@del('/path') @head('/path') @options('/path')\n```\n\nNote the delete decorator is `@del`, not `@delete` (the word `delete` is reserved in TypeScript, so it cannot be a decorator name).\n\n### `@route`: the explicit form\n\n`@route` is the general form. Reach for it when you want to set the body codec per route, or you just prefer an object:\n\n```ts\n@route({ method: Methods.POST, path: '/upload', stream: DataStream.Binary })\npublic upload(body: FileData): FileResult { /* ... */ }\n```\n\n`method` (from the `Methods` enum) and `path` are required; `stream` is optional and overrides the controller default. `Methods` and `DataStream` are global enums (like the decorators themselves, they need no import).\n\n## Path parameters\n\nA path segment written as `:name` is a **path parameter**: it captures whatever the request has in that position. Read it with `ctx.param('name')`.\n\n```ts\n@get('/todos/:id/items/:itemId')\npublic getItem(ctx: RouteContext): Response {\n const id = ctx.param('id'); // \"42\" for /todos/42/items/9\n const itemId = ctx.param('itemId'); // \"9\"\n return Response.json(`{\"todo\":\"${id}\",\"item\":\"${itemId}\"}`);\n}\n```\n\nMatching is **segment-exact**: the request path must have the same number of `/`-separated segments, the static segments must match literally, and each `:param` captures one segment. The query string is removed before matching. A captured param is always a string; convert it yourself if you need a number (for example `u64.parse(ctx.param('id'))`).\n\n## Method parameters: reading the request\n\nA route method may declare zero, one, or two parameters. toiljs looks at their types to decide what to pass:\n\n- a parameter typed `RouteContext` receives the [request context](#the-routecontext-object) (path params, query, headers, raw body);\n- any other type is treated as the **request body**, decoded into that [`@data`](./data.md) type.\n\n```ts\n@get('/status')\npublic status(): StatusResponse { /* no body, no context */ }\n\n@get('/user/:id')\npublic getUser(ctx: RouteContext): User { /* context only */ }\n\n@post('/create')\npublic create(input: NewTodo): Todo { /* body only */ }\n\n@post('/user/:id/score')\npublic addScore(input: ScoreDelta, ctx: RouteContext): Player {\n const id = ctx.param('id'); // body AND context\n /* ... */\n}\n```\n\nThe order of the two parameters does not matter; toiljs classifies them by type.\n\n## Return types\n\nYou return one of two things from a route, and toiljs encodes it for you:\n\n| You return | toiljs sends |\n| --- | --- |\n| a [`@data`](./data.md) value | The value serialized (JSON by default, binary if the route is in binary mode). Status `200`. |\n| a `Response` | Exactly that response: your status, headers, cookies, and body, untouched. |\n| `void` (nothing) | `204 No Content`. |\n\nReturning a `@data` value is the short path when you just want to send the data. Returning a `Response` gives you full control: a custom status, extra headers, cookies, caching. Use whichever fits.\n\n```ts\n// Short path: return the data, let toiljs serialize it as JSON.\n@get('/me')\npublic me(): Player { return currentPlayer(); }\n\n// Full control: custom 404, a header, and the body serialized by hand.\n@get('/:id')\npublic get(ctx: RouteContext): Response {\n const id = u64.parse(ctx.param('id'));\n if (!store.has(id)) return Response.notFound();\n return Response.json(store.get(id).toJSON().toString())\n .setHeader('cache-control', 'no-store');\n}\n```\n\n## Request and response bodies\n\nEvery route is either a **JSON route** (the default) or a **Binary route**. This decides how request bodies are decoded and response values are encoded:\n\n- **JSON**: the request body is parsed as JSON and revived into your `@data` type; the response value is serialized to JSON. Best for endpoints a browser or a third party calls directly, because JSON is universally readable.\n- **Binary**: the request body and response use toiljs's compact binary codec (`DataWriter`/`DataReader`). Smaller and faster, and exact for very large integers. Best for app-to-app traffic and anything performance sensitive.\n\nSet the mode on the whole controller with `@rest({ stream: DataStream.Binary })`, or per route with `@route({ ..., stream: DataStream.Binary })`. Full detail on both codecs is in [Data types](./data.md).\n\n> Large integers and JSON: numbers of 64 bits or more (`u64`, `i64`, `u128`, `u256`, and friends) are sent over JSON as decimal strings, so they stay exact at any size (plain JSON numbers would lose precision). The generated client turns them back into `bigint`. See [Types](../concepts/types.md).\n\n## The `RouteContext` object\n\n`RouteContext` is your window into the incoming request. toiljs builds one and passes it to any route method that declares a `RouteContext` parameter.\n\n| Member | Signature | What it gives you |\n| --- | --- | --- |\n| `request` | `Request` | The raw request (method, path, headers, body). |\n| `param` | `param(name: string): string` | A captured path param, or `\"\"` if absent. |\n| `query` | `query(name: string): string` | A query-string value (`?q=hi`), or `\"\"` if absent. URL-decoded once; `+` becomes a space. |\n| `header` | `header(name: string): string \\| null` | A request header, case-insensitive, or `null`. |\n| `text` | `text(): string` | The raw request body decoded as UTF-8 text. |\n| `clientIp` | `clientIp(): string` | The connecting client's IP, or `\"\"` if unavailable. |\n\n`clientIp()` is the real socket address the edge observed, not a forgeable header like `X-Forwarded-For`, so it is safe to key rate limits, geo lookups, or audit logs on it.\n\n## The `Request` object\n\nThe raw request. You get it as `ctx.request`, or directly as the argument to a hand-written `handle(req)`.\n\n**Fields:**\n\n| Field | Type | Notes |\n| --- | --- | --- |\n| `method` | `Method` | `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS`, or `UNKNOWN`. |\n| `path` | `string` | The path, including the query string. |\n| `headers` | `Array<Header>` | Ordered list; a `Header` is `{ name, value }`. |\n| `body` | `Uint8Array` | The raw request body bytes. |\n\n**Methods:**\n\n| Method | Signature | Notes |\n| --- | --- | --- |\n| `header` | `header(name: string): string \\| null` | Case-insensitive lookup, `null` if absent. |\n| `cookies` | `cookies(): CookieMap` | Parses the `Cookie` header (values percent-decoded); cached per request. |\n| `cookie` | `cookie(name: string): string \\| null` | A single cookie value, or `null`. |\n\nThe `Method` enum and the `Header` class are exported from `toiljs/server/runtime`.\n\n## Building a response\n\n`Response` is what you return. Create one with a static factory, then chain instance methods to add headers, cookies, and caching. Every instance method returns the same `Response`, so calls chain.\n\n### Static factories\n\n| Factory | Signature | Status | Content-Type |\n| --- | --- | --- | --- |\n| `Response.text` | `text(body: string, status = 200)` | 200 | `text/plain; charset=utf-8` |\n| `Response.html` | `html(body: string, status = 200)` | 200 | `text/html; charset=utf-8` |\n| `Response.json` | `json(body: string, status = 200)` | 200 | `application/json; charset=utf-8` |\n| `Response.bytes` | `bytes(body: Uint8Array, status = 200)` | 200 | `application/octet-stream` |\n| `Response.empty` | `empty(status)` | custom | (none) |\n| `Response.notFound` | `notFound()` | 404 | text |\n| `Response.badRequest` | `badRequest(msg = 'bad request')` | 400 | text |\n| `Response.internalError` | `internalError(msg = 'internal error')` | 500 | text |\n| `Response.unhandled` | `unhandled()` | 404 | text, plus a marker header (see below) |\n\n`Response.json` takes an **already-serialized** string, not an object. Build it from a `@data` value with `value.toJSON().toString()`, or return the `@data` value directly and let toiljs serialize it (usually simpler).\n\n### Instance methods\n\n| Method | Signature | What it does |\n| --- | --- | --- |\n| `setHeader` | `setHeader(name, value): Response` | Appends a header (call again to add more). |\n| `setCookie` | `setCookie(cookie: Cookie): Response` | Appends a `Set-Cookie`. |\n| `setCookieKV` | `setCookieKV(name, value): Response` | Shorthand for a cookie with no attributes. |\n| `clearCookie` | `clearCookie(name, path = '/', domain = ''): Response` | Emits a deletion cookie (empty value, `Max-Age=0`). |\n| `cache` | `cache(edgeTtlMinutes, browserTtlSeconds = 0, privateScope = false, allowAuth = false): Response` | Marks the response cacheable. See [Caching](../services/caching.md). |\n| `cacheFor` | `cacheFor(minutes): Response` | Shorthand for edge-caching for N minutes. |\n\n```ts\nreturn Response.json('{\"id\":42}')\n .setHeader('x-trace', traceId)\n .setCookieKV('seen', '1')\n .cacheFor(5);\n```\n\nSee [Cookies](../services/cookies.md) for the full cookie builder and [Caching](../services/caching.md) for the caching rules.\n\n## How dispatch works\n\nEvery `@rest` controller registers itself into a global `Rest` registry when its module loads. At request time, `Rest.dispatch(req)` walks the controllers and tries their routes.\n\n```mermaid\nflowchart TD\n A[\"Request arrives\"] --> B[\"Rest.dispatch(req)\"]\n B --> C{\"Any controller<br/>route match<br/>the method + path?\"}\n C -->|\"Yes\"| D[\"Run that method\"]\n D --> E[\"Return its Response\"]\n C -->|\"No\"| F[\"dispatch returns null\"]\n F --> G[\"Your fallback logic<br/>(or Response.unhandled)\"]\n```\n\nMatching order is deterministic: controllers are tried in the order their modules load, and routes within a controller in declaration order. The **first match wins**, so put more specific routes before catch-all ones.\n\n## How routes are discovered\n\n`toiljs build` scans every file under `server/` and finds your decorated classes on its own, so a route file is picked up as soon as it exists. To keep a plain `toilscript` run (and your editor) seeing the same set, projects also `import` each route file once in `server/main.ts`:\n\n```ts\n// server/main.ts (excerpt)\nimport './routes/Players';\nimport './routes/Todos';\n```\n\nAdding a new controller is two steps: write the file, add the one-line import.\n\n## Dispatch and the 404 fallback\n\nInside your handler, the usual pattern is: try REST first, then fall through to anything else.\n\n```ts\nconst hit = Rest.dispatch(req); // Response, or null if nothing matched\nif (hit != null) return hit;\nreturn Response.unhandled(); // no route matched here\n```\n\nThere are two different 404s, and the difference matters:\n\n- **`Response.notFound()`** means \"I looked, and that resource does not exist.\" It is sent to the client as a plain `404`.\n- **`Response.unhandled()`** means \"this server has no route for that path.\" It is a `404` carrying a marker header (`x-toil-unhandled`). The edge (and the dev server) reads that marker and tries to serve the path another way: a static file, or the client-side app. The marker is stripped before anything reaches the browser.\n\nRule of thumb: return `unhandled()` when a path is simply not yours to handle, and `notFound()` when the path is yours but the specific thing is missing.\n\nIf your project is REST-only, you do not need a custom handler at all. toiljs ships `RestHandler`, which does exactly the dispatch-then-`unhandled` dance:\n\n```ts\nimport { Server, RestHandler } from 'toiljs/server/runtime';\nServer.handler = () => new RestHandler();\n```\n\n## Guards: auth, rate limits, caching\n\nYou can stack extra decorators on a route (or a whole controller) to protect or cache it. They compose with the verb decorators:\n\n```ts\n@rest('admin')\nclass Admin {\n @get('/stats')\n @auth // reject with 401 if there is no valid session\n @ratelimit(RateLimit.SlidingWindow, 30, 60) // at most 30 requests per 60 seconds\n public stats(): Stats { /* ... */ }\n}\n```\n\n- `@auth` requires a valid signed session, else the request is rejected with `401` before your method runs. See the [Auth guide](../auth/README.md).\n- `@ratelimit` caps how often a caller may hit the route. See [Rate limiting](../services/ratelimit.md).\n- Response caching is opt-in per response with `.cache(...)` / `.cacheFor(...)`. See [Caching](../services/caching.md).\n\n## A complete CRUD example\n\nA small in-memory players API showing create, read, update, and delete. In a real app you would store players in [ToilDB](../database/README.md) instead of a local map, because each request gets a fresh handler (see [statelessness](./README.md#stateless-by-default)); this example keeps it in memory to stay focused on routing.\n\n```ts\n// server/models/NewPlayer.ts\n@data\nexport class NewPlayer {\n name: string = '';\n}\n```\n\n```ts\n// server/models/Player.ts\n@data\nexport class Player {\n id: u64 = 0;\n name: string = '';\n score: i64 = 0;\n}\n```\n\n```ts\n// server/routes/Players.ts\nimport { Response, RouteContext } from 'toiljs/server/runtime';\nimport { NewPlayer } from '../models/NewPlayer';\nimport { Player } from '../models/Player';\n\n// A stand-in store. Real apps use ToilDB (see the database section).\nconst store = new Map<u64, Player>();\nlet nextId: u64 = 1;\n\n@rest('players')\nclass Players {\n // CREATE: POST /players (JSON body -> Player)\n @post('/')\n public create(input: NewPlayer): Player {\n const p = new Player();\n p.id = nextId++;\n p.name = input.name;\n p.score = 0;\n store.set(p.id, p);\n return p; // 200 with the player as JSON\n }\n\n // READ: GET /players/:id\n @get('/:id')\n public get(ctx: RouteContext): Response {\n const id = u64.parse(ctx.param('id'));\n if (!store.has(id)) return Response.notFound();\n return Response.json(store.get(id).toJSON().toString());\n }\n\n // UPDATE: PUT /players/:id (JSON body -> Player)\n @put('/:id')\n public update(input: NewPlayer, ctx: RouteContext): Response {\n const id = u64.parse(ctx.param('id'));\n if (!store.has(id)) return Response.notFound();\n const p = store.get(id);\n p.name = input.name;\n return Response.json(p.toJSON().toString());\n }\n\n // DELETE: DELETE /players/:id\n @del('/:id')\n public remove(ctx: RouteContext): Response {\n const id = u64.parse(ctx.param('id'));\n if (!store.has(id)) return Response.notFound();\n store.delete(id);\n return Response.empty(204); // 204 No Content\n }\n}\n```\n\nCalling it from anywhere:\n\n```sh\ncurl -X POST localhost:5173/players -d '{\"name\":\"Ada\"}'\ncurl localhost:5173/players/1\ncurl -X PUT localhost:5173/players/1 -d '{\"name\":\"Ada Lovelace\"}'\ncurl -X DELETE localhost:5173/players/1\n```\n\nBecause `@rest` also generates a typed fetch client, your React frontend can call the same routes without writing URLs:\n\n```ts\nawait Server.REST.players.create({ body: new NewPlayer('Ada') });\nawait Server.REST.players.get({ params: { id: 1 } });\n```\n\nSee [RPC and the generated client](./rpc.md#the-rest-fetch-client) for that client.\n\n## Gotchas\n\n- **Fields do not persist.** A fresh controller instance serves each request, so instance fields reset every time and are never shared between requests or edge nodes. Persist to [ToilDB](../database/README.md).\n- **`Response.json` wants a string.** Pass an already-serialized JSON string (or return the `@data` value directly). Passing an object will not do what you expect.\n- **`@del`, not `@delete`.** `delete` is a reserved word, so the decorator is `@del`.\n- **Query keys and values are decoded once.** `ctx.query('q')` decodes UTF-8 percent escapes and form `+`; malformed escapes remain literal. Remove a previous manual `Cookies.decodeValue` call to avoid double decoding.\n- **Path matching is exact on segment count.** `/todos/:id` does not match `/todos/1/extra`. Add a route for the longer path.\n- **`notFound()` vs `unhandled()`.** Returning `notFound()` from your top handler stops the edge from falling through to static files or the client app. Use `unhandled()` for \"not my path.\"\n\n## Related\n\n- [Data types (`@data`)](./data.md): the request and response body structs, and the JSON vs binary codecs.\n- [Typed RPC](./rpc.md): call your backend from your frontend with end-to-end types (and the generated REST fetch client).\n- [Backend overview](./README.md): the request lifecycle and handler model.\n- [Route execution and transport limits](../concepts/config.md#route-execution-and-transport-limits): handler budgets, HTTP timeouts, and upload size limits.\n- [Cookies](../services/cookies.md), [Caching](../services/caching.md), [Rate limiting](../services/ratelimit.md): response helpers and guards.\n- [Auth](../auth/README.md): protecting routes with `@auth`.\n- [The database](../database/README.md): persisting data between requests.\n\n\n### Data responses with a status\n\n`Response.data(answer, 422)` serializes a `@data` answer as JSON and returns the\nrequested HTTP status with `application/json; charset=utf-8`. It also composes\nwith response headers and cookies. Binary routes can use\n`Response.bytes(answer.encode(), status)` explicitly.\n",
15
16
  "backend/rpc.md": "# Typed RPC (`@service` / `@remote`)\n\nWrite a server function, tag it `@remote`, and call it from your React frontend like a local async function, with the argument and return types checked end to end.\n\n## What RPC is\n\n**RPC** stands for Remote Procedure Call. The idea is old and simple: call a function that actually runs somewhere else (here, on the edge) as if it were a normal function in your own code. You write a method on the server, and on the client you `await` it. No URLs, no `fetch`, no manual JSON. Just a function call.\n\ntoiljs makes that call **fully typed**. When you build the server, it generates a TypeScript file (`shared/server.ts`) describing every callable function, its arguments, and its return type. Your frontend imports nothing extra: a global object called `Server` is available with all of it typed. If you change a server function's signature and rebuild, your frontend code stops type-checking until you fix the call. The client can never drift from the server.\n\n## Why and when\n\nUse RPC when **your own frontend** talks to **your own backend**. It is the most ergonomic and safest way to do that:\n\n- End-to-end types: rename a field on the server, and the client sees it immediately.\n- No plumbing: no route paths to invent, no request or response shapes to hand-write.\n- Exact numbers: 64-bit-and-larger integers arrive as `bigint`, never rounded.\n\nUse [`@rest`](./rest.md) instead when the caller is **not** your frontend: a webhook, a third-party integration, a public API, a mobile client, or anything that speaks in plain URLs and HTTP methods. RPC uses one internal endpoint and a binary wire format, so it is not meant to be called by hand.\n\nYou can use both in the same project. A common split: RPC for your app's own screens, REST for everything public.\n\n## Declaring callable functions\n\nTwo decorators expose server code to the client:\n\n- **`@remote`** on a top-level function makes it directly callable.\n- **`@service`** on a class groups related `@remote` methods under a namespace.\n\n```ts\n// server/services/Stats.ts\nimport { store } from '../core/store';\n\n@service\nclass Stats {\n @remote\n public playerCount(): i32 {\n return store.size;\n }\n}\n```\n\n```ts\n// server/services/remotes.ts\n@remote\nfunction ping(n: i32): i32 {\n return n + 1;\n}\n```\n\nThat is the whole server side. Build the server and the client can call them.\n\n## Calling from the frontend\n\nThe generated client surfaces everything on a global `Server`. A `@service` becomes a namespace keyed by the class name with a lowercase first letter (`Stats` becomes `stats`). A free `@remote` sits directly on `Server`. Every call returns a `Promise`.\n\n```ts\n// anywhere in your React app, no import needed\nconst count = await Server.stats.playerCount(); // number\nconst next = await Server.ping(41); // number -> 42\n```\n\nAutocomplete, argument checking, and the return type all come from `shared/server.ts`, which the build regenerates every time (and `toiljs dev` regenerates on save), so it is always in sync.\n\n## The round trip\n\nHere is what actually happens under that innocent-looking `await`.\n\n```mermaid\nsequenceDiagram\n participant C as Browser (Server.stats.playerCount)\n participant E as Dacely edge\n participant W as Your backend (WASM)\n C->>C: encode args with DataWriter\n C->>E: POST /__toil_rpc<br/>header dacely-rpc = method id<br/>body = encoded args\n E->>W: dispatch to the matching @remote\n W->>W: run playerCount(), encode the result\n W->>E: encoded result bytes\n E->>C: 200 application/octet-stream\n C->>C: decode into the typed value\n```\n\nA few facts worth knowing:\n\n- Every callable has a stable numeric **method id** (a hash of `\"Service.method\"` or the function name). The client sends it in the `dacely-rpc` header; the server dispatches on it.\n- Arguments and results travel in the compact **binary `@data` codec** (see [Data types](./data.md)), so large integers are exact and payloads are small.\n- The endpoint is a single reserved path, `/__toil_rpc`. You never route it yourself; the framework handles it before your `handle` runs.\n\n## RPC is stateless too\n\nJust like a REST controller, a fresh service instance serves each call. Fields you set on a `@service` class do not survive between calls. If two calls need to share data, that data lives in [ToilDB](../database/README.md), not in an instance field. See [statelessness](./README.md#stateless-by-default).\n\n## Argument and return types\n\nArguments and return values may be scalars, arrays, or [`@data`](./data.md) classes, in both directions. Here is how toilscript's types map to what you see on the TypeScript client:\n\n| ToilScript type | TypeScript type |\n| --- | --- |\n| `u8`, `u16`, `u32`, `i8`, `i16`, `i32`, `f32`, `f64` | `number` |\n| `u64`, `i64`, `u128`, `i128`, `u256`, `i256` | `bigint` |\n| `bool` | `boolean` |\n| `string` | `string` |\n| a `@data` class `T` | `T` (the generated class) |\n| `T[]` | `T[]` |\n\nIntegers of 64 bits or more become `bigint` on the client, so they are exact at any magnitude. See [Types](../concepts/types.md) for the full number story.\n\nPassing a `@data` value is just as easy as a scalar. Construct it on the client and pass it in:\n\n```ts\nimport { NewPlayer } from './shared/server';\n\nconst created = await Server.roster.add(new NewPlayer('Ada')); // returns a typed Player\n```\n\nThe `@data` classes in `shared/server.ts` share a byte-for-byte identical codec with the server, so values round-trip exactly.\n\n## Reading and writing the database from a `@remote`\n\nA `@remote` can use the database, but with a safety default: **a plain `@remote` is read-only.** If it tries to write to ToilDB, the compiler rejects it. To let a `@remote` write, add `@action`:\n\n```ts\n@service\nclass Roster {\n @remote\n public count(): i32 { // read-only: fine to just read\n return db.players.count();\n }\n\n @remote\n @action // opts into writes\n public add(input: NewPlayer): Player {\n return db.players.create(/* ... */);\n }\n}\n```\n\n`@query` is the explicit opposite of `@action`: it marks a function read-only on purpose (the default for a `@remote`, so you rarely need to write it). These are ToilDB **function kinds**; the full rules, including what each kind may and may not do, are in the [database docs](../database/README.md). The takeaway for RPC: reads work out of the box, and a write needs `@action`, so a read-only endpoint can never silently mutate your data.\n\n## Guarding a `@remote`\n\nGuards stack on a `@remote` exactly as they do on a REST route:\n\n```ts\n@service\nclass Stats {\n @remote\n @auth // reject with 401 when there is no valid session\n public secretCount(): i32 {\n return store.size;\n }\n}\n```\n\nThe RPC dispatcher enforces `@auth` (and `@ratelimit`) the same way the REST router does: the guard runs first, and an unauthenticated call gets a `401` before your method body executes. See the [Auth guide](../auth/README.md) and [Rate limiting](../services/ratelimit.md).\n\n## The generated `Server` surface\n\n`shared/server.ts` declares `Server` as a global with a shape like this (schematic):\n\n```ts\ndeclare global {\n const Server: {\n // free @remote functions\n ping(n: number): Promise<number>;\n\n // @service classes, keyed by lowercased name\n readonly stats: {\n playerCount(): Promise<number>;\n secretCount(): Promise<number>;\n };\n\n // @rest controllers get a fetch client under REST (see below)\n readonly REST: { /* ... */ };\n\n // @stream classes get a client under Stream (see the realtime docs)\n readonly Stream: { /* ... */ };\n };\n}\n```\n\nYou never edit this file; the build regenerates it. If a `Server` method throws that it is \"unavailable,\" the generated client has not loaded yet: run the server build (or `toiljs dev`, which does it on save).\n\n## The REST fetch client\n\n`@rest` controllers also get a typed client, under `Server.REST.<controller>.<route>`. It is real `fetch` code (because REST is just HTTP), and it is handy when you want your frontend to call a route you also expose publicly:\n\n```ts\n// controller @rest('players') with a create route taking a NewPlayer body\nconst player = await Server.REST.players.create({\n body: new NewPlayer('Ada'), // present only if the route takes a body\n // params: { id: 7 }, // present only if the path has :params\n query: { ref: 'home' }, // optional\n headers: { 'x-trace': id }, // optional\n});\n```\n\nThe wrapper builds the URL, substitutes `:params`, appends `query`, sends the request, throws on a non-2xx status, and decodes the response into the route's return type. A route declared to return `Response` resolves to the raw `fetch` `Response` so you can inspect headers or stream it yourself. See [REST](./rest.md) for the routes themselves.\n\n## RPC vs REST at a glance\n\n| | RPC (`@service` / `@remote`) | REST (`@rest`) |\n| --- | --- | --- |\n| Caller | Your own frontend | Anyone (browser, webhook, third party, `curl`) |\n| Client | `Server.svc.method(args)` | `Server.REST.ctrl.route(args)`, or plain `fetch` |\n| URL shape | One internal endpoint | Real paths and HTTP methods you design |\n| Wire format | Compact binary `@data` | JSON (or binary), your choice |\n| Types | End to end, automatic | End to end for the generated client |\n| Best for | App-internal calls | Public APIs, integrations, webhooks |\n\n## Gotchas\n\n- **RPC is not a public API.** It uses one reserved endpoint and a binary format meant for the generated client. If an outside system needs to call in, expose a [`@rest`](./rest.md) route.\n- **Instance fields do not persist.** A fresh service instance serves every call. Shared state belongs in [ToilDB](../database/README.md).\n- **Writes need `@action`.** A plain `@remote` is read-only; the compiler rejects a database write unless the method is `@action`.\n- **Rebuild after signature changes.** `shared/server.ts` is generated. If autocomplete looks stale, rebuild the server (`toiljs dev` does this on save).\n- **`bigint`, not `number`, for 64-bit values.** A `u64`/`i64`/`u256` argument or return is a `bigint` on the client. Pass `10n`, not `10`.\n\n## Related\n\n- [Data types (`@data`)](./data.md): the structs your RPC arguments and results are made of, and the binary codec they travel in.\n- [HTTP routes (`@rest`)](./rest.md): the public-facing alternative, and the `Server.REST` fetch client.\n- [Types](../concepts/types.md): `u64`, `u256`, and how they map to `number` / `bigint`.\n- [The database](../database/README.md): `@action` vs `@query`, and persisting state.\n- [Fetching data on the frontend](../frontend/data-fetching.md): using `Server.*` from your React components.\n- [Auth](../auth/README.md): guarding a `@remote` with `@auth`.\n",
16
17
  "backend/testing-races.md": "# Deterministic request races\n\n`WasmServerModule.dispatchAsync(request, hooks)` runs a fresh Wasm request\ninstance while allowing another request to use the same dev database. It uses\nWebAssembly JavaScript Promise Integration (JSPI), so the Node runtime must\nprovide `WebAssembly.Suspending` and `WebAssembly.promising`. It reports a clear\nerror when those APIs are unavailable. The normal synchronous dispatcher is\nunchanged.\n\nHooks are `beforeDatabaseOperation(point)` and `afterDatabaseOperation(point)`;\neither may return a Promise. The point includes the request, import name,\nresolved collection and a copied encoded key (or a batch-key frame for\n`get_many`). The after hook also receives the result. Await a barrier inside a\nhook to pause that request, run another request to completion, then release the\nbarrier. Database result-drain and metadata imports are not suspension points.\n\n```ts\nlet release!: () => void;\nlet reached!: () => void;\nconst ready = new Promise<void>(resolve => { reached = resolve; });\nconst resume = new Promise<void>(resolve => { release = resolve; });\nconst send = module.dispatchAsync(sendRequest, {\n beforeDatabaseOperation: async point => {\n if (point.operation !== 'data.compare_exchange') return;\n reached();\n await resume;\n },\n});\nawait ready;\nawait module.dispatchAsync(deleteThreadRequest);\nrelease();\nconst result = await send;\n```\n\nThis executes the actual guest code and shared-store operations at the chosen\norder; it does not imitate a race by rewriting test database state. Use it to\ncheck caller-observed CAS conflicts and partial-work recovery. It does not\nsimulate mesh replication delay, storage-node failover or native lease timing.\n",
17
- "background/daemons.md": "# Daemons (`@daemon` / `@scheduled`)\n\nA `@daemon` is a single, long-lived background worker for your whole app. You mark a class `@daemon`, add `@scheduled` methods that fire on a timer, and the Dacely edge keeps exactly **one** copy of it running worldwide, restarting it elsewhere if the machine it is on fails.\n\n## What a daemon is\n\nThe word \"daemon\" (say \"DEE-mon\") is an old computing term for a program that runs quietly in the background, not tied to any single user. That is exactly what this is.\n\nCompare the three ways your server code can run:\n\n| Kind | How many run | Lives for |\n| ------------------------------- | ------------------------------------ | ----------------------------- |\n| [Request handler](../backend/rest.md) (`@rest`) | a fresh one per request | one request |\n| [Stream box](../realtime/streams.md) (`@stream`) | one per open connection | one connection |\n| **Daemon** (`@daemon`) | **exactly one for the whole app** | as long as it holds the lease |\n\nBecause it is a single, resident instance, its fields persist across scheduled runs (a request handler forgets everything after each request; a daemon does not). It is the right home for work that must happen **once globally on a cadence**, not once per user and not once per server.\n\n```ts\n@daemon\nclass Jobs {\n @scheduled('1h')\n hourly(): void {\n // Runs once an hour, on the one elected worker. Put recurring background\n // work here: rollups, cleanup, polling an upstream, and so on.\n }\n}\n```\n\n## `@scheduled`: run on a cadence\n\nA `@scheduled` method fires on a schedule. The single string argument is the cadence, and it comes in two flavours.\n\n### Interval schedules\n\nAn **interval** fires every fixed span of time. Write a number followed by a unit: `s` (seconds), `m` (minutes), `h` (hours), or `d` (days). The number must be at least 1, and the span may not exceed 7 days.\n\n```ts\n@scheduled('30s') everyHalfMinute(): void { /* ... */ }\n@scheduled('5m') everyFiveMinutes(): void { /* ... */ }\n@scheduled('1h') hourly(): void { /* ... */ }\n@scheduled('1d') daily(): void { /* ... */ }\n```\n\n### Cron schedules\n\nA **cron** expression fires at wall-clock times (\"every weekday at 9:15\", \"midnight on the first of the month\"). Use it when you care about the actual time of day, not just a repeating gap. A cron spec is five fields separated by spaces, in this order:\n\n```\nminute hour day-of-month month day-of-week\n```\n\ntoiljs recognises a cron spec by the spaces in it (an interval has none).\n\n```ts\n@scheduled('15 9 * * 1-5') // 09:15, Monday to Friday\nweekdayMorning(): void { /* ... */ }\n\n@scheduled('0 0 1 * *') // 00:00 on the 1st of every month\nmonthlyReset(): void { /* ... */ }\n```\n\nCron times are evaluated in **UTC** and are **minute-granular** (the smallest cron step is one minute). A `*` means \"every value\" for that field.\n\n### Rules\n\n- A `@scheduled` method takes **no arguments and returns `void`**.\n- A daemon class may have **several** `@scheduled` methods, each on its own cadence.\n- Because only the one elected worker fires them, a task runs **once per tick for the whole app**, never once per server.\n\n### `onStart`: run once at boot\n\nA daemon may also declare a plain `onStart(): void` method (not decorated). It runs **once**, when the daemon box first starts on the elected worker. Use it to set up state or kick off a long-running loop.\n\n`onStart` and untagged scheduled ticks execute database calls with **Action** permissions on the edge and in dev. Point reads and record writes, event appends, counters, membership mutations, and unique claims are allowed. Scans (`Events.latest`, `Events.since`, `Membership.list`) and `View.publish` are rejected. A scheduled method tagged `@job` instead runs with **Job** permissions: scans, arbitrary record writes, and `View.publish` are allowed, with the Job database budget and deadline. This requires toilscript 0.1.65, toiljs 0.0.126, and an edge host supporting daemon catalog v2. Older edge hosts reject a Job catalog at load time. Tagging a helper `@job` does not elevate startup or an untagged tick that calls it. Each Action call gets a fresh budget: 64 database operations, 32 writes, 64 keys per `getMany`, 128 KiB per database result, and 2 MiB of result bytes in total. Each Job tick gets a fresh background budget: 65,535 operations and writes, 1024 keys per `getMany`, 1 MiB per database result, and 16 MiB of result bytes in total. Operators may change operation counts and deadlines. Startup has a separate 512,000,000 gas allowance; scheduled ticks use the host's tick gas setting. A startup trap or nonzero `init`/`daemon_start` result is reported as a failed start and tasks are not registered.\n\nUse `Log.info('cleanup started')`, `Log.warn(...)`, or `Log.error(...)` for server logging. These work in request handlers, streams, and daemons. Messages pass UTF-8 bytes to the host and include the tenant identity in edge logs. A message may contain at most 4096 UTF-8 bytes; at most 32 messages are emitted per call. Each method returns `false` when the message allowance is spent. Invalid arguments abort the call. Avoid secrets and personal data in log messages. `console` imports are rejected when compiling a cold daemon artifact.\n\n```ts\n@daemon\nclass Jobs {\n onStart(): void {\n // one-time setup when this daemon becomes active\n }\n\n @scheduled('1h')\n hourly(): void { /* ... */ }\n}\n```\n\n## No backfill: missed runs are skipped, not replayed\n\nThis is the single most important thing to understand about scheduling.\n\nIf the daemon is down when a tick was due (say the leader failed and a standby is still taking over), or if the clock jumps forward, toiljs does **not** go back and run all the ticks you missed. It simply fires the **next** due run and moves on. This is called a **no-backfill** policy.\n\nTwo practical consequences:\n\n1. **Design tasks to be safe to skip.** \"Recompute the summary\" is fine to miss (the next run fixes it). \"Charge every user once\" is not, unless you make it idempotent.\n2. **Make tasks idempotent where a missed run matters.** Idempotent means running it twice (or catching up later) has the same effect as running it once. For example, \"set yesterday's total to X\" is idempotent; \"add 1 to a counter\" is not.\n\n## One global worker, with safe failover\n\nThere is exactly **one** daemon running for your app at any moment. A second machine keeps a **warm standby** ready but idle. If the active worker's hold on the job expires (it crashed, lost the network, or was shut down), the standby takes over and fires the following runs.\n\nThe mechanism is a **lease**. Think of the lease as a \"who is in charge\" token that only one worker can hold at a time, and that has to be renewed to keep. Only the worker holding the lease (the **leader**) runs the schedule.\n\n```mermaid\nsequenceDiagram\n participant A as Worker A (leader)\n participant L as Lease\n participant B as Worker B (standby)\n A->>L: hold the lease, renew it\n Note over A: A fires @scheduled ticks\n Note over B: B stays idle, watching\n A--xL: A crashes, stops renewing\n Note over L: lease expires\n B->>L: acquire the lease\n Note over B: B is now leader, fires the next ticks\n```\n\nThe important guarantee: **two workers never run the same tick at the same time.** This is called **at-most-once** scheduling. The trade-off is the no-backfill behaviour above: to be sure a tick is never run twice, the edge would rather skip the in-flight tick when a leader is lost than risk running it on two machines. You never start, stop, or place the daemon yourself; the edge elects the leader and drives it.\n\n## Leadership fencing: side effects only run on the leader\n\nA subtle risk with a warm standby is a \"split brain\": for a brief moment, two workers might both think they are the leader. To make that harmless, toiljs **fences** every side effect behind a leadership check. A **side effect** is anything that changes the outside world:\n\n- **Database writes** (creating, patching, deleting rows, adding to counters, appending events, publishing views).\n- **Outbound HTTP calls** (`http_call`, described below).\n\nThese run **only** on the confirmed leader. If code that is not the leader tries one, the edge refuses it (a \"not leader\" error) rather than let it happen twice. Plain **reads** and computation are not fenced (they are safe to do anywhere). So even if two workers briefly overlap, only one of them can actually write or call out. You do not write the fencing yourself; it is automatic. The upshot: put your writes and outbound calls in `@scheduled` methods freely, and trust that they happen once.\n\n## `daemon.*` host calls\n\nA daemon has a small set of host abilities beyond ordinary computation:\n\n- **Database access.** A daemon reads and writes [ToilDB](../database/README.md) with the same collection handles you use in a route or a derive (`.get`, `.add`, `.append`, `.publish`, and so on). Writes are leader-fenced as described above.\n- **Outbound HTTP (`http_call`).** A daemon can call an external service (to poll an API, post to a webhook). This is the one place your server code reaches out to the internet, so it is deliberately restricted:\n - It is **leader-only** (fenced, like any side effect).\n - It is **SSRF-bounded**. SSRF (server-side request forgery) is an attack where code is tricked into calling internal addresses it should not reach. The edge resolves the target host and blocks private or internal addresses, so a daemon cannot use `http_call` to poke around inside the network.\n - It is **metered**: making many calls or pulling huge responses costs budget, which caps abuse.\n- **Leadership info** (`is_leader`, `current_epoch`). A daemon can check whether it is currently the leader, which is useful for guarding a long `onStart` loop.\n\n> **Note:** In `toiljs dev` (the single-process local emulator), the daemon is always the leader (there is nothing to fail over to), and `http_call` is stubbed to return a \"call failed\" result rather than make real network requests. Everything else, including the schedule and your database writes, runs exactly as it does on the edge.\n\n### The `Daemon` global\n\nInside a `@daemon` class, `Daemon` is an ambient global (no import), like `Analytics`. It needs `toilscript` 0.1.60 or newer.\n\n| Member | Description |\n| --- | --- |\n| `Daemon.isLeader(): bool` | Whether this worker currently holds the lease. A snapshot: re-check it inside a long task rather than trusting the value it started with. |\n| `Daemon.epoch(): i64` | The monotonic fencing token, bumped on every (re)acquire, or `-1` when this worker is not the leader. Stamp it into work that must not outlive the lease that authorized it. |\n| `Daemon.taskCount(): i32` | How many `@scheduled` tasks are registered. |\n| `Daemon.nextFireMs(taskId: i32): i64` | The next fire time for a task, in epoch milliseconds, or `-1` when the id is unknown or the cron never fires again. |\n| `Daemon.yieldNow(): DaemonError` | Give the edge a chance to observe a lost lease. `DaemonError.None` means you are still the leader. |\n| `Daemon.sleep(ms: i64): DaemonError` | Park the task. The edge clamps this to 3 seconds. `LeaseLost` means the lease went away while you slept, and the task should stop. |\n| `Daemon.httpCall(request, responseCap?)` | Make an outbound HTTP request. Returns a `DaemonHttpResponse`, or `null` on failure. |\n| `Daemon.lastError(): DaemonError` | The failure recorded by the most recent `Daemon` call. |\n\n### Outbound HTTP\n\n`Daemon.httpCall` performs the leader-fenced, SSRF-bounded, metered call described above. Its usage shows up in the `Analytics` counters `daemonHttpCallAttempts` / `daemonHttpCallFailures`.\n\n```ts\n@daemon\nclass Jobs {\n @scheduled('5m')\n poll(): void {\n const req = new DaemonHttpRequest('POST', 'https://api.example.com/events');\n req.header('content-type', 'application/json');\n req.body = Uint8Array.wrap(String.UTF8.encode('{\"ping\":true}'));\n\n const res = Daemon.httpCall(req);\n if (res == null) {\n // Daemon.lastError(): NotLeader, CallFailed, ResponseTooLarge, BadEnvelope\n return;\n }\n if (res.status == 200) App.events.add(new Event(res.text()));\n }\n}\n```\n\nA `null` result is never ambiguous: read `Daemon.lastError()`.\n\n| `DaemonError` | Meaning |\n| --- | --- |\n| `NotLeader` | This worker does not hold the lease. The edge refused without touching the network. |\n| `LeaseLost` | The lease went away mid-call. |\n| `CallFailed` | The request did not complete: blocked by the SSRF guard, timed out, or the transport failed. |\n| `ResponseTooLarge` | The response did not fit your buffer. **The call already happened**, so do not blindly retry it: pass a larger `responseCap` instead. |\n| `BadEnvelope` | Your request broke a host cap (nothing was sent), or the response could not be parsed. |\n\nThe caps the edge enforces, which `httpCall` checks in the guest so an over-cap request never costs you a round trip: the method is 1 to 16 bytes, the URL at most 8 KiB, at most 64 headers of at most 8 KiB each, and a request body of at most 256 KiB. Responses are truncated at 1 MiB; `responseCap` defaults to 64 KiB.\n\nIn `toiljs dev` the emulator returns `CallFailed` for every `httpCall` rather than reaching the network, so a daemon that polls an external service does nothing locally. Everything else behaves as it does on the edge.\n\n## The `main.daemon.ts` file (a separate tier)\n\nLike streams, daemons live in their **own entry file**, `server/main.daemon.ts`, and compile into their **own artifact**, `build/server/release-cold.wasm`. Importing your `@daemon` module there pulls it into that artifact.\n\n```ts\n// server/main.daemon.ts\nimport { revertOnError } from 'toiljs/server/runtime/abort/abort';\n\nimport './daemon/Jobs'; // add each @daemon module here\n\n// NOTE: unlike main.ts / main.stream.ts, the daemon entry does NOT re-export the\n// request runtime. A daemon artifact exposes its schedule hooks, not the request handler.\nexport function abort(message: string, fileName: string, line: u32, column: u32): void {\n revertOnError(message, fileName, line, column);\n}\n```\n\n`toiljs build` produces `release-cold.wasm` automatically when your project declares a `@daemon` surface:\n\n```sh\n$ ls build/server/*.wasm\nbuild/server/release.wasm # L1 request (@rest / @service)\nbuild/server/release-stream.wasm # L2/L3 stream (@stream)\nbuild/server/release-cold.wasm # L4 daemon (@daemon)\n```\n\nThere is **at most one** `@daemon` class per project, and it is a compile error to put a `@daemon` in the request build. See [Compute tiers](../concepts/tiers.md) for how one source tree becomes three artifacts.\n\n## Worked example: a periodic rollup\n\nA common daemon job: every hour, read a running total and store a small summary so pages can show it with one cheap read. This reads a [counter](../database/counters.md) and writes a summary [document](../database/documents.md); the write only takes effect on the leader.\n\n```ts\n// server/models/StatKey.ts and Summary.ts (@data types)\n@data\nclass StatKey {\n name: string = 'signups';\n constructor(name: string = 'signups') { this.name = name; }\n}\n\n@data\nclass Summary {\n total: u64 = 0;\n updatedAt: u64 = 0;\n}\n\n// server/data/StatsDb.ts\n@database\nclass StatsDb {\n @collection static signups: Counter<StatKey>;\n @collection static summary: Documents<StatKey, Summary>;\n}\n\n// server/daemon/Jobs.ts\n@daemon\nclass Jobs {\n @scheduled('1h')\n rollup(): void {\n const key = new StatKey('signups');\n const total = StatsDb.signups.get(key); // a read (allowed anywhere)\n\n const s = new Summary();\n s.total = total;\n s.updatedAt = <u64>(Date.now() / 1000);\n StatsDb.summary.patch(key, s); // a write: runs only on the leader\n }\n}\n```\n\nNow any request handler can serve the summary with a single keyed read, and it is never more than an hour stale. Because the write is fenced to the leader and the rollup is idempotent (it *sets* the total rather than adding to it), a missed or failed-over tick is harmless: the next hourly run simply refreshes it.\n\n## When not to use a daemon\n\n- **When a user is waiting for the result.** Do that work in a [route](../backend/rest.md) or [RPC](../backend/rpc.md), on the request path.\n- **When you need a fast read-view kept in sync with data changes.** That is a [`@derive`](./derive.md), which runs on every write rather than on a timer.\n- **When you need exactly-once, never-skipped execution.** Scheduling is at-most-once with no backfill, so make tasks idempotent or safe to skip. A daemon is not a guaranteed job queue.\n\n## Related\n\n- [Background overview](./README.md): daemons versus `@derive`, and which to reach for.\n- [Derived views (`@derive`)](./derive.md): keep a read-view in sync on every write.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): the daemon runs on the L4 global tier.\n- [Counters](../database/counters.md), [Documents](../database/documents.md), [Events](../database/events.md): the data a daemon reads and writes.\n\n\n## Public development task and HTTP test API\n\nImport `DaemonHost` from `toiljs/devserver`, call `refresh()` to load its artifact,\nthen call `host.runTask(taskName, atMillis)`. Use the catalogued names in\n`host.tasks`. The result contains `status`, `task`, `atMillis`, `returnCode`,\n`error`, `durationMs`, and the task's database `budget`. Statuses distinguish\nsuccess, a returned error, a trap, a skipped/inactive task and an unknown name.\nA trapped task leaves the resident box available for another call.\n\nThe fifth constructor argument accepts `{ clock, httpMock }`. `clock` supplies\nthe instance's default guest time; `runTask` temporarily uses its supplied time\nwithout replacing process-wide `Date.now`. The synchronous `httpMock(request)`\nreceives decoded method, absolute URL, headers and body, and returns\n`{ status, headers?, body? }` or `null`. It exercises the real daemon HTTP wire\ncodec and native buffer/size limits without making a network connection. When\nno mock is installed, the dev import retains the `DaemonCallFailed` result.\n\nThis hook is a test transport, not an emulation of DNS/SSRF policy or production\nHTTP timing. Validate those on the native host.\n\n### Startup with Job permissions\n\nAnnotate the daemon's `onStart` method with `@job` when initialization needs\nbackground scans or view publication:\n\n```ts\n@daemon\nclass Maintenance {\n @job\n onStart(): void {\n // Membership.list/listPage and View.publish are available here.\n // Initialize indexes or resume persisted startup work idempotently.\n }\n}\n```\n\nThe host selects Job permissions and its DB budget before calling `daemon_start`.\nThe unannotated method keeps Action permissions. Startup runs once per resident\nbox start; a restart or replacement box runs it again, so initialization must be\nidempotent. It is not a durable exactly-once migration. Scheduled tasks retain\ntheir own declared kind and budget.\n\nJob startup emits daemon catalog **v3** with an explicit startup-kind byte;\nolder catalogs retain Action startup. Updated dev and native source hosts accept\nv1/v2/v3. An older native host rejects v3 rather than silently running startup\nwith reduced permissions. Actual deployed-host versions still need to be checked\nagainst the deployment inventory before rollout.\n",
18
+ "background/daemons.md": "# Daemons (`@daemon` / `@scheduled`)\n\nA `@daemon` is a single, long-lived background worker for your whole app. You mark a class `@daemon`, add `@scheduled` methods that fire on a timer, and the Dacely edge keeps exactly **one** copy of it running worldwide, restarting it elsewhere if the machine it is on fails.\n\n## What a daemon is\n\nThe word \"daemon\" (say \"DEE-mon\") is an old computing term for a program that runs quietly in the background, not tied to any single user. That is exactly what this is.\n\nCompare the three ways your server code can run:\n\n| Kind | How many run | Lives for |\n| ------------------------------- | ------------------------------------ | ----------------------------- |\n| [Request handler](../backend/rest.md) (`@rest`) | a fresh one per request | one request |\n| [Stream box](../realtime/streams.md) (`@stream`) | one per open connection | one connection |\n| **Daemon** (`@daemon`) | **exactly one for the whole app** | as long as it holds the lease |\n\nBecause it is a single, resident instance, its fields persist across scheduled runs (a request handler forgets everything after each request; a daemon does not). It is the right home for work that must happen **once globally on a cadence**, not once per user and not once per server.\n\n```ts\n@daemon\nclass Jobs {\n @scheduled('1h')\n hourly(): void {\n // Runs once an hour, on the one elected worker. Put recurring background\n // work here: rollups, cleanup, polling an upstream, and so on.\n }\n}\n```\n\n## `@scheduled`: run on a cadence\n\nA `@scheduled` method fires on a schedule. The single string argument is the cadence, and it comes in two flavours.\n\n### Interval schedules\n\nAn **interval** fires every fixed span of time. Write a number followed by a unit: `s` (seconds), `m` (minutes), `h` (hours), or `d` (days). The number must be at least 1, and the span may not exceed 7 days.\n\n```ts\n@scheduled('30s') everyHalfMinute(): void { /* ... */ }\n@scheduled('5m') everyFiveMinutes(): void { /* ... */ }\n@scheduled('1h') hourly(): void { /* ... */ }\n@scheduled('1d') daily(): void { /* ... */ }\n```\n\n### Cron schedules\n\nA **cron** expression fires at wall-clock times (\"every weekday at 9:15\", \"midnight on the first of the month\"). Use it when you care about the actual time of day, not just a repeating gap. A cron spec is five fields separated by spaces, in this order:\n\n```\nminute hour day-of-month month day-of-week\n```\n\ntoiljs recognises a cron spec by the spaces in it (an interval has none).\n\n```ts\n@scheduled('15 9 * * 1-5') // 09:15, Monday to Friday\nweekdayMorning(): void { /* ... */ }\n\n@scheduled('0 0 1 * *') // 00:00 on the 1st of every month\nmonthlyReset(): void { /* ... */ }\n```\n\nCron times are evaluated in **UTC** and are **minute-granular** (the smallest cron step is one minute). A `*` means \"every value\" for that field.\n\n### Rules\n\n- A `@scheduled` method takes **no arguments and returns `void`**.\n- A daemon class may have **several** `@scheduled` methods, each on its own cadence.\n- Because only the one elected worker fires them, a task runs **once per tick for the whole app**, never once per server.\n\n### `onStart`: run once at boot\n\nA daemon may also declare a plain `onStart(): void` method (not decorated). It runs **once**, when the daemon box first starts on the elected worker. Use it to set up state or kick off a long-running loop.\n\nAn **unannotated** `onStart` and untagged scheduled ticks execute database calls\nwith **Action** permissions on the edge and in dev. Point reads and record\nwrites, event appends, counters, membership mutations, and unique claims are\nallowed. Scans (`Events.latest`, `Events.since`, `Membership.list`) and\n`View.publish` are rejected for these Action calls.\n\nA scheduled method tagged `@job` instead runs with **Job** permissions: scans,\narbitrary record writes, and `View.publish` are allowed, with the Job database\nbudget and deadline. Scheduled Jobs require toilscript 0.1.65, toiljs 0.0.126,\nand an edge host supporting daemon catalog v2. Annotating `onStart` itself with\n`@job` also selects **Job** permissions for startup; this requires toilscript\n0.1.66, toiljs 0.0.128, and catalog v3. See\n[startup with Job permissions](#startup-with-job-permissions). Older hosts reject\nunsupported catalogs at load time. Tagging a helper `@job` does not elevate\nAction startup or an untagged tick that calls it.\n\nEach Action call gets a fresh budget: 64 database operations, 32 writes, 64 keys\nper `getMany`, 128 KiB per database result, and 2 MiB of result bytes in total.\nEach Job call gets a fresh background budget: 65,535 operations and writes,\n1024 keys per `getMany`, 1 MiB per database result, and 16 MiB of result bytes\nin total. Operators may change operation counts and deadlines. Startup has a\nseparate 512,000,000 gas allowance; scheduled ticks use the host's tick gas\nsetting. A startup trap or nonzero `init`/`daemon_start` result is reported as a\nfailed start and tasks are not registered.\n\nUse `Log.info('cleanup started')`, `Log.warn(...)`, or `Log.error(...)` for server logging. These work in request handlers, streams, and daemons. Messages pass UTF-8 bytes to the host and include the tenant identity in edge logs. A message may contain at most 4096 UTF-8 bytes; at most 32 messages are emitted per call. Each method returns `false` when the message allowance is spent. Invalid arguments abort the call. Avoid secrets and personal data in log messages. `console` imports are rejected when compiling a cold daemon artifact.\n\n```ts\n@daemon\nclass Jobs {\n onStart(): void {\n // one-time setup when this daemon becomes active\n }\n\n @scheduled('1h')\n hourly(): void { /* ... */ }\n}\n```\n\n## No backfill: missed runs are skipped, not replayed\n\nThis is the single most important thing to understand about scheduling.\n\nIf the daemon is down when a tick was due (say the leader failed and a standby is still taking over), or if the clock jumps forward, toiljs does **not** go back and run all the ticks you missed. It simply fires the **next** due run and moves on. This is called a **no-backfill** policy.\n\nTwo practical consequences:\n\n1. **Design tasks to be safe to skip.** \"Recompute the summary\" is fine to miss (the next run fixes it). \"Charge every user once\" is not, unless you make it idempotent.\n2. **Make tasks idempotent where a missed run matters.** Idempotent means running it twice (or catching up later) has the same effect as running it once. For example, \"set yesterday's total to X\" is idempotent; \"add 1 to a counter\" is not.\n\n## One global worker, with safe failover\n\nThere is exactly **one** daemon running for your app at any moment. A second machine keeps a **warm standby** ready but idle. If the active worker's hold on the job expires (it crashed, lost the network, or was shut down), the standby takes over and fires the following runs.\n\nThe mechanism is a **lease**. Think of the lease as a \"who is in charge\" token that only one worker can hold at a time, and that has to be renewed to keep. Only the worker holding the lease (the **leader**) runs the schedule.\n\n```mermaid\nsequenceDiagram\n participant A as Worker A (leader)\n participant L as Lease\n participant B as Worker B (standby)\n A->>L: hold the lease, renew it\n Note over A: A fires @scheduled ticks\n Note over B: B stays idle, watching\n A--xL: A crashes, stops renewing\n Note over L: lease expires\n B->>L: acquire the lease\n Note over B: B is now leader, fires the next ticks\n```\n\nThe important guarantee: **two workers never run the same tick at the same time.** This is called **at-most-once** scheduling. The trade-off is the no-backfill behaviour above: to be sure a tick is never run twice, the edge would rather skip the in-flight tick when a leader is lost than risk running it on two machines. You never start, stop, or place the daemon yourself; the edge elects the leader and drives it.\n\n## Leadership fencing: side effects only run on the leader\n\nA subtle risk with a warm standby is a \"split brain\": for a brief moment, two workers might both think they are the leader. To make that harmless, toiljs **fences** every side effect behind a leadership check. A **side effect** is anything that changes the outside world:\n\n- **Database writes** (creating, patching, deleting rows, adding to counters, appending events, publishing views).\n- **Outbound HTTP calls** (`http_call`, described below).\n\nThese run **only** on the confirmed leader. If code that is not the leader tries one, the edge refuses it (a \"not leader\" error) rather than let it happen twice. Plain **reads** and computation are not fenced (they are safe to do anywhere). So even if two workers briefly overlap, only one of them can actually write or call out. You do not write the fencing yourself; it is automatic. The upshot: put your writes and outbound calls in `@scheduled` methods freely, and trust that they happen once.\n\n## `daemon.*` host calls\n\nA daemon has a small set of host abilities beyond ordinary computation:\n\n- **Database access.** A daemon reads and writes [ToilDB](../database/README.md) with the same collection handles you use in a route or a derive (`.get`, `.add`, `.append`, `.publish`, and so on). Writes are leader-fenced as described above.\n- **Outbound HTTP (`http_call`).** A daemon can call an external service (to poll an API, post to a webhook). This is the one place your server code reaches out to the internet, so it is deliberately restricted:\n - It is **leader-only** (fenced, like any side effect).\n - It is **SSRF-bounded**. SSRF (server-side request forgery) is an attack where code is tricked into calling internal addresses it should not reach. The edge resolves the target host and blocks private or internal addresses, so a daemon cannot use `http_call` to poke around inside the network.\n - It is **metered**: making many calls or pulling huge responses costs budget, which caps abuse.\n- **Leadership info** (`is_leader`, `current_epoch`). A daemon can check whether it is currently the leader, which is useful for guarding a long `onStart` loop.\n\n> **Note:** In `toiljs dev` (the single-process local emulator), the daemon is always the leader (there is nothing to fail over to), and `http_call` is stubbed to return a \"call failed\" result rather than make real network requests. Everything else, including the schedule and your database writes, runs exactly as it does on the edge.\n\n### The `Daemon` global\n\nInside a `@daemon` class, `Daemon` is an ambient global (no import), like `Analytics`. It needs `toilscript` 0.1.60 or newer.\n\n| Member | Description |\n| --- | --- |\n| `Daemon.isLeader(): bool` | Whether this worker currently holds the lease. A snapshot: re-check it inside a long task rather than trusting the value it started with. |\n| `Daemon.epoch(): i64` | The monotonic fencing token, bumped on every (re)acquire, or `-1` when this worker is not the leader. Stamp it into work that must not outlive the lease that authorized it. |\n| `Daemon.taskCount(): i32` | How many `@scheduled` tasks are registered. |\n| `Daemon.nextFireMs(taskId: i32): i64` | The next fire time for a task, in epoch milliseconds, or `-1` when the id is unknown or the cron never fires again. |\n| `Daemon.yieldNow(): DaemonError` | Give the edge a chance to observe a lost lease. `DaemonError.None` means you are still the leader. |\n| `Daemon.sleep(ms: i64): DaemonError` | Park the task. The edge clamps this to 3 seconds. `LeaseLost` means the lease went away while you slept, and the task should stop. |\n| `Daemon.httpCall(request, responseCap?)` | Make an outbound HTTP request. Returns a `DaemonHttpResponse`, or `null` on failure. |\n| `Daemon.lastError(): DaemonError` | The failure recorded by the most recent `Daemon` call. |\n\n### Outbound HTTP\n\n`Daemon.httpCall` performs the leader-fenced, SSRF-bounded, metered call described above. Its usage shows up in the `Analytics` counters `daemonHttpCallAttempts` / `daemonHttpCallFailures`.\n\n```ts\n@daemon\nclass Jobs {\n @scheduled('5m')\n poll(): void {\n const req = new DaemonHttpRequest('POST', 'https://api.example.com/events');\n req.header('content-type', 'application/json');\n req.body = Uint8Array.wrap(String.UTF8.encode('{\"ping\":true}'));\n\n const res = Daemon.httpCall(req);\n if (res == null) {\n // Daemon.lastError(): NotLeader, CallFailed, ResponseTooLarge, BadEnvelope\n return;\n }\n if (res.status == 200) App.events.add(new Event(res.text()));\n }\n}\n```\n\nA `null` result is never ambiguous: read `Daemon.lastError()`.\n\n| `DaemonError` | Meaning |\n| --- | --- |\n| `NotLeader` | This worker does not hold the lease. The edge refused without touching the network. |\n| `LeaseLost` | The lease went away mid-call. |\n| `CallFailed` | The request did not complete: blocked by the SSRF guard, timed out, or the transport failed. |\n| `ResponseTooLarge` | The response did not fit your buffer. **The call already happened**, so do not blindly retry it: pass a larger `responseCap` instead. |\n| `BadEnvelope` | Your request broke a host cap (nothing was sent), or the response could not be parsed. |\n\nThe caps the edge enforces, which `httpCall` checks in the guest so an over-cap request never costs you a round trip: the method is 1 to 16 bytes, the URL at most 8 KiB, at most 64 headers of at most 8 KiB each, and a request body of at most 256 KiB. Responses are truncated at 1 MiB; `responseCap` defaults to 64 KiB.\n\nIn `toiljs dev` the emulator returns `CallFailed` for every `httpCall` rather than reaching the network, so a daemon that polls an external service does nothing locally. Everything else behaves as it does on the edge.\n\n## The `main.daemon.ts` file (a separate tier)\n\nLike streams, daemons live in their **own entry file**, `server/main.daemon.ts`, and compile into their **own artifact**, `build/server/release-cold.wasm`. Importing your `@daemon` module there pulls it into that artifact.\n\n```ts\n// server/main.daemon.ts\nimport { revertOnError } from 'toiljs/server/runtime/abort/abort';\n\nimport './daemon/Jobs'; // add each @daemon module here\n\n// NOTE: unlike main.ts / main.stream.ts, the daemon entry does NOT re-export the\n// request runtime. A daemon artifact exposes its schedule hooks, not the request handler.\nexport function abort(message: string, fileName: string, line: u32, column: u32): void {\n revertOnError(message, fileName, line, column);\n}\n```\n\n`toiljs build` produces `release-cold.wasm` automatically when your project declares a `@daemon` surface:\n\n```sh\n$ ls build/server/*.wasm\nbuild/server/release.wasm # L1 request (@rest / @service)\nbuild/server/release-stream.wasm # L2/L3 stream (@stream)\nbuild/server/release-cold.wasm # L4 daemon (@daemon)\n```\n\nThere is **at most one** `@daemon` class per project, and it is a compile error to put a `@daemon` in the request build. See [Compute tiers](../concepts/tiers.md) for how one source tree becomes three artifacts.\n\n## Worked example: a periodic rollup\n\nA common daemon job: every hour, read a running total and store a small summary so pages can show it with one cheap read. This reads a [counter](../database/counters.md) and writes a summary [document](../database/documents.md); the write only takes effect on the leader.\n\n```ts\n// server/models/StatKey.ts and Summary.ts (@data types)\n@data\nclass StatKey {\n name: string = 'signups';\n constructor(name: string = 'signups') { this.name = name; }\n}\n\n@data\nclass Summary {\n total: u64 = 0;\n updatedAt: u64 = 0;\n}\n\n// server/data/StatsDb.ts\n@database\nclass StatsDb {\n @collection static signups: Counter<StatKey>;\n @collection static summary: Documents<StatKey, Summary>;\n}\n\n// server/daemon/Jobs.ts\n@daemon\nclass Jobs {\n @scheduled('1h')\n rollup(): void {\n const key = new StatKey('signups');\n const total = StatsDb.signups.get(key); // a read (allowed anywhere)\n\n const s = new Summary();\n s.total = total;\n s.updatedAt = <u64>(Date.now() / 1000);\n StatsDb.summary.patch(key, s); // a write: runs only on the leader\n }\n}\n```\n\nNow any request handler can serve the summary with a single keyed read, and it is never more than an hour stale. Because the write is fenced to the leader and the rollup is idempotent (it *sets* the total rather than adding to it), a missed or failed-over tick is harmless: the next hourly run simply refreshes it.\n\n## When not to use a daemon\n\n- **When a user is waiting for the result.** Do that work in a [route](../backend/rest.md) or [RPC](../backend/rpc.md), on the request path.\n- **When you need a fast read-view kept in sync with data changes.** That is a [`@derive`](./derive.md), which runs on every write rather than on a timer.\n- **When you need exactly-once, never-skipped execution.** Scheduling is at-most-once with no backfill, so make tasks idempotent or safe to skip. A daemon is not a guaranteed job queue.\n\n## Related\n\n- [Background overview](./README.md): daemons versus `@derive`, and which to reach for.\n- [Derived views (`@derive`)](./derive.md): keep a read-view in sync on every write.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): the daemon runs on the L4 global tier.\n- [Counters](../database/counters.md), [Documents](../database/documents.md), [Events](../database/events.md): the data a daemon reads and writes.\n\n\n## Public development task and HTTP test API\n\nImport `DaemonHost` from `toiljs/devserver`, call `refresh()` to load its artifact,\nthen call `host.runTask(taskName, atMillis)`. Use the catalogued names in\n`host.tasks`. The result contains `status`, `task`, `atMillis`, `returnCode`,\n`error`, `durationMs`, and the task's database `budget`. Statuses distinguish\nsuccess, a returned error, a trap, a skipped/inactive task and an unknown name.\nA trapped task leaves the resident box available for another call.\n\nThe fifth constructor argument accepts `{ clock, httpMock }`. `clock` supplies\nthe instance's default guest time; `runTask` temporarily uses its supplied time\nwithout replacing process-wide `Date.now`. The synchronous `httpMock(request)`\nreceives decoded method, absolute URL, headers and body, and returns\n`{ status, headers?, body? }` or `null`. It exercises the real daemon HTTP wire\ncodec and native buffer/size limits without making a network connection. When\nno mock is installed, the dev import retains the `DaemonCallFailed` result.\n\nThis hook is a test transport, not an emulation of DNS/SSRF policy or production\nHTTP timing. Validate those on the native host.\n\n### Startup with Job permissions\n\nAnnotate the daemon's `onStart` method with `@job` when initialization needs\nbackground scans or view publication:\n\n```ts\n@daemon\nclass Maintenance {\n @job\n onStart(): void {\n // Membership.list/listPage and View.publish are available here.\n // Initialize indexes or resume persisted startup work idempotently.\n }\n}\n```\n\nThe host selects Job permissions and its DB budget before calling `daemon_start`.\nThe unannotated method keeps Action permissions. Startup runs once per resident\nbox start; a restart or replacement box runs it again, so initialization must be\nidempotent. It is not a durable exactly-once migration. Scheduled tasks retain\ntheir own declared kind and budget.\n\nJob startup emits daemon catalog **v3** with an explicit startup-kind byte;\nolder catalogs retain Action startup. Updated dev and native source hosts accept\nv1/v2/v3. An older native host rejects v3 rather than silently running startup\nwith reduced permissions. Actual deployed-host versions still need to be checked\nagainst the deployment inventory before rollout.\n",
18
19
  "background/derive.md": "# Derived views (`@derive`)\n\nA `@derive` keeps a fast, precomputed **View** of your data in sync automatically. You write a method that reads your source data and publishes a summary; toiljs re-runs it whenever the source data changes, so your pages can read the summary with one cheap lookup instead of doing the work on every request.\n\n## The problem it solves\n\nSome reads are expensive. \"Show the 10 newest comments\" means scanning an [events](../database/events.md) log. \"Show the leaderboard\" means totalling up scores. A **scan** (walking many rows to build a result) can fan out across an unbounded amount of data, and that is too slow and too unpredictable to do while a user waits.\n\nSo toiljs **bars scans on the request path**. A [route](../backend/rest.md) handler runs under a restricted mode:\n\n- A `@get` runs as a **query** (reads only, no scans).\n- A `@post` / `@put` / `@patch` / `@del` runs as an **action** (keyed reads and writes, still no scans).\n\nIf you cannot scan in a route, how do you show \"the latest 10\"? You precompute it. A `@derive` does the scan **off** the request path, folds the result into a [View](../database/views.md) (a read-optimized snapshot stored by key), and your route reads that View with a single keyed lookup, which is not a scan and so is allowed.\n\n```mermaid\nflowchart LR\n W[\"POST /guestbook<br/>(action: append + count)\"] --> S[(Events + Counter<br/>source data)]\n S -->|write triggers| D[\"@derive recompute()<br/>scans, builds, publishes\"]\n D --> V[(View<br/>precomputed snapshot)]\n G[\"GET /guestbook<br/>(query: one keyed read)\"] --> V\n```\n\n## A worked example: a guestbook\n\nHere is the whole pattern in one database class: an [events](../database/events.md) log of signatures, a [counter](../database/counters.md) of how many there are, and a [View](../database/views.md) that holds the ready-to-serve page.\n\n```ts\n@data\nclass GuestKey {\n room: string = 'main';\n constructor(room: string = 'main') { this.room = room; }\n}\n\n@database\nclass GuestbookDb {\n @collection static entries: Events<GuestKey, GuestEntry>; // a source: the log\n @collection static totals: Counter<GuestKey>; // a source: the count\n @collection static book: View<GuestKey, GuestbookView>; // the view we publish\n\n // Recompute the view from the sources. It MAY scan and publish; a route may not.\n @derive\n recompute(): void {\n const key = new GuestKey('main');\n const view = new GuestbookView();\n view.total = GuestbookDb.totals.get(key); // a keyed read\n view.entries = GuestbookDb.entries.latest(key, 10); // a scan: allowed here\n GuestbookDb.book.publish(key, view); // publish the snapshot\n }\n}\n```\n\nThe route then writes to the sources and reads the view:\n\n```ts\n@rest('guestbook')\nclass Guestbook {\n @get('/')\n list(): GuestbookView {\n const key = new GuestKey('main');\n const view = GuestbookDb.book.get(key); // one keyed read, not a scan\n return view == null ? new GuestbookView() : view; // empty until first publish\n }\n\n @post('/')\n sign(input: NewMessage): GuestbookView {\n const key = new GuestKey('main');\n GuestbookDb.entries.append(key, new GuestEntry(input.author, input.message, 0));\n GuestbookDb.totals.add(key, 1);\n // The @derive republishes `book` right after this action returns, so GET\n // serves the new entry. The action just acks with the new total (a counter\n // read is allowed here; scanning the entries list is not).\n const view = new GuestbookView();\n view.total = GuestbookDb.totals.get(key);\n return view;\n }\n}\n```\n\nSign the guestbook twice and the total climbs across requests, because the data lives in the database (and its view), not in module memory.\n\n## What a `@derive` may do\n\nA `@derive` runs under a special **derive** mode that is more powerful than a route:\n\n| Ability | Query (`@get`) | Action (`@post` ...) | Derive |\n| -------------------------------------------- | :------------: | :------------------: | :----------: |\n| Keyed reads (`.get`, counter total) | yes | yes | yes |\n| Writes (`create`, `patch`, `add`, `append`) | no | yes | yes |\n| **Scans** (`events.latest`, membership list) | **no** | **no** | **yes** |\n| `view.publish` / `view.append` | no | no | yes |\n\nSo a derive is exactly the place to do the reads and scans a route cannot, and to publish the result.\n\n## Declaring a derive\n\nA `@derive` is a method on your [`@database`](../database/setup.md) class, next to the collections it reads and the View it writes.\n\n```ts\n@database\nclass MyDb {\n @collection static events: Events<Key, Fact>; // a source\n @collection static home: View<Key, HomePage>; // the materialized view\n\n @derive\n rebuild(): void {\n // read sources, build the value, publish it\n }\n}\n```\n\nRules:\n\n- A `@derive` method takes **no arguments and returns `void`**.\n- A database may declare **multiple** `@derive` methods; each runs independently.\n- The View value and its key are ordinary [`@data`](../backend/data.md) types, so they round-trip through the codec like any other stored value.\n\n## When a derive runs\n\nYou never call a derive yourself. The runtime runs it for you at two moments:\n\n1. **After a write to a source.** When a request, job, or daemon writes one of the database's source collections (an `events.append`, a `counter.add`, a document `create` or `patch`), that database's derives run **right after the response is produced**, so the view reflects the new data on the next read. Cold artifacts include the shared databases' materializers and run them after startup and scheduled writes without needing an HTTP request. Rebuild cold artifacts with the updated compiler to get this behavior. Older cold artifacts without materializers retain their deferred hot-request fallback. Many writes to one database in a single request are **coalesced** into one recompute (it does not run once per write).\n\n2. **On box load.** When a server box starts, hot-reloads, or notices the underlying data changed out of band, the views are rebuilt from their sources **before the first read is served**. This is also where a value type's [`@migrate`](../backend/data.md) runs against old stored events, as the derive re-reads and republishes them.\n\nA derive's own `view.publish` never re-triggers it, so there is no infinite loop.\n\nA failed cold fold retains its pending work and leaves its checkpoint unchanged.\nThe daemon scheduler retries pending folds on its next iteration, including idle\niterations when no scheduled task is due, while it holds the leadership lease.\nDev retries once per second. No HTTP request is needed to trigger a retry.\n\nThe same code runs under `toiljs dev` (the in-process emulator) and on the production edge, with no flags or wiring to change.\n\n## Folding a growing log incrementally\n\nThe guestbook above uses `events.latest` and **recomputes** the view from scratch on every change. That is simple, correct, and the right default for a **bounded** read: the latest N, a counter total, a small set.\n\nSome views instead fold an **unbounded** log: a running total over every event ever, an activity rollup, an audit summary. Rescanning the whole log on every change gets slower as it grows. For those, read the source with [`events.since`](../database/events.md) instead of `latest`. `since` hands you only the events you have **not folded yet**, so the derive folds forward incrementally.\n\n```ts\n@derive\nrollup(): void {\n const key = new StatsKey('all');\n const view = StatsDb.summary.get(key) ?? new Summary(); // the running view so far\n let batch = StatsDb.events.since(key, 500);\n while (batch.length > 0) { // drain the new events in bounded batches\n for (let i = 0; i < batch.length; i++) view.apply(batch[i]);\n batch = StatsDb.events.since(key, 500);\n }\n StatsDb.summary.publish(key, view);\n}\n```\n\nThe host owns the cursor, you never manage it: it seeds `since` from a durable checkpoint, advances it as it hands you events, and saves it **only after** your `publish` lands (so a crash re-folds the batch instead of skipping it). On the next trigger the derive resumes exactly where it left off.\n\n**One rule: the fold must be idempotent per event.** A rare crash-recovery case (an event that \"heals\" at an older position after the derive already passed it) makes the host re-read the whole log that one run, so applying an event twice must not change the result. Use set-style updates keyed by the event's id, not blind `count += 1` accumulation. If your fold cannot be idempotent, stay on the simple `latest` recompute path.\n\n## Guarantees and limitations\n\n**Guarantees**\n\n- **It converges to a correct snapshot.** Publishes are last-writer-wins (the host versions each publish so a later one always supersedes an earlier one), and a derive recomputes from the source of truth, so the view always ends up matching its sources.\n- **Reads stay cheap.** A route serves the view with a single keyed lookup, never a scan.\n\n**Limitations (read these)**\n\n- **By default it recomputes from scratch each time.** A derive re-reads its sources and republishes on every trigger. That is the simple path and a great fit for a **bounded** read: the latest N, a counter total, a small set. To fold an **unbounded, ever-growing** log efficiently, read it with [`events.since`](../database/events.md) instead of `latest` (see [Folding a growing log incrementally](#folding-a-growing-log-incrementally) above); it folds only the new events since a checkpoint.\n- **It is eventually consistent, by a moment.** The view is republished right after the writing request finishes, so there is a tiny window where a reader could see the pre-write view. For most pages (a feed, a leaderboard) that is invisible and fine.\n- **`view.publish` is derive-only.** Routes cannot publish; they can only read the view. That is the whole point: the expensive build happens off the request path.\n\n## When not to use a derive\n\n- **When the read is already cheap.** If a route can answer with a plain keyed `.get`, you do not need a view at all.\n- **When the task is only a scheduled side effect.** Use a [daemon Job](./daemons.md). A timed materialized projection can call `Db.runDerive` from that Job (see below).\n- **When the source is an unbounded full-history fold.** See the limitation above; keep derives to bounded reads.\n\n## Related\n\n- [Views](../database/views.md): the `View<K, V>` family a derive publishes into, and how to read it.\n- [Events](../database/events.md): the append-only log a derive commonly folds into a view.\n- [Counters](../database/counters.md): running totals a derive can read.\n- [Background overview](./README.md): `@derive` versus `@daemon`, and which to reach for.\n- [Data types (`@data`)](../backend/data.md): the value and key types a view stores.\n\n\n## Stable incremental checkpoints\n\nDurable `events.since` checkpoints use the database and method name, independently\nof the artifact-local numeric dispatch index. Inserting or reordering a derive\ntherefore preserves each existing method's cursor. Renaming a database or method\ncreates a new cursor. Upgrading from ordinal-only checkpoints starts named cursors\nfrom the beginning, rather than attach another method's cursor; folds must remain\nidempotent when replaying existing events.\n\n\n## Reading invalidated keys\n\n`Db.changes()` is available inside a derive. It returns `fullRescan: bool` and\n`keys: DbChange[]`; each entry contains `database`, `collection` (without the\ndatabase prefix), and the original encoded `key`. Decode the key with that\ncollection's key type, then read the current row. An absent row means the\nmaterialized entry must be removed. Keep enough index information to remove an\nentry whose old sort key or group changed.\n\n```ts\nconst changes = Db.changes();\nif (changes.fullRescan) {\n // Rebuild from your source index or resumable event log.\n} else {\n for (let i = 0; i < changes.keys.length; i++) {\n const change = changes.keys[i];\n if (change.collection != 'listings') continue;\n const key = ListingKey.decode(change.key);\n const current = Market.listings.get(key);\n // Idempotently replace or remove the indexed listing.\n }\n}\n```\n\nKeys are deduplicated invalidation hints from collections that committed writes;\nthey can include reads, retries, and no-op attempts in those collections. They\nare not an ordered event stream and contain neither old values nor write counts.\nOnly the derive's database is included. Membership and event keys identify the\nset or partition, rather than an individual member or event.\n\nAlways implement the full-rescan path. Startup, failed-run retries, hints arriving\nfrom another execution surface, an unknown mutation, or overflow requests a full\nrescan with an empty key list. The context holds at most 256 keys and 64 KiB of\nframed metadata. It is request context rather than durable history; keep\n`events.since` for durable event processing. Reading context consumes host gas,\nwithout consuming a database operation or replacing the last result stash.\n\n## Running a derive on a timer\n\nA scheduled Job can invoke a materializer directly with\n`Db.runDerive(databaseName, methodName, body)`. This enters Derive context for\nthe callback, supplies `Db.changes().fullRescan`, and uses the same named\n`events.since` checkpoint as automatic runs. The Job's existing budget and\nconsumed counters remain in effect.\n\n```ts\nfunction refreshBrowse(): void { new Market().refreshBrowse(); }\n\n@daemon\nclass Timers {\n @scheduled('1h')\n @job\n refresh(): void {\n Db.runDerive('Market', 'refreshBrowse', refreshBrowse);\n }\n}\n```\n\nThe database and method strings must exactly match the `@derive` declaration.\nKeep the database in a shared source file included in both artifacts. Checkpoints\ncommit after the callback returns successfully. A trap preserves completed\nwrites and leaves its checkpoint unadvanced, so callbacks must be idempotent.\nCalls outside a Job, nested calls, and empty or oversized identities trap.\nThis API lets a scheduled Job remove expired events from a projection without\nappending a synthetic source change. It runs one bounded invocation per call;\nkeep large rebuilds resumable within the Job budget.\n\n## Requesting another invocation\n\nCall `Db.continueDerive()` when a bounded fold has more work. The request is\npersisted before the call returns. The resident cold scheduler polls queued work\nwhile idle, so no unrelated write or HTTP request is required. Repeated calls\nwithin one invocation coalesce into one DB operation/write. The budget meter\nincludes that operation and its control-row bytes.\n\n```ts\n@derive\nfold(): void {\n const rows = Market.changes.since(new FeedKey(), 64);\n for (let i = 0; i < rows.length; i++) applyIdempotently(rows[i]);\n if (rows.length == 64) Db.continueDerive();\n}\n```\n\nA continuation runs with fresh gas/DB limits and `Db.changes().fullRescan`; its\nnamed `events.since` cursors still resume after successfully published batches.\nA crash before a cursor commit can repeat a batch, so processing must remain\nidempotent. Acknowledgements match a generation: an older run cannot clear a\nnewer continuation. The queue is bounded to 1024 identities and 256 KiB per\ntenant; a full queue fails explicitly. Removed/renamed methods do not inherit\nanother method's pending work.\n\nInclude a resident `@daemon` (an empty class is sufficient) and put materializer\ndatabases in shared source files compiled into both artifacts. The framework\nbuild rejects missing cold materializers when a hot artifact imports this API.\nRun the cold scheduler and use the same persistent ToilDB control storage for\nthe hot and cold workers. The native in-memory adapter is ephemeral; persistent ToilDB provides\nthe durable queue. Dev persists it with the configured DB snapshot. Updated\nnative host imports are required. Calls outside Derive, or with no deployed\n`@derive` identity, fail closed. `Db.runDerive` can also request a continuation\nwhen its names match a deployed materializer.\n",
19
- "background/README.md": "# Background work\n\nBackground work is code that runs **without a user waiting for it**: on a timer, once globally, or automatically after your data changes. toiljs gives you two tools for it, `@daemon` and `@derive`, and this page helps you pick the right one.\n\n## Why background work\n\nMost of your server code runs **because a user asked**: a browser hits a [route](../backend/rest.md) or calls an [RPC](../backend/rpc.md), your handler runs, and a response goes back. But some work does not belong on that path:\n\n- It should happen **on a schedule** (every hour, every night at 2am), not when a request happens to arrive.\n- It would be **too slow** to do inside a request, so you want it precomputed and ready.\n- It must happen **exactly once across the whole world**, not once per user and not once per server.\n\nThat is background work. In toiljs there are two kinds, and they solve two different problems.\n\n## The two tools\n\n```mermaid\nflowchart TD\n Q{What do you need?}\n Q -->|Run on a timer, or once globally| D[\"@daemon + @scheduled<br/>a single background worker\"]\n Q -->|Keep a fast read-view in sync with your data| V[\"@derive<br/>maintains a materialized View\"]\n D --> DD[\"e.g. nightly cleanup, hourly poll,<br/>periodic rollup\"]\n V --> VV[\"e.g. a leaderboard, a 'latest 10' feed,<br/>a home-page summary\"]\n```\n\n### `@daemon`: a scheduled, global worker\n\nA [daemon](./daemons.md) is one long-lived background worker for your whole app. It runs on a **schedule** you set (an interval like every 5 minutes, or a cron time like \"9:15 on weekdays\"), and there is exactly **one** of it worldwide at any moment (a \"singleton\"). Use it for work that is driven by **time** or that must run **once globally**:\n\n- clean up stale rows every night;\n- poll an external API every few minutes;\n- send a daily digest email;\n- roll up yesterday's numbers into a summary.\n\n### `@derive`: keep a read-view up to date\n\nA [derive](./derive.md) is not on a timer. It runs **automatically whenever the data it depends on changes**, and its job is to keep a precomputed **View** (a read-optimized copy of your data) fresh. Use it when a page needs data that is **expensive to compute on every read**, like a leaderboard or a \"latest 10 comments\" list, so the read itself stays a single cheap lookup:\n\n- fold an [events](../database/events.md) log into a \"latest N\" list;\n- total up [counters](../database/counters.md) into a scoreboard;\n- assemble a home-page summary from several sources.\n\n## Which one do I reach for?\n\n| Question | Use |\n| ----------------------------------------------------- | ------------ |\n| \"Run this every hour / at midnight.\" | `@daemon` |\n| \"Do this once for the whole app, not per server.\" | `@daemon` |\n| \"Poll or call an outside service on a schedule.\" | `@daemon` |\n| \"This page's data is too slow to compute per request.\"| `@derive` |\n| \"Keep a leaderboard / feed in sync as data changes.\" | `@derive` |\n\nA simple rule of thumb: if the trigger is **the clock**, use a `@daemon`. If the trigger is **a change to your data** and the goal is a fast read, use a `@derive`.\n\nThey also combine well. A `@daemon` might do a heavy nightly aggregation and write a summary row, while a `@derive` keeps a small live view fresh on every write. They are different tiers of the edge and are covered on their own pages.\n\n## `@job`: the widest database surface for background work\n\n`@daemon` and `@derive` decide **where and when** background code runs. `@job` answers a different question: **what a function is allowed to do to the database.** It is one of the ToilDB **function kinds** (the same family as `@query`, `@action`, and `@derive`), and it grants the **widest** data surface of them all.\n\nA **function kind** is a label the compiler puts on a backend function to gate which database operations it may issue. This is a safety rail: a read-only endpoint physically cannot write, and an expensive scan cannot run on the hot request path. The kinds line up from narrowest to widest:\n\n| Kind | Typical trigger | Point reads | **Scan** (`latest`, membership `list`) | Writes | `publish` a View |\n| ---------- | ------------------------- | ----------- | -------------------------------------- | ----------------- | ---------------- |\n| `@query` | a `@get` / plain `@remote`| yes | no | no | no |\n| `@action` | a `@post` / `@action` | yes | no | yes (bounded) | no |\n| `@derive` | your data changed | yes | yes | append / counter add only | yes |\n| `@job` | you drive it (background) | yes | yes | yes (all) | yes |\n\nA **scan** is a read that can fan out across many rows (like \"the newest 50 events\" via `events.latest`, or \"every member of this set\" via `membership.list`). Scans are **barred from request handlers** because a request must stay fast and bounded. `@derive` and `@job` run **off the request path**, so they are the only kinds allowed to scan.\n\n### When to reach for `@job`\n\nUse `@job` when a piece of background work needs **more** database power than the default:\n\n- it must **scan** (fold `events.latest`, walk `membership.list`), and/or\n- it must **publish a View** *while also* doing arbitrary writes (`create`, `patch`, `delete`). A `@derive` can publish a View but cannot `patch` or `delete` a record; a `@job` can do everything.\n\nWith **toilscript 0.1.65**, **toiljs 0.0.126**, and an edge host that supports daemon catalog v2, the compiler records `@job` on a `@daemon`'s `@scheduled` method and the host executes that tick with Job permissions and budgets. Tag a scheduled task `@job` when it needs that full surface (say, a nightly repair that scans a log, fixes rows, and republishes a summary View). A plain, **untagged** `@scheduled` method runs with the **`@action`** surface instead: point reads plus bounded writes, which is all most rollups and cleanups need.\n\n```ts\n@daemon\nclass Jobs {\n // A plain scheduled method: point reads + bounded writes (the @action surface).\n @scheduled('1h')\n rollup(): void { /* get a counter, patch a summary row */ }\n\n // A scheduled method that also needs SCANS and to PUBLISH a View: tag it @job.\n @scheduled('1d')\n @job\n nightlyRepair(): void {\n // @job unlocks scan-class reads (events.latest / membership.list)\n // and publishing a View, on top of ordinary reads and writes.\n }\n}\n```\n\n`onStart` always runs as Action. A helper tagged `@job` inherits its caller's runtime permissions; calling it from startup or an untagged scheduled method does not elevate the call. Job ticks carry a v2 daemon catalog, which older edge hosts reject at load time. Action-only daemons retain the v1 catalog and remain compatible.\n\n### `@job` versus `@derive`\n\nThey overlap (both run off the request path, both may scan, both may publish a View), but they are triggered differently and sized differently:\n\n- **`@derive`** is **change-triggered**: it re-runs automatically whenever its source data changes, and its narrow job is to keep one **View** in sync. It cannot `create` / `patch` / `delete` records (only append, counter-add, and publish). Reach for it when a read is too slow and you want it kept fresh on every write.\n- **`@job`** is **you-drive-it** background work (typically a `@scheduled` daemon method) with the **full** write surface. Reach for it when the work is clock-driven or one-off and needs to both scan and mutate freely.\n\n> **Rule of thumb.** Clock-driven and needs the full database surface: a `@job` (usually inside a `@daemon`). Change-driven and only maintains a View: a `@derive`. Clock-driven with modest reads and writes: a plain `@scheduled` method (no `@job` needed).\n\nFor the complete permission grid see the [function-kind matrix](../database/setup.md#how-access-is-gated-query-action-and-friends), and for the decorator itself see [every decorator](../concepts/decorators.md#database-function-kinds-data-access-policy).\n\n## Related\n\n- [Daemons and scheduled jobs](./daemons.md): `@daemon`, `@scheduled`, interval vs cron, and how a single global worker fails over safely.\n- [Derived views (`@derive`)](./derive.md): keeping a materialized View in sync with its source data.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): where daemons and request handlers each run on the edge.\n- [Views](../database/views.md) and [Events](../database/events.md): the database families a `@derive` reads from and writes to.\n",
20
+ "background/README.md": "# Background work\n\nBackground work is code that runs **without a user waiting for it**: on a timer, once globally, or automatically after your data changes. toiljs gives you two tools for it, `@daemon` and `@derive`, and this page helps you pick the right one.\n\n## Why background work\n\nMost of your server code runs **because a user asked**: a browser hits a [route](../backend/rest.md) or calls an [RPC](../backend/rpc.md), your handler runs, and a response goes back. But some work does not belong on that path:\n\n- It should happen **on a schedule** (every hour, every night at 2am), not when a request happens to arrive.\n- It would be **too slow** to do inside a request, so you want it precomputed and ready.\n- It must happen **exactly once across the whole world**, not once per user and not once per server.\n\nThat is background work. In toiljs there are two kinds, and they solve two different problems.\n\n## The two tools\n\n```mermaid\nflowchart TD\n Q{What do you need?}\n Q -->|Run on a timer, or once globally| D[\"@daemon + @scheduled<br/>a single background worker\"]\n Q -->|Keep a fast read-view in sync with your data| V[\"@derive<br/>maintains a materialized View\"]\n D --> DD[\"e.g. nightly cleanup, hourly poll,<br/>periodic rollup\"]\n V --> VV[\"e.g. a leaderboard, a 'latest 10' feed,<br/>a home-page summary\"]\n```\n\n### `@daemon`: a scheduled, global worker\n\nA [daemon](./daemons.md) is one long-lived background worker for your whole app. It runs on a **schedule** you set (an interval like every 5 minutes, or a cron time like \"9:15 on weekdays\"), and there is exactly **one** of it worldwide at any moment (a \"singleton\"). Use it for work that is driven by **time** or that must run **once globally**:\n\n- clean up stale rows every night;\n- poll an external API every few minutes;\n- send a daily digest email;\n- roll up yesterday's numbers into a summary.\n\n### `@derive`: keep a read-view up to date\n\nA [derive](./derive.md) is not on a timer. It runs **automatically whenever the data it depends on changes**, and its job is to keep a precomputed **View** (a read-optimized copy of your data) fresh. Use it when a page needs data that is **expensive to compute on every read**, like a leaderboard or a \"latest 10 comments\" list, so the read itself stays a single cheap lookup:\n\n- fold an [events](../database/events.md) log into a \"latest N\" list;\n- total up [counters](../database/counters.md) into a scoreboard;\n- assemble a home-page summary from several sources.\n\n## Which one do I reach for?\n\n| Question | Use |\n| ----------------------------------------------------- | ------------ |\n| \"Run this every hour / at midnight.\" | `@daemon` |\n| \"Do this once for the whole app, not per server.\" | `@daemon` |\n| \"Poll or call an outside service on a schedule.\" | `@daemon` |\n| \"This page's data is too slow to compute per request.\"| `@derive` |\n| \"Keep a leaderboard / feed in sync as data changes.\" | `@derive` |\n\nA simple rule of thumb: if the trigger is **the clock**, use a `@daemon`. If the trigger is **a change to your data** and the goal is a fast read, use a `@derive`.\n\nThey also combine well. A `@daemon` might do a heavy nightly aggregation and write a summary row, while a `@derive` keeps a small live view fresh on every write. They are different tiers of the edge and are covered on their own pages.\n\n## `@job`: the widest database surface for background work\n\n`@daemon` and `@derive` decide **where and when** background code runs. `@job` answers a different question: **what a function is allowed to do to the database.** It is one of the ToilDB **function kinds** (the same family as `@query`, `@action`, and `@derive`), and it grants the **widest** data surface of them all.\n\nA **function kind** is a label the compiler puts on a backend function to gate which database operations it may issue. This is a safety rail: a read-only endpoint physically cannot write, and an expensive scan cannot run on the hot request path. The kinds line up from narrowest to widest:\n\n| Kind | Typical trigger | Point reads | **Scan** (`latest`, membership `list`) | Writes | `publish` a View |\n| ---------- | ------------------------- | ----------- | -------------------------------------- | ----------------- | ---------------- |\n| `@query` | a `@get` / plain `@remote`| yes | no | no | no |\n| `@action` | a `@post` / `@action` | yes | no | yes (bounded) | no |\n| `@derive` | your data changed | yes | yes | append / counter add only | yes |\n| `@job` | you drive it (background) | yes | yes | yes (all) | yes |\n\nA **scan** is a read that can fan out across many rows (like \"the newest 50 events\" via `events.latest`, or \"every member of this set\" via `membership.list`). Scans are **barred from request handlers** because a request must stay fast and bounded. `@derive` and `@job` run **off the request path**, so they are the only kinds allowed to scan.\n\n### When to reach for `@job`\n\nUse `@job` when a piece of background work needs **more** database power than the default:\n\n- it must **scan** (fold `events.latest`, walk `membership.list`), and/or\n- it must **publish a View** *while also* doing arbitrary writes (`create`, `patch`, `delete`). A `@derive` can publish a View but cannot `patch` or `delete` a record; a `@job` can do everything.\n\nWith **toilscript 0.1.65**, **toiljs 0.0.126**, and an edge host that supports daemon catalog v2, the compiler records `@job` on a `@daemon`'s `@scheduled` method and the host executes that tick with Job permissions and budgets. Tag a scheduled task `@job` when it needs that full surface (say, a nightly repair that scans a log, fixes rows, and republishes a summary View). A plain, **untagged** `@scheduled` method runs with the **`@action`** surface instead: point reads plus bounded writes, which is all most rollups and cleanups need.\n\n```ts\n@daemon\nclass Jobs {\n // A plain scheduled method: point reads + bounded writes (the @action surface).\n @scheduled('1h')\n rollup(): void { /* get a counter, patch a summary row */ }\n\n // A scheduled method that also needs SCANS and to PUBLISH a View: tag it @job.\n @scheduled('1d')\n @job\n nightlyRepair(): void {\n // @job unlocks scan-class reads (events.latest / membership.list)\n // and publishing a View, on top of ordinary reads and writes.\n }\n}\n```\n\nAn unannotated `onStart` runs as Action. Annotate `onStart` itself with `@job`\nfor Job permissions at startup; this requires toilscript 0.1.66, toiljs 0.0.128,\nand a native host accepting daemon catalog v3. A helper tagged `@job` inherits\nits caller's runtime permissions, so calling it from Action startup or an\nuntagged tick does not elevate the call. Scheduled Job ticks use catalog v2\nunless Job startup requires v3. Daemons with Action startup and only Action\nticks retain v1. Older hosts reject unsupported catalogs at load time. See\n[startup with Job permissions](./daemons.md#startup-with-job-permissions).\n\n### `@job` versus `@derive`\n\nThey overlap (both run off the request path, both may scan, both may publish a View), but they are triggered differently and sized differently:\n\n- **`@derive`** is **change-triggered**: it re-runs automatically whenever its source data changes, and its narrow job is to keep one **View** in sync. It cannot `create` / `patch` / `delete` records (only append, counter-add, and publish). Reach for it when a read is too slow and you want it kept fresh on every write.\n- **`@job`** is **you-drive-it** background work (typically a `@scheduled` daemon method) with the **full** write surface. Reach for it when the work is clock-driven or one-off and needs to both scan and mutate freely.\n\n> **Rule of thumb.** Clock-driven and needs the full database surface: a `@job` (usually inside a `@daemon`). Change-driven and only maintains a View: a `@derive`. Clock-driven with modest reads and writes: a plain `@scheduled` method (no `@job` needed).\n\nFor the complete permission grid see the [function-kind matrix](../database/setup.md#how-access-is-gated-query-action-and-friends), and for the decorator itself see [every decorator](../concepts/decorators.md#database-function-kinds-data-access-policy).\n\n## Related\n\n- [Daemons and scheduled jobs](./daemons.md): `@daemon`, `@scheduled`, interval vs cron, and how a single global worker fails over safely.\n- [Derived views (`@derive`)](./derive.md): keeping a materialized View in sync with its source data.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): where daemons and request handlers each run on the edge.\n- [Views](../database/views.md) and [Events](../database/events.md): the database families a `@derive` reads from and writes to.\n",
20
21
  "cli/README.md": "# The toiljs CLI\n\nThe `toiljs` command is how you scaffold, run, build, self-host, and diagnose a toiljs app. This page lists every command and every flag, with copy-pasteable examples.\n\n## What it is\n\nWhen you install the `toiljs` package, it adds one executable to your project: `toiljs`. Everything you do day to day (start the dev server, produce a production build, check your setup) goes through it.\n\nYou almost never type the full path. A freshly scaffolded project already has npm scripts that call it, so you run `npm run dev` and `npm run build`. When you want a command that has no script (like `doctor` or `db`), run it with `npx`:\n\n```bash\nnpx toiljs doctor\n```\n\n`toiljs` needs **Node.js 24 or newer** (older versions will not run it).\n\n## Command overview\n\n| Command | What it does |\n| --- | --- |\n| `toiljs create [name]` | Scaffold a brand new toiljs app in a new folder. |\n| `toiljs dev` | Start the local development server with hot reload. |\n| `toiljs test` | Run Vitest unit or real-browser tests, installing missing tooling automatically. |\n| `toiljs build` | Produce the optimized production build (client bundle + server WebAssembly). |\n| `toiljs start` | Self-host the built app on a fast production HTTP server. |\n| `toiljs configure` | Turn styling features (Sass/Less/Stylus, Tailwind) on or off in an existing project. |\n| `toiljs doctor` | Diagnose your project setup and (with `--fix`) repair common wiring. |\n| `toiljs update` | Check npm for newer dependency versions and apply the ones you pick. |\n| `toiljs db <action>` | Inspect, reset, snapshot, or restore the local dev database. |\n| `toiljs generate auth` | Generate private auth keys and the matching client public key, preserving existing credentials. |\n| `toiljs help` | Print the built-in help. Also `--help` or `-h`. |\n| `toiljs --version` | Print the installed toiljs version. Also `-v`. |\n\nRun `toiljs help` any time to see this list in your terminal.\n\n## Global behavior\n\nA few things apply to every command.\n\n- **`--root <dir>`**: run the command against a project in another directory instead of the current one. Every command accepts it.\n- **Automatic update check**: on every run (including `npm run dev`, which calls the CLI under the hood), toiljs quietly asks the npm registry whether a newer `toiljs` exists and prints a one-line notice on stderr if you are behind. It never blocks or slows the command in a meaningful way (the answer is cached for an hour and the network call is capped at two seconds). To turn it off, set the environment variable `TOILJS_NO_UPDATE_CHECK=1`. It also respects the common `NO_UPDATE_NOTIFIER` and `CI` variables.\n\n```bash\n# Run any command against a project in another folder.\ntoiljs build --root ./apps/marketing\n\n# Silence the \"newer version available\" notice.\nTOILJS_NO_UPDATE_CHECK=1 toiljs dev\n```\n\n## `toiljs generate auth`\n\n```bash\ntoiljs generate auth\ntoiljs generate auth --root ./apps/marketing\n```\n\nSaves private authentication keys in `.env.secrets` (mode `0600`) and\n`VITE_AUTH_KEM_PUBLIC_KEY` in `.env`, and adds both files to `.gitignore`. It preserves\nunrelated settings and existing credentials, and can recover a missing public key from the\nexisting private key. It refuses invalid or mismatched keys rather than rotating them.\nNo secret values are printed. Use this for initial setup or completing an existing key set.\n\nPin the public key in your client's auth options, build with that `.env` on the build machine,\nand install the private settings in your backend's secure env store. See\n[auth configuration](../auth/configuration.md) for the client snippet and toil-backend deployment steps.\n\n## `toiljs create`\n\nScaffolds a new project into a new folder. By default it is interactive: it asks a short series of questions (project name, template, styling, and so on), then writes the files and installs dependencies. Pass flags to skip questions, or `-y` to accept every default and run with no questions at all.\n\n```bash\n# Interactive: answer the prompts.\nnpx toiljs create\n\n# Give it a name up front.\nnpx toiljs create my-app\n\n# Fully non-interactive (great for scripts and CI).\nnpx toiljs create my-app --yes --template app --style css\n```\n\n### What it sets up\n\nEvery new project comes wired for you: the enforced TypeScript 7, Oxlint + tsgolint, Prettier, and Vitest unit/browser/coverage presets, file-based routing, a `toil.config.ts`, a `toilconfig.json` (the server compiler settings), a `.gitignore`, and the native TypeScript 7 editor settings. It also scaffolds a `server/migrations/` folder (where ToilDB schema migrations live) and, unless you opt out, a set of AI assistant helper files.\n\nThe scaffolded `package.json` includes these scripts:\n\n| Script | Runs |\n| --- | --- |\n| `npm run dev` | `toiljs dev` |\n| `npm run build` | `toiljs build` |\n| `npm run build:server` | `toiljs build --server` |\n| `npm run lint` | `oxlint --type-aware client` |\n| `npm run typecheck` | `tsc --noEmit` |\n| `npm test` | `toiljs test` |\n| `npm run test:watch` | `toiljs test --watch` |\n| `npm run test:browser` | `toiljs test --browser` |\n| `npm run test:all` | `toiljs test --all` |\n| `npm run test:coverage` | `toiljs test --all --coverage` |\n| `npm run format` | `prettier --write ...` |\n\n### Generated docs and AI-assistant pointers\n\nEvery project carries a full copy of this documentation set at `.toil/docs/`. You do not maintain it: toiljs regenerates it from the installed toiljs version on every `toiljs dev` and `toiljs build`, so it always matches the version you are on. Do not edit those files by hand (your changes are overwritten on the next dev or build).\n\nUnless you opt out, `toiljs create` also writes small **pointer files** at the project root that tell AI coding assistants to read `.toil/docs/` before touching the project: `CLAUDE.md` (Claude Code), `AGENTS.md` (Codex and others), `.cursor/rules/toiljs.mdc` (Cursor), and `.github/copilot-instructions.md` (GitHub Copilot). These are written once, committed, and yours to edit. Control them with `--ai` / `--no-ai` (when you pass neither, `create` asks).\n\n### create options\n\n| Flag | Meaning |\n| --- | --- |\n| `[name]` | The project folder name (a positional argument). If omitted, you are asked. |\n| `-t, --template <app\\|minimal>` | `app` is the full starter (landing page, layout, styles, demo routes). `minimal` is just a layout and a home route. Default `app`. |\n| `--style <css\\|sass\\|less\\|stylus>` | Which CSS flavor to set up. Default `css` (plain CSS). |\n| `--tailwind` / `--no-tailwind` | Add or skip Tailwind CSS (v4). Off by default. |\n| `--ai` / `--no-ai` | Include or skip AI assistant files (like `CLAUDE.md`). When omitted, you are asked. |\n| `--images` / `--no-images` | Enable or skip build-time image optimization. On by default. |\n| `--git` / `--no-git` | Initialize a git repository. When omitted, you are asked (default yes). |\n| `--install` / `--no-install` | Install dependencies after scaffolding. When omitted, you are asked (default yes). |\n| `--pm <npm\\|pnpm\\|yarn\\|bun>` | Which package manager to install with. Default `npm`. |\n| `-y, --yes` | Accept all defaults and skip every prompt. |\n\nFor a walkthrough, see [Create a project](../getting-started/create-project.md).\n\n## `toiljs test`\n\nRuns unit tests by default. All templates include the dependencies, configuration,\nand runnable unit and React browser examples. Existing projects get missing tooling\ninstalled automatically; custom configs, scripts, and existing files are preserved.\n\n```bash\nnpx toiljs test\nnpx toiljs test --browser\nnpx toiljs test --all --coverage\nnpx toiljs test --watch\nnpx toiljs test Greeting --reporter=verbose\n```\n\n| Flag | Meaning |\n| --- | --- |\n| `--browser` | Run the native browser project with Chrome and WebdriverIO. |\n| `--all` | Run both native projects. Cannot be combined with `--browser`. |\n| `--watch`, `-w` | Watch for changes instead of running once. |\n| `--coverage` | Collect V8 coverage; reports go to `coverage/`. |\n| `--root <dir>` | Run against a project in another directory. |\n\nOther options and file filters pass through to Vitest. An explicit `--project`\noverrides native selection. Custom configs keep their own project selection, with\n`--browser` forwarded to Vitest. Test failures preserve a nonzero shell exit status.\nSee [Testing and coverage](../frontend/testing.md) for setup, browser binaries,\nframework globals, coverage reports, and configuration.\n\n## `toiljs dev`\n\nStarts the local development server with hot reload, so you edit a file and the browser updates in place. This is the command you leave running while you build.\n\n```bash\nnpm run dev\n# or, to pick a port:\nnpx toiljs dev --port 4000\n```\n\n### What the dev server emulates\n\nThe whole point of the dev server is to run your app locally the same way the real Dacely edge runs it in production, so what you see locally is what you ship. It emulates three things:\n\n1. **The edge.** For a project with a server (any project with a `toilconfig.json`), a small local HTTP server takes the public port and dispatches incoming requests into your compiled `server.wasm` using the exact same request envelope the production edge uses. Anything your server does not claim (page routes, static assets, the hot-reload websocket) is proxied to Vite behind the scenes. So your React frontend and your WebAssembly backend run together, on one URL, exactly like production.\n2. **The database.** ToilDB runs in-process as a local emulator. Every family (documents, views, unique, events, counters, membership, capacity) works, and the data is written to `.toil/devdata.json` so it survives restarts. You manage that file with [`toiljs db`](#toiljs-db).\n3. **The host functions.** The platform services your server code calls (email, environment variables and secrets, time, crypto, rate limiting, auth) are wired up locally so they behave like the edge. Email actually sends if you configure a provider (see [Email](../services/email.md)).\n\nA **client-only** project (no `toilconfig.json`) just gets the plain Vite dev server on your port, unchanged.\n\n### How hot reload works\n\n```mermaid\nflowchart TD\n E[\"You edit a file\"] --> Q{\"Which file?\"}\n Q -->|\"client/ (React, CSS)\"| V[\"Vite hot-swaps it in the browser\"]\n Q -->|\"server/ (a @rest / @data / @service file)\"| S[\"toilscript recompiles the server\"]\n S --> G[\"shared/server.ts is regenerated\"]\n G --> V2[\"Vite hot-swaps the new typed client\"]\n S --> W[\"the dev server hot-swaps the new server.wasm\"]\n V --> B[\"Browser updates, no full reload\"]\n V2 --> B\n W --> B\n```\n\nClient edits go straight through Vite's hot module replacement. Server edits trigger a toilscript rebuild: toiljs recompiles your backend, regenerates `shared/server.ts` (the typed client the browser imports to call your server), and hot-swaps the recompiled WebAssembly, all without you touching the browser. Rebuilds are debounced (grouped over about 150 milliseconds) so a \"save all\" or a formatter pass does not trigger a storm of builds.\n\nIf your project has an `emails/` folder, the dev server also prints an email-preview URL at `/__toil/emails`.\n\n### dev options\n\n| Flag | Meaning |\n| --- | --- |\n| `--port <n>` | Port to listen on. Default `3000` (or `client.port` from your config). |\n| `--root <dir>` | Run against a project in another directory. |\n\nPress `Ctrl+C` to stop. toiljs restores your terminal and force-exits even if a native listener is slow to close, so you never end up with an orphaned dev server rebuilding in the background.\n\n## `toiljs build`\n\nProduces the optimized production build. Run this before you deploy or before `toiljs start`.\n\n```bash\nnpm run build\n# or build only the server:\nnpx toiljs build --server\n```\n\n### What it produces\n\nA full build runs in a careful order so the pieces line up:\n\n```mermaid\nflowchart LR\n A[\"Your project\"] --> S[\"1. Compile the server<br/>(toilscript)\"]\n S --> W[\"build/server/release.wasm\"]\n S --> R[\"shared/server.ts<br/>(typed client, regenerated)\"]\n R --> C[\"2. Bundle the client<br/>(Vite)\"]\n C --> O[\"build/client/<br/>(HTML, JS, CSS, assets)\"]\n C --> X[\"3. Prerender + SEO<br/>(SSG pages, robots.txt,<br/>sitemap.xml, llms.txt)\"]\n```\n\n1. **The server is built first.** toilscript compiles every decorated server file (not just the entry) into `build/server/release.wasm`, and regenerates `shared/server.ts`. Doing this first means the client always bundles against a current, correct typed server client. A project that also declares `@stream` or `@daemon` surfaces compiles those into their own artifacts (`release-stream.wasm`, `release-cold.wasm`).\n2. **The client is bundled** by Vite into `build/client/` (your HTML, JavaScript, CSS, and optimized assets). The dev toolbar and error overlay are stripped out of the production bundle.\n3. **Static pages and SEO files are generated**: any route that opts into static generation is prerendered to HTML, and if you configured `client.seo`, toiljs writes `robots.txt`, `sitemap.xml`, and `llms.txt`. Routes that opt into server-side rendering get their HTML-with-holes templates baked for the edge.\n\n### build options\n\n| Flag | Meaning |\n| --- | --- |\n| `--server` | Build **only** the server (recompile the wasm and regenerate `shared/server.ts`), and skip the client bundle. Fast when you only touched backend code. This is what `npm run build:server` runs. |\n| `--root <dir>` | Run against a project in another directory. |\n\nA client-only project (no `toilconfig.json`) skips step 1 and just bundles the client.\n\n## `toiljs start`\n\nSelf-hosts the app you just built, on a fast production HTTP server (hyper-express, backed by uWebSockets.js). It serves your static client, runs your `server.wasm` for dynamic requests, does server-side rendering, supports daemons, and exposes a `/_toil` websocket channel. Use it to run your app on your own machine or server instead of deploying to the Dacely edge.\n\n```bash\nnpm run build # start needs a build to serve\nnpx toiljs start\nnpx toiljs start --port 8080 --host 0.0.0.0 --threads 4\n```\n\n`start` fails fast if there is no build yet (it looks for `build/client/index.html`), so run `toiljs build` first.\n\n### start options\n\n| Flag | Meaning |\n| --- | --- |\n| `--port <n>` | Port to listen on. Default `3000` (or `client.port`). |\n| `--host <host>` | Address to bind. Default `127.0.0.1` (loopback only). Pass `0.0.0.0` to accept connections from other machines. |\n| `--threads <n>` | Number of HTTP worker processes. Default is automatic (one per available CPU). Pass `1` to disable the worker pool. `--workers` is an accepted alias. This can also be set as `server.threads` in your config. |\n| `--root <dir>` | Run against a project in another directory. |\n\n## `toiljs configure`\n\nToggles a project's client styling features (the CSS preprocessor and Tailwind) after the fact, on an existing app. It detects your current setup, asks what you want, then rewrites the stylesheets and your app entry's imports, edits `package.json`, and syncs `node_modules` so removed packages are actually uninstalled.\n\n```bash\n# Interactive.\nnpx toiljs configure\n\n# Non-interactive: switch to Sass and turn Tailwind on.\nnpx toiljs configure --style sass --tailwind\n```\n\n### configure options\n\n| Flag | Meaning |\n| --- | --- |\n| `--style <css\\|sass\\|less\\|stylus>` | Switch the CSS preprocessor. |\n| `--tailwind` / `--no-tailwind` | Turn Tailwind on or off. |\n| `--images` / `--no-images` | Turn build-time image optimization on or off (sets `client.images` in your config). |\n| `--no-install` | Edit the files but do not run the package manager. You then run install yourself. |\n| `--root <dir>` | Run against a project in another directory. |\n\nPassing any of `--style`, `--tailwind`, or `--images` makes the command non-interactive (it skips the prompts you did not answer with a flag). See [Styling](../frontend/styling.md) for the full picture.\n\n## `toiljs doctor`\n\nRead-only project diagnostics. It gathers facts from disk (your `package.json`, lockfiles, the resolved config, your app entry, `index.html`, your routes, and the server target), runs a set of checks, and prints a grouped report. It never changes anything unless you pass `--fix`, and it never crashes on a partial or non-toiljs project (missing pieces just become warnings or failures). It exits with a non-zero status when any check **fails** (warnings do not fail), so it is safe to run in CI.\n\n```bash\n# Human-readable report.\nnpx toiljs doctor\n\n# Machine-readable, for CI.\nnpx toiljs doctor --json\n\n# Auto-repair the common wiring.\nnpx toiljs doctor --fix\n```\n\n### What it checks\n\nThe report is grouped:\n\n| Group | Example checks |\n| --- | --- |\n| **Environment** | Node.js version, that `toiljs` and its peer dependencies (React and so on) are installed and new enough, that TypeScript 7 is installed and its declared range stays within 7.x, that Oxlint and tsgolint are configured for type-aware linting, that a lockfile exists, and that your scripts do not wrap `toiljs` in a stray `npx`. |\n| **Project + routing** | The `client/` and `routes/` folders exist, `index.html` has a `<div id=\"root\">`, your app entry calls `mount(...)` with the `slots` argument, at least one route exists, no two routes collide on the same URL, and no asset paths are written in a way that 404s on nested routes. |\n| **Config + assets** | Your `toil.config` loads, the base path is well formed, `client.seo` has a `url` if SEO is configured, and your styling packages are actually installed. |\n| **Testing** | Actual installed Vitest, browser provider, WebdriverIO, and V8 coverage versions; compatible declared ranges; matching Vitest/coverage releases; config presence and unit/browser/watch/coverage scripts. Missing testing is a warning for legacy apps, while broken configured tooling fails. |\n| **Server / WASM** | The `toilconfig.json` and its entry files exist, `toilscript` is installed, a compiled `.wasm` exists, the typed-RPC wiring is in place, your `@rest` controllers are actually dispatched, the Prettier and editor plugins are wired, and a `migrations/` folder exists. |\n| **Security** | If your server uses auth, whether `AUTH_SESSION_SECRET` is set (an unset secret means sessions fall back to a published dev key, which is forgeable). |\n\n### What `--fix` repairs\n\n`--fix` migrates unsupported or missing TypeScript declarations to `^7.0.2`, enables the native TypeScript editor, and repairs testing setup in any project. Testing repairs add missing packages and scripts, migrate unsupported registry versions, align Vitest and coverage, add the preset and examples when there is no custom config, include tests in plain JSON TypeScript configs, and ignore test reports. Existing custom configs, nonempty scripts, explicit package sources, and existing files are preserved; commented TypeScript configs get a manual repair note. It does not install packages or launch a browser. The rest only touch a server project (one with a `toilconfig.json`), repairing the wiring that is easy to get wrong or that older projects predate:\n\n- adds `--rpcModule shared/server.ts` to your server build scripts,\n- adds `shared` and the `shared/*` path alias to `tsconfig.json`,\n- adds `shared/server.ts` to `.gitignore`,\n- lifts the `toilscript` version floor if it is too old,\n- adds the `toiljs/prettier-plugin` to your Prettier config (so Prettier does not choke on server decorators),\n- removes the legacy toilscript JavaScript language-service plugin, which cannot run in the TypeScript 7 native language server; `toiljs build --server` provides the WebAssembly dialect diagnostics,\n- refreshes the editor-only server globals declaration file.\n\nIt is idempotent: it only writes files it actually needs to change, and it tells you which ones changed and which need a manual edit (for example a `tsconfig.json` that contains comments). If it changed `package.json`, run your installer afterward.\n\n### doctor options\n\n| Flag | Meaning |\n| --- | --- |\n| `--json` | Emit machine-readable JSON instead of the human report (the banner is suppressed so stdout stays valid JSON). |\n| `--fix` | Repair testing, TypeScript, editor, and server wiring in place, as above. |\n| `--root <dir>` | Run against a project in another directory. |\n\n## `toiljs update`\n\nA friendly wrapper over `npm-check-updates`. It checks the registry for newer versions of your dependencies, groups them by how big the jump is (major, minor, patch), lets you pick which to apply (or `-y` to apply all), bumps `package.json`, and runs your package manager's install. It also makes sure your `server/migrations/` folder exists and adds missing testing setup when updates are applied. `--yes` repairs and installs missing testing even when no dependency upgrades are available. Custom configs and scripts are preserved; declining updates leaves testing untouched. Native test updates stay within supported versions, and selecting either Vitest or V8 coverage updates both to a matching release. `npm-check-updates` runs via `npx`, so it never becomes a permanent dependency of your project.\n\nTypeScript updates must stay within supported **7.x** releases. Older and future compiler majors,\nunbounded ranges, and prereleases are withheld. An older project is offered the latest 7.x migration\neven with `--target patch`. Select that migration before applying other updates. The command writes\nthe exact reviewed versions before installing, so a second registry query cannot substitute a\ndifferent compiler major.\n\n```bash\n# Interactive picker.\nnpx toiljs update\n\n# Apply everything, non-interactively.\nnpx toiljs update --yes\n\n# Only patch-level updates.\nnpx toiljs update --target patch\n```\n\n### update options\n\n| Flag | Meaning |\n| --- | --- |\n| `-y, --yes` | Apply all available updates without the picker. |\n| `--target <latest\\|minor\\|patch\\|newest\\|greatest>` | How far to bump. Default `latest`. |\n| `--root <dir>` | Run against a project in another directory. |\n\n## `toiljs db`\n\nManages the local dev database: the on-disk ToilDB store your dev server writes to `.toil/devdata.json`. Use it to inspect data, wipe a corrupt state, save a snapshot to share as a fixture, or restore one. The snapshot is exactly the JSON the dev database uses, so an exported file imports cleanly.\n\n```bash\n# See what is stored.\nnpx toiljs db status\n\n# Wipe all dev data.\nnpx toiljs db reset\n\n# Save a snapshot (to a file, or to stdout if you omit the file).\nnpx toiljs db export fixture.json\n\n# Restore a snapshot.\nnpx toiljs db import fixture.json\n\n# Print the on-disk path (scriptable).\nnpx toiljs db path\n```\n\n### db actions\n\n| Action | What it does |\n| --- | --- |\n| `status` (alias `info`) | Show the database path, its size, and per-family row counts. |\n| `reset` (alias `purge`) | Delete all dev data (removes `devdata.json`). |\n| `export [file]` | Write a formatted snapshot to `file`, or to stdout if you omit it (pipe-friendly). |\n| `import <file>` | Replace the dev database with the snapshot in `file`. It refuses a file that is not a valid snapshot. |\n| `path` | Print the `devdata.json` path and nothing else. |\n\nThe dev database is per-project and lives under `.toil/`, which is gitignored. See [Database setup](../database/setup.md) for what actually populates it.\n\n## The dev, build, and deploy flow\n\nHere is how the commands fit together across your workflow.\n\n```mermaid\nflowchart LR\n subgraph Develop\n D[\"toiljs dev<br/>(hot reload, local edge + DB)\"]\n end\n subgraph Ship\n B[\"toiljs build<br/>(client bundle + server.wasm)\"]\n end\n subgraph Run\n ST[\"toiljs start<br/>(self-host locally)\"]\n DP[\"deploy to the Dacely edge\"]\n end\n D --> B\n B --> ST\n B --> DP\n```\n\n- **Develop** with `toiljs dev`. Everything runs locally and reloads as you type.\n- **Ship** with `toiljs build`. This produces the artifacts: the client bundle in `build/client/` and the server WebAssembly in `build/server/`.\n- **Run** the build two ways: `toiljs start` self-hosts it on your own machine, or you deploy the same build to the Dacely edge to serve it worldwide.\n\n## Gotchas\n\n- **`start` needs a build.** `toiljs start` serves what is in `build/`. Run `toiljs build` first, or it exits with an error.\n- **Run `toiljs`, not `npx toiljs`, inside npm scripts.** Under `npm run`, `node_modules/.bin` is already on your PATH, so an extra `npx` layer is redundant and can leave your terminal in a broken input mode after `Ctrl+C`. `doctor` warns about this; the scaffold gets it right.\n- **`--host` and `--threads` are `start`-only.** `toiljs dev` always binds locally and does not take `--host` or `--threads`.\n- **`--server` builds the backend only.** Use it while iterating on server code, but run a full `toiljs build` before you deploy so the client bundle is current.\n- **The update notice is not an error.** The \"newer toiljs available\" line is informational and prints to stderr. Set `TOILJS_NO_UPDATE_CHECK=1` to hide it.\n\n## Related\n\n- [Installation](../getting-started/installation.md) and [Create a project](../getting-started/create-project.md)\n- [Project structure](../getting-started/project-structure.md)\n- [Configuration reference (`toil.config.ts`)](../concepts/config.md)\n- [Styling](../frontend/styling.md)\n- [Database setup](../database/setup.md) and the [database overview](../database/README.md)\n- [Compute tiers (L1 to L4)](../concepts/tiers.md)\n",
21
- "concepts/ai-guide.md": "# Writing toiljs correctly\n\nThis is a fast, high-signal cheat-sheet for writing toiljs and toilscript code that compiles and behaves. It is aimed at AI assistants generating code (and at humans in a hurry): the patterns to follow, the mistakes to avoid, and a link to the deep page whenever you need more. It does not re-teach the framework; each section points you at the authoritative doc.\n\n## Project shape\n\nA toiljs project has three top-level folders, and knowing which one a file belongs to tells you which rules apply:\n\n- **`client/`**: your React app that runs in the browser. Pages live under `client/routes/`, one file per URL, and each route file `export default`s its component. See [Frontend](../frontend/README.md) and [Routing](../frontend/routing.md).\n- **`shared/`**: a generated typed bridge (`shared/server.ts`) that lets the browser call the backend with full types. It is regenerated on every build, so **never hand-edit it**.\n- **`server/`**: your backend, written in TypeScript but compiled by **toilscript** to WebAssembly. It runs on the Dacely edge, not in Node or the browser. See [Backend](../backend/README.md).\n\nMost code runs on the L1 request tier. Long-lived connections (`@stream`) and scheduled work (`@daemon`) are opt-in tiers in their own entry files. See [Compute tiers](./tiers.md).\n\n## Client rules (the browser, React side)\n\n**Call the backend only through the generated `Server` client.** This is the number one rule. Use `Server.REST.<controller>.<route>(args)` for `@rest` HTTP controllers, or `Server.<service>.<method>(args)` / `Server.<remote>(args)` for RPC. Raw `fetch` to your own backend throws away the type safety, the argument and result decoding, and the binary wire codec, and it silently breaks when a route is renamed. `fetch` is only for third-party URLs (an external API, a CDN). See [Fetching data](../frontend/data-fetching.md).\n\n```ts\n// WRONG: raw fetch to your own backend\nawait fetch('/account/session', { method: 'POST' });\n\n// RIGHT: the typed client (renames become compile errors; args + result typed)\nawait Server.REST.account.session();\n```\n\n**Use the ambient `Toil.*` globals with no import.** `Toil` is the `toiljs/client` package exposed as a global and typed via a generated `toil-env.d.ts`, so it autocompletes with no import: `Toil.Link` / `Toil.NavLink` for navigation, `Toil.useParams`, `Toil.useLoaderData`, `Toil.Image`, `Toil.useHead` / `Toil.Head`, `Toil.Form` / `Toil.useAction`, and more. `Server` and `parseError` are also bare globals; `FastMap`, `FastSet`, `DataWriter`, and `DataReader` are bare globals too (write `new DataWriter()`, not `new Toil.DataWriter()`). Full index: [The Toil global](../frontend/toil-global.md).\n\n**Load page data with a `loader`, not a `useEffect` fetch.** A route file exports a `loader`, and the component reads its result with `Toil.useLoaderData`. The loader runs on navigation in parallel with the route chunk, integrates with `loading.tsx`, caching, and SSR hydration. A `useEffect` fetch runs only after mount (slower, invisible to the server).\n\n```tsx\n// client/routes/blog/[id].tsx\nexport const loader = async ({ params }: Toil.LoaderArgs) => {\n return Server.REST.blog.get({ params: { id: params.id } });\n};\n\nexport default function BlogPost() {\n const post = Toil.useLoaderData<typeof loader>();\n return <article><h1>{post.title}</h1></article>;\n}\n```\n\n**Mutate with `Toil.useAction` or `<Toil.Form>`, then revalidate.** Both track pending and error state and refetch the affected loader data on success, so the page updates without a manual refetch. Use `<Toil.Form>` for form submits, `useAction` for anything else (a delete button, a toggle). Reach for `Toil.revalidate()` / `router.revalidate()` after a write that these do not cover.\n\n**Per-route SEO with `export const metadata`** (or `Toil.useHead` / `<Toil.Head>` from inside a component). Opt a route into edge SSR with `export const ssr = true`. See [Metadata and SEO](../frontend/metadata.md) and [Rendering and SSR](../frontend/rendering.md).\n\n**Typed hrefs.** `Toil.Link` `href`, `Toil.navigate`, and `router.push` are all type-checked against your real routes, so a typo is a compile error. Use `Toil.href(str)` only when a URL is assembled from data and TypeScript cannot prove it is a real route. See [Navigation](../frontend/navigation.md).\n\n**`getUser()` on the client is display-only.** It reads a readable session cookie with no network call, so it is instant but **forgeable**. Use it to render \"logged in as ...\", never to gate real access. The authoritative check is a server route guarded with `@auth`. See [Auth usage](../auth/usage.md).\n\n## Server rules (toilscript, compiles to WASM)\n\nThe decorators, each doing one job (full list in [Decorators](./decorators.md)):\n\n- **`@data`** on a class: generates the binary and JSON codec so the value can cross the wire and the database. Every field needs a default; field order **is** the binary layout, so add new fields at the end. See [Data types](../backend/data.md).\n- **`@rest('name')`** on a class mounts an HTTP controller at `/name`; **`@get`/`@post`/`@put`/`@del`/`@patch`** on its methods declare routes (`@del`, not `@delete`, which is reserved). See [REST](../backend/rest.md).\n- **`@service`** + **`@remote`** expose typed RPC callable from your own frontend as `Server.<service>.<method>()`. See [RPC](../backend/rpc.md).\n- **`@user`** declares the authenticated-user shape and enables `AuthService.getUser()`. **Exactly one `@user` per project.** **`@auth`** guards a route or a whole `@rest` class. See [Auth](../auth/README.md).\n- **`@ratelimit(strategy, limit, window)`** caps how often a caller may hit a route, rejected at the edge before your code runs. See [Security](./security.md).\n- **`@database`** + **`@collection`** declare a ToilDB schema (below).\n\n```ts\n@rest('players')\nclass Players {\n @get('/:id')\n public get(ctx: RouteContext): Response {\n const id = ctx.param('id');\n return Response.json(`{\"id\":\"${id}\"}`);\n }\n}\n```\n\n**`@auth` rejects with 401 before your handler runs.** So inside an `@auth`-guarded handler, `AuthService.getUser()!` is guaranteed non-null and safe to assert. Without `@auth`, `getUser()` can be null, so null-check it instead. Either way the server re-verifies the signed session, so it (not the client cookie) is the real authorization boundary.\n\n```ts\n@auth\n@get('/settings')\npublic settings(): Response {\n const user = AuthService.getUser()!; // safe: @auth guarantees a session\n return Response.text('hi ' + user.username);\n}\n```\n\n**Server code is a strict, WASM-targeted dialect (AssemblyScript), not full TypeScript.** The real constraints, verified against the toilscript standard library:\n\n- **Use explicit value types**, never `number`: `i32` / `u32` / `i64` / `u64` / `f64` (and `i8`/`u8`/`i16`/`u16`/`f32`, plus `u128`..`u256`), `bool`, `string`, `Uint8Array`. Plain `number` resolves to `f64`, which is wrong for ids and counts. Integer math **wraps** on overflow (it never throws), and integer `/` truncates. See [The type system](./types.md).\n- **No `any`.** Every value has a concrete type; that is what lets it compile to WASM.\n- **No arbitrary npm.** Only the toilscript standard library plus the toiljs host APIs.\n- **Use `null`, not `undefined`** for \"no value\" (`T | null`, narrowed with `if (x != null)` or a `!` assertion).\n- **No usable built-in `RegExp`** (it is a host stub that throws). Parse strings by hand.\n- **Structured values are `@data` classes, not object literals.** Encode and decode raw binary with `DataWriter` / `DataReader` (imported on the server from the `data` module: `import { DataWriter, DataReader } from 'data';`). For dynamic JSON, use the ambient `JSON` value tree.\n- **Read config with `Environment.get(key)` and secrets with `Environment.getSecure(key)`** (each returns `string | null`; the two buckets are disjoint so a secret can never leak through `get`). See [Environment](../services/environment.md).\n- **Return a runtime `Response`** (`Response.json` / `.text` / `.html` / `.bytes` / `.notFound` / ...), or return a `@data` value and let toiljs serialize it.\n\n**ToilDB has seven collection families; pick the one that matches the job** (do not force everything into one). Declare each as a `static` `@collection` field on a `@database` class, typed by its family, and reach it statically (`AppDb.users.get(...)`). See [The database](../database/README.md) and [Setup](../database/setup.md).\n\n- **`Documents<K,V>`**: the default record store, looked up by id (users, posts, orders).\n- **`Unique<K,V>`**: a globally one-of-a-kind claim (usernames, emails, slugs).\n- **`Counter<K>`**: a running total many callers bump at once (likes, views); `add` a delta only.\n- **`Events<K,V>`**: an append-only log kept in order (feeds, audit trails).\n `get(key, eventId)` reads an `appendOnce` event by ID; `last(key)` reads the\n newest event. Both are request-safe and return `V | null`; check `Db.lastError()`\n immediately on null. `latest`/`since` are background scans. A `last` followed by\n an append is not atomic; duplicate IDs do not replace existing events. See\n [Events](../database/events.md#get-and-last).\n- **`Capacity<K>`**: a limited quantity handed out without overselling (tickets, seats).\n- **`Membership<K,M>`**: sets of who belongs to what (followers, tags, room members).\n- **`View<K,V>`**: a precomputed read-optimized snapshot (leaderboards, home pages).\n\n**Data access is gated by function kind.** A `@get` route is a read-only **Query**; a `@post` route is an **Action** (may write); a plain `@remote` defaults to read-only Query, so add **`@action`** to let it write. Scans (`events.latest`, `membership.list`) are barred from request handlers: do them in a `@derive` and have the request read the resulting `View`. The compiler enforces this and the edge re-checks it.\n\n## Common mistakes\n\nA short do-not list. Every one of these is a real, avoidable error:\n\n- **Raw `fetch` to your own backend.** Go through `Server.*` instead.\n- **Importing `Toil.*`.** They are ambient globals; importing them is wrong.\n- **Fetching page data in a `useEffect`.** Use a route `loader` + `Toil.useLoaderData`.\n- **A plain `<a>` for in-app links.** Use `Toil.Link` (a bare `<a>` triggers a full reload).\n- **More than one `@user`.** Exactly one per project.\n- **Trusting client `getUser()` for authorization.** It is display-only and forgeable; enforce on the server with `@auth`.\n- **`any`, `number`, or `RegExp` in server code.** Use explicit value types; there is no usable `RegExp`.\n- **Reordering `@data` fields** (or changing a field type) on a stored type. Field order is the layout; add at the end and use `@migrate` to evolve. See [Data types](../backend/data.md).\n- **Writing from a plain `@remote` or `@get`.** Reads are the default; a write needs `@action`.\n- **Calling a scan (`events.latest`, `membership.list`) from a request handler.** Do it in a `@derive`.\n- **Hand-editing `shared/server.ts` or `.toil/`.** They are generated; rebuild instead.\n\n## Where to go deeper\n\n- Concepts: [Decorators](./decorators.md), [Type system](./types.md), [Security](./security.md), [Compute tiers](./tiers.md).\n- Backend: [Overview](../backend/README.md), [REST](../backend/rest.md), [RPC](../backend/rpc.md), [Data types](../backend/data.md).\n- Frontend: [Overview](../frontend/README.md), [Fetching data](../frontend/data-fetching.md), [Routing](../frontend/routing.md), [Navigation](../frontend/navigation.md), [The Toil global](../frontend/toil-global.md).\n- Database: [ToilDB overview](../database/README.md), [Setup](../database/setup.md).\n- Auth: [Overview](../auth/README.md), [Usage](../auth/usage.md).\n- Services: [Environment](../services/environment.md), [Rate limiting](../services/ratelimit.md).\n</content>\n</invoke>\n",
22
- "concepts/config.md": "# Configuration (`toil.config.ts`)\n\n`toil.config.ts` is the one file that configures your whole toiljs app: the client (React/Vite) side and the server (WebAssembly) side. Every field is optional and has a sensible default, so most projects keep it tiny.\n\n## The shortest possible config\n\nA scaffolded project ships something like this:\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n // Optimize images at build time (resize and compress imported images).\n images: true,\n },\n});\n```\n\n`defineConfig` does not do anything at runtime: it is an identity helper that gives you full editor autocomplete and type-checking for the config shape. Always wrap your config in it.\n\nAn empty config is valid too. `export default defineConfig({})` gives you a working app with all defaults.\n\n## Where the file lives\n\ntoiljs looks in your project root for the first file that matches, in this order:\n\n```\ntoil.config.ts toil.config.mts toil.config.js toil.config.mjs\ntoiljs.config.ts toiljs.config.mts toiljs.config.js toiljs.config.mjs\n```\n\nUse whichever you like. `toil.config.ts` is the convention.\n\n## Config vs. environment variables\n\nThere are two very different places settings live, and it matters which one you use.\n\n| | `toil.config.ts` (this page) | Environment variables |\n| --- | --- | --- |\n| **When it applies** | Build time and dev time | Runtime, per request |\n| **What it holds** | Framework and build options (routing, styling, SEO, which features to compile) | Values and secrets your running server reads (API keys, feature flags, connection info) |\n| **Committed to git?** | Yes, it is source | No. Local values go in `.env` / `.env.secrets` (both gitignored); production values live on your deploy target |\n| **Read in code with** | Not read from your app code | `Environment.get(...)` / `Environment.getSecure(...)` on the server |\n\nRule of thumb: if it is a **secret** (a password, an API key, a session key), it does **not** go in `toil.config.ts`. It goes in the environment. See [Environment and secrets](../services/environment.md) for the full story.\n\nThere is also a **third** file, `toilconfig.json`, which is a different thing entirely. See [`toil.config.ts` is not `toilconfig.json`](#toilconfigts-is-not-toilconfigjson) at the bottom.\n\n## The top-level shape\n\n```ts\ninterface ToilConfig {\n root?: string; // project root (defaults to the current working directory)\n client?: ClientConfig; // the React / Vite frontend\n server?: ServerConfig; // the toilscript / WebAssembly backend\n}\n```\n\nEverything else lives under `client` or `server`.\n\n## `client` reference\n\nConfigures the frontend: source folders, the dev server, and build-time optimizations.\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `srcDir` | `string` | `\"client\"` | Your frontend source directory, relative to the project root. |\n| `routesDir` | `string` | `\"routes\"` | Your file-based routes directory, relative to `srcDir`. |\n| `publicDir` | `string` | `\"<srcDir>/public\"` | Static assets directory. Holds `index.html` (which you own) plus files served as-is (favicons, images). |\n| `outDir` | `string` | `\"build/client\"` | Where the production client bundle is written. |\n| `base` | `string` | `\"/\"` | The public base path. Use this if you serve the app under a sub-path (a non-root base should start and end with `/`, like `\"/app/\"`). |\n| `port` | `number` | `3000` | The dev server port. `--port` on the CLI overrides it. |\n| `images` | `boolean` | `true` | Optimize imported images at build time (resize and convert). See [Images](../frontend/images.md). |\n| `fonts` | `boolean` | `true` | Preload bundled fonts (inject `<link rel=\"preload\">` for each `@font-face`) so text paints faster. |\n| `cspSources` | `Readonly<Record<string, readonly string[]>>` | `{}` | Append resource origins or Trusted Types policy names to the default CSP. See [`client.cspSources`](#clientcspsources). |\n| `viewTransitions` | `boolean` | `false` | Animate page navigations with the browser View Transitions API (a crossfade by default). Respects `prefers-reduced-motion`. |\n| `transitions` | `boolean` | `false` | Wrap navigations in a React transition, keeping the current page visible while the next route's loader runs (instead of showing its loading state immediately). |\n| `devtools` | `boolean` or object | `true` | The floating dev toolbar (route/build info, errors, live controls). It is dev-only and never ships in production. Set `false` to disable, or pass an object to configure its AI integration. |\n| `seo` | object | (off) | Build-time SEO: bakes site-level metadata into the HTML and generates `robots.txt`, `sitemap.xml`, `llms.txt`. See [`client.seo`](#clientseo) below. |\n| `vite` | Vite `InlineConfig` | `{}` | An escape hatch: raw Vite options, deep-merged over the framework's own Vite setup. toiljs owns the Vite config; use this only to override specific options. |\n\n### Example\n\n```ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n images: true,\n fonts: true,\n viewTransitions: true,\n // Serve the app under https://example.com/app/\n base: '/app/',\n },\n});\n```\n\n### `client.cspSources`\n\nCSP, COOP, and Trusted Types are enabled by default. Use `cspSources` to permit resources from additional origins without replacing the generated script policy:\n\n```ts\nexport default defineConfig({\n client: {\n cspSources: {\n 'connect-src': ['https://api.example.com'],\n 'img-src': ['https://images.example.com'],\n 'frame-src': ['https://widgets.example.com'],\n },\n },\n});\n```\n\nEntries extend the directive's defaults in development and production. Rebuild before deploying a change. Supported directives, validation rules, Trusted Types policy names, and external-host requirements are covered in [Security](./security.md#allowing-additional-resources). Script execution rules and Trusted Types enforcement cannot be disabled through this option. This setting applies to frontend documents; custom backend HTML handlers set their policies with `Response.setHeader`.\n\n### `client.devtools`\n\nThe dev toolbar is on by default. To turn it off, or to give it an AI provider (so its \"explain this error\" helpers can call a model), pass an object:\n\n```ts\nimport { defineConfig, AiProvider } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n devtools: {\n ai: {\n provider: AiProvider.Anthropic, // 'anthropic' or 'openai'\n model: 'claude-sonnet-4-6',\n // The name of the env var holding the API key. It is read\n // server-side by the dev process and never sent to the browser.\n apiKeyEnv: 'ANTHROPIC_API_KEY',\n // Optional: a custom POST endpoint ({ prompt } in, { text } out)\n // that overrides `provider` entirely.\n // endpoint: 'http://localhost:5000/ai',\n },\n },\n },\n});\n```\n\n| `devtools.ai` field | Type | What it does |\n| --- | --- | --- |\n| `provider` | `AiProvider` | Built-in provider: `AiProvider.Anthropic` (`'anthropic'`) or `AiProvider.OpenAI` (`'openai'`). |\n| `model` | `string` | The model id, for example `'claude-sonnet-4-6'` or `'gpt-4o'`. |\n| `apiKeyEnv` | `string` | The **name** of the environment variable that holds the API key. The key stays server-side and never reaches the browser. |\n| `endpoint` | `string` | A custom POST endpoint. When set, it takes precedence over `provider`. |\n\nThe toolbar always offers hand-off links to Claude and ChatGPT even without any AI config; this only enables the in-toolbar helpers.\n\n### `client.seo`\n\n`client.seo` turns on build-time search-engine and social metadata. It bakes tags into your HTML `<head>` (so crawlers and link-preview bots that do not run JavaScript still see real metadata) and generates `robots.txt`, `sitemap.xml`, and `llms.txt`. This is a large section with its own guide; see [Metadata and SEO](../frontend/metadata.md) for the complete field list and examples. The one thing worth knowing here: set `seo.url` to your absolute site URL (like `\"https://example.com\"`), because the sitemap and canonical links need it.\n\n```ts\nexport default defineConfig({\n client: {\n seo: {\n url: 'https://example.com',\n title: 'My App',\n description: 'A toiljs app.',\n },\n },\n});\n```\n\n## `server` reference\n\nConfigures the backend: which platform features to compile in, and how the dev server and self-host behave.\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `auth` | `boolean` | `false` | Opt into the framework's built-in post-quantum login. See [`server.auth`](#serverauth) below. |\n| `email` | object | (off) | The non-secret email backend config for the dev server and self-host. See [`server.email`](#serveremail) below. |\n| `daemon` | object | (defaults) | Background-job (L4 daemon) settings for dev and self-host. See [`server.daemon`](#serverdaemon) below. |\n| `nodeMode` | string | `\"all\"` | Which compute layer the single dev/self-host process emulates. See [`server.nodeMode`](#servernodemode) below. |\n| `threads` | `number` or `\"auto\"` | `\"auto\"` | HTTP worker count for `toiljs start`. `\"auto\"` uses one per CPU; `1` disables the worker pool. `--threads` on the CLI overrides it. |\n| `srcDir` | `string` | `\"server\"` | Declarative: your server source directory. See the note below. |\n| `outDir` | `string` | `\"build/server\"` | Declarative: the server build output directory. See the note below. |\n\n> **Note on `server.srcDir` / `server.outDir`.** These fields exist in the config type, but the actual location of your server source and its compiled output is driven by `toilconfig.json` (the toilscript compiler config), not by these two fields. Change your server paths in `toilconfig.json`. These fields are currently declarative and left for forward compatibility. See [not `toilconfig.json`](#toilconfigts-is-not-toilconfigjson) below.\n\n### `server.auth`\n\nSet `auth: true` to get a complete post-quantum login system with no boilerplate. The build appends a shipped `@rest('auth')` controller and its `@user` shape to your server, giving you `/auth/register`, `/auth/login`, `/auth/me`, and `/auth/logout` plus sessions.\n\n```ts\nexport default defineConfig({\n server: {\n auth: true,\n },\n});\n```\n\nTwo things to know:\n\n- If you opt in, your app must **not** declare its own `@user` type. The built-in auth owns the single per-program one.\n- There is an escape hatch: adding `import 'toiljs/server/auth'` in `server/main.ts` turns on the same built-in auth surface without this flag.\n\nAuth has its own configuration (session secrets, the OPRF and KEM keys) that lives in the **environment**, not here. See [Auth configuration](../auth/configuration.md).\n\n### `server.email`\n\nThe **non-secret** part of your email setup: which provider, the \"from\" address, and send caps. The dev server and self-host read it. The API key or SMTP password is a **secret** and never goes here; it comes from `.env.secrets` (`TOIL_EMAIL_API_KEY`). Any `TOIL_EMAIL_*` environment variable overrides the matching field here.\n\n```ts\nexport default defineConfig({\n server: {\n email: {\n provider: 'resend',\n from: 'hello@example.com',\n maxPerMin: 60,\n },\n },\n});\n```\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `provider` | `'resend'` \\| `'gmail'` \\| `'smtp'` | `'resend'` | Which email backend to use. |\n| `from` | `string` | (none) | The \"from\" address. Validated (single address, no line breaks). |\n| `maxPerMin` | `number` | `60` | Per-process send ceiling per minute (rolling). `0` means unlimited. |\n| `maxPerDay` | `number` | `0` | Per-process send ceiling per day (rolling). `0` means unlimited. |\n| `maxPerRecipientPerHour` | `number` | `5` | Per-recipient hourly cap (anti-abuse). |\n| `smtp` | object | (none) | Connection details for the `gmail` / `smtp` providers: `host`, `port` (defaults to 587 STARTTLS; 465 is implicit TLS), and `user` (defaults to `from`). |\n\nSee the full guide at [Email and 2FA](../services/email.md).\n\n### `server.daemon`\n\nSettings for the daemon (L4) background layer, used by the dev process and self-host. In dev, the local process is always the leader, so region fields are informational.\n\n```ts\nexport default defineConfig({\n server: {\n daemon: {\n defaultIntervalMs: 60000,\n maxTasks: 64,\n },\n },\n});\n```\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `region` | `string` | (none) | Region the daemon is pinned to (informational in dev). |\n| `standbyRegion` | `string` | (none) | Warm standby region (informational in dev). |\n| `defaultIntervalMs` | `number` | `60000` | Default interval for a `@scheduled` task that declares none. Values below `1000` are clamped up to `1000` (a sub-second loop would flood the console). |\n| `tickBudgetMs` | `number` | `30000` | Per-tick wall-clock budget before the dev scheduler logs an overrun. |\n| `gasTick` | `number` | `0` | Per-tick gas cap (a dev stub: charged then ignored). |\n| `maxTasks` | `number` | `64` | Maximum number of `@scheduled` tasks. Clamped to the range 1 to 1024. |\n\nSee [Daemons and scheduled jobs](../background/daemons.md).\n\n### `server.nodeMode`\n\nWhich compute layer the single local process emulates. This is a dev and self-host knob only; in production the Dacely edge decides each server's role. Valid values are `hot`, `regional`, `continental`, `daemon`, and `all`. The default, `all`, runs every surface (requests, streams, and daemons) in one process, which is what you want for a full local run. An invalid value falls back to `all` with a warning rather than failing. See [Compute tiers (L1 to L4)](../concepts/tiers.md) for what each layer means.\n\n```ts\nexport default defineConfig({\n server: {\n nodeMode: 'all', // run everything locally (the default)\n },\n});\n```\n\n## Route execution and transport limits\n\n`server.daemon.tickBudgetMs` applies only to scheduled daemon ticks. It is an overrun warning emitted after a tick returns; it does not cancel the tick or set a REST/RPC route deadline. There is no route execution timeout setting in `toil.config.ts`.\n\nFor `toiljs dev` and the Node self-host (`toiljs start`):\n\n| Limit | Default | What it bounds |\n| --- | --- | --- |\n| HTTP request body | 8 MiB | The body accepted by the front server, before handler dispatch. |\n| HTTP idle timeout | 60 seconds | An idle connection. |\n| HTTP response timeout | 120 seconds | A response stalled while sending under backpressure. |\n| WASM handler execution | No elapsed-time cutoff or gas metering | Synchronous `handle`/`render` execution on its worker. |\n\nThe HTTP timeouts do not interrupt a WASM handler that is still running. A busy loop can occupy its worker indefinitely, so a browser abort or reverse-proxy timeout must not be treated as proof that a write was cancelled. The low-level `startDevServer` / `startBuiltServer` APIs accept `maxBodyLength`; the CLI uses the default above.\n\nThe Dacely production edge meters execution with a per-request **gas budget** (a charge for WASM instructions and host operations). The current public free-plan HTTP and scheduled-tick budget is **128,000,000 gas**; Pro uses **256,000,000 gas**. Module start has a separate **20,000,000 gas** allowance, and daemon startup has **512,000,000 gas**. Host plans and operator configuration determine the deployed values. Gas exhaustion traps the call. Gas is a work budget rather than a guaranteed number of milliseconds; Node hosts do not emulate WASM instruction gas.\n\nFor optional database budget checks on the local Node hosts, set `TOIL_DEV_CHECK_DB_LIMITS=1`. This checks the native defaults for operation/write counts, write payloads, and per-result/cumulative bytes. See [database size limits](../database/documents.md#size-limits-and-file-uploads). It does not emulate storage latency, wait deadlines, or internal unique-field operations.\n\nProduction asynchronous database waits have their own deadlines: the current defaults are **50 ms for a Query**, **250 ms for an Action**, and **5 seconds for a Job or Derive**. The edge operator configures these through `db_quota`, separately from `toil.config.ts`. They bound DB waits rather than the whole route's execution time, and the local emulator does not enforce them. Deployed transport and database budgets are controlled by the host; there is no universal route time limit in seconds to infer from the daemon setting.\n\nKeep each upload request bounded by bytes, chunk count, and database operations. Continue large jobs across requests or background tasks rather than looping until a wall-clock deadline. See [Documents size limits and file uploads](../database/documents.md#size-limits-and-file-uploads) and [Time](../services/time.md#upload-expiry-versus-elapsed-deadlines).\n\n## Defaults at a glance\n\nIf you write nothing, this is what you get.\n\n| Setting | Default |\n| --- | --- |\n| `client.srcDir` | `\"client\"` |\n| `client.routesDir` | `\"routes\"` |\n| `client.publicDir` | `\"client/public\"` |\n| `client.outDir` | `\"build/client\"` |\n| `client.base` | `\"/\"` |\n| `client.port` | `3000` |\n| `client.images` | `true` |\n| `client.fonts` | `true` |\n| `client.viewTransitions` | `false` |\n| `client.transitions` | `false` |\n| `client.devtools` | on |\n| `client.seo` | off |\n| `server.auth` | `false` |\n| `server.email` | off |\n| `server.nodeMode` | `\"all\"` |\n| `server.threads` | `\"auto\"` |\n| `server.daemon.defaultIntervalMs` | `60000` |\n| `server.daemon.tickBudgetMs` | `30000` |\n| `server.daemon.maxTasks` | `64` |\n\n## A fuller example\n\n```ts\nimport { defineConfig, AiProvider } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n images: true,\n fonts: true,\n viewTransitions: true,\n seo: {\n url: 'https://example.com',\n title: 'Example',\n description: 'Built with toiljs.',\n },\n devtools: {\n ai: { provider: AiProvider.Anthropic, model: 'claude-sonnet-4-6', apiKeyEnv: 'ANTHROPIC_API_KEY' },\n },\n },\n server: {\n auth: true,\n email: { provider: 'resend', from: 'hello@example.com' },\n threads: 'auto',\n },\n});\n```\n\n## `toil.config.ts` is not `toilconfig.json`\n\nThese two look almost the same and are easy to confuse. They are not the same file.\n\n| File | What it is |\n| --- | --- |\n| `toil.config.ts` | **This page.** The framework config: client and server options, styling, SEO, which features to build. You edit it often. |\n| `toilconfig.json` | The **toilscript compiler** config: which server files are entry points, where the `.wasm` is written, and low-level WebAssembly options (optimization level, memory layout, enabled wasm features). It is scaffolded for you and you rarely touch it. Its presence is also what tells toiljs \"this project has a server.\" |\n\nIf you ever need to change where your server source lives or what the compiled artifact is named, that is `toilconfig.json`, not `toil.config.ts`.\n\n## The `toilconfig.json` reference\n\n`toilconfig.json` is the **toilscript compiler** config. toilscript is the compiler that turns your `server/` TypeScript into a `.wasm` file (WebAssembly, the sandboxed binary your backend ships as). This file tells toilscript which server files to compile, where to write the output, and which low-level WebAssembly options to use.\n\n`toiljs create` scaffolds it for you and most projects never touch it. You only edit it if you want to rename the compiled artifact, move your server entry, or hand-tune the WebAssembly codegen. Its presence at the project root is also the signal toiljs uses to decide \"this project has a server\" (a project with no `toilconfig.json` is a client-only app).\n\nA scaffolded file looks like this:\n\n```json\n{\n \"entries\": [\"server/main.ts\"],\n \"targets\": {\n \"release\": {\n \"outFile\": \"build/server/release.wasm\",\n \"textFile\": \"build/server/release.wat\"\n }\n },\n \"options\": {\n \"sourceMap\": false,\n \"optimizeLevel\": 3,\n \"shrinkLevel\": 1,\n \"converge\": true,\n \"noAssert\": false,\n \"enable\": [\n \"sign-extension\",\n \"mutable-globals\",\n \"nontrapping-f2i\",\n \"bulk-memory\",\n \"simd\",\n \"reference-types\",\n \"multi-value\"\n ],\n \"runtime\": \"stub\",\n \"lib\": [\"node_modules/toiljs/server/globals\"],\n \"memoryBase\": 65536,\n \"initialMemory\": 4,\n \"debug\": false,\n \"trapMode\": \"allow\"\n }\n}\n```\n\n### `entries`\n\nAn array of your server entry files: the toilscript starting points for the compile. The scaffold lists just `server/main.ts`, and `main.ts` imports your other surface modules so they all get pulled in. (Under `toiljs build`, toiljs compiles every decorated server file it finds, not only the entries, so a `@rest` or `@data` file you drop in is picked up even if `main.ts` does not import it.)\n\nA project that also has a streams tier or a daemon tier lists their entry files here too, so each tier can compile into its own artifact:\n\n```json\n\"entries\": [\"server/main.ts\", \"server/main.stream.ts\", \"server/main.daemon.ts\"]\n```\n\n### `targets`\n\nA map of named build targets. Each target names its output files. The scaffold has one target, `release`.\n\n| Field | Type | What it does |\n| --- | --- | --- |\n| `outFile` | `string` | Where the compiled `.wasm` is written. The scaffold uses `build/server/release.wasm`. |\n| `textFile` | `string` | Where the `.wat` (WebAssembly **text** format, the human-readable text form of the same module) is written. Handy for inspecting the output; not needed at runtime. |\n\n### `options`\n\nLow-level WebAssembly codegen options passed straight to toilscript. The defaults are already tuned for production, so change these only if you know you need to.\n\n| Field | Type | Scaffold value | What it controls |\n| --- | --- | --- | --- |\n| `sourceMap` | `boolean` | `false` | Emit a source map alongside the `.wasm` so a debugger can map machine code back to your TypeScript. Off by default (it makes the build bigger). |\n| `optimizeLevel` | `number` | `3` | How hard the optimizer works on **speed**, from `0` (none) to `3` (most). `3` is a production release setting. |\n| `shrinkLevel` | `number` | `1` | How hard the optimizer works on **size**, from `0` to `2`. `1` trades a little speed for a smaller binary. |\n| `converge` | `boolean` | `true` | Re-run the optimizer until the output stops getting better. Squeezes out a bit more at the cost of a slower build. |\n| `noAssert` | `boolean` | `false` | Strip `assert(...)` checks from the output (replace them with just their value, no trap). `false` keeps the safety checks in. |\n| `enable` | `string[]` | (see below) | Which modern WebAssembly features the compiled module is allowed to use. |\n| `runtime` | `string` | `\"stub\"` | The memory-management runtime baked into the module. `\"stub\"` is a minimal runtime that never frees memory, which fits toiljs's model exactly: the edge runs one fresh instance per request and throws its whole memory away when the request ends, so there is nothing to garbage-collect. |\n| `lib` | `string[]` | `[\"node_modules/toiljs/server/globals\"]` | Extra library paths whose top-level exports become **ambient globals** (usable with no `import`). This is what makes toiljs's server globals (like `crypto` and the auth primitives) available everywhere in `server/`. |\n| `memoryBase` | `number` | `65536` | The byte offset where your server's static data starts. Requests that fit below this offset use the reserved prefix at offset 0. The current edge and dev host deliver larger requests above the heap; the toiljs entrypoint reserves the input before decoding. Raising this value enlarges the prefix fast path and costs initial memory; it is not a hard upload-body cap. |\n| `initialMemory` | `number` | `4` | How much linear memory the module starts with, in **pages**. One WebAssembly page is 64 KiB, so `4` is 256 KiB. It grows on demand past this. |\n| `debug` | `boolean` | `false` | Include debug information (names and the like) in the binary. Off for production. |\n| `trapMode` | `string` | `\"allow\"` | What happens on a trapping operation (like a bad float-to-int conversion). `\"allow\"` lets it trap (the default and correct choice); `\"clamp\"` replaces traps with clamping instead. |\n\nThe `enable` array turns on WebAssembly features that are off by default in the compiler. The scaffold enables the modern set the compiled server relies on: `sign-extension`, `mutable-globals`, `nontrapping-f2i` (non-trapping float-to-int conversions), `bulk-memory` (fast `memory.copy` / `memory.fill`), `simd` (vector operations), `reference-types`, and `multi-value` (functions that return more than one value). Leave this list as scaffolded unless you have a specific reason to change it; removing an entry can make the module fail to compile or run.\n\n### The `--rpcModule` build flag\n\nOne toilscript flag is worth knowing even though it lives in your npm scripts, not in `toilconfig.json`: `--rpcModule shared/server.ts`. It tells the compiler to also emit `shared/server.ts`, the fully typed client the browser imports to call your server (the `@data` codec plus the typed `Server` surface). toiljs adds this flag for you on the request build. If your `build:server` script is missing it (older projects predate it), `toiljs doctor --fix` injects it. See [the CLI reference](../cli/README.md#what---fix-repairs).\n\n## Gotchas\n\n- **Wrap the config in `defineConfig`.** Without it you lose autocomplete and type errors on typos.\n- **Secrets never go here.** API keys, session secrets, and passwords belong in the environment, not in `toil.config.ts` (which is committed to git). See [Environment and secrets](../services/environment.md).\n- **`server.srcDir` / `server.outDir` do not move your server.** The server source location is governed by `toilconfig.json` entries. Editing these two config fields has no effect today.\n- **`nodeMode` and `daemon` are dev/self-host only.** In production the edge assigns each server its role; these settings never override that.\n- **An invalid `nodeMode` does not crash the build.** It warns and falls back to `all`.\n\n## Related\n\n- [The CLI](../cli/README.md): the commands that read this config.\n- [Environment and secrets](../services/environment.md): runtime values and how they differ from build-time config.\n- [Auth configuration](../auth/configuration.md): the auth-related environment settings behind `server.auth`.\n- [Email and 2FA](../services/email.md): the full email setup behind `server.email`.\n- [Metadata and SEO](../frontend/metadata.md): the full `client.seo` field list.\n- [Daemons and scheduled jobs](../background/daemons.md): the background layer behind `server.daemon`.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): what `server.nodeMode` selects.\n- [Images](../frontend/images.md) and [Styling](../frontend/styling.md): the features `client.images` and `toiljs configure` control.\n",
22
+ "concepts/ai-guide.md": "# Writing toiljs correctly\n\nThis is a fast, high-signal cheat-sheet for writing toiljs and toilscript code that compiles and behaves. It is aimed at AI assistants generating code (and at humans in a hurry): the patterns to follow, the mistakes to avoid, and a link to the deep page whenever you need more. It does not re-teach the framework; each section points you at the authoritative doc.\n\n## Project shape\n\nA toiljs project has three top-level folders, and knowing which one a file belongs to tells you which rules apply:\n\n- **`client/`**: your React app that runs in the browser. Pages live under `client/routes/`, one file per URL, and each route file `export default`s its component. See [Frontend](../frontend/README.md) and [Routing](../frontend/routing.md).\n- **`shared/`**: a generated typed bridge (`shared/server.ts`) that lets the browser call the backend with full types. It is regenerated on every build, so **never hand-edit it**.\n- **`server/`**: your backend, written in TypeScript but compiled by **toilscript** to WebAssembly. It runs on the Dacely edge, not in Node or the browser. See [Backend](../backend/README.md).\n\nMost code runs on the L1 request tier. Long-lived connections (`@stream`) and scheduled work (`@daemon`) are opt-in tiers in their own entry files. See [Compute tiers](./tiers.md).\n\n## Client rules (the browser, React side)\n\n**Call the backend only through the generated `Server` client.** This is the number one rule. Use `Server.REST.<controller>.<route>(args)` for `@rest` HTTP controllers, or `Server.<service>.<method>(args)` / `Server.<remote>(args)` for RPC. Raw `fetch` to your own backend throws away the type safety, the argument and result decoding, and the binary wire codec, and it silently breaks when a route is renamed. `fetch` is only for third-party URLs (an external API, a CDN). See [Fetching data](../frontend/data-fetching.md).\n\n```ts\n// WRONG: raw fetch to your own backend\nawait fetch('/account/session', { method: 'POST' });\n\n// RIGHT: the typed client (renames become compile errors; args + result typed)\nawait Server.REST.account.session();\n```\n\n**Use the ambient `Toil.*` globals with no import.** `Toil` is the `toiljs/client` package exposed as a global and typed via a generated `toil-env.d.ts`, so it autocompletes with no import: `Toil.Link` / `Toil.NavLink` for navigation, `Toil.useParams`, `Toil.useLoaderData`, `Toil.Image`, `Toil.useHead` / `Toil.Head`, `Toil.Form` / `Toil.useAction`, and more. `Server` and `parseError` are also bare globals; `FastMap`, `FastSet`, `DataWriter`, and `DataReader` are bare globals too (write `new DataWriter()`, not `new Toil.DataWriter()`). Full index: [The Toil global](../frontend/toil-global.md).\n\n**Load page data with a `loader`, not a `useEffect` fetch.** A route file exports a `loader`, and the component reads its result with `Toil.useLoaderData`. The loader runs on navigation in parallel with the route chunk, integrates with `loading.tsx`, caching, and SSR hydration. A `useEffect` fetch runs only after mount (slower, invisible to the server).\n\n```tsx\n// client/routes/blog/[id].tsx\nexport const loader = async ({ params }: Toil.LoaderArgs) => {\n return Server.REST.blog.get({ params: { id: params.id } });\n};\n\nexport default function BlogPost() {\n const post = Toil.useLoaderData<typeof loader>();\n return <article><h1>{post.title}</h1></article>;\n}\n```\n\n**Mutate with `Toil.useAction` or `<Toil.Form>`, then revalidate.** Both track pending and error state and refetch the affected loader data on success, so the page updates without a manual refetch. Use `<Toil.Form>` for form submits, `useAction` for anything else (a delete button, a toggle). Reach for `Toil.revalidate()` / `router.revalidate()` after a write that these do not cover.\n\n**Per-route SEO with `export const metadata`** (or `Toil.useHead` / `<Toil.Head>` from inside a component). Opt a route into edge SSR with `export const ssr = true`. See [Metadata and SEO](../frontend/metadata.md) and [Rendering and SSR](../frontend/rendering.md).\n\n**Typed hrefs.** `Toil.Link` `href`, `Toil.navigate`, and `router.push` are all type-checked against your real routes, so a typo is a compile error. Use `Toil.href(str)` only when a URL is assembled from data and TypeScript cannot prove it is a real route. See [Navigation](../frontend/navigation.md).\n\n**`getUser()` on the client is display-only.** It reads a readable session cookie with no network call, so it is instant but **forgeable**. Use it to render \"logged in as ...\", never to gate real access. The authoritative check is a server route guarded with `@auth`. See [Auth usage](../auth/usage.md).\n\n## Server rules (toilscript, compiles to WASM)\n\nThe decorators, each doing one job (full list in [Decorators](./decorators.md)):\n\n- **`@data`** on a class: generates the binary and JSON codec so the value can cross the wire and the database. Every field needs a default; field order **is** the binary layout, so add new fields at the end. See [Data types](../backend/data.md).\n- **`@rest('name')`** on a class mounts an HTTP controller at `/name`; **`@get`/`@post`/`@put`/`@del`/`@patch`** on its methods declare routes (`@del`, not `@delete`, which is reserved). See [REST](../backend/rest.md).\n- **`@service`** + **`@remote`** expose typed RPC callable from your own frontend as `Server.<service>.<method>()`. See [RPC](../backend/rpc.md).\n- **`@user`** declares the authenticated-user shape and enables `AuthService.getUser()`. **Exactly one `@user` per project.** **`@auth`** guards a route or a whole `@rest` class. See [Auth](../auth/README.md).\n- **`@ratelimit(strategy, limit, window)`** caps how often a caller may hit a route, rejected at the edge before your code runs. See [Security](./security.md).\n- **`@database`** + **`@collection`** declare a ToilDB schema (below).\n\n```ts\n@rest('players')\nclass Players {\n @get('/:id')\n public get(ctx: RouteContext): Response {\n const id = ctx.param('id');\n return Response.json(`{\"id\":\"${id}\"}`);\n }\n}\n```\n\n**`@auth` rejects with 401 before your handler runs.** So inside an `@auth`-guarded handler, `AuthService.getUser()!` is guaranteed non-null and safe to assert. Without `@auth`, `getUser()` can be null, so null-check it instead. Either way the server re-verifies the signed session, so it (not the client cookie) is the real authorization boundary.\n\n```ts\n@auth\n@get('/settings')\npublic settings(): Response {\n const user = AuthService.getUser()!; // safe: @auth guarantees a session\n return Response.text('hi ' + user.username);\n}\n```\n\n**Server code is a strict, WASM-targeted dialect (AssemblyScript), not full TypeScript.** The real constraints, verified against the toilscript standard library:\n\n- **Use explicit value types**, never `number`: `i32` / `u32` / `i64` / `u64` / `f64` (and `i8`/`u8`/`i16`/`u16`/`f32`, plus `u128`..`u256`), `bool`, `string`, `Uint8Array`. Plain `number` resolves to `f64`, which is wrong for ids and counts. Integer math **wraps** on overflow (it never throws), and integer `/` truncates. See [The type system](./types.md).\n- **No `any`.** Every value has a concrete type; that is what lets it compile to WASM.\n- **No arbitrary npm.** Only the toilscript standard library plus the toiljs host APIs.\n- **Use `null`, not `undefined`** for \"no value\" (`T | null`, narrowed with `if (x != null)` or a `!` assertion).\n- **`RegExp` is not implemented.** Construction and matching are rejected at compile time. Use string operations or a supported parser.\n- **Structured values are `@data` classes, not object literals.** Encode and decode raw binary with `DataWriter` / `DataReader` (imported on the server from the `data` module: `import { DataWriter, DataReader } from 'data';`). For dynamic JSON, use the ambient `JSON` value tree.\n- **Read config with `Environment.get(key)` and secrets with `Environment.getSecure(key)`** (each returns `string | null`; the two buckets are disjoint so a secret can never leak through `get`). See [Environment](../services/environment.md).\n- **Return a runtime `Response`** (`Response.json` / `.text` / `.html` / `.bytes` / `.notFound` / ...), or return a `@data` value and let toiljs serialize it.\n\n**ToilDB has seven collection families; pick the one that matches the job** (do not force everything into one). Declare each as a `static` `@collection` field on a `@database` class, typed by its family, and reach it statically (`AppDb.users.get(...)`). See [The database](../database/README.md) and [Setup](../database/setup.md).\n\n- **`Documents<K,V>`**: the default record store, looked up by id (users, posts, orders).\n- **`Unique<K,V>`**: a globally one-of-a-kind claim (usernames, emails, slugs).\n- **`Counter<K>`**: a running total many callers bump at once (likes, views); `add` a delta only.\n- **`Events<K,V>`**: an append-only log kept in order (feeds, audit trails).\n `get(key, eventId)` reads an `appendOnce` event by ID; `last(key)` reads the\n newest event. Both are request-safe and return `V | null`; check `Db.lastError()`\n immediately on null. `latest`/`since` are background scans. A `last` followed by\n an append is not atomic; duplicate IDs do not replace existing events. See\n [Events](../database/events.md#get-and-last).\n- **`Capacity<K>`**: a limited quantity handed out without overselling (tickets, seats).\n- **`Membership<K,M>`**: sets of who belongs to what (followers, tags, room members).\n- **`View<K,V>`**: a precomputed read-optimized snapshot (leaderboards, home pages).\n\n**Data access is gated by function kind.** A `@get` route is a read-only **Query**; a `@post` route is an **Action** (may write); a plain `@remote` defaults to read-only Query, so add **`@action`** to let it write. Scans (`events.latest`, `membership.list`) are barred from request handlers: do them in a `@derive` and have the request read the resulting `View`. The compiler enforces this and the edge re-checks it.\n\n## Common mistakes\n\nA short do-not list. Every one of these is a real, avoidable error:\n\n- **Raw `fetch` to your own backend.** Go through `Server.*` instead.\n- **Importing `Toil.*`.** They are ambient globals; importing them is wrong.\n- **Fetching page data in a `useEffect`.** Use a route `loader` + `Toil.useLoaderData`.\n- **A plain `<a>` for in-app links.** Use `Toil.Link` (a bare `<a>` triggers a full reload).\n- **More than one `@user`.** Exactly one per project.\n- **Trusting client `getUser()` for authorization.** It is display-only and forgeable; enforce on the server with `@auth`.\n- **`any`, `number`, or `RegExp` in server code.** Use explicit value types; there is no usable `RegExp`.\n- **Reordering `@data` fields** (or changing a field type) on a stored type. Field order is the layout; add at the end and use `@migrate` to evolve. See [Data types](../backend/data.md).\n- **Writing from a plain `@remote` or `@get`.** Reads are the default; a write needs `@action`.\n- **Calling a scan (`events.latest`, `membership.list`) from a request handler.** Do it in a `@derive`.\n- **Hand-editing `shared/server.ts` or `.toil/`.** They are generated; rebuild instead.\n\n## Where to go deeper\n\n- Concepts: [Decorators](./decorators.md), [Type system](./types.md), [Security](./security.md), [Compute tiers](./tiers.md).\n- Backend: [Overview](../backend/README.md), [REST](../backend/rest.md), [RPC](../backend/rpc.md), [Data types](../backend/data.md).\n- Frontend: [Overview](../frontend/README.md), [Fetching data](../frontend/data-fetching.md), [Routing](../frontend/routing.md), [Navigation](../frontend/navigation.md), [The Toil global](../frontend/toil-global.md).\n- Database: [ToilDB overview](../database/README.md), [Setup](../database/setup.md).\n- Auth: [Overview](../auth/README.md), [Usage](../auth/usage.md).\n- Services: [Environment](../services/environment.md), [Rate limiting](../services/ratelimit.md).\n</content>\n</invoke>\n",
23
+ "concepts/config.md": "# Configuration (`toil.config.ts`)\n\n`toil.config.ts` is the one file that configures your whole toiljs app: the client (React/Vite) side and the server (WebAssembly) side. Every field is optional and has a sensible default, so most projects keep it tiny.\n\n## The shortest possible config\n\nA scaffolded project ships something like this:\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n // Optimize images at build time (resize and compress imported images).\n images: true,\n },\n});\n```\n\n`defineConfig` does not do anything at runtime: it is an identity helper that gives you full editor autocomplete and type-checking for the config shape. Always wrap your config in it.\n\nAn empty config is valid too. `export default defineConfig({})` gives you a working app with all defaults.\n\n## Where the file lives\n\ntoiljs looks in your project root for the first file that matches, in this order:\n\n```\ntoil.config.ts toil.config.mts toil.config.js toil.config.mjs\ntoiljs.config.ts toiljs.config.mts toiljs.config.js toiljs.config.mjs\n```\n\nUse whichever you like. `toil.config.ts` is the convention.\n\n## Config vs. environment variables\n\nThere are two very different places settings live, and it matters which one you use.\n\n| | `toil.config.ts` (this page) | Environment variables |\n| --- | --- | --- |\n| **When it applies** | Build time and dev time | Runtime, per request |\n| **What it holds** | Framework and build options (routing, styling, SEO, which features to compile) | Values and secrets your running server reads (API keys, feature flags, connection info) |\n| **Committed to git?** | Yes, it is source | No. Local values go in `.env` / `.env.secrets` (both gitignored); production values live on your deploy target |\n| **Read in code with** | Not read from your app code | `Environment.get(...)` / `Environment.getSecure(...)` on the server |\n\nRule of thumb: if it is a **secret** (a password, an API key, a session key), it does **not** go in `toil.config.ts`. It goes in the environment. See [Environment and secrets](../services/environment.md) for the full story.\n\nThere is also a **third** file, `toilconfig.json`, which is a different thing entirely. See [`toil.config.ts` is not `toilconfig.json`](#toilconfigts-is-not-toilconfigjson) at the bottom.\n\n## The top-level shape\n\n```ts\ninterface ToilConfig {\n root?: string; // project root (defaults to the current working directory)\n client?: ClientConfig; // the React / Vite frontend\n server?: ServerConfig; // the toilscript / WebAssembly backend\n}\n```\n\nEverything else lives under `client` or `server`.\n\n## `client` reference\n\nConfigures the frontend: source folders, the dev server, and build-time optimizations.\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `srcDir` | `string` | `\"client\"` | Your frontend source directory, relative to the project root. |\n| `routesDir` | `string` | `\"routes\"` | Your file-based routes directory, relative to `srcDir`. |\n| `publicDir` | `string` | `\"<srcDir>/public\"` | Static assets directory. Holds `index.html` (which you own) plus files served as-is (favicons, images). |\n| `outDir` | `string` | `\"build/client\"` | Where the production client bundle is written. |\n| `base` | `string` | `\"/\"` | The public base path. Use this if you serve the app under a sub-path (a non-root base should start and end with `/`, like `\"/app/\"`). |\n| `port` | `number` | `3000` | The dev server port. `--port` on the CLI overrides it. |\n| `images` | `boolean` | `true` | Optimize imported images at build time (resize and convert). See [Images](../frontend/images.md). |\n| `fonts` | `boolean` | `true` | Preload bundled fonts (inject `<link rel=\"preload\">` for each `@font-face`) so text paints faster. |\n| `cspSources` | `Readonly<Record<string, readonly string[]>>` | `{}` | Append resource origins or Trusted Types policy names to the default CSP. See [`client.cspSources`](#clientcspsources). |\n| `viewTransitions` | `boolean` | `false` | Animate page navigations with the browser View Transitions API (a crossfade by default). Respects `prefers-reduced-motion`. |\n| `transitions` | `boolean` | `false` | Wrap navigations in a React transition, keeping the current page visible while the next route's loader runs (instead of showing its loading state immediately). |\n| `devtools` | `boolean` or object | `true` | The floating dev toolbar (route/build info, errors, live controls). It is dev-only and never ships in production. Set `false` to disable, or pass an object to configure its AI integration. |\n| `seo` | object | (off) | Build-time SEO: bakes site-level metadata into the HTML and generates `robots.txt`, `sitemap.xml`, `llms.txt`. See [`client.seo`](#clientseo) below. |\n| `vite` | Vite `InlineConfig` | `{}` | An escape hatch: raw Vite options, deep-merged over the framework's own Vite setup. toiljs owns the Vite config; use this only to override specific options. |\n\n### Example\n\n```ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n images: true,\n fonts: true,\n viewTransitions: true,\n // Serve the app under https://example.com/app/\n base: '/app/',\n },\n});\n```\n\n### `client.cspSources`\n\nCSP, COOP, and Trusted Types are enabled by default. Use `cspSources` to permit resources from additional origins without replacing the generated script policy:\n\n```ts\nexport default defineConfig({\n client: {\n cspSources: {\n 'connect-src': ['https://api.example.com'],\n 'img-src': ['https://images.example.com'],\n 'frame-src': ['https://widgets.example.com'],\n },\n },\n});\n```\n\nResource entries extend the directive's defaults in development and production.\nExplicit `script-src`/`script-src-elem` arrays instead replace generated script\ntrust, and an empty `require-trusted-types-for` array disables DOM sink enforcement.\nOmitting these overrides preserves the strict defaults. Rebuild before deploying\na change. Supported directives, validation rules, security tradeoffs, Trusted Types\npolicy names, and external-host requirements are covered in\n[Security](./security.md#allowing-additional-resources). This setting applies to\nfrontend documents; custom backend HTML handlers set policies with `Response.setHeader`.\n\n### `client.devtools`\n\nThe dev toolbar is on by default. To turn it off, or to give it an AI provider (so its \"explain this error\" helpers can call a model), pass an object:\n\n```ts\nimport { defineConfig, AiProvider } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n devtools: {\n ai: {\n provider: AiProvider.Anthropic, // 'anthropic' or 'openai'\n model: 'claude-sonnet-4-6',\n // The name of the env var holding the API key. It is read\n // server-side by the dev process and never sent to the browser.\n apiKeyEnv: 'ANTHROPIC_API_KEY',\n // Optional: a custom POST endpoint ({ prompt } in, { text } out)\n // that overrides `provider` entirely.\n // endpoint: 'http://localhost:5000/ai',\n },\n },\n },\n});\n```\n\n| `devtools.ai` field | Type | What it does |\n| --- | --- | --- |\n| `provider` | `AiProvider` | Built-in provider: `AiProvider.Anthropic` (`'anthropic'`) or `AiProvider.OpenAI` (`'openai'`). |\n| `model` | `string` | The model id, for example `'claude-sonnet-4-6'` or `'gpt-4o'`. |\n| `apiKeyEnv` | `string` | The **name** of the environment variable that holds the API key. The key stays server-side and never reaches the browser. |\n| `endpoint` | `string` | A custom POST endpoint. When set, it takes precedence over `provider`. |\n\nThe toolbar always offers hand-off links to Claude and ChatGPT even without any AI config; this only enables the in-toolbar helpers.\n\n### `client.seo`\n\n`client.seo` turns on build-time search-engine and social metadata. It bakes tags into your HTML `<head>` (so crawlers and link-preview bots that do not run JavaScript still see real metadata) and generates `robots.txt`, `sitemap.xml`, and `llms.txt`. This is a large section with its own guide; see [Metadata and SEO](../frontend/metadata.md) for the complete field list and examples. The one thing worth knowing here: set `seo.url` to your absolute site URL (like `\"https://example.com\"`), because the sitemap and canonical links need it.\n\n```ts\nexport default defineConfig({\n client: {\n seo: {\n url: 'https://example.com',\n title: 'My App',\n description: 'A toiljs app.',\n },\n },\n});\n```\n\n## `server` reference\n\nConfigures the backend: which platform features to compile in, and how the dev server and self-host behave.\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `auth` | `boolean` | `false` | Opt into the framework's built-in post-quantum login. See [`server.auth`](#serverauth) below. |\n| `email` | object | (off) | The non-secret email backend config for the dev server and self-host. See [`server.email`](#serveremail) below. |\n| `daemon` | object | (defaults) | Background-job (L4 daemon) settings for dev and self-host. See [`server.daemon`](#serverdaemon) below. |\n| `nodeMode` | string | `\"all\"` | Which compute layer the single dev/self-host process emulates. See [`server.nodeMode`](#servernodemode) below. |\n| `threads` | `number` or `\"auto\"` | `\"auto\"` | HTTP worker count for `toiljs start`. `\"auto\"` uses one per CPU; `1` disables the worker pool. `--threads` on the CLI overrides it. |\n| `srcDir` | `string` | `\"server\"` | Declarative: your server source directory. See the note below. |\n| `outDir` | `string` | `\"build/server\"` | Declarative: the server build output directory. See the note below. |\n\n> **Note on `server.srcDir` / `server.outDir`.** These fields exist in the config type, but the actual location of your server source and its compiled output is driven by `toilconfig.json` (the toilscript compiler config), not by these two fields. Change your server paths in `toilconfig.json`. These fields are currently declarative and left for forward compatibility. See [not `toilconfig.json`](#toilconfigts-is-not-toilconfigjson) below.\n\n### `server.auth`\n\nSet `auth: true` to get a complete post-quantum login system with no boilerplate. The build appends a shipped `@rest('auth')` controller and its `@user` shape to your server, giving you `/auth/register`, `/auth/login`, `/auth/me`, and `/auth/logout` plus sessions.\n\n```ts\nexport default defineConfig({\n server: {\n auth: true,\n },\n});\n```\n\nTwo things to know:\n\n- If you opt in, your app must **not** declare its own `@user` type. The built-in auth owns the single per-program one.\n- There is an escape hatch: adding `import 'toiljs/server/auth'` in `server/main.ts` turns on the same built-in auth surface without this flag.\n\nAuth has its own configuration (session secrets, the OPRF and KEM keys) that lives in the **environment**, not here. See [Auth configuration](../auth/configuration.md).\n\n### `server.email`\n\nThe **non-secret** part of your email setup: which provider, the \"from\" address, and send caps. The dev server and self-host read it. The API key or SMTP password is a **secret** and never goes here; it comes from `.env.secrets` (`TOIL_EMAIL_API_KEY`). Any `TOIL_EMAIL_*` environment variable overrides the matching field here.\n\n```ts\nexport default defineConfig({\n server: {\n email: {\n provider: 'resend',\n from: 'hello@example.com',\n maxPerMin: 60,\n },\n },\n});\n```\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `provider` | `'resend'` \\| `'gmail'` \\| `'smtp'` | `'resend'` | Which email backend to use. |\n| `from` | `string` | (none) | The \"from\" address. Validated (single address, no line breaks). |\n| `maxPerMin` | `number` | `60` | Per-process send ceiling per minute (rolling). `0` means unlimited. |\n| `maxPerDay` | `number` | `0` | Per-process send ceiling per day (rolling). `0` means unlimited. |\n| `maxPerRecipientPerHour` | `number` | `5` | Per-recipient hourly cap (anti-abuse). |\n| `smtp` | object | (none) | Connection details for the `gmail` / `smtp` providers: `host`, `port` (defaults to 587 STARTTLS; 465 is implicit TLS), and `user` (defaults to `from`). |\n\nSee the full guide at [Email and 2FA](../services/email.md).\n\n### `server.daemon`\n\nSettings for the daemon (L4) background layer, used by the dev process and self-host. In dev, the local process is always the leader, so region fields are informational.\n\n```ts\nexport default defineConfig({\n server: {\n daemon: {\n defaultIntervalMs: 60000,\n maxTasks: 64,\n },\n },\n});\n```\n\n| Field | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `region` | `string` | (none) | Region the daemon is pinned to (informational in dev). |\n| `standbyRegion` | `string` | (none) | Warm standby region (informational in dev). |\n| `defaultIntervalMs` | `number` | `60000` | Default interval for a `@scheduled` task that declares none. Values below `1000` are clamped up to `1000` (a sub-second loop would flood the console). |\n| `tickBudgetMs` | `number` | `30000` | Per-tick wall-clock budget before the dev scheduler logs an overrun. |\n| `gasTick` | `number` | `0` | Per-tick gas cap (a dev stub: charged then ignored). |\n| `maxTasks` | `number` | `64` | Maximum number of `@scheduled` tasks. Clamped to the range 1 to 1024. |\n\nSee [Daemons and scheduled jobs](../background/daemons.md).\n\n### `server.nodeMode`\n\nWhich compute layer the single local process emulates. This is a dev and self-host knob only; in production the Dacely edge decides each server's role. Valid values are `hot`, `regional`, `continental`, `daemon`, and `all`. The default, `all`, runs every surface (requests, streams, and daemons) in one process, which is what you want for a full local run. An invalid value falls back to `all` with a warning rather than failing. See [Compute tiers (L1 to L4)](../concepts/tiers.md) for what each layer means.\n\n```ts\nexport default defineConfig({\n server: {\n nodeMode: 'all', // run everything locally (the default)\n },\n});\n```\n\n## Route execution and transport limits\n\n`server.daemon.tickBudgetMs` applies only to scheduled daemon ticks. It is an overrun warning emitted after a tick returns; it does not cancel the tick or set a REST/RPC route deadline. There is no route execution timeout setting in `toil.config.ts`.\n\nFor `toiljs dev` and the Node self-host (`toiljs start`):\n\n| Limit | Default | What it bounds |\n| --- | --- | --- |\n| HTTP request body | 8 MiB | The body accepted by the front server, before handler dispatch. |\n| HTTP idle timeout | 60 seconds | An idle connection. |\n| HTTP response timeout | 120 seconds | A response stalled while sending under backpressure. |\n| WASM handler execution | No elapsed-time cutoff or gas metering | Synchronous `handle`/`render` execution on its worker. |\n\nThe HTTP timeouts do not interrupt a WASM handler that is still running. A busy loop can occupy its worker indefinitely, so a browser abort or reverse-proxy timeout must not be treated as proof that a write was cancelled. The low-level `startDevServer` / `startBuiltServer` APIs accept `maxBodyLength`; the CLI uses the default above.\n\nThe Dacely production edge meters execution with a per-request **gas budget** (a charge for WASM instructions and host operations). The current public free-plan HTTP and scheduled-tick budget is **128,000,000 gas**; Pro uses **256,000,000 gas**. Module start has a separate **20,000,000 gas** allowance, and daemon startup has **512,000,000 gas**. Host plans and operator configuration determine the deployed values. Gas exhaustion traps the call. Gas is a work budget rather than a guaranteed number of milliseconds; Node hosts do not emulate WASM instruction gas.\n\nFor optional database budget checks on the local Node hosts, set `TOIL_DEV_CHECK_DB_LIMITS=1`. This checks the native defaults for operation/write counts, write payloads, and per-result/cumulative bytes. See [database size limits](../database/documents.md#size-limits-and-file-uploads). It does not emulate storage latency, wait deadlines, or internal unique-field operations.\n\nProduction asynchronous database waits have their own deadlines: the current defaults are **50 ms for a Query**, **250 ms for an Action**, and **5 seconds for a Job or Derive**. The edge operator configures these through `db_quota`, separately from `toil.config.ts`. They bound DB waits rather than the whole route's execution time, and the local emulator does not enforce them. Deployed transport and database budgets are controlled by the host; there is no universal route time limit in seconds to infer from the daemon setting.\n\nKeep each upload request bounded by bytes, chunk count, and database operations. Continue large jobs across requests or background tasks rather than looping until a wall-clock deadline. See [Documents size limits and file uploads](../database/documents.md#size-limits-and-file-uploads) and [Time](../services/time.md#upload-expiry-versus-elapsed-deadlines).\n\n## Defaults at a glance\n\nIf you write nothing, this is what you get.\n\n| Setting | Default |\n| --- | --- |\n| `client.srcDir` | `\"client\"` |\n| `client.routesDir` | `\"routes\"` |\n| `client.publicDir` | `\"client/public\"` |\n| `client.outDir` | `\"build/client\"` |\n| `client.base` | `\"/\"` |\n| `client.port` | `3000` |\n| `client.images` | `true` |\n| `client.fonts` | `true` |\n| `client.viewTransitions` | `false` |\n| `client.transitions` | `false` |\n| `client.devtools` | on |\n| `client.seo` | off |\n| `server.auth` | `false` |\n| `server.email` | off |\n| `server.nodeMode` | `\"all\"` |\n| `server.threads` | `\"auto\"` |\n| `server.daemon.defaultIntervalMs` | `60000` |\n| `server.daemon.tickBudgetMs` | `30000` |\n| `server.daemon.maxTasks` | `64` |\n\n## A fuller example\n\n```ts\nimport { defineConfig, AiProvider } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n images: true,\n fonts: true,\n viewTransitions: true,\n seo: {\n url: 'https://example.com',\n title: 'Example',\n description: 'Built with toiljs.',\n },\n devtools: {\n ai: { provider: AiProvider.Anthropic, model: 'claude-sonnet-4-6', apiKeyEnv: 'ANTHROPIC_API_KEY' },\n },\n },\n server: {\n auth: true,\n email: { provider: 'resend', from: 'hello@example.com' },\n threads: 'auto',\n },\n});\n```\n\n## `toil.config.ts` is not `toilconfig.json`\n\nThese two look almost the same and are easy to confuse. They are not the same file.\n\n| File | What it is |\n| --- | --- |\n| `toil.config.ts` | **This page.** The framework config: client and server options, styling, SEO, which features to build. You edit it often. |\n| `toilconfig.json` | The **toilscript compiler** config: which server files are entry points, where the `.wasm` is written, and low-level WebAssembly options (optimization level, memory layout, enabled wasm features). It is scaffolded for you and you rarely touch it. Its presence is also what tells toiljs \"this project has a server.\" |\n\nIf you ever need to change where your server source lives or what the compiled artifact is named, that is `toilconfig.json`, not `toil.config.ts`.\n\n## The `toilconfig.json` reference\n\n`toilconfig.json` is the **toilscript compiler** config. toilscript is the compiler that turns your `server/` TypeScript into a `.wasm` file (WebAssembly, the sandboxed binary your backend ships as). This file tells toilscript which server files to compile, where to write the output, and which low-level WebAssembly options to use.\n\n`toiljs create` scaffolds it for you and most projects never touch it. You only edit it if you want to rename the compiled artifact, move your server entry, or hand-tune the WebAssembly codegen. Its presence at the project root is also the signal toiljs uses to decide \"this project has a server\" (a project with no `toilconfig.json` is a client-only app).\n\nA scaffolded file looks like this:\n\n```json\n{\n \"entries\": [\"server/main.ts\"],\n \"targets\": {\n \"release\": {\n \"outFile\": \"build/server/release.wasm\",\n \"textFile\": \"build/server/release.wat\"\n }\n },\n \"options\": {\n \"sourceMap\": false,\n \"optimizeLevel\": 3,\n \"shrinkLevel\": 1,\n \"converge\": true,\n \"noAssert\": false,\n \"enable\": [\n \"sign-extension\",\n \"mutable-globals\",\n \"nontrapping-f2i\",\n \"bulk-memory\",\n \"simd\",\n \"reference-types\",\n \"multi-value\"\n ],\n \"runtime\": \"stub\",\n \"lib\": [\"node_modules/toiljs/server/globals\"],\n \"memoryBase\": 65536,\n \"initialMemory\": 4,\n \"debug\": false,\n \"trapMode\": \"allow\"\n }\n}\n```\n\n### `entries`\n\nAn array of your server entry files: the toilscript starting points for the compile. The scaffold lists just `server/main.ts`, and `main.ts` imports your other surface modules so they all get pulled in. (Under `toiljs build`, toiljs compiles every decorated server file it finds, not only the entries, so a `@rest` or `@data` file you drop in is picked up even if `main.ts` does not import it.)\n\nA project that also has a streams tier or a daemon tier lists their entry files here too, so each tier can compile into its own artifact:\n\n```json\n\"entries\": [\"server/main.ts\", \"server/main.stream.ts\", \"server/main.daemon.ts\"]\n```\n\n### `targets`\n\nA map of named build targets. Each target names its output files. The scaffold has one target, `release`.\n\n| Field | Type | What it does |\n| --- | --- | --- |\n| `outFile` | `string` | Where the compiled `.wasm` is written. The scaffold uses `build/server/release.wasm`. |\n| `textFile` | `string` | Where the `.wat` (WebAssembly **text** format, the human-readable text form of the same module) is written. Handy for inspecting the output; not needed at runtime. |\n\n### `options`\n\nLow-level WebAssembly codegen options passed straight to toilscript. The defaults are already tuned for production, so change these only if you know you need to.\n\n| Field | Type | Scaffold value | What it controls |\n| --- | --- | --- | --- |\n| `sourceMap` | `boolean` | `false` | Emit a source map alongside the `.wasm` so a debugger can map machine code back to your TypeScript. Off by default (it makes the build bigger). |\n| `optimizeLevel` | `number` | `3` | How hard the optimizer works on **speed**, from `0` (none) to `3` (most). `3` is a production release setting. |\n| `shrinkLevel` | `number` | `1` | How hard the optimizer works on **size**, from `0` to `2`. `1` trades a little speed for a smaller binary. |\n| `converge` | `boolean` | `true` | Re-run the optimizer until the output stops getting better. Squeezes out a bit more at the cost of a slower build. |\n| `noAssert` | `boolean` | `false` | Strip `assert(...)` checks from the output (replace them with just their value, no trap). `false` keeps the safety checks in. |\n| `enable` | `string[]` | (see below) | Which modern WebAssembly features the compiled module is allowed to use. |\n| `runtime` | `string` | `\"stub\"` | The memory-management runtime baked into the module. `\"stub\"` is a minimal runtime that never frees memory, which fits toiljs's model exactly: the edge runs one fresh instance per request and throws its whole memory away when the request ends, so there is nothing to garbage-collect. |\n| `lib` | `string[]` | `[\"node_modules/toiljs/server/globals\"]` | Extra library paths whose top-level exports become **ambient globals** (usable with no `import`). This is what makes toiljs's server globals (like `crypto` and the auth primitives) available everywhere in `server/`. |\n| `memoryBase` | `number` | `65536` | The byte offset where your server's static data starts. Requests that fit below this offset use the reserved prefix at offset 0. The current edge and dev host deliver larger requests above the heap; the toiljs entrypoint reserves the input before decoding. Raising this value enlarges the prefix fast path and costs initial memory; it is not a hard upload-body cap. |\n| `initialMemory` | `number` | `4` | How much linear memory the module starts with, in **pages**. One WebAssembly page is 64 KiB, so `4` is 256 KiB. It grows on demand past this. |\n| `debug` | `boolean` | `false` | Include debug information (names and the like) in the binary. Off for production. |\n| `trapMode` | `string` | `\"allow\"` | What happens on a trapping operation (like a bad float-to-int conversion). `\"allow\"` lets it trap (the default and correct choice); `\"clamp\"` replaces traps with clamping instead. |\n\nThe `enable` array turns on WebAssembly features that are off by default in the compiler. The scaffold enables the modern set the compiled server relies on: `sign-extension`, `mutable-globals`, `nontrapping-f2i` (non-trapping float-to-int conversions), `bulk-memory` (fast `memory.copy` / `memory.fill`), `simd` (vector operations), `reference-types`, and `multi-value` (functions that return more than one value). Leave this list as scaffolded unless you have a specific reason to change it; removing an entry can make the module fail to compile or run.\n\n### The `--rpcModule` build flag\n\nOne toilscript flag is worth knowing even though it lives in your npm scripts, not in `toilconfig.json`: `--rpcModule shared/server.ts`. It tells the compiler to also emit `shared/server.ts`, the fully typed client the browser imports to call your server (the `@data` codec plus the typed `Server` surface). toiljs adds this flag for you on the request build. If your `build:server` script is missing it (older projects predate it), `toiljs doctor --fix` injects it. See [the CLI reference](../cli/README.md#what---fix-repairs).\n\n## Gotchas\n\n- **Wrap the config in `defineConfig`.** Without it you lose autocomplete and type errors on typos.\n- **Secrets never go here.** API keys, session secrets, and passwords belong in the environment, not in `toil.config.ts` (which is committed to git). See [Environment and secrets](../services/environment.md).\n- **`server.srcDir` / `server.outDir` do not move your server.** The server source location is governed by `toilconfig.json` entries. Editing these two config fields has no effect today.\n- **`nodeMode` and `daemon` are dev/self-host only.** In production the edge assigns each server its role; these settings never override that.\n- **An invalid `nodeMode` does not crash the build.** It warns and falls back to `all`.\n\n## Related\n\n- [The CLI](../cli/README.md): the commands that read this config.\n- [Environment and secrets](../services/environment.md): runtime values and how they differ from build-time config.\n- [Auth configuration](../auth/configuration.md): the auth-related environment settings behind `server.auth`.\n- [Email and 2FA](../services/email.md): the full email setup behind `server.email`.\n- [Metadata and SEO](../frontend/metadata.md): the full `client.seo` field list.\n- [Daemons and scheduled jobs](../background/daemons.md): the background layer behind `server.daemon`.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): what `server.nodeMode` selects.\n- [Images](../frontend/images.md) and [Styling](../frontend/styling.md): the features `client.images` and `toiljs configure` control.\n",
23
24
  "concepts/decorators.md": "# Decorators reference\n\nEvery feature of a toiljs backend, an HTTP route, an RPC method, a database collection, a scheduled job, is switched on by a **decorator**. This page lists them all, grouped by what they do, so you can find the right one at a glance and jump to the page that covers it in depth.\n\n## What a decorator is\n\nA **decorator** is the `@name` you write on the line just above a class, a method, or a field. It attaches meaning to that code without changing what the code itself does. You are labelling it so the compiler knows how to wire it up.\n\n```ts\n@rest('users') // <- a class decorator: \"this class is an HTTP controller\"\nclass Users {\n @get('/:id') // <- a method decorator: \"this method answers GET /users/:id\"\n public byId(): Response { /* ... */ }\n}\n```\n\nThree things to notice, because they decide where each decorator can go:\n\n- Some decorators apply to a **class** (`@rest`, `@service`, `@stream`, `@daemon`, `@database`, `@data`, `@user`).\n- Some apply to a **method** or a free **function** (`@get`, `@remote`, `@scheduled`, `@query`).\n- One applies to a **field** (`@collection`).\n\nSome take arguments, like `@get('/:id')` or `@cache(60)`; the bare ones, like `@rest` or `@daemon`, do not. You never register anything by hand: tagging the code is enough, and the build discovers it.\n\nEach decorator also belongs to a **tier** (where its code runs) or is **shared** (compiled into every tier). If tiers are new to you, read [Compute tiers](./tiers.md) first; the short version is L1 = per-request at the edge, L2 / L3 = long-lived stream connections, L4 = one global daemon.\n\n## Routing and HTTP (L1)\n\nTurn a class into an HTTP controller and its methods into routes. All run on the L1 request tier. Covered in [REST](../backend/rest.md).\n\n| Decorator | Applies to | What it does |\n| --- | --- | --- |\n| `@rest` | class | Marks the class an HTTP controller, mounted at a prefix (`@rest('users')` -> `/users`). |\n| `@route` | method | Declares a route with an explicit method + path: `@route({ method: Methods.GET, path: '/' })`. |\n| `@get` | method | Shorthand for a `GET` route: `@get('/:id')`. |\n| `@post` | method | Shorthand for a `POST` route. |\n| `@put` | method | Shorthand for a `PUT` route. |\n| `@del` | method | Shorthand for a `DELETE` route (named `del` because `delete` is a reserved word). |\n| `@patch` | method | Shorthand for a `PATCH` route. |\n| `@head` | method | Shorthand for a `HEAD` route. |\n| `@options` | method | Shorthand for an `OPTIONS` route. |\n\n## RPC (L1)\n\nExpose server functions that your own frontend calls like typed async functions. Run on L1. Covered in [RPC](../backend/rpc.md).\n\n| Decorator | Applies to | What it does |\n| --- | --- | --- |\n| `@service` | class | Marks an RPC service; its `@remote` methods are namespaced under the generated client as `Server.<service>.<method>()`. |\n| `@remote` | method / function | Marks a method (of a `@service`) or a top-level function as a client-callable RPC endpoint. |\n\n## Guards and policy (L1)\n\nAttach a rule to a route (or a whole controller). These stack above a route method. Run on L1.\n\n| Decorator | Applies to | What it does | Covered in |\n| --- | --- | --- | --- |\n| `@auth` | class / method | Requires a valid session; returns `401` otherwise. On a class it guards every route. | [Auth usage](../auth/usage.md) |\n| `@cache` | method | Caches the response at the edge and browser: `@cache(edgeMinutes, browserSeconds?, privateScope?, allowAuth?)`. | [Caching](../services/caching.md) |\n| `@ratelimit` | method | Rate-limits a route: `@ratelimit(strategy, limit, window)`. | [Rate limiting](../services/ratelimit.md) |\n\n## Realtime streams (L2 / L3)\n\nHandle a long-lived connection, keeping state per connected client. The `@stream` class runs on the L2 / L3 stream tier; its lifecycle-hook methods fire as events arrive. Covered in [Realtime streams](../realtime/streams.md).\n\n| Decorator | Applies to | What it does |\n| --- | --- | --- |\n| `@stream` | class | Marks a stream protocol handler. `@stream('name')` sets the mount name; `@stream({ scope })` picks Regional (L2) or Continental (L3). |\n| `@connect` | method | Lifecycle hook: fires when a client connects (returns a `StreamOutbound` accept/reject). |\n| `@message` | method | Lifecycle hook: fires on each inbound packet. |\n| `@close` | method | Lifecycle hook: fires on a graceful close. |\n| `@disconnect` | method | Lifecycle hook: fires on an abrupt transport loss. |\n\nA server-side broadcast hook, `@channel`, is planned but not live in the current runtime. See [Channels](../realtime/channels.md) for the status and the working client-side `useChannel` hook you can use today.\n\n## Background and daemon (L4)\n\nRecurring, run-once-globally background work. `@daemon` runs on the single L4 leader. Covered in [Daemons](../background/daemons.md).\n\n| Decorator | Applies to | What it does |\n| --- | --- | --- |\n| `@daemon` | class | Marks the single daemon class (at most one per project). May declare a zero-arg `onStart()` run once at boot. |\n| `@scheduled` | method | Runs the method on a cadence: an interval (`'30s'`, `'5m'`, `'1h'`, `'1d'`) or a 5-field cron string (`'15 9 * * 1-5'`). |\n\n## Database structure (shared)\n\nDeclare your database schema. These carry no tier of their own; they are compiled into every artifact so any tier can use them. Covered in the [database section](../database/README.md).\n\n| Decorator | Applies to | What it does |\n| --- | --- | --- |\n| `@database` | class | Marks a class as a ToilDB database; each `@collection` field becomes a typed handle (`App.users.get(...)`). |\n| `@collection` | field | Declares a field as a collection handle (`Documents` / `View` / `Unique` / `Counter` / `Events` / `Membership` / `Capacity`). |\n| `@data` | class | Marks a class serializable: the compiler generates a binary codec so it can cross the wire and the database. See [Data types](../backend/data.md). |\n| `@migrate` | function | Schema migration for a `@data` type: a free function that upgrades a record written under an old layout to the current shape (lives in `migrations/<Type>.migration.ts`). See [Data types](../backend/data.md). |\n\n## Database function kinds (data-access policy)\n\nA **function kind** labels a function or method with *which* database operations it is allowed to issue, and the compiler enforces it (a read-only `@query` that tries to write is a compile error). Covered across the [database section](../database/README.md).\n\n| Decorator | Applies to | What it does | Covered in |\n| --- | --- | --- | --- |\n| `@query` | function / method | Read-only data access. | [Database](../database/README.md) |\n| `@action` | function / method | Read plus bounded writes and claims. | [Database](../database/README.md) |\n| `@derive` | function / method | Publishes materialized views and rollups (a background materializer). | [@derive](../background/derive.md) |\n| `@job` | function / method | Background work. | [Background work](../background/README.md) |\n| `@admin` | function / method | Control-plane only operations. | [Database](../database/README.md) |\n\n## Auth and structure\n\n| Decorator | Applies to | What it does | Covered in |\n| --- | --- | --- | --- |\n| `@user` | class | Declares the authenticated-user shape; enables the typed `AuthService.getUser()`. At most one per project. | [Auth usage](../auth/usage.md) |\n| `@main` | function | Marks a single top-level function as the module entry point (exported as the WASM `main`). Rarely written by hand: toiljs supplies the entry glue. | [Project structure](../getting-started/project-structure.md) |\n\n## A note on low-level decorators\n\nAssemblyScript (the language toilscript is built on) has its own low-level decorators such as `@inline`, `@unsafe`, and `@operator`. They tune how a symbol compiles and are for advanced library authors, not everyday app code. You will not need them to build a normal toiljs app, and they are out of scope here.\n\n## Related\n\n- [Compute tiers](./tiers.md): where each decorator's code runs (L1 to L4).\n- [The type system](./types.md): the types (`u64`, `string`, `@data`) these decorators work with.\n- [REST](../backend/rest.md) and [RPC](../backend/rpc.md): the L1 surfaces.\n- [Realtime streams](../realtime/streams.md): the `@stream` surface.\n- [Daemons](../background/daemons.md) and [@derive](../background/derive.md): L4 and background work.\n- [The database (ToilDB)](../database/README.md): `@database`, `@collection`, and the function kinds.\n- [Auth](../auth/README.md): `@auth` and `@user`.\n",
24
- "concepts/security.md": "# Security\n\ntoiljs enables an enforced Content Security Policy (CSP), Cross-Origin-Opener-Policy (COOP), and Trusted Types by default in its development and self-host servers. Production builds include script integrity metadata and security headers for deployment. This page explains those defaults, how to allow additional resources, and what an external host must serve.\n\n## The model\n\nToil is built for **defense in depth**: many independent layers, so that one weak spot is not one breach. The goal is the top of our internal security bar, the Resilience and Scale Grade (see [../../RSG.md](../../RSG.md)), where each of these holds at the same time:\n\n- All traffic is encrypted in transit with modern TLS (Transport Layer Security, the encryption every `https://` connection uses).\n- The login design never lets the server see a password it could reuse.\n- Secrets never live in your code.\n- Built scripts and styles carry integrity metadata; module-graph verification also applies in browsers supporting import-map integrity.\n- There is no implicit trust between the parts of the system (zero trust): each request is checked on its own merits.\n\nThe rest of this page walks through each layer and points to where it is documented in full.\n\n## Default browser security\n\nNo configuration is needed for the framework's development or self-host servers. The defaults are:\n\n| Protection | Default | Purpose |\n| --- | --- | --- |\n| Content Security Policy | Enforced `Content-Security-Policy` header | Restricts script execution and resource loading. This is not a report-only policy. |\n| Opener isolation | `Cross-Origin-Opener-Policy: same-origin` | Isolates the document from cross-origin openers and popups. |\n| Trusted Types | `require-trusted-types-for 'script'` in the CSP | Requires trusted values at DOM injection sinks in supporting browsers. |\n| Policy creation | `trusted-types toil-script dompurify` | Allows the framework's script and HTML policies. No default policy is installed. |\n\nHSTS is not emitted by toiljs. Configure it at your HTTPS deployment if needed.\n\n### The enforced CSP\n\nThe production policy uses these directives. The script hashes are generated from the build; do not copy placeholder hashes into a deployment.\n\n| Directive | Default |\n| --- | --- |\n| `default-src` | `'self'` |\n| `base-uri` | `'none'` |\n| `object-src` | `'none'` |\n| `frame-ancestors` | `'self'` |\n| `script-src` | Generated script hashes, `'strict-dynamic'`, and `'wasm-unsafe-eval'` |\n| `script-src-attr` | `'none'` |\n| `style-src` | `'self' 'unsafe-inline'` |\n| `img-src` | `'self' data: blob:` |\n| `font-src` | `'self' data:` |\n| `connect-src` | `'self'` |\n| `worker-src` | `'self' blob:` |\n| `require-trusted-types-for` | `'script'` |\n| `trusted-types` | `toil-script dompurify` |\n\nThe compiler authorizes inline template scripts by their content hashes and external entry scripts by their integrity hashes. It also includes the integrity hashes for the bundled module graph. Prerendered pages, SSG pages, and SSR templates inherit the protected shell. Request values inserted into SSR slots do not receive new script hashes.\n\nInline event handlers and JavaScript `eval` are blocked. `'wasm-unsafe-eval'` permits WebAssembly compilation, which client password hashing needs, without allowing JavaScript `eval`. Inline CSS remains allowed for React style props and framework styles.\n\nBackend responses without an explicit CSP receive the same resource and DOM protections with `script-src 'none'`. Consequently, a standalone `Response.html(...)` does not authorize executable scripts. A custom HTML handler that needs scripts must provide an appropriate CSP explicitly.\n\n### Development and SSR\n\n`toiljs dev` uses fresh request nonces for scripts instead of production hashes. WebSocket connections (`ws:` and `wss:`) are permitted for HMR. This applies both to the client-only Vite server and to the Vite proxy used by backend projects.\n\nDevelopment SSR rotates the nonce in the trusted template before inserting request values. Production SSR takes its policy from the built template. Both paths preserve script loading and hydration without enabling unrestricted inline scripts or JavaScript `eval`.\n\n### Loading scripts\n\nUse [`Toil.Script`](../frontend/scripts.md) for application-controlled scripts loaded from React:\n\n```tsx\n<Toil.Script src=\"https://widgets.example.com/widget.js\" />\n\n<Toil.Script id=\"configure-widget\">\n {'window.widgetOptions = { compact: true };'}\n</Toil.Script>\n```\n\nExternal script URLs must use HTTP(S). Executable inline snippets load through temporary blob URLs created by the framework; those URLs are revoked after loading. `onLoad` and `onReady` run after an executable script has loaded and executed. Inert data blocks such as `type=\"application/json\"` remain inline. Inline module snippets must use absolute import URLs because relative imports cannot resolve against a blob URL.\n\nOnly pass application-controlled code and URLs to this component. A third-party script can require additional connection, image, stylesheet, or frame origins; authorizing the script itself does not allow every resource it might request.\n\n### Trusted Types and HTML\n\nIn supporting browsers, raw string assignments to protected DOM sinks such as `innerHTML` are rejected. `Toil.Script` handles its own trusted script values. `Toil.RawHtml` sanitizes HTML in the browser through a private DOMPurify instance and supplies a trusted HTML value where supported:\n\n```tsx\n<Toil.RawHtml id=\"article\" html={articleHtml} />\n```\n\n**Sanitize HTML on the server before putting it into an SSR raw slot.** Browser sanitization cannot protect the initial HTML response, which is parsed before hydration. The same server responsibility applies to `SlotValues.setRaw` and `HtmlBuilder.raw`.\n\n`Toil.sanitizeHtml(html)` is also available for browser code that needs sanitized HTML for React's `dangerouslySetInnerHTML`. It returns `string | TrustedHTML` and throws without a browser DOM. If a component calls it while rendering, place that component inside `Toil.Island` so it runs only after hydration. Browsers without Trusted Types still receive DOMPurify sanitization and the other supported CSP protections.\n\n### Allowing additional resources\n\nAdd resource origins in `client.cspSources` rather than replacing the generated CSP:\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n cspSources: {\n 'connect-src': ['https://api.example.com', 'wss://events.example.com'],\n 'img-src': ['https://images.example.com'],\n 'style-src': ['https://styles.example.com'],\n 'font-src': ['https://fonts.example.com'],\n 'frame-src': ['https://widgets.example.com'],\n },\n },\n});\n```\n\nValues are appended to the directive's defaults. If an allowed directive is absent from the default policy, toiljs creates it starting with `'self'`. Changes apply to development and to the production header and meta policy after rebuilding.\n\nSupported keys are `connect-src`, `img-src`, `media-src`, `font-src`, `style-src`, `frame-src`, `child-src`, `worker-src`, `manifest-src`, `trusted-types`, `form-action`, and `frame-ancestors`. For `trusted-types`, supply policy names rather than origins, and only add names for reviewed policies your application needs.\n\nEach array entry must be a nonempty source token without whitespace, semicolons, commas, or angle brackets. Unsupported keys and invalid values are rejected. `script-src`, `script-src-elem`, `script-src-attr`, `default-src`, `base-uri`, `object-src`, and `require-trusted-types-for` cannot be changed through this option. Script trust and DOM enforcement remain framework-owned. See the [configuration reference](./config.md#clientcspsources).\n\n### COOP and custom responses\n\n`Cross-Origin-Opener-Policy: same-origin` affects integrations that depend on a cross-origin popup retaining its opener. It does not enable COEP or guarantee `window.crossOriginIsolated` by itself.\n\nA backend handler can explicitly set CSP or COOP with `Response.setHeader`. Framework defaults fill absent headers case-insensitively and preserve explicit application values. For example, a custom handler that deliberately needs opener compatibility can set:\n\n```ts\nreturn Response.html(html)\n .setHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups');\n```\n\nThis changes that handler's response. It does not change the policy of frontend pages served from the build. Keep the CSP header and the built HTML's meta policy consistent; a more permissive header does not remove restrictions from an existing meta policy.\n\n### Deployment headers\n\n`toiljs start` serves CSP and COOP automatically, including when running multiple HTTP workers. Native backend HTTP response envelopes also include defaults. The production build writes `_headers` into the configured client output directory (`build/client/_headers` by default):\n\n```text\n/*\n Content-Security-Policy: <the complete policy generated for this build>\n Cross-Origin-Opener-Policy: same-origin\n```\n\nHosts that support this file format can consume it directly. Other static hosts, reverse proxies, and managed edge integrations must apply the generated headers to their document responses, including SSR responses. Merely uploading the HTML does not configure an external host's HTTP headers.\n\nThe HTML includes a CSP meta fallback. **COOP and `frame-ancestors` require HTTP headers**; the fallback cannot supply them. Preserve the generated import map, integrity attributes, and CSP metadata. Rebuild after changing scripts or resource permissions, and deploy matching HTML, assets, and headers together. See [Deploying a toiljs app](../getting-started/deploy.md#default-browser-security).\n\n### Checking a deployment\n\nInspect a real document response from your deployed origin:\n\n```bash\ncurl -sSI https://app.example.com/\n```\n\nConfirm it includes an enforced `Content-Security-Policy` with `require-trusted-types-for 'script'` and `Cross-Origin-Opener-Policy: same-origin`. Check an SSR URL too if your app uses SSR. In browser developer tools, review CSP violations while exercising navigation, scripts, and integrations. A CSP violation usually identifies the resource and directive that need attention.\n\nThe framework's regression suite checks headers, native response envelopes, sanitization, and browser behavior. From the framework checkout, run:\n\n```bash\nnpm run build\nnpx vitest run test/security.test.ts test/security-native.test.ts test/dom/security.test.tsx\nTOILJS_BROWSER_TESTS=1 npx vitest run test/security-browser.test.ts\n```\n\nThe browser suite requires Chrome. Set `CHROME_BIN` if it is installed outside `/usr/bin/google-chrome`. It checks blocked injections alongside SSR hydration, lazy routes, `Toil.Script`, static serving, production workers, and development HMR.\n\n## The backend is a sandbox\n\nEvery site (every tenant) on toil runs inside a **sandbox**: a walled-off compartment that can only touch what the host explicitly hands it, and can never reach the host itself or another tenant. Your server code is compiled to **WebAssembly** (wasm, a portable binary instruction format that runs in a tightly controlled virtual machine), and the edge loads each tenant as its own isolated wasm module.\n\nThat isolation is backed by **hard per-host limits**, enforced by the host and not by your code:\n\n- **A committed-memory cap.** Each tenant may commit only a bounded amount of real memory (on the order of tens of MiB). A tenant cannot grow without bound and starve its neighbors.\n- **A compute cap.** Each request gets a bounded compute budget, and when a request exceeds it, the host stops it. A tenant cannot spin forever on the request path.\n- **Rate limits.** How often one client may call a route is capped (see [Transport and rate limiting](#transport-and-rate-limiting) below).\n- **Hostile-wasm containment.** The runtime is hardened to run untrusted, even deliberately malicious, wasm without letting it escape.\n\nThe point of all of this: a buggy or malicious tenant can crash or hang only itself. It cannot escape its sandbox, exhaust the host, or read or corrupt another tenant's data.\n\n## Passwords: post-quantum login\n\nToil ships a complete login system you turn on with one line, and it is built so the server never handles a usable password. See [../auth/README.md](../auth/README.md) for the overview and [../auth/how-it-works.md](../auth/how-it-works.md) for the mechanism.\n\nHere is why that matters. The pattern almost the whole internet uses is \"send the password over TLS, then hash it on the server.\" That is the accepted baseline, but it caps security below the top grade, because for a moment the server holds a live, replayable credential. Anything that reads server memory or a stray log line at the wrong instant walks away with real passwords, and that is one of the most common breach paths in practice.\n\nToil designs that surface away. The proof that you know your password happens without the password ever crossing the wire in a form anyone can replay, so a fully breached server still yields no usable credentials.\n\n## Subresource Integrity (SRI) on the client bundle\n\nThis is the layer that protects the code running in your users' browsers.\n\n### The risk\n\nYour app's JavaScript and CSS are static files served over the network, often through a CDN (Content Delivery Network, the fleet of edge caches that sits between your server and the browser). If any point in that path is compromised (the host, a cache, or the network itself), an attacker can serve **tampered** JavaScript or CSS: a modified bundle that steals sessions, skims form input, or rewrites the page. The browser, on its own, has no way to know the bytes it received are not the bytes you shipped.\n\n### What toil does at build time\n\n**Subresource Integrity (SRI)** is a browser feature that closes this gap. You attach a cryptographic fingerprint of a file to the tag that loads it, and the browser refuses to use the file unless its bytes match that fingerprint.\n\nAt build time (verified in [../../src/compiler/sri.ts](../../src/compiler/sri.ts)), toil adds that fingerprint to every **local** asset tag in the built HTML:\n\n- every `<script src=...>`,\n- every `<link rel=\"modulepreload\" href=...>`,\n- every `<link rel=\"stylesheet\" href=...>`.\n\nTo each it adds two attributes: `integrity=\"sha384-<base64>\"` and `crossorigin=\"anonymous\"`.\n\n- **`sha384`** is the hash algorithm: the file's bytes are run through SHA-384 (a member of the SHA-2 family), producing a fixed fingerprint that changes if even one byte changes. The `integrity` value is that fingerprint, base64-encoded, with a `sha384-` prefix.\n- **`crossorigin=\"anonymous\"`** is required for the browser to actually verify the fingerprint. It is a no-op when the asset is same-origin, so adding it is always safe.\n\nTags that are not toil's to hash are left completely untouched: external URLs (anything with a scheme like `https:`, a protocol-relative `//cdn/...`, or a `data:` URI), inline scripts (a `<script>` with no `src`), and any tag that already carries its own `integrity`.\n\n### Why an import map is also emitted\n\nA per-tag `integrity` only protects the **entry** script: the one file named directly in the tag. But a modern app is an ES module graph (ECMAScript modules, the browser's native `import` system). The entry script statically imports other chunks (for example the shared React vendor chunk), and it lazily pulls in each route with a dynamic `import()` as the user navigates. Those follow-on files are fetched by the browser's **module loader**, which does **not** inherit the entry tag's `integrity`. Without more, everything past the entry point would be unverified.\n\nSo toil also emits an **import map**: a `<script type=\"importmap\">` tag (a standard browser mechanism for describing module resolution). Its `integrity` section maps every emitted JavaScript chunk to its own `sha384` fingerprint. This is the platform mechanism that extends verification to the module loader's fetches, so the **full** dynamic `import()` graph is covered, not just the entry tag. Browsers that do not yet support the `integrity` key simply ignore it (progressive enhancement: nothing breaks on older browsers, they just get one fewer check).\n\n### Why it stays stable\n\nA fingerprint is only useful if it keeps matching the bytes actually served. Toil guarantees that by **content-hashing** every asset it puts SRI on: the build tool (Vite) names each JavaScript chunk and each CSS file with a hash of its own contents baked into the URL (verified in [../../src/compiler/vite.ts](../../src/compiler/vite.ts)). Because the URL is pinned to the exact bytes, the fingerprint baked into the HTML can never falsely mismatch.\n\nThis prevents a real failure mode. Imagine a stylesheet kept a stable URL but its bytes changed on a new deploy. A user still holding an older HTML page (with the old baked fingerprint) would fetch the new bytes, the hashes would disagree, and the browser would **block** the stylesheet, breaking the page for that user. Content-hashing sidesteps this: new bytes get a new URL, so old HTML keeps pointing at the old bytes, and every fingerprint always matches. (Images and fonts keep stable names on purpose: they carry no SRI and are often referenced by fixed path.)\n\n### What the browser does\n\nFor each asset that carries an `integrity` value (from a tag or from the import map), the browser hashes the bytes it received and compares them to the expected fingerprint. If they match, it runs the script or applies the stylesheet. If they do not match, it refuses: the asset is blocked and tampered code never runs.\n\n```mermaid\nflowchart TD\n A[\"Browser loads the built page HTML\"] --> B[\"Reads integrity tags plus the importmap integrity section\"]\n B --> C[\"Fetches an asset: entry script, vendor chunk, route chunk, or stylesheet\"]\n C --> D[\"Computes the sha384 hash of the received bytes\"]\n D --> E{\"Hash matches the baked fingerprint?\"}\n E -->|yes| F[\"Runs the script or applies the stylesheet\"]\n E -->|no| G[\"Refuses: blocks the asset, tampered code never runs\"]\n```\n\n### When it applies\n\nSRI is part of the **production build output**. The dev server hands the browser un-hashed modules straight from Vite, where SRI would be meaningless, so it is not applied there. You get the protection automatically in what you ship, with nothing to configure.\n\n## Secrets\n\nSecrets (API keys, signing keys, and the like) are **never compiled into the wasm**. They are provided per-host at runtime through the secure environment store and read with `Environment.getSecure(key)`, which is kept strictly separate from the plain-variable `Environment.get(key)`: a secret can never leak out through a code path that only reads plain config. Because secrets live outside your code, they are never in your repository or its history. See [../services/environment.md](../services/environment.md) for the full model.\n\n## Transport and rate limiting\n\nAll traffic runs over modern **TLS**, so nothing sensitive travels in the clear. The edge speaks **HTTP/3** (built on QUIC, a faster, head-of-line-blocking-free transport) with graceful fallback to HTTP/2 and HTTP/1.1, so newer clients get the modern path and older clients still connect and work.\n\nOn top of that, you can cap how often a client may hit any given route. Adding the `@ratelimit` decorator to a route makes the edge reject a client that goes over the limit **before your code runs**, which blunts brute-force and abuse and helps absorb bursts and denial-of-service (DDoS) pressure at the edge rather than inside your handler. Only routes that opt in pay any cost; everything else stays on the untouched fast path. See [../services/ratelimit.md](../services/ratelimit.md) for the strategies and per-user (keyed) limits.\n\n## Related\n\n- [Authentication](../auth/README.md): the post-quantum login system and `@auth`-guarded routes.\n- [Environment](../services/environment.md): plain variables versus secrets, and where they live.\n- [Rate limiting](../services/ratelimit.md): the `@ratelimit` decorator, strategies, and keyed limits.\n- [Design principles](../introduction/design-principles.md): the ideas the framework is built on.\n",
25
+ "concepts/security.md": "# Security\n\ntoiljs enables an enforced Content Security Policy (CSP), Cross-Origin-Opener-Policy (COOP), and Trusted Types by default in its development and self-host servers. Production builds include script integrity metadata and security headers for deployment. This page explains those defaults, how to allow additional resources, and what an external host must serve.\n\n## The model\n\nToil is built for **defense in depth**: many independent layers, so that one weak spot is not one breach. The goal is the top of our internal security bar, the Resilience and Scale Grade (see [../../RSG.md](../../RSG.md)), where each of these holds at the same time:\n\n- All traffic is encrypted in transit with modern TLS (Transport Layer Security, the encryption every `https://` connection uses).\n- The login design never lets the server see a password it could reuse.\n- Secrets never live in your code.\n- Built scripts and styles carry integrity metadata; module-graph verification also applies in browsers supporting import-map integrity.\n- There is no implicit trust between the parts of the system (zero trust): each request is checked on its own merits.\n\nThe rest of this page walks through each layer and points to where it is documented in full.\n\n## Default browser security\n\nNo configuration is needed for the framework's development or self-host servers. The defaults are:\n\n| Protection | Default | Purpose |\n| --- | --- | --- |\n| Content Security Policy | Enforced `Content-Security-Policy` header | Restricts script execution and resource loading. This is not a report-only policy. |\n| Opener isolation | `Cross-Origin-Opener-Policy: same-origin` | Isolates the document from cross-origin openers and popups. |\n| Trusted Types | `require-trusted-types-for 'script'` in the CSP | Requires trusted values at DOM injection sinks in supporting browsers. |\n| Policy creation | `trusted-types toil-script dompurify` | Allows the framework's script and HTML policies. No default policy is installed. |\n\nHSTS is not emitted by toiljs. Configure it at your HTTPS deployment if needed.\n\n### The enforced CSP\n\nThe production policy uses these directives. The script hashes are generated from the build; do not copy placeholder hashes into a deployment.\n\n| Directive | Default |\n| --- | --- |\n| `default-src` | `'self'` |\n| `base-uri` | `'none'` |\n| `object-src` | `'none'` |\n| `frame-ancestors` | `'self'` |\n| `script-src` | Generated script hashes, `'strict-dynamic'`, and `'wasm-unsafe-eval'` |\n| `script-src-attr` | `'none'` |\n| `style-src` | `'self' 'unsafe-inline'` |\n| `img-src` | `'self' data: blob:` |\n| `font-src` | `'self' data:` |\n| `connect-src` | `'self'` |\n| `worker-src` | `'self' blob:` |\n| `require-trusted-types-for` | `'script'` |\n| `trusted-types` | `toil-script dompurify` |\n\nThe compiler authorizes inline template scripts by their content hashes and external entry scripts by their integrity hashes. It also includes the integrity hashes for the bundled module graph. Prerendered pages, SSG pages, and SSR templates inherit the protected shell. Request values inserted into SSR slots do not receive new script hashes.\n\nInline event handlers and JavaScript `eval` are blocked. `'wasm-unsafe-eval'` permits WebAssembly compilation, which client password hashing needs, without allowing JavaScript `eval`. Inline CSS remains allowed for React style props and framework styles.\n\nBackend responses without an explicit CSP receive the same resource and DOM protections with `script-src 'none'`. Consequently, a standalone `Response.html(...)` does not authorize executable scripts. A custom HTML handler that needs scripts must provide an appropriate CSP explicitly.\n\n### Development and SSR\n\n`toiljs dev` uses fresh request nonces for scripts instead of production hashes. WebSocket connections (`ws:` and `wss:`) are permitted for HMR. This applies both to the client-only Vite server and to the Vite proxy used by backend projects.\n\nDevelopment SSR rotates the nonce in the trusted template before inserting request values. Production SSR takes its policy from the built template. Both paths preserve script loading and hydration without enabling unrestricted inline scripts or JavaScript `eval`.\n\n### Loading scripts\n\nUse [`Toil.Script`](../frontend/scripts.md) for application-controlled scripts loaded from React:\n\n```tsx\n<Toil.Script src=\"https://widgets.example.com/widget.js\" />\n\n<Toil.Script id=\"configure-widget\">\n {'window.widgetOptions = { compact: true };'}\n</Toil.Script>\n```\n\nExternal script URLs must use HTTP(S). Executable inline snippets load through temporary blob URLs created by the framework; those URLs are revoked after loading. `onLoad` and `onReady` run after an executable script has loaded and executed. Inert data blocks such as `type=\"application/json\"` remain inline. Inline module snippets must use absolute import URLs because relative imports cannot resolve against a blob URL.\n\nOnly pass application-controlled code and URLs to this component. A third-party script can require additional connection, image, stylesheet, or frame origins; authorizing the script itself does not allow every resource it might request.\n\n### Trusted Types and HTML\n\nIn supporting browsers, raw string assignments to protected DOM sinks such as `innerHTML` are rejected. `Toil.Script` handles its own trusted script values. `Toil.RawHtml` sanitizes HTML in the browser through a private DOMPurify instance and supplies a trusted HTML value where supported:\n\n```tsx\n<Toil.RawHtml id=\"article\" html={articleHtml} />\n```\n\n**Sanitize HTML on the server before putting it into an SSR raw slot.** Browser sanitization cannot protect the initial HTML response, which is parsed before hydration. The same server responsibility applies to `SlotValues.setRaw` and `HtmlBuilder.raw`.\n\n`Toil.sanitizeHtml(html)` is also available for browser code that needs sanitized HTML for React's `dangerouslySetInnerHTML`. It returns `string | TrustedHTML` and throws without a browser DOM. If a component calls it while rendering, place that component inside `Toil.Island` so it runs only after hydration. Browsers without Trusted Types still receive DOMPurify sanitization and the other supported CSP protections.\n\n### Allowing additional resources\n\nAdd resource origins in `client.cspSources` rather than replacing the generated CSP:\n\n```ts\n// toil.config.ts\nimport { defineConfig } from 'toiljs/compiler';\n\nexport default defineConfig({\n client: {\n cspSources: {\n 'connect-src': ['https://api.example.com', 'wss://events.example.com'],\n 'img-src': ['https://images.example.com'],\n 'style-src': ['https://styles.example.com'],\n 'font-src': ['https://fonts.example.com'],\n 'frame-src': ['https://widgets.example.com'],\n },\n },\n});\n```\n\nValues are appended to the directive's defaults. If an allowed directive is absent from the default policy, toiljs creates it starting with `'self'`. Changes apply to development and to the production header and meta policy after rebuilding.\n\nSupported keys are `connect-src`, `img-src`, `media-src`, `font-src`, `style-src`, `frame-src`, `child-src`, `worker-src`, `manifest-src`, `trusted-types`, `form-action`, `frame-ancestors`, `script-src`, `script-src-elem`, and `require-trusted-types-for`. For `trusted-types`, supply policy names rather than origins, and only add names for reviewed policies your application needs.\n\nEach array entry must be a nonempty source token without whitespace, semicolons, commas, or angle brackets. Unsupported keys and invalid values are rejected. `script-src-attr`, `default-src`, `base-uri`, and `object-src` remain framework-owned. See the [configuration reference](./config.md#clientcspsources).\n\nExplicit `script-src` and `script-src-elem` arrays **replace** their generated\ndirectives instead of extending them. An empty script array means `'none'`.\nAn empty `require-trusted-types-for` array removes DOM sink enforcement. Omitting\nthese options preserves the strict hash/nonce, strict-dynamic, and Trusted Types\ndefaults. These explicit overrides are for integrations that inject scripts after\nthe build and cannot use the normal trusted script loader.\n\nFor example, a site that chooses Cloudflare's automatically injected Web Analytics\nand JavaScript Detections can configure:\n\n```ts\nclient: {\n cspSources: {\n 'script-src': [\"'self'\", \"'unsafe-inline'\", \"'wasm-unsafe-eval'\", 'blob:',\n 'https://static.cloudflareinsights.com', 'https://challenges.cloudflare.com'],\n 'connect-src': ['https://cloudflareinsights.com', 'https://challenges.cloudflare.com'],\n 'frame-src': ['https://challenges.cloudflare.com'],\n 'require-trusted-types-for': [],\n },\n}\n```\n\nThis permits arbitrary inline script elements and raw DOM sinks, so it offers\nless injection protection than the default policy. Inline event handlers and\nJavaScript eval remain blocked. Prefer the default with `Toil.Script` for\nintegrations you control, or a fresh per-response nonce integration at the origin.\nDeploy rebuilt HTML and the updated HTTP policy together: a more permissive\nheader cannot override an older restrictive HTML meta policy, or vice versa.\n\n### COOP and custom responses\n\n`Cross-Origin-Opener-Policy: same-origin` affects integrations that depend on a cross-origin popup retaining its opener. It does not enable COEP or guarantee `window.crossOriginIsolated` by itself.\n\nA backend handler can explicitly set CSP or COOP with `Response.setHeader`. Framework defaults fill absent headers case-insensitively and preserve explicit application values. For example, a custom handler that deliberately needs opener compatibility can set:\n\n```ts\nreturn Response.html(html)\n .setHeader('Cross-Origin-Opener-Policy', 'same-origin-allow-popups');\n```\n\nThis changes that handler's response. It does not change the policy of frontend pages served from the build. Keep the CSP header and the built HTML's meta policy consistent; a more permissive header does not remove restrictions from an existing meta policy.\n\n### Deployment headers\n\n`toiljs start` serves CSP and COOP automatically, including when running multiple HTTP workers. Native backend HTTP response envelopes also include defaults. The production build writes `_headers` into the configured client output directory (`build/client/_headers` by default):\n\n```text\n/*\n Content-Security-Policy: <the complete policy generated for this build>\n Cross-Origin-Opener-Policy: same-origin\n```\n\nHosts that support this file format can consume it directly. Other static hosts, reverse proxies, and managed edge integrations must apply the generated headers to their document responses, including SSR responses. Merely uploading the HTML does not configure an external host's HTTP headers.\n\nAfter a successful client build, `toiljs build` prints deployment instructions\nfrom the final `_headers` file, including rules written by project plugins. The\noutput includes Cloudflare filter expressions, header names, complete values,\nand the **Set static** or **Remove** operation for each rule, in file order.\nThe hostname comes from `client.seo.url` when configured; otherwise the output\nasks you to scope the expressions to your deployment hostname. Paths, wildcard\nrules, CSP resource origins, and COOP exceptions come from the generated rules.\nRules using placeholders are shown with instructions to configure them at the\norigin or in a Worker. No additional logging flag is required. Server-only\nbuilds and builds without generated CSP/COOP policies do not print these steps.\n\nThe HTML includes a CSP meta fallback. **COOP and `frame-ancestors` require HTTP headers**; the fallback cannot supply them. Preserve the generated import map, integrity attributes, and CSP metadata. Rebuild after changing scripts or resource permissions, and deploy matching HTML, assets, and headers together. See [Deploying a toiljs app](../getting-started/deploy.md#default-browser-security).\n\n### Checking a deployment\n\nInspect a real document response from your deployed origin:\n\n```bash\ncurl -sSI https://app.example.com/\n```\n\nConfirm it includes an enforced `Content-Security-Policy` with `require-trusted-types-for 'script'` and `Cross-Origin-Opener-Policy: same-origin`. Check an SSR URL too if your app uses SSR. In browser developer tools, review CSP violations while exercising navigation, scripts, and integrations. A CSP violation usually identifies the resource and directive that need attention.\n\nThe framework's regression suite checks headers, native response envelopes, sanitization, and browser behavior. From the framework checkout, run:\n\n```bash\nnpm run build\nnpx vitest run test/security.test.ts test/security-native.test.ts test/dom/security.test.tsx\nTOILJS_BROWSER_TESTS=1 npx vitest run test/security-browser.test.ts\n```\n\nThe browser suite requires Chrome. Set `CHROME_BIN` if it is installed outside `/usr/bin/google-chrome`. It checks blocked injections alongside SSR hydration, lazy routes, `Toil.Script`, static serving, production workers, and development HMR.\n\n## The backend is a sandbox\n\nEvery site (every tenant) on toil runs inside a **sandbox**: a walled-off compartment that can only touch what the host explicitly hands it, and can never reach the host itself or another tenant. Your server code is compiled to **WebAssembly** (wasm, a portable binary instruction format that runs in a tightly controlled virtual machine), and the edge loads each tenant as its own isolated wasm module.\n\nThat isolation is backed by **hard per-host limits**, enforced by the host and not by your code:\n\n- **A committed-memory cap.** Each tenant may commit only a bounded amount of real memory (on the order of tens of MiB). A tenant cannot grow without bound and starve its neighbors.\n- **A compute cap.** Each request gets a bounded compute budget, and when a request exceeds it, the host stops it. A tenant cannot spin forever on the request path.\n- **Rate limits.** How often one client may call a route is capped (see [Transport and rate limiting](#transport-and-rate-limiting) below).\n- **Hostile-wasm containment.** The runtime is hardened to run untrusted, even deliberately malicious, wasm without letting it escape.\n\nThe point of all of this: a buggy or malicious tenant can crash or hang only itself. It cannot escape its sandbox, exhaust the host, or read or corrupt another tenant's data.\n\n## Passwords: post-quantum login\n\nToil ships a complete login system you turn on with one line, and it is built so the server never handles a usable password. See [../auth/README.md](../auth/README.md) for the overview and [../auth/how-it-works.md](../auth/how-it-works.md) for the mechanism.\n\nHere is why that matters. The pattern almost the whole internet uses is \"send the password over TLS, then hash it on the server.\" That is the accepted baseline, but it caps security below the top grade, because for a moment the server holds a live, replayable credential. Anything that reads server memory or a stray log line at the wrong instant walks away with real passwords, and that is one of the most common breach paths in practice.\n\nToil designs that surface away. The proof that you know your password happens without the password ever crossing the wire in a form anyone can replay, so a fully breached server still yields no usable credentials.\n\n## Subresource Integrity (SRI) on the client bundle\n\nThis is the layer that protects the code running in your users' browsers.\n\n### The risk\n\nYour app's JavaScript and CSS are static files served over the network, often through a CDN (Content Delivery Network, the fleet of edge caches that sits between your server and the browser). If any point in that path is compromised (the host, a cache, or the network itself), an attacker can serve **tampered** JavaScript or CSS: a modified bundle that steals sessions, skims form input, or rewrites the page. The browser, on its own, has no way to know the bytes it received are not the bytes you shipped.\n\n### What toil does at build time\n\n**Subresource Integrity (SRI)** is a browser feature that closes this gap. You attach a cryptographic fingerprint of a file to the tag that loads it, and the browser refuses to use the file unless its bytes match that fingerprint.\n\nAt build time (verified in [../../src/compiler/sri.ts](../../src/compiler/sri.ts)), toil adds that fingerprint to every **local** asset tag in the built HTML:\n\n- every `<script src=...>`,\n- every `<link rel=\"modulepreload\" href=...>`,\n- every `<link rel=\"stylesheet\" href=...>`.\n\nTo each it adds two attributes: `integrity=\"sha384-<base64>\"` and `crossorigin=\"anonymous\"`.\n\n- **`sha384`** is the hash algorithm: the file's bytes are run through SHA-384 (a member of the SHA-2 family), producing a fixed fingerprint that changes if even one byte changes. The `integrity` value is that fingerprint, base64-encoded, with a `sha384-` prefix.\n- **`crossorigin=\"anonymous\"`** is required for the browser to actually verify the fingerprint. It is a no-op when the asset is same-origin, so adding it is always safe.\n\nTags that are not toil's to hash are left completely untouched: external URLs (anything with a scheme like `https:`, a protocol-relative `//cdn/...`, or a `data:` URI), inline scripts (a `<script>` with no `src`), and any tag that already carries its own `integrity`.\n\n### Why an import map is also emitted\n\nA per-tag `integrity` only protects the **entry** script: the one file named directly in the tag. But a modern app is an ES module graph (ECMAScript modules, the browser's native `import` system). The entry script statically imports other chunks (for example the shared React vendor chunk), and it lazily pulls in each route with a dynamic `import()` as the user navigates. Those follow-on files are fetched by the browser's **module loader**, which does **not** inherit the entry tag's `integrity`. Without more, everything past the entry point would be unverified.\n\nSo toil also emits an **import map**: a `<script type=\"importmap\">` tag (a standard browser mechanism for describing module resolution). Its `integrity` section maps every emitted JavaScript chunk to its own `sha384` fingerprint. This is the platform mechanism that extends verification to the module loader's fetches, so the **full** dynamic `import()` graph is covered, not just the entry tag. Browsers that do not yet support the `integrity` key simply ignore it (progressive enhancement: nothing breaks on older browsers, they just get one fewer check).\n\n### Why it stays stable\n\nA fingerprint is only useful if it keeps matching the bytes actually served. Toil guarantees that by **content-hashing** every asset it puts SRI on: the build tool (Vite) names each JavaScript chunk and each CSS file with a hash of its own contents baked into the URL (verified in [../../src/compiler/vite.ts](../../src/compiler/vite.ts)). Because the URL is pinned to the exact bytes, the fingerprint baked into the HTML can never falsely mismatch.\n\nThis prevents a real failure mode. Imagine a stylesheet kept a stable URL but its bytes changed on a new deploy. A user still holding an older HTML page (with the old baked fingerprint) would fetch the new bytes, the hashes would disagree, and the browser would **block** the stylesheet, breaking the page for that user. Content-hashing sidesteps this: new bytes get a new URL, so old HTML keeps pointing at the old bytes, and every fingerprint always matches. (Images and fonts keep stable names on purpose: they carry no SRI and are often referenced by fixed path.)\n\n### What the browser does\n\nFor each asset that carries an `integrity` value (from a tag or from the import map), the browser hashes the bytes it received and compares them to the expected fingerprint. If they match, it runs the script or applies the stylesheet. If they do not match, it refuses: the asset is blocked and tampered code never runs.\n\n```mermaid\nflowchart TD\n A[\"Browser loads the built page HTML\"] --> B[\"Reads integrity tags plus the importmap integrity section\"]\n B --> C[\"Fetches an asset: entry script, vendor chunk, route chunk, or stylesheet\"]\n C --> D[\"Computes the sha384 hash of the received bytes\"]\n D --> E{\"Hash matches the baked fingerprint?\"}\n E -->|yes| F[\"Runs the script or applies the stylesheet\"]\n E -->|no| G[\"Refuses: blocks the asset, tampered code never runs\"]\n```\n\n### When it applies\n\nSRI is part of the **production build output**. The dev server hands the browser un-hashed modules straight from Vite, where SRI would be meaningless, so it is not applied there. You get the protection automatically in what you ship, with nothing to configure.\n\n## Secrets\n\nSecrets (API keys, signing keys, and the like) are **never compiled into the wasm**. They are provided per-host at runtime through the secure environment store and read with `Environment.getSecure(key)`, which is kept strictly separate from the plain-variable `Environment.get(key)`: a secret can never leak out through a code path that only reads plain config. Because secrets live outside your code, they are never in your repository or its history. See [../services/environment.md](../services/environment.md) for the full model.\n\n## Transport and rate limiting\n\nAll traffic runs over modern **TLS**, so nothing sensitive travels in the clear. The edge speaks **HTTP/3** (built on QUIC, a faster, head-of-line-blocking-free transport) with graceful fallback to HTTP/2 and HTTP/1.1, so newer clients get the modern path and older clients still connect and work.\n\nOn top of that, you can cap how often a client may hit any given route. Adding the `@ratelimit` decorator to a route makes the edge reject a client that goes over the limit **before your code runs**, which blunts brute-force and abuse and helps absorb bursts and denial-of-service (DDoS) pressure at the edge rather than inside your handler. Only routes that opt in pay any cost; everything else stays on the untouched fast path. See [../services/ratelimit.md](../services/ratelimit.md) for the strategies and per-user (keyed) limits.\n\n## Related\n\n- [Authentication](../auth/README.md): the post-quantum login system and `@auth`-guarded routes.\n- [Environment](../services/environment.md): plain variables versus secrets, and where they live.\n- [Rate limiting](../services/ratelimit.md): the `@ratelimit` decorator, strategies, and keyed limits.\n- [Design principles](../introduction/design-principles.md): the ideas the framework is built on.\n",
25
26
  "concepts/tiers.md": "# Compute tiers\n\nYour toiljs backend runs across four **compute tiers**, from a per-request handler at the very edge (L1) up to a single worldwide coordinator (L4). You write one project; the build decides which code belongs to which tier.\n\n## What a tier is\n\nA **tier** is a place your server code runs, defined by two things: how *close* it sits to the user, and how *long* one copy of it lives. The Dacely **edge** is a fleet of servers in many cities. Some work wants to run as close to the user as possible for speed. Other work wants exactly one copy in the whole world so it stays coordinated. A tier is the framework's answer to \"where and for how long should this piece of code live?\"\n\nThere are four tiers, named L1 through L4. The number is the **scope**: L1 is the smallest and nearest (one edge node), and each higher number widens the scope until L4 covers the entire globe.\n\n```mermaid\nflowchart TB\n subgraph L4[\"L4 - Global (one leader worldwide)\"]\n direction TB\n D[\"@daemon / @scheduled<br/>rollups, cleanup, polling\"]\n subgraph L3[\"L3 - Continental (per continent)\"]\n direction TB\n C[\"@stream (Continental scope)<br/>cross-region coordination\"]\n subgraph L2[\"L2 - Regional (per region)\"]\n direction TB\n R[\"@stream (Regional scope)<br/>chat, presence, live cursors\"]\n subgraph L1[\"L1 - Hot / edge (per request)\"]\n H[\"@rest, @service, @remote<br/>HTTP + RPC, the default\"]\n end\n end\n end\n end\n```\n\nRead the diagram as concentric rings: L1 is the inner ring nearest the user, and each outer ring is a wider, longer-lived scope. Most of your code lives in the innermost ring.\n\n## The four tiers at a glance\n\n| Tier | Name | How close | How many copies | Lives for | Runs |\n| --- | --- | --- | --- | --- | --- |\n| **L1** | Hot / edge | The exact node nearest the user | A fresh one per request | One request | `@rest`, `@service` / `@remote` |\n| **L2** | Regional | A region (a group of nearby cities) | One box per connection | The connection | `@stream` (Regional scope) |\n| **L3** | Continental | A continent | One box per connection | The connection | `@stream` (Continental scope) |\n| **L4** | Global / daemon | One place worldwide | Exactly one leader (plus a warm standby) | Until redeployed | `@daemon`, `@scheduled` |\n\nThe tier names come straight from the edge runtime (its node roles are `Hot`, `Regional`, `Continental`, and `Daemon`).\n\n## L1: Hot (request/response)\n\n**What:** a plain request-in, response-out handler. This is the default tier and where most code lives.\n\n**How it behaves:** a fresh copy of your handler serves each request, on whatever node is nearest the caller. Nothing you store on a field survives to the next request, because the next request may be a brand-new copy on the other side of the planet. This is called being **stateless**. It is what lets your app scale to the whole world with no coordination. When you need something to persist, you write it to [ToilDB](../database/README.md), the shared database.\n\nL1 is the lowest latency tier: the code runs on the node the user already reached, so there is no extra hop.\n\n```ts\n// L1: a fresh box per request. `hits` does NOT persist across requests.\n@rest('hello')\nclass Hello {\n private hits: i32 = 0; // reset every request\n\n @get('/')\n public greet(): Response {\n this.hits = this.hits + 1; // always 1\n return Response.text('hi\\n');\n }\n}\n```\n\nSee [REST](../backend/rest.md) and [RPC](../backend/rpc.md).\n\n## L2 and L3: streams (long-lived connections)\n\n**What:** a **stream** is a long-lived connection (think a chat socket) where the server keeps state *per connected client* for as long as they stay connected.\n\n**How it behaves:** when a client connects, the edge creates one resident **box** (one running copy of your `@stream` class) and pins it to a single worker. That same box handles every message from that client and is torn down when they leave. Because the box stays alive, its fields *do* persist across events, unlike L1. This is what makes a running message count, a game session, or a live cursor possible.\n\nA `@stream` picks its scope with `@stream({ scope })`:\n\n- **`StreamScope.Regional`** puts the box in the user's region (L2). Closest, lowest latency, smallest blast radius. Use it for per-connection state that only that one client cares about.\n- **`StreamScope.Continental`** puts the box at a continent-wide node (L3). A little farther, but many clients across a continent can be steered to the *same* box, which is what you want when connected users must share state (a shared room, a leaderboard everyone updates).\n\nThe trade-off is the theme of this whole page: nearer (L2) is faster; wider (L3) lets more clients coordinate on one box.\n\n```ts\n// L2/L3: the box is resident, so `count` survives every message.\n@stream({ scope: StreamScope.Regional })\nclass Echo {\n private count: i32 = 0;\n\n @connect onConnect(): StreamOutbound {\n this.count = 0;\n return StreamOutbound.accept();\n }\n @message onMessage(pkt: StreamPacket): StreamOutbound {\n this.count = this.count + 1; // persists across events\n return StreamOutbound.empty();\n }\n @close onClose(): void { /* box torn down after this */ }\n}\n```\n\nSee [Realtime streams](../realtime/streams.md).\n\n## L4: the daemon (global coordination)\n\n**What:** the daemon is a single, elected leader for your whole app, running recurring background work on a schedule.\n\n**How it behaves:** unlike every other tier, there is exactly **one** live daemon box in the entire world for your domain (with a warm standby ready to take over if the leader fails). It is not tied to any request or connection. It wakes on a cadence (an interval like `\"1h\"`, or a cron schedule) and does coordination work: rolling up analytics, cleaning up expired rows, polling an upstream API. Because there is only ever one leader, a `@scheduled` task runs **at most once** per due tick across the planet, which is exactly what you want for work that must not double-fire.\n\nL4 is the highest-latency, most-consistent tier: it is far from any single user, but it is the one place where \"do this exactly once, globally\" is true.\n\n```ts\n// L4: one leader worldwide runs this hourly.\n@daemon\nclass Jobs {\n @scheduled('1h')\n hourly(): void {\n // rollups, cleanup, polling an upstream, ...\n }\n}\n```\n\nSee [Daemons](../background/daemons.md).\n\n## How code is routed to a tier\n\nYou do not configure tiers. You opt into one by adding an **entry file** with the right name and using the matching **surface decorator**. A surface decorator is the top-level decorator that says what kind of endpoint a class is (`@rest`, `@stream`, `@daemon`).\n\nAt build time, `toiljs build` runs the compiler once per tier and hands each pass only the code that belongs to it. Each tier compiles into its own WebAssembly file (its own `.wasm` **artifact**), so the request build never carries stream or daemon code, and vice versa.\n\n| Entry file (`server/`) | Surface decorator | Artifact | Tier |\n| --- | --- | --- | --- |\n| `main.ts` | `@rest`, `@service` / `@remote` | `release.wasm` | L1 request |\n| `main.stream.ts` | `@stream` | `release-stream.wasm` | L2 / L3 stream |\n| `main.daemon.ts` | `@daemon`, `@scheduled` | `release-cold.wasm` | L4 daemon |\n\nShared building blocks carry no tier of their own. Your [`@data` classes](../backend/data.md) and your [`@database` schema](../database/README.md) are compiled into *every* artifact, because any tier may need to read or write the database. The stream and daemon tiers are opt-in: a project with no `@stream` and no `@daemon` just builds the single `release.wasm` and behaves exactly like a request-only app.\n\nFor the entry-file conventions and the full build flow, see [Project structure](../getting-started/project-structure.md).\n\n## Why tiers matter: latency vs consistency\n\nPicking a tier is a trade-off between two things a junior developer should keep in mind:\n\n- **Latency** (how fast a single user gets an answer): lower tiers win. L1 runs on the node the user already reached.\n- **Consistency and shared state** (many actors agreeing on one thing): higher tiers win. L4 has exactly one copy in the world, so it is trivially consistent, but it is far from everyone.\n\nA rule of thumb:\n\n- Answering one request as fast as possible: **L1**.\n- Keeping per-connection state for one live client: **L2**.\n- Letting many connected clients across a continent share one box's state: **L3**.\n- Doing a job exactly once, globally, on a schedule: **L4**.\n\n## Gotchas\n\n- **L1 fields reset every request.** If you set a field in one request and read it in the next, it will be gone. Persist to [ToilDB](../database/README.md) instead.\n- **A project using `@stream` may not also declare `@service` or `@remote`** anywhere (the compiler enforces this). Streams and RPC live in different artifacts. Keep them in separate entry files (`main.stream.ts` vs `main.ts`).\n- **There is at most one `@daemon` class per project.** It compiles only into the cold artifact; a `@daemon` in the request build is a compile error.\n- **Higher tier is not \"better\".** Do not reach for L4 to hold shared state you read on every request; that adds a long hop. Use the database for shared reads, and the daemon only for scheduled, run-once work.\n\n## Related\n\n- [Backend overview](../backend/README.md): the L1 request model in depth.\n- [REST](../backend/rest.md) and [RPC](../backend/rpc.md): the L1 surfaces.\n- [Realtime streams](../realtime/streams.md): the L2 / L3 surface and `StreamScope`.\n- [Daemons](../background/daemons.md) and [@derive](../background/derive.md): scheduled and background work.\n- [The database (ToilDB)](../database/README.md): where shared, persistent state lives.\n- [Decorators](./decorators.md): the full list of surface decorators and their tiers.\n- [Project structure](../getting-started/project-structure.md): entry files and the build.\n",
26
27
  "concepts/types.md": "# The server type system\n\nYour backend is TypeScript, but a stricter, faster dialect of it. Numbers have an exact bit width (`u32`, `i64`, `f64`, and friends) instead of one loose `number`, and a few TypeScript features do not exist. This page explains the types you write in `server/` code.\n\n## Why the server types are different\n\nYour frontend TypeScript runs in a browser, where a JavaScript engine figures out types as it goes. Your **server** code is different: the **toilscript** compiler turns it into [WebAssembly](../backend/README.md) (WASM), a compact machine-like binary. To emit that binary, the compiler must know the *exact* size of every value ahead of time. \"A number\" is not enough; it needs to know \"a 32-bit unsigned integer\" so it can pick the right machine instruction and lay out memory.\n\ntoilscript is built on **AssemblyScript**, a strict subset of TypeScript designed to compile to WASM. So the server language looks and reads like TypeScript, but every number is a fixed-width type, and there is no room for the fuzzy parts of JavaScript. The payoff is speed and safety: your code compiles to something close to hand-written native code, and whole classes of bugs cannot occur.\n\nYou already know the syntax. You only need to learn the number types and a handful of rules.\n\n## The number types\n\nThere is no plain `number` in server code. Instead you pick the exact type. The name tells you three things: signed or unsigned, how many bits, integer or float.\n\n- The letter: `u` = unsigned integer (zero and up), `i` = signed integer (can be negative), `f` = floating-point (has a fractional part).\n- The number: how many bits wide it is.\n\n| Type | Kind | Bits | Range | Use it for |\n| --- | --- | --- | --- | --- |\n| `bool` | boolean | 1 | `true` / `false` | flags, yes/no |\n| `u8` | unsigned int | 8 | 0 to 255 | a byte, a small enum |\n| `u16` | unsigned int | 16 | 0 to 65,535 | ports, small counts |\n| `u32` | unsigned int | 32 | 0 to ~4.29 billion | sizes, ids, most counts |\n| `u64` | unsigned int | 64 | 0 to ~1.8e19 | timestamps (ms), big counters, large ids |\n| `i8` | signed int | 8 | -128 to 127 | tiny signed values |\n| `i16` | signed int | 16 | -32,768 to 32,767 | small signed values |\n| `i32` | signed int | 32 | ~-2.1 to 2.1 billion | the default integer; loop counters, deltas |\n| `i64` | signed int | 64 | ~-9.2e18 to 9.2e18 | large signed counts, database counters |\n| `f32` | float | 32 | ~7 decimal digits | low-precision decimals (rare) |\n| `f64` | float | 64 | ~15-16 decimal digits | any value with a fraction: prices, ratios, math |\n\nThere are also 128-bit and 256-bit integers (`u128`, `i128`, `u256`, `i256`) for cryptography and very large ids. See [Big integers](#big-integers-u128-to-u256) below.\n\n### Which one should I pick?\n\nWhen in doubt, use these defaults and you will rarely be wrong:\n\n- A counter, a size, a loop index, an id you do not do math on: **`u32`** (or `i32` if it can go negative).\n- A millisecond timestamp, a like count that might grow huge, or a value that must never wrap: **`u64`** / **`i64`**.\n- Anything with a decimal point (money, averages, percentages): **`f64`**.\n- A true/false flag: **`bool`**.\n- One raw byte, or an element of a byte buffer: **`u8`**.\n\nSmaller types do not make your program meaningfully faster; they exist to match binary layouts and save memory in big arrays. Default to 32-bit unless a value is genuinely large or genuinely a byte.\n\n## Integer overflow: it wraps, it does not throw\n\nThis is the single most important difference from everyday JavaScript. Integer math is **modular**: if a value goes past the top of its range, it silently wraps around to the bottom (two's complement). It never throws an error and never turns into a bigger type on its own.\n\n```ts\nlet x: u8 = 255;\nx = x + 1; // x is now 0, not 256 (wrapped around)\n\nlet y: u8 = 0;\ny = y - 1; // y is now 255 (wrapped the other way)\n\nlet z: i32 = 2147483647; // the largest i32\nz = z + 1; // z is now -2147483648 (wrapped to the minimum)\n```\n\nThe lesson: choose a type wide enough that your values cannot reach its edge. A counter that could exceed ~4.29 billion needs `u64`, not `u32`. Timestamps in milliseconds always use `u64`.\n\nFloating-point (`f32` / `f64`) does not wrap; it follows the usual IEEE rules (very large values become `Infinity`, `0/0` is `NaN`).\n\n## Casting between number types\n\nBecause types are explicit, the compiler will not silently mix them. To convert, cast. There are two equivalent spellings; use whichever reads better:\n\n```ts\nconst big: u64 = 300;\nconst small: u8 = big as u8; // \"as\" form\nconst small2 = u8(big); // call the type like a function\n```\n\nCasting a wider integer into a narrower one **truncates**: it keeps only the low bits, so `u8(300)` is `44` (300 wraps modulo 256). Casting a float to an integer drops the fraction toward zero (`i32(3.9)` is `3`). None of these throw, so cast deliberately.\n\n```ts\nconst f: f64 = 3.9;\nconst i = i32(f); // 3 (fraction dropped)\nconst n = u8(300); // 44 (truncated to 8 bits)\n```\n\nInteger division also truncates (it is not float division):\n\n```ts\nconst half = 5 / 2; // both operands are i32 -> result is 2, not 2.5\nconst real = 5.0 / 2.0; // f64 division -> 2.5\n```\n\n## `bool`\n\n`bool` is a real 1-bit type, not \"any truthy value\". Comparisons (`==`, `<`, `>=`) produce a `bool`, and `if`/`while` expect one. It stores as 0 or 1.\n\n## Big integers: `u128` to `u256`\n\nFor values too large for 64 bits, toilscript provides `u128`, `i128`, `u256`, and `i256` as native global types (no import needed). They support the normal operators (`+`, `-`, `*`, `/`, `==`, `<`, `<<`, and so on) through operator overloading, plus static helpers like `u256.fromString(...)` and instance methods like `.toString()`, `.toBytes()`, and `.toUint8Array()`.\n\n```ts\nconst a = u256.fromString('123456789012345678901234567890');\nconst b = a + u256.One;\nconst hex = b.toString(16);\n```\n\nThese are mainly for cryptography and very large ids. Everyday counts and sizes should stay in `u32` / `u64`.\n\n### `ToilUserId`: a 256-bit identity\n\nThe built-in auth system represents a logged-in user as a **`ToilUserId`**, a stable 256-bit value (four `u64` words) derived from their key, identifier, and your domain. It is a global type, like `crypto`. It is the right key to store per-user data on. Comparison is overloaded and O(1), and `.toHex()` gives you a 64-character string key.\n\n```ts\nconst id: ToilUserId = AuthService.userId()!; // the current user's stable id\nconst key = id.toHex(); // a convenient string key\n```\n\nFull reference (including the `==` null-check gotcha) is in [Extending auth](../auth/extending.md).\n\n## Strings\n\nStrings work as you expect: `'hello'`, template literals, `.length`, `.substring(...)`, `+` to concatenate. Under the hood a server string is **UTF-16** (the same 16-bit code units as JavaScript), so `.length` counts code units, not visible characters or bytes.\n\nWhen you need the **bytes** of a string (to hash it, write it to a binary body, or send it over a stream), encode it explicitly. UTF-8 is almost always what you want on the wire:\n\n```ts\nconst buf: ArrayBuffer = String.UTF8.encode('hello'); // UTF-8 bytes\nconst text: string = String.UTF8.decode(buf); // back to a string\n```\n\n`String.UTF8.byteLength(s)` gives the encoded byte length. There is a matching `String.UTF16` namespace when you need raw UTF-16 bytes.\n\n## Binary data: `Uint8Array`\n\nRaw bytes are a `Uint8Array` (a fixed-length array of `u8`), exactly like the browser type. It is the standard currency for request bodies, hashes, crypto keys, and stream packets.\n\n```ts\nconst bytes = new Uint8Array(32);\nbytes[0] = 0xff; // each element is a u8\nconst n: i32 = bytes.length;\n```\n\nYou will also see `StaticArray<u8>` (a fixed-size, lower-overhead byte array) and `ArrayBuffer` (a raw buffer that `Uint8Array` and the encoders view). For most app code, `Uint8Array` is all you need.\n\n## Arrays and collections\n\nTyped arrays and the familiar collection types are available and must be typed:\n\n```ts\nconst nums: i32[] = [1, 2, 3]; // Array<i32>\nconst names = new Array<string>();\nconst seen = new Map<string, u32>();\nconst tags = new Set<string>();\n```\n\n`Array`, `Map`, and `Set` behave like their JavaScript counterparts (`.push`, `.get`, `.has`, `.forEach`), but every element type is fixed at compile time. There is no mixed-type array.\n\n## Objects: `@data` classes, not object literals\n\nServer code has no free-form object type. A structured value is a **class**, and to send it between the browser and the server (or in and out of the database) you tag it `@data`. That makes the compiler generate a binary codec plus a matching client type. See [Data types](../backend/data.md).\n\n```ts\n@data\nclass Player {\n username: string = '';\n score: u64 = 0;\n constructor(username: string = '', score: u64 = 0) {\n this.username = username;\n this.score = score;\n }\n}\n```\n\n## Key differences from normal TypeScript\n\n| Thing | Normal TypeScript | Server (toilscript) |\n| --- | --- | --- |\n| Numbers | one `number` | explicit `u8` / `i32` / `u64` / `f64` / ... |\n| `number` type | everywhere | avoid it; pick a fixed-width type |\n| `any` | allowed | not allowed: everything is typed |\n| Integer overflow | numbers just get bigger | wraps around silently |\n| `/` on integers | `5 / 2` is `2.5` | `5 / 2` is `2` (truncates) |\n| Mixing number types | implicit | explicit cast (`x as u8` / `u8(x)`) |\n| npm packages | `import` anything | only toilscript's standard library and toiljs APIs |\n| `undefined` | common | use `null` (a `T | null`), not `undefined` |\n| Objects | `{ a: 1 }` literals | a `class` (usually `@data`) |\n| Strings | UTF-16 | UTF-16 (same), encode to bytes for the wire |\n\nA few rules worth stating plainly:\n\n- **No `any`.** Every value has a concrete type. This is what makes the code compile to WASM at all.\n- **No arbitrary npm.** Server code cannot pull in npm packages; it uses the toilscript standard library (the types on this page) plus the toiljs host APIs (database, crypto, email, and so on). This is the sandbox that keeps the edge safe.\n- **No plain `number`.** If you write `number`, it resolves to `f64` (a float), which is almost never what you want for an id or a count. Always pick an explicit type.\n- **Use `null`, not `undefined`,** for \"no value\": a nullable is written `T | null` and you narrow it with an `if (x != null)` check or a `!` assertion when you are sure.\n\n## How server types cross to the browser\n\nWhen a `@data` value or an RPC result travels to your frontend, the compiler maps each server type to a matching TypeScript type in the generated client. You do not write this mapping; it is generated. It matters because it tells you what your React code receives.\n\n| Server type | Browser (generated TS) |\n| --- | --- |\n| `u8`, `u16`, `u32`, `i8`, `i16`, `i32`, `f32`, `f64` | `number` |\n| `u64`, `i64`, `u128`, `i128`, `u256`, `i256` | `bigint` |\n| `bool` | `boolean` |\n| `string` | `string` |\n| a `@data` class `T` | the generated class `T` |\n| `T[]` | `T[]` |\n\nThe important row is the 64-bit-and-larger integers: they become `bigint` on the client and travel as decimal strings on the JSON wire, so they stay **exact at any size** (they never lose precision the way a giant JavaScript `number` would). See [RPC](../backend/rpc.md) for the generated client.\n\n## Related\n\n- [Data types (`@data`)](../backend/data.md): defining structs that cross the wire and the database.\n- [RPC and the generated client](../backend/rpc.md): how server types map to browser types.\n- [Extending auth](../auth/extending.md): the `ToilUserId` 256-bit identity in full.\n- [The database (ToilDB)](../database/README.md): the collections your typed keys and values live in.\n- [Decorators](./decorators.md): the decorators referenced throughout this page.\n",
27
28
  "database/atomic.md": "# Atomic partitioned documents\n\n`Db.atomic(partition, token)` builds an all-or-nothing conditional batch for an\nAction. It can write up to sixteen records across `Documents` collections in\none database. All collections must declare `replication: 'localOnly'` and have\nno `@unique` fields. An absent-record condition provides uniqueness within the\npartition, such as one message per sequence number in a thread.\n\n```ts\n@database class Messages {\n @collection({ replication: 'localOnly', placement: 'local' })\n static messages: Documents<MessageKey, Message>;\n @collection({ replication: 'localOnly', placement: 'local' })\n static threads: Documents<ThreadKey, Thread>;\n}\n\nconst partition = new ThreadId(threadId);\nconst observed = Messages.threads.partition(partition).getSnapshot(threadKey);\nconst batch = Db.atomic(partition, stableRequestToken);\nbatch.create(Messages.messages, messageKey, message);\nbatch.compareExchange(Messages.threads, threadKey, observed, updatedThread);\nif (!batch.commit()) return Response.text('Thread changed; retry', 409);\n```\n\n`create(collection, key, value)` requires absence. `compareExchange(collection,\nkey, snapshot, value)` requires the exact encoded snapshot, or absence if the\nsnapshot is null. `compareDelete(collection, key, snapshot)` conditionally\ndeletes a record. Each key may appear once. If any condition fails, `commit()`\nreturns false and changes no records or decision markers. All input validation\nand budget checks happen before the storage commit. Other errors throw.\n\nPartitioned records occupy a separate namespace. Read them through\n`collection.partition(partition).get(key)`, `getSnapshot(key)`, or `require(key)`.\nOrdinary `collection.get`, `scan`, and mutation methods address ordinary records.\nIntroducing a partition does not migrate existing data. Every partitioned write\nuses `Db.atomic`, including a batch containing one record. Reads are linearizable\nand bypass request and replica caches. Separate reads may straddle\na commit; there is no multi-read snapshot API.\n\nThe token is 16–64 bytes and identifies one exact batch, including its ordered\nkeys, expected bytes, new bytes, and schema versions. Retry a lost response with\nthe same partition, token, and batch inputs. Successful retries return true\nwithout reapplying writes, even after a subsequent update or deletion. Reusing\nthe token for different inputs fails with a conflict. If an Action rebuilds a\nbatch from freshly read state, retain the original expected/new values for a\nresponse-loss retry, or check an application-owned receipt before rebuilding.\nDecision markers persist with the partition and consume storage.\n\nPartition encodings are 1–512 bytes; record keys are at most 4096 bytes. The\npartition, token, keys, expected bytes, new bytes, and 32-byte decision digest\ntogether are capped at 128 KiB. A batch charges one write operation per record\nand one for the durable decision, including retry attempts. `Db.budget()` includes\nthese operations and bytes. Queries, Jobs, and Derives cannot commit batches.\nDerive invalidations for committed collections use `fullRescan` because changed\nkeys alone do not identify the partition.\n\nNative commits the records and decision together in one conditional operation.\nAll callers for a partition must use the same persistent ToilDB deployment.\n`localOnly` data does not replicate between independent POP stores.\nChoose a partition per bounded business aggregate, such as a thread; putting all\ntenant traffic under one constant partition creates a hotspot. These operations\nrequire the updated native host imports. Existing unpartitioned data retains its\ncurrent storage and replication behavior.\n\nThe dev emulator validates the same limits and commits synchronously without\ncallbacks or suspension between mutations; its normal snapshot file persists\nboth records and successful decisions. Test overlapping requests through the\n[DB barrier hook](../backend/testing-races.md).\n",
@@ -32,7 +33,7 @@ export const TOIL_DOCS = {
32
33
  "database/events.md": "# Events (append-only logs)\n\nAn `Events` collection is an **append-only log**: a growing list of immutable\nfacts under a key. Normal writes append events rather than editing history.\nUse explicit [redaction](#redacting-personal-data) when a stored payload must be erased.\n\n## What and why\n\nAn \"append-only log\" means exactly two things happen to it:\n\n1. You **append** a new event (it goes on the end).\n2. You **read** a specific event, the newest event, or a batch of events.\n\nEach event records something that happened: \"Ada signed the guestbook\", \"order\n1234 was refunded\", \"user logged in from a new device\".\n\nUse an `Events` log when you care about the **history**, not just the latest\nstate:\n\n- **Activity feeds:** \"what happened in this room, newest first\".\n- **Audit trails:** a tamper-resistant record of every important action.\n- **Event sourcing:** treat the log as the source of truth and compute other\n values (totals, summaries, leaderboards) from it.\n\nIf you only ever need the *current* value of something (a user's profile, a\nshopping cart), use [Documents](./documents.md) instead. If you only need a\nrunning total (likes, page views), use a [Counter](./counters.md). Events are\nfor keeping the full list of what happened.\n\n```mermaid\nflowchart LR\n A[\"append(user, event)\"] --> L[(\"Event log for user<br/>(oldest ... newest)\")]\n B[\"append(user, event)\"] --> L\n L --> R[\"latest(user, 20)<br/>returns newest 20\"]\n```\n\n## The type\n\nAn `Events` collection has two type parameters: the **key** (which log) and the\n**event** (what each entry stores).\n\n```ts\nEvents<K, V>\n```\n\n- `K` is the key type: it picks *which* log you are appending to. One key, one\n log. For a per-user activity feed, the key is the user id.\n- `V` is the event type: the shape of a single entry. Both `K` and `V` are\n [`@data`](../concepts/types.md) classes so they can be stored as bytes.\n\nYou declare it as a `@collection` field inside a `@database` class:\n\n```ts\n@data\nclass UserKey {\n id: string = '';\n constructor(id: string = '') { this.id = id; }\n}\n\n@data\nclass Activity {\n action: string = ''; // 'login', 'post.create', 'comment', ...\n detail: string = '';\n at: u64 = 0; // unix seconds\n constructor(action: string = '', detail: string = '', at: u64 = 0) {\n this.action = action; this.detail = detail; this.at = at;\n }\n}\n\n@database\nclass FeedDb {\n @collection static activity: Events<UserKey, Activity>;\n}\n```\n\nThe field name (`activity`) names the collection; the class name (`FeedDb`) names\nthe database. You reach the log through `FeedDb.activity`.\n\n## Operations\n\nThe [toilscript](../concepts/decorators.md) API exposes these operations:\n\n| Operation | Signature | What it does |\n| --- | --- | --- |\n| `append` | `append(key: K, event: V): void` | Add one event to the end of the log. |\n| `appendOnce` | `appendOnce(key: K, eventId: string, event: V): bool` | Add one event, but only if that `eventId` was never seen before. |\n| `get` | `get(key: K, eventId: string): V \\| null` | Read the event stored by `appendOnce` under this ID. Bounded request-path read. |\n| `last` | `last(key: K): V \\| null` | Read the newest appended event. Bounded request-path read. |\n| `latest` | `latest(key: K, limit: i32): V[]` | Read up to `limit` events, newest first. |\n| `since` | `since(key: K, limit: i32): V[]` | Read the NEXT batch of events past a `@derive`'s checkpoint, oldest first. For folding a growing log incrementally. |\n\n### `append`\n\nThe everyday operation. It adds one event and returns nothing.\n\n```ts\nFeedDb.activity.append(\n new UserKey('ada'),\n new Activity('login', 'from Paris', now),\n);\n```\n\n`append` is a **write**, so you may call it from an action handler (`@post`,\n`@put`, `@patch`, `@del`) but not from a read-only `@get`. See\n[decorators](../concepts/decorators.md) for what each handler kind may do.\n\n### `appendOnce` (idempotent append)\n\n`appendOnce` adds an event **at most once** for a given id. \"Idempotent\" means\nrunning it more than once has the same effect as running it once: the extra calls\nchange nothing.\n\nWhy you want this: networks retry. A client (or another service) may send the\nsame request twice because the first reply got lost. With plain `append`, that\ndouble-delivery writes the event twice. With `appendOnce`, you pass a stable\n`eventId` (a string you choose that is unique for that logical event), and the\nlog records it only once.\n\n```ts\n// `orderId` uniquely identifies this order event. If the request is retried,\n// the second call is a no-op and the log still has exactly one entry.\nconst first = FeedDb.activity.appendOnce(\n new UserKey('ada'),\n `order-refunded:${orderId}`, // the idempotency id\n new Activity('order.refund', orderId, now),\n);\n// first === true -> this call appended the event\n// first === false -> a previous call already appended it; nothing happened now\n```\n\nThe return value tells you which happened:\n\n- `true`: this call appended the event (it was the first with that id).\n- `false`: a call with the same id already appended it, so this was a no-op.\n\nPick an `eventId` that is truly unique per event: an order id, a payment id, a\nmessage uuid. Do not reuse one id for two different events, or the second will be\nsilently dropped as a \"duplicate\".\n\n### `get` and `last`\n\nUse these when a request needs one event. Both are bounded reads allowed in a\nroute, query, action, derive, or job. They return `V | null` and decode the event\nusing its stored schema version, including any `@migrate` transform. Reading an\nevent does not rewrite it or advance a derive checkpoint.\n\n#### `get(key, eventId)`: retrieve a known event\n\nPass the exact string ID used with `appendOnce`:\n\n```ts\n// In an action: keep this ID stable when retrying the same operation.\nconst key = new UserKey('ada');\nFeedDb.activity.appendOnce(\n key,\n 'order-refunded:123',\n new Activity('order.refund', '123', 1700000000),\n);\n\n// In a query or action:\nconst event = FeedDb.activity.get(key, 'order-refunded:123');\n```\n\nThe ID is scoped to the collection and stream key. Looking up the same ID under\n`new UserKey('grace')` reads Grace's stream, not Ada's. Ordinary `append` does not\nexpose an ID for `get`; use `appendOnce` when you need to retrieve an event later\nby a caller-chosen ID. The ID is not an array offset or a built-in revision number.\n\n#### `last(key)`: retrieve the newest event\n\n```ts\nconst newest = FeedDb.activity.last(new UserKey('ada'));\n```\n\n`last` reads the event with the highest stored sequence, using the same ordering\nas `latest(key, 1)`. It works for events written with either `append` or\n`appendOnce`. It does not sort your event IDs, revision fields, or timestamps.\nAn empty stream returns `null`.\n\nUnlike `latest`, `last` is allowed in request handlers. Use `last` for one event;\nuse `latest` in a derive or job for a list.\n\n#### Handle absence separately from unavailability\n\nA null result can mean either \"not found\" or a read failure. Inspect\n`Db.lastError()` immediately after the null result, before another database read:\n\n```ts\n@query\nexport function findActivity(userId: string, eventId: string): Activity | null {\n const event = FeedDb.activity.get(new UserKey(userId), eventId);\n if (event == null && Db.lastError() != DbError.None) {\n throw new Error('Activity temporarily unavailable');\n }\n return event; // null here means the event was not found.\n}\n```\n\nApply the same check to `last`. At an HTTP boundary, map an availability failure\nto a retryable response instead of reporting a missing event. `Db.isRetryable`\nclassifies transient errors when implementing retry handling.\n\nFor example, a crash during `appendOnce` can leave its ID reserved before its\nevent row is stored. `get` reports unavailable in that state; retrying the original\n`appendOnce` can recover the original event. Reads do not perform that recovery.\n\n#### Concurrent writes and duplicate IDs\n\nA duplicate `appendOnce` neither replaces the original event nor moves it to the\nend of the stream. Its `false` result means the ID was already used, even if the\nnew payload differs. Use `get` to inspect the stored payload when reconciling a\nretry; do not assume the duplicate's payload was accepted.\n\n`last` is a snapshot read, not a lock. Another writer can append immediately after\nit returns. A `last` followed by an `append` is two separate operations, not an\natomic \"append only if the current revision is X\" operation. These reads do not\nvalidate revision sequences or add compare-and-swap semantics.\n\nUse [Documents `enqueue`](./documents.md#writing-create-vs-upsert-vs-patch-vs-enqueue)\nfor conditional updates to an existing document. Keep [Unique](./unique.md) for\nownership constraints such as a username across accounts; event ID deduplication\nonly applies within its collection and stream.\n\n#### Runtime requirements and existing dev data\n\nProduction async reads fetch from the stream's home cell. Synchronous execution\nreports unavailable when the home is remote. Home-routing failures, including a\nstale placement decision, are unavailable results, not proof that an event is\nmissing. Event IDs are limited to 4096 UTF-8 bytes; stream keys are limited to\n4096 bytes of their encoded `@data` representation.\n\nDeploy the updated backend and mesh peers before deploying modules that call\nthese methods. Older hosts do not provide the new imports, and older mesh peers\ndo not understand the Events point-read extension. These methods do not require\na new ToilDB storage namespace.\n\nDev snapshots created before event ID positions were recorded cannot reliably\nassociate old deduplication IDs with events. For such IDs, `get` reports\n`DbError.Unavailable`; `last`, `latest`, and `since` can still read the stored events.\nNew `appendOnce` entries retain their ID positions across dev-server restarts.\n\n### `latest`\n\nReads the newest events back, up to a limit, newest first.\n\n```ts\nconst recent = FeedDb.activity.latest(new UserKey('ada'), 20);\n// recent[0] is the most recent event, recent[1] the next, ...\n```\n\n`latest` is a **scan**: it can walk many rows. Scans are barred on the request\npath, so you **cannot** call `latest` from a `@get` or a `@post`. This is a\ndeliberate guardrail: a log can grow without bound, and a per-request scan would\nget slower and more expensive as the log grows.\n\nInstead you scan the log **off** the request path, in a\n[`@derive`](../background/derive.md), and publish a small precomputed\n[View](./views.md) that your routes read cheaply. The next section shows the full\npattern.\n\n### `since` (incremental read for a `@derive`)\n\n`latest` rescans the tail every time. For a log that grows without bound, that gets slower and slower. `since`\nreads only the events you have **not folded yet**: the next batch past a saved cursor, oldest first, up to a\nlimit. It is how a [`@derive`](../background/derive.md) folds a huge log incrementally instead of rescanning\nit from the start on every change.\n\nYou do not pass or manage the cursor. The host owns it: it seeds `since` from a durable checkpoint, advances\nit as it hands you events, and saves it after your fold's view publish lands. So you just loop until the\nbatch is empty:\n\n```ts\n@derive\nrollup(): void {\n const key = new StatsKey('global');\n const view = StatsDb.summary.get(key) ?? new Summary(); // the running view\n let batch = StatsDb.events.since(key, 500);\n while (batch.length > 0) { // drain in bounded batches\n for (let i = 0; i < batch.length; i++) view.apply(batch[i]);\n batch = StatsDb.events.since(key, 500);\n }\n StatsDb.summary.publish(key, view);\n}\n```\n\nTwo rules:\n\n- **`@derive` or `@job` only.** Like `latest`, `since` is a scan, so it is barred on the request path (`@get`\n / `@post`). Calling it there is rejected.\n- **Your fold must be idempotent per event.** A rare crash-recovery case (a \"healed\" event that arrives at an\n older position) makes the host re-read the log from the start that one run, so applying an event twice must\n not change the result. Use set-style updates (`view.byId[e.id] = e.value`), not blind accumulation\n (`view.count += 1`). If your fold cannot be idempotent, use `latest` and recompute instead.\n\n`since` is the efficient path; `latest` (recompute) is the simple path. See [`@derive`](../background/derive.md)\nfor the full picture.\n\n## Worked example: an activity feed\n\nHere is the whole loop: an action appends an event, a `@derive` folds the log\ninto a view, and a `@get` serves the view.\n\n```ts\nimport { Activity } from '../models/Activity';\nimport { UserKey } from '../models/UserKey';\nimport { FeedView } from '../models/FeedView';\nimport { NewActivity } from '../models/NewActivity';\n\n@database\nclass FeedDb {\n // The source of truth: every activity, appended forever.\n @collection static activity: Events<UserKey, Activity>;\n // The precomputed snapshot the GET serves: the newest 20 activities.\n @collection static feed: View<UserKey, FeedView>;\n\n // A @derive runs OFF the request path, so it is allowed to scan the log\n // (`latest`) and publish the view. The runtime runs it right after an append,\n // so the view reflects the new event on the next read.\n @derive\n rebuild(): void {\n const key = new UserKey('ada'); // (real code would loop per active user)\n const view = new FeedView();\n view.items = FeedDb.activity.latest(key, 20);\n FeedDb.feed.publish(key, view);\n }\n}\n\n@rest('feed')\nclass Feed {\n // GET reads the precomputed view: a single keyed read, NOT a scan.\n @get('/')\n public list(): FeedView {\n const view = FeedDb.feed.get(new UserKey('ada'));\n return view == null ? new FeedView() : view;\n }\n\n // POST appends one activity. The @derive republishes `feed` right after.\n @post('/')\n public record(input: NewActivity): FeedView {\n const at = <u64>(Date.now() / 1000);\n FeedDb.activity.append(new UserKey('ada'), new Activity(input.action, input.detail, at));\n // We do NOT scan here (that would be barred). We just acknowledge; the GET\n // serves the updated list from the view the derive rebuilds.\n return new FeedView();\n }\n}\n```\n\nThe two `@data` models:\n\n```ts\n@data\nexport class Activity {\n action: string = '';\n detail: string = '';\n at: u64 = 0;\n}\n\n@data\nexport class FeedView {\n items: Activity[] = [];\n}\n```\n\nThe key idea: the **log** is the durable history, and the **view** is a small,\nread-cheap snapshot derived from it. Reads hit the view; the log grows quietly in\nthe background.\n\n## Ordering and consistency\n\nToilDB is a **worldwide** database: your data lives in many regions at once. A\nfew honest details about what that means for events:\n\n- **Ordering within a log is stable.** Each key (each log) has one \"home\" location\n where appends are serialized and stamped with an increasing sequence number. So\n `latest` always returns a consistent newest-first order for that key.\n- **`latest` is newest first.** Index `0` is the most recent event.\n- **Background scans and derived views can lag across regions.** An append is applied at the log's\n home first, then copied out to other regions in the background (this is called\n *asynchronous replication*, and the result is *eventual consistency*: given a\n little time, every region converges to the same log). A read served from a far\n region may briefly miss the very newest event. A `@derive` runs right after the\n append that triggered it, so the view it publishes reflects that write.\n `get` and `last` instead read from the stream’s home; they still do not lock\n the stream against subsequent writes.\n- **`appendOnce` dedups by your id.** The at-most-once guarantee is anchored to\n the `eventId` you pass, so retries are safe even across a flaky network.\n- **A log grows without bound.** Appending never shrinks it. Keep events small,\n and read them through a bounded `latest(key, N)` in a derive rather than trying\n to hold the whole log in memory.\n\n## Gotchas\n\n- **Routes can read individual events, but cannot scan the log.** Use `get` or\n `last` for a single event. `latest` and `since` require a `@derive` or `@job`;\n use a [View](./views.md) when a route needs a precomputed list.\n- **Normal changes append new facts.** Record an `order.refund` event rather\n than editing `order.create`. Explicit redaction is available for erasing\n personal payloads; it preserves event references and deduplication.\n- **Choose `eventId` carefully for `appendOnce`.** It must be unique per logical\n event. Reusing an id drops the new event as a duplicate.\n- **Do not treat a counter as a log.** A [Counter](./counters.md) gives you a\n running total but forgets the individual events. If you need the list, use\n `Events`.\n\n## Related\n\n- [Documents](./documents.md): mutable, one value per key (edit in place).\n- [Counters](./counters.md): a single running total per key.\n- [Views](./views.md): the precomputed snapshot your routes read.\n- [`@derive`](../background/derive.md): folds an event log into a View, off the\n request path.\n- [Data types (`@data`)](../concepts/types.md): how keys and events are stored.\n- [Decorators](../concepts/decorators.md): which handler kinds may append vs scan.\n\n## Redacting personal data\n\n`Events.redact(key, reference)` erases one event payload and returns `true` when\nits current recovery copies are scrubbed. Each native call cleans a bounded\npage of append-once markers. A `false` result means cleanup is still pending:\nretain the reference and call again in a later action or job. The entry is hidden\nfrom `get`, `last`, `latest`, `since`, and `entries` after the first successful\ncall. Queries and derives cannot redact.\n\nFor an `appendOnce` entry, obtain the reference with `reference(key, eventId)`.\nThis is a bounded read allowed in request handlers and still returns a reference\nwhile cleanup is pending. It returns `null` when the ID is absent; consult\n`Db.lastError()` if the read failed.\n\n```ts\nconst reference = Logs.changes.reference(key, 'change:42');\nif (reference != null) {\n const complete = Logs.changes.redact(key, reference);\n // Persist the reference in the cleanup job when complete is false.\n}\n```\n\nFor ordinary appends, a background function can enumerate references with\n`entries(key, limit = 128, after = 0)`. It returns an `EventPage<V>` containing\n`entries` (`EventEntry<V>.value` and `.reference`), `.cursor`, and `.hasMore`.\nPages are oldest first, limits are 1..1024, and the cursor is exclusive. Resume\nwith the returned cursor while `hasMore` is true, including after an empty page.\nA full final page can require one additional empty read. This scan is allowed\nonly in jobs and derives, independently of the host-managed `since` checkpoint.\n\nReferences include both the sequence and original HLC, so erasing an old\nreference does not erase a newer event at a reused position. Erasure progress\nis stored durably and replicated; retrying an append-once delivery, replaying an\nold envelope, or installing a late snapshot must not restore the erased entry.\nThe dev database retains references and erasure state across restarts. Its\nappend-once index stores positions rather than payload copies, so cleanup can\nfinish in one call there.\n\nRedaction marks the source as changed and forces affected derives to reread\nfrom the start. Rebuild projections without the erased facts and use\n[View.delete](./views.md) for projection keys that no longer exist. Application\nfolds that reuse previous view state must clear that state before a full rebuild.\n\nThis operation scrubs current event and append-once recovery payloads. Historical\nreplication envelopes, retained backups, and obsolete storage files follow their\nown retention and compaction policies; redaction does not rewrite those archives.\nKeep the erasure ledger when restoring or rebuilding a database.\n",
33
34
  "database/membership.md": "# Membership (sets and relationships)\n\nA `Membership` collection stores **sets**: unordered groups of members under a\nkey. You add and remove members, ask whether a member is in the set, and list a\nset's members. It is the natural fit for many-to-many relationships like group\nmembers, followers, and tags.\n\n## What and why\n\nA \"set\" is a collection with no duplicates and no order: a member is either in it\nor not. `Membership` gives you one set per key. The key names the set; each member\nis one item in it.\n\nThis maps directly onto **many-to-many relationships**, where each thing on one\nside can relate to many things on the other:\n\n- **Group members:** the key is a group id, the members are user ids.\n- **Followers:** the key is a user id, the members are the ids of their followers.\n- **Tags:** the key is an article id, the members are tag names.\n- **Access control:** the key is a resource id, the members are the users allowed\n in.\n\nYou could try to store these as an array field inside a [Document](./documents.md)\n(for example `group.memberIds: string[]`). That works for **small, rarely-changed**\nsets, but it has real limits:\n\n| | Array in a Document | `Membership` set |\n| --- | --- | --- |\n| Add/remove one member | Read the whole array, edit it, write it all back | One direct `add`/`remove`, no read-modify-write |\n| Concurrent edits | Two writers can clobber each other's array | Each `add`/`remove` is its own operation |\n| Big sets | The whole array is loaded on every read/write | Members are stored separately; you read a bounded page |\n| \"Is X a member?\" | Load the array and search it | One direct `contains` check |\n\nRule of thumb: a **handful** of stable items (a user's two or three roles) is fine\nas an array in a Document. A set that **grows** or is **edited concurrently**\n(followers, group members, tags across many articles) should be a `Membership`.\n\n```mermaid\nflowchart LR\n K[\"Group key: 'eng'\"] --> S[(\"Membership set\")]\n S --> M1[\"ada\"]\n S --> M2[\"grace\"]\n S --> M3[\"linus\"]\n```\n\n## The type\n\n```ts\nMembership<K, M>\n```\n\n- `K` is the key type: it picks *which* set. For group membership, the key is the\n group id.\n- `M` is the member type: the shape of one member. For user membership, that is a\n user id. Both are [`@data`](../concepts/types.md) classes.\n\nDeclare it as a `@collection` field on a `@database` class:\n\n```ts\n@data\nclass GroupKey {\n group: string = '';\n constructor(group: string = '') { this.group = group; }\n}\n\n@data\nclass Member {\n userId: string = '';\n constructor(userId: string = '') { this.userId = userId; }\n}\n\n@database\nclass GroupsDb {\n @collection static members: Membership<GroupKey, Member>;\n}\n```\n\n## Operations\n\nFour operations, matching the toilscript API exactly. Exact signatures:\n\n| Operation | Signature | What it does |\n| --- | --- | --- |\n| `contains` | `contains(key: K, member: M): bool` | Is `member` in the set? |\n| `add` | `add(key: K, member: M): void` | Put `member` in the set (idempotent). |\n| `remove` | `remove(key: K, member: M): void` | Take `member` out of the set (idempotent). |\n| `list` | `list(key: K, limit: i32): M[]` | Up to `limit` members of the set. |\n| `listPage` | `listPage(key: K, limit: i32, cursor?: Uint8Array \\| null): MembershipPage<M>` | An ordered page and an opaque cursor for the next page. |\n\n### `contains`\n\nA direct membership check. It is a keyed read, so it is allowed from any handler,\nincluding a read-only `@get`.\n\n```ts\nif (GroupsDb.members.contains(new GroupKey('eng'), new Member('ada'))) {\n // ada is in the 'eng' group\n}\n```\n\n### `add` and `remove`\n\nBoth are **writes**, so you call them from an action handler (`@post`, `@put`,\n`@patch`, `@del`), not from a `@get`. Both are **idempotent**: \"idempotent\"\nmeans doing it again has no extra effect.\n\n- `add` on a member already in the set: no change, no error.\n- `remove` on a member not in the set: no change, no error.\n\n```ts\nGroupsDb.members.add(new GroupKey('eng'), new Member('ada')); // ada joins\nGroupsDb.members.add(new GroupKey('eng'), new Member('ada')); // no-op, still one 'ada'\nGroupsDb.members.remove(new GroupKey('eng'), new Member('linus')); // linus leaves (or no-op)\n```\n\nBecause they are idempotent, you do not need to check `contains` before calling\nthem. Just `add` to join and `remove` to leave.\n\n### `listPage`: walk a large set\n\nUse `listPage` in a job or derive to resume strictly after the last encoded member.\nPass `null` for the first page, then pass the returned `cursor` unchanged. Keep\nthat raw cursor: re-encoding a migrated member could produce different bytes.\nA page contains `members: M[]` and `cursor: Uint8Array | null`. A short page ends\nthe walk; a full final page may require one empty call to establish the end.\n\n```ts\nlet cursor: Uint8Array | null = null;\ndo {\n const page = GroupsDb.members.listPage(key, 100, cursor);\n // Process this bounded page; persist cursor when checkpointing a job.\n cursor = page.cursor;\n} while (cursor != null);\n```\n\nPage limits must be positive: at most 32 on Query, 64 on Action, and 1024 in background work. Result and cumulative byte budgets also apply.\nThe ordering is lexicographic over encoded member bytes, not alphabetical over\ndisplay names. Removing the cursor member does not prevent continuation. This is\nnot a snapshot: additions behind the cursor appear on a subsequent walk, and\nconcurrent removals can omit members. Reads remain scoped to one collection\nand set key. Bounded `listPage` is allowed on Query and Action; `list` remains a background scan.\n\n### `list`\n\nReturns up to `limit` members of a set.\n\n```ts\nconst roster = GroupsDb.members.list(new GroupKey('eng'), 100);\n```\n\n`list` is a **scan** (it can walk many rows), so it is barred on the request\npath: you **cannot** call it from a `@get` or a `@post`. Like reading a whole\nevent log, listing a whole set belongs off the request path, in a\n[`@derive`](../background/derive.md) or a `@job`, which publishes a\n[View](./views.md) your routes read. The [worked example](#worked-example-group-membership)\nbelow shows this.\n\n`list` returns up to `limit` members. A set can be larger than one page, so treat\nthe result as \"a bounded page of members\", not necessarily \"every member\".\n\n## Worked example: group membership\n\nA user joins or leaves a group from a route; a derive lists the roster into a\nview; a route reads the view. Membership checks happen directly in the route.\n\n```ts\nimport { GroupKey } from '../models/GroupKey';\nimport { Member } from '../models/Member';\nimport { Roster } from '../models/Roster';\nimport { JoinRequest } from '../models/JoinRequest';\n\n@database\nclass GroupsDb {\n // The set: who is in each group.\n @collection static members: Membership<GroupKey, Member>;\n // A precomputed roster for the GET (listing is a scan, barred on routes).\n @collection static roster: View<GroupKey, Roster>;\n\n @derive\n rebuild(): void {\n const key = new GroupKey('eng');\n const r = new Roster();\n r.users = GroupsDb.members.list(key, 500); // scan, allowed in a derive\n GroupsDb.roster.publish(key, r);\n }\n}\n\n@rest('groups')\nclass Groups {\n // GET the roster from the view (a keyed read, not a scan).\n @get('/eng')\n public list(): Roster {\n const r = GroupsDb.roster.get(new GroupKey('eng'));\n return r == null ? new Roster() : r;\n }\n\n // Direct membership check: `contains` is a keyed read, legal in a GET.\n @get('/eng/is-member')\n public isMember(userId: string): bool {\n return GroupsDb.members.contains(new GroupKey('eng'), new Member(userId));\n }\n\n // Join: `add` is idempotent, so joining twice is harmless.\n @post('/eng/join')\n public join(input: JoinRequest): bool {\n GroupsDb.members.add(new GroupKey('eng'), new Member(input.userId));\n return true; // the @derive rebuilds the roster view right after\n }\n\n // Leave: `remove` is idempotent, so leaving when not a member is harmless.\n @post('/eng/leave')\n public leave(input: JoinRequest): bool {\n GroupsDb.members.remove(new GroupKey('eng'), new Member(input.userId));\n return true;\n }\n}\n```\n\nThe models:\n\n```ts\n@data\nexport class Member {\n userId: string = '';\n}\n\n@data\nexport class Roster {\n users: Member[] = [];\n}\n```\n\nThe split is the point: `contains`/`add`/`remove` act on a single member and are\nlegal on the request path; `list` scans the whole set and lives in a derive that\nfeeds a view.\n\n## Consistency\n\n- **Add and remove serialize at the set's home.** Each set key has one home\n location where its writes are applied in order, so an `add` followed by a\n `remove` of the same member lands in that order and the set ends up correct.\n- **Reads can lag slightly across regions.** ToilDB is worldwide. A change made\n at a set's home is copied to other regions in the background (asynchronous\n replication, giving eventual consistency: every region converges after a short\n delay). A `contains` or a `list` served from a far region may briefly miss a\n just-made change.\n- **`add`/`remove` are idempotent**, so retries are safe: re-adding an existing\n member or re-removing an absent one does nothing.\n- **A set can grow without bound.** Adding never shrinks it. Read it through a\n bounded `list(key, N)` in a derive, not all at once.\n\n## Gotchas\n\n- **You cannot `list` from a route.** `list` is a scan, legal only in a `@derive`\n or `@job`. To show a roster on a page, publish it to a [View](./views.md) from a\n derive and `get` that view in the route.\n- **`list` returns a bounded page.** A large set may have more members than your\n `limit`. Do not assume the returned array is the entire set.\n- **Sets have no application-level order.** `listPage` uses encoded-byte order for continuation. Do not treat it as an order by display name or creation time.\n- **Use `Membership` for growth or concurrency.** A small, stable set is fine as\n an array in a Document. Reach for `Membership` when the set grows, is edited\n concurrently, or you frequently ask \"is X a member?\".\n\n## Related\n\n- [Documents](./documents.md): when a small array field is enough (and when it is\n not).\n- [Views](./views.md): where a roster/list belongs so routes can read it cheaply.\n- [`@derive`](../background/derive.md): runs `list` off the request path.\n- [Data types (`@data`)](../concepts/types.md): how set keys and members are stored.\n- [Decorators](../concepts/decorators.md): which handler kinds may add/remove vs scan.\n\n\n## Sorted request indexes\n\nDeclare `SortedIndex<GroupKey, ItemId>` as a collection to maintain an ordered,\nquery-readable index backed by membership storage:\n\n```ts\n@database\nclass Listings {\n @collection static byDate: SortedIndex<BoardKey, ListingId>;\n}\n// In an Action or Job; index stable IDs, then fetch the current documents.\nListings.byDate.add(board, SortKey.descendingU64(timestamp), listingId);\nconst page = Listings.byDate.page(board, 16, cursor); // page.items, page.cursor\n```\n\nOrder keys compare by UTF-8 bytes. `SortKey.u64` and `descendingU64` produce\nfixed-width keys with unsigned numeric order. Encoded item bytes break ties.\nAdding the same order-key/item pair is idempotent. To change an entry's order,\nremove the old pair with `remove(board, oldOrder, listingId)` and add the new one.\nEach page is one bounded read, subject to the limits above. Cursors are exclusive;\na full page can require an empty final page. Pagination is not a snapshot of\nconcurrent changes and has the same replica consistency as membership reads.\n",
34
35
  "database/README.md": "# ToilDB\n\nToilDB is the database built into toiljs. It is **global**, it needs **no setup or connection string**, and your backend talks to it with plain typed method calls.\n\nIf you have used Postgres, MySQL, or MongoDB before, ToilDB will feel a little different, and this page explains why. If you have never used a database, that is fine too: read on and every term is defined as it appears.\n\nThe conditional-write, event-redaction, Membership cursor, and View-delete APIs\nrequire **toiljs 0.0.125 or later**, **toilscript 0.1.64 or later**, and a backend\nbuilt with their corresponding `data.*` imports. Rebuild the hot and cold\nartifacts together to include background materializers and the updated schema.\n\n## What \"a globally distributed edge database\" means\n\nLet us take that phrase one word at a time.\n\n- A **database** is a place your program stores data so it is still there on the next request. Your handler runs, finishes, and forgets everything in memory (a fresh WebAssembly instance runs each request), so anything you want to keep, a user account, a like count, a guestbook entry, has to go into a database.\n- The **edge** is a network of servers spread around the world, each one physically close to some of your users. Your compiled backend runs on the edge server nearest whoever is calling it. (For the full picture of where code runs, see [Tiers](../concepts/tiers.md).)\n- **Globally distributed** means the database is not one machine in one city. Its data lives on many machines in many regions at once. A user in Tokyo and a user in Paris each read from a copy near them, so reads are fast everywhere instead of fast in one place and slow everywhere else.\n\nPut together: ToilDB is storage that lives out on that same worldwide edge, next to your code, so a database read does not have to fly across an ocean and back.\n\n```mermaid\nflowchart LR\n subgraph edge[\"Dacely edge (worldwide)\"]\n direction LR\n H1[\"Your backend<br/>(Tokyo)\"] --> D1[(\"ToilDB<br/>copy near Tokyo\")]\n H2[\"Your backend<br/>(Paris)\"] --> D2[(\"ToilDB<br/>copy near Paris\")]\n end\n D1 <-->|\"replication<br/>(keeps copies in sync)\"| D2\n UA[\"User in Tokyo\"] --> H1\n UB[\"User in Paris\"] --> H2\n```\n\nYou never pick a region, open a connection, or run a migration script. You declare what you want to store (see [Setup](./setup.md)) and ToilDB is there.\n\n## Why seven families instead of one big \"table\"\n\nMost databases give you one general-purpose tool: a table (or a collection) that you read and write however you like. That is flexible, but on a system spread across the whole planet, the flexible tool is also the slow and error-prone tool. The classic example is a counter. If two servers on opposite sides of the world both try to do \"read the number, add one, write it back\" at the same moment, one of the two increments is silently lost, because each read the same starting value.\n\nToilDB solves this by giving you **seven specialized collection types**, called **families**. Each family is tuned for one job and exposes only the operations that are safe and fast for that job. A counter family, for instance, has no \"set to this value\" operation at all: you can only `add` a delta, and the database merges concurrent deltas from around the world without losing any. You cannot misuse it, because the unsafe operation does not exist.\n\nSo instead of one generic table you reach for, you pick the family that matches what you are doing. Picking the right one is the main skill, and the guide below walks you through it.\n\nThe seven families are:\n\n| Family | It stores | Read a page |\n| --- | --- | --- |\n| **Documents** | Records you look up by id (users, posts, orders). | [Documents](./documents.md) |\n| **Unique** | A claim on a value that must be one-of-a-kind (usernames, emails, slugs). | [Unique](./unique.md) |\n| **Counter** | A running total that many callers increment at once (likes, views). | [Counters](./counters.md) |\n| **Events** | An append-only log (feeds, audit trails); read one event with `get` or `last`, or scan batches in the background. | [Events](./events.md) |\n| **Capacity** | A limited quantity you hand out without overselling (tickets, seats). | [Capacity](./capacity.md) |\n| **Membership** | Sets of \"who belongs to what\" (followers, tags, room members). | [Membership](./membership.md) |\n| **View** | A precomputed, read-optimized snapshot (home pages, leaderboards). | [Views](./views.md) |\n\nFor files, use [Blobs](./blobs.md): typed file namespaces with streamed transfers\nand range reads, backed by object storage in production and disk in dev.\n\n## The one idea shared by all seven: key then value\n\nEvery family, underneath, works the same way: it maps a **key** to a **value**.\n\n- A **key** is how you find your data. Think of it as the label on a drawer: a user id, a username, a room name.\n- A **value** is what is in the drawer: the user record, the owner of a username, the members of a room.\n\nIn ToilDB, both the key and the value are ordinary TypeScript classes that you tag with `@data`. The `@data` tag tells toilscript (the compiler that turns your backend into WebAssembly) how to pack that class into bytes for storage and unpack it again. You write a normal class with normal fields, give each field a default, and the compiler does the rest.\n\n```ts\n// A key: how you address one record.\n@data\nclass UserId {\n id: string = '';\n constructor(id: string = '') { this.id = id; }\n}\n\n// A value: what you store under that key.\n@data\nclass User {\n id: string = '';\n name: string = '';\n score: u64 = 0;\n}\n```\n\nYou then declare a collection that maps that key type to that value type, for example `Documents<UserId, User>`. Every family is generic over its key and value types in exactly this way, so once you understand `@data` keys and values you understand all seven. The full `@data` reference is on the [data types page](../backend/data.md); how to declare collections is on [Setup](./setup.md).\n\n## Eventual consistency, in plain words\n\nBecause ToilDB keeps copies of your data in many regions, there is one honest trade-off you need to understand: **eventual consistency**.\n\nEvery key has one **home**: a single region that officially owns that key's data. All **writes** to a key travel to its home, where they are applied one at a time, in order. That is what makes writes safe: even if a thousand servers write the same key at once, the home lines them up so nothing is lost or corrupted.\n\n**Reads**, on the other hand, are served from the copy nearest the reader, which is fast but may be a beat behind. After a write lands at the home, it takes a brief moment (usually milliseconds) to fan out to the other regions' copies. During that moment, a reader in another region might still see the previous value. The copies always catch up; they are *eventually* consistent, not *instantly* consistent everywhere.\n\nWhat this means in practice:\n\n- **It is usually invisible.** The lag is tiny, and most apps never notice.\n- **Do not assume a write is visible everywhere the instant it returns.** For example, right after you create a record, a read from a far-away region might briefly not see it yet.\n- **Some families are stronger.** Because writes to a single key are serialized at its home, operations that must never race, claiming a unique username, reserving the last ticket, are decided at the home and are safe. The Unique and Capacity families lean on this so two callers can never both win. See [Unique](./unique.md) and [Capacity](./capacity.md).\n\nEach family page spells out its own consistency behavior, so you always know what to expect.\n\n## Choosing a family: the decision guide\n\nStart from what you are trying to do, not from a data structure. This table maps a real need to the family that was built for it.\n\n| I need to... | Use | Why |\n| --- | --- | --- |\n| Store and update a thing I look up by id (a user, a post, an order). | **Documents** | The general-purpose record store: create, read, update, delete by key. |\n| Guarantee a value is used by only one owner across the whole world (username, email, slug). | **Unique** | Claims are decided at the key's home, so two people cannot claim the same name. |\n| Count something that many people bump at the same time (likes, page views, stock tally). | **Counter** | Concurrent `add`s from anywhere merge without ever losing an increment. |\n| Keep a growing list of things that happened, in order (activity feed, audit log). | **Events** | Append-only: you add events and read the newest, but never edit history. |\n| Hand out a limited quantity and never sell more than exist (tickets, seats, inventory). | **Capacity** | Reserve/confirm/cancel holds at the home prevent overselling. |\n| Track which members belong to a set (followers, tags, room members, permissions). | **Membership** | Add/remove/check membership without loading a whole record to edit a list. |\n| Serve a precomputed, ready-to-render result quickly (leaderboard, home page snapshot). | **View** | A background job computes it once; requests read it with a single fast lookup. |\n\nIf two families seem to fit, this flowchart resolves it. Read it top to bottom.\n\n```mermaid\nflowchart TD\n START[\"What are you storing?\"] --> Q1{\"Is it a running<br/>total (a number many<br/>callers increase)?\"}\n Q1 -->|Yes| COUNTER[\"Counter\"]\n Q1 -->|No| Q2{\"Must a value be<br/>one-of-a-kind across<br/>everyone (username,<br/>email, slug)?\"}\n Q2 -->|Yes| UNIQUE[\"Unique\"]\n Q2 -->|No| Q3{\"Is it a limited stock<br/>you must not oversell<br/>(tickets, seats)?\"}\n Q3 -->|Yes| CAPACITY[\"Capacity\"]\n Q3 -->|No| Q4{\"Is it an append-only<br/>log of events that<br/>happened, kept in order?\"}\n Q4 -->|Yes| EVENTS[\"Events\"]\n Q4 -->|No| Q5{\"Is it a set of members<br/>you add/remove/check<br/>(followers, tags)?\"}\n Q5 -->|Yes| MEMBERSHIP[\"Membership\"]\n Q5 -->|No| Q6{\"Is it a precomputed<br/>read-only snapshot a<br/>background job builds?\"}\n Q6 -->|Yes| VIEW[\"View\"]\n Q6 -->|No| DOCUMENTS[\"Documents<br/>(the default record store)\"]\n```\n\nA quick sanity check when you land somewhere: **Documents is the default.** If you are storing \"a thing with fields that I update by id,\" it is almost always Documents. The other six exist for the specific jobs above where Documents would be slow, unsafe under concurrency, or awkward.\n\nReal apps mix families freely. The demo guestbook, for example, uses **Events** for the log of signatures, a **Counter** for the running total, and a **View** for the ready-to-serve snapshot, all in one small feature.\n\n## Where to go next\n\n- [Setup](./setup.md): declare a database, its collections, and reach them from a handler.\n- [Documents](./documents.md): the general-purpose record store (start here).\n- [Atomic partitioned documents](./atomic.md): conditional batches across collections in one explicit partition.\n- [Unique](./unique.md), [Counters](./counters.md), [Events](./events.md), [Views](./views.md), [Membership](./membership.md), [Capacity](./capacity.md): the specialized families.\n\n## Related\n\n- [Setup](./setup.md): how to declare `@database`, `@collection`, and `@data` types.\n- [Data types (`@data`)](../backend/data.md): the typed keys and values every family uses.\n- [Tiers](../concepts/tiers.md): where your backend and its data run.\n- [Decorators](../concepts/decorators.md): `@query`, `@action`, `@derive`, and friends.\n\n## Catalog and collection ceilings\n\nThe native default catalog accepts 32 logical databases, **128 collections per\ndatabase**, and **512 collections total**, with up to 512 resolved handles per\ninstance. Catalog sections are capped at 256 KiB and values at 256 declared\nfields. Framework authentication collections count too. The dev catalog parser\nchecks these same defaults. The `u16` collection count is the wire encoding,\nnot an allowance of 65,535 collections.\n\nOperators can change the native `db_limits` settings, including\n`max_databases`, `max_collections_per_db`, `max_collections_total`, and\n`max_handles`; validate against the settings of the deployment you will use.\n",
35
- "database/setup.md": "# Declaring a database\n\nYou set up ToilDB by **declaring** it in code: a `@database` class listing your collections, plus the `@data` key and value types those collections use. There is no schema file, no migration command, and no connection string.\n\n## What and why\n\nA **database declaration** tells toiljs three things at compile time: which collections exist, which family each one is, and what key and value types it stores. The compiler bakes that list into your server's WebAssembly, and both the dev server and the production edge read it back to set up your collections automatically. You declare; the platform provisions.\n\nReach for this on day one: before you can read or write any data, you need a `@database` with at least one `@collection`.\n\nGroup related data into collections within a small number of databases. A new\nfeature usually needs a new collection, not another `@database` class. Database\nnamespaces do not replace application authorization: enforce account and\norganization access in server routes and scope collection keys appropriately.\n\n## How: the three pieces\n\nA working database is always these three pieces together.\n\n1. **`@data` key and value types.** Plain classes, tagged `@data`, that describe what you store.\n2. **A `@database` class** whose static fields are `@collection`s, each typed by a family.\n3. **A handler** (a `@rest` route or an RPC method) that reads and writes those collections.\n\nHere is a complete, minimal example: a store of users you look up by id.\n\n```ts\n// A @data key: how you address one user.\n@data\nclass UserId {\n id: string = '';\n constructor(id: string = '') { this.id = id; }\n}\n\n// A @data value: what you store for each user.\n@data\nclass User {\n id: string = '';\n name: string = '';\n score: u64 = 0;\n}\n\n// The database declaration. Each @collection is one collection,\n// typed by its family (here, Documents) with <Key, Value>.\n@database\nclass AppDb {\n @collection static users: Documents<UserId, User>;\n}\n\n// A route that reads and writes the collection.\n@rest('users')\nclass Users {\n @get('/:id')\n public getUser(ctx: RouteContext): User {\n const user = AppDb.users.get(new UserId(ctx.param('id')));\n return user == null ? new User() : user;\n }\n\n @post('/')\n public createUser(input: User): User {\n AppDb.users.create(new UserId(input.id), input);\n return input;\n }\n}\n```\n\nThat is the whole setup. Run `toiljs dev` and `AppDb.users` works immediately.\n\n### The `@data` types\n\nBoth the key and the value are `@data` classes. `@data` is what makes a class storable: the compiler synthesizes a binary codec (pack to bytes, unpack from bytes) so ToilDB can persist it. The rules that matter here:\n\n- **Give every field a default** (`= ''`, `= 0`, and so on). The decoder builds an empty instance and fills it, so it needs defaults.\n- **A value type must be default-constructible** (creatable with `new User()` and no arguments). Keys often add a convenience constructor, as `UserId` does above, so you can write `new UserId('abc')`.\n- Fields may be numbers (`u8`..`u256`, `i8`..`i256`, `f32`, `f64`), `bool`, `string`, another `@data` class, or an array of any of these.\n\nThe full reference, including how the same type becomes a typed client type, is on the [data types page](../backend/data.md).\n\n### The `@database` class and `@collection` fields\n\n```ts\n@database\nclass AppDb {\n @collection static users: Documents<UserId, User>;\n @collection static likes: Counter<UserId>;\n}\n```\n\n- `@database` marks the class as a database. You can have more than one `@database` class; each is a separate namespace of collections.\n- Each `@collection` is one collection. Declare it as a **`static`** field with **no initializer**: you write the type, and the compiler wires up the actual handle for you.\n- The field's **type is its family**: `Documents<K, V>`, `Counter<K>`, `Events<K, V>`, `Unique<K, V>`, `Membership<K, M>`, `Capacity<K>`, or `View<K, V>`. The compiler reads the family straight from this type, so getting it right here is how you pick a family (see [Choosing a family](./README.md#choosing-a-family-the-decision-guide)).\n\nYou reach a collection through the class, statically: `AppDb.users.get(...)`, `AppDb.likes.add(...)`. There is nothing to instantiate.\n\n### Reaching collections from a handler\n\nAny backend function can read and write collections by referencing them on the database class. What that function is allowed to do depends on its **kind**, covered next.\n\n## How access is gated: `@query`, `@action`, and friends\n\nToilDB will not let every function do everything. Each backend function runs as one **function kind**, and each kind is allowed a different slice of database operations. This is a safety rail: a read-only endpoint physically cannot write, and an expensive scan cannot run on the hot request path.\n\nYou rarely write these decorators by hand, because routes get a sensible kind automatically:\n\n- A **`@get`** route (a safe, read-only HTTP method) runs as a **Query**.\n- A **`@post`** route (a mutating method) runs as an **Action**.\n- A plain RPC **`@remote`** method defaults to a **Query** (read-only) because it has no HTTP method to infer from. Tag it `@action` if it writes.\n\nYou can override the default with `@query` or `@action` on the method when the automatic choice is wrong (for example, a `@get` that genuinely needs to write, though that is unusual).\n\nWhat each kind may do:\n\n| Kind | Set by | May do | May **not** do |\n| --- | --- | --- | --- |\n| **Query** | `@get`, plain `@remote`, or `@query` | Point reads: `get`, `getMany`, `exists`, `lookup`, `contains`, counter `get`, view `get`, Events `get`/`last`, capacity `available`. | Any write. Any scan. |\n| **Action** | `@post` or `@action` | Everything a Query can, plus bounded writes: `create`, `patch`, `delete`, `getDelete`, `enqueue`, `append`, `appendOnce`, counter `add`, membership `add`/`remove`, unique `claim`/`release`, capacity `reserve`/`confirm`/`cancel`. | Scans. Publishing a View. |\n| **Derive / Job** | Host dispatches Derive / Job; compiler checks `@derive` / `@job` | Reads including **scans** (`latest`, membership `list`), plus `publish` a View. | (Run off the request path; see below.) |\n\n**The host determines the execution kind.** With toilscript 0.1.65, toiljs 0.0.126, and a v2-capable edge host, a `@scheduled` method tagged `@job` runs as **Job**, including scans and `View.publish`. Daemon `onStart` and untagged ticks run as **Action**. Tagging a helper `@job` does not change its caller's runtime permissions. Job catalogs use v2; older edge hosts reject them rather than silently downgrade to Action. See [daemon permissions](../background/daemons.md#onstart-run-once-at-boot).\n\nTwo rules trip people up, so they are worth stating plainly:\n\n- **Scans are barred from request handlers.** Reading \"the newest N events\" (`events.latest`) or \"the members of this set\" (`membership.list`) can fan out across many rows, so a `@get` or `@post` cannot call them. Do the scan in a `@derive` (a small function that recomputes a snapshot off the request path) and have the request read the snapshot. See [Views](./views.md) and [@derive](../background/derive.md).\n- **Only a call executing as Derive or Job may `publish` a View.** A `@job` annotation on code called from an Action does not change the caller's execution kind.\n\nBoth gates are enforced twice: the compiler rejects an illegal call at build time, and the edge rejects it again at runtime, so a hand-edited module cannot sneak past. For the decorator catalog, see [Decorators](../concepts/decorators.md).\n\n## No manual provisioning: how it actually gets set up\n\nYou never create a table or run a migration. Here is the machinery, so the \"it just works\" is not a mystery.\n\nWhen toilscript compiles your backend, it scans every `@database` class and writes a small catalog into the `.wasm` file: for each collection, its name, its family, its key and value type names, and the value's schema version. This catalog rides *inside* the compiled module.\n\nThen, wherever your backend runs, the host reads that catalog once at startup and builds your collections to match:\n\n- Under **`toiljs dev`**, the host is an in-process emulator. It reads the catalog and stands up all seven families, persisting development data under `.toil/devdata.json` across restarts. This is a single-process, single-tenant development store, so you can test ToilDB behavior with no services to run.\n- On the **Dacely edge**, the host is the real ToilDB, with durable, distributed storage. It reads the *same* catalog and serves the *same* operations, now durable and worldwide.\n\nBecause both sides read the same catalog, **the same code runs unchanged in dev and in production.** There is no connection string to swap and no provisioning step to run.\n\n```mermaid\nflowchart TD\n SRC[\"@database AppDb<br/>@collection static users: Documents...<br/>@data UserId / User\"]\n SRC -->|toilscript compile| WASM[\"server.wasm<br/>(with an embedded<br/>toildb catalog section)\"]\n WASM -->|toiljs dev reads the catalog| DEV[\"Dev store<br/>(one process, local snapshot)\"]\n WASM -->|edge reads the same catalog| EDGE[(\"ToilDB on the Dacely edge<br/>(worldwide, durable)\")]\n```\n\n## Gotchas\n\n- **Declare collections as `static` fields with no initializer.** Do not try to `new` a collection or assign a handle yourself; the compiler owns that.\n- **Every `@data` field needs a default, and value types must be default-constructible.** A missing default fails to compile.\n- **Dev storage is local.** The `toiljs dev` snapshot survives restarts but is not a production backup or a distributed store. Delete `.toil/devdata.json` to reset it. Direct test-host instances stay in memory unless configured for persistence.\n- **Changing a `@data` type is a format change.** Reordering fields or changing a field's type changes the stored layout. Add new fields at the end, and use a migration when you evolve a stored type. See [data types](../backend/data.md).\n- **Pick the family at the type.** The family is read from the collection's declared type, so `Counter<K>` versus `Documents<K, V>` is a real, load-bearing choice, not a hint. Revisit [Choosing a family](./README.md#choosing-a-family-the-decision-guide) if unsure.\n\n## Related\n\n- [ToilDB overview](./README.md): the seven families and how to choose.\n- [Documents](./documents.md): the general-purpose record family (a good first collection).\n- [Data types (`@data`)](../backend/data.md): keys, values, and the codec.\n- [Decorators](../concepts/decorators.md): `@database`, `@collection`, `@query`, `@action`, `@derive`.\n- [@derive](../background/derive.md): recompute snapshots and run scans off the request path.\n",
36
+ "database/setup.md": "# Declaring a database\n\nYou set up ToilDB by **declaring** it in code: a `@database` class listing your collections, plus the `@data` key and value types those collections use. There is no schema file, no migration command, and no connection string.\n\n## What and why\n\nA **database declaration** tells toiljs three things at compile time: which collections exist, which family each one is, and what key and value types it stores. The compiler bakes that list into your server's WebAssembly, and both the dev server and the production edge read it back to set up your collections automatically. You declare; the platform provisions.\n\nReach for this on day one: before you can read or write any data, you need a `@database` with at least one `@collection`.\n\nGroup related data into collections within a small number of databases. A new\nfeature usually needs a new collection, not another `@database` class. Database\nnamespaces do not replace application authorization: enforce account and\norganization access in server routes and scope collection keys appropriately.\n\n## How: the three pieces\n\nA working database is always these three pieces together.\n\n1. **`@data` key and value types.** Plain classes, tagged `@data`, that describe what you store.\n2. **A `@database` class** whose static fields are `@collection`s, each typed by a family.\n3. **A handler** (a `@rest` route or an RPC method) that reads and writes those collections.\n\nHere is a complete, minimal example: a store of users you look up by id.\n\n```ts\n// A @data key: how you address one user.\n@data\nclass UserId {\n id: string = '';\n constructor(id: string = '') { this.id = id; }\n}\n\n// A @data value: what you store for each user.\n@data\nclass User {\n id: string = '';\n name: string = '';\n score: u64 = 0;\n}\n\n// The database declaration. Each @collection is one collection,\n// typed by its family (here, Documents) with <Key, Value>.\n@database\nclass AppDb {\n @collection static users: Documents<UserId, User>;\n}\n\n// A route that reads and writes the collection.\n@rest('users')\nclass Users {\n @get('/:id')\n public getUser(ctx: RouteContext): User {\n const user = AppDb.users.get(new UserId(ctx.param('id')));\n return user == null ? new User() : user;\n }\n\n @post('/')\n public createUser(input: User): User {\n AppDb.users.create(new UserId(input.id), input);\n return input;\n }\n}\n```\n\nThat is the whole setup. Run `toiljs dev` and `AppDb.users` works immediately.\n\n### The `@data` types\n\nBoth the key and the value are `@data` classes. `@data` is what makes a class storable: the compiler synthesizes a binary codec (pack to bytes, unpack from bytes) so ToilDB can persist it. The rules that matter here:\n\n- **Give every field a default** (`= ''`, `= 0`, and so on). The decoder builds an empty instance and fills it, so it needs defaults.\n- **A value type must be default-constructible** (creatable with `new User()` and no arguments). Keys often add a convenience constructor, as `UserId` does above, so you can write `new UserId('abc')`.\n- Fields may be numbers (`u8`..`u256`, `i8`..`i256`, `f32`, `f64`), `bool`, `string`, another `@data` class, or an array of any of these.\n\nThe full reference, including how the same type becomes a typed client type, is on the [data types page](../backend/data.md).\n\n### The `@database` class and `@collection` fields\n\n```ts\n@database\nclass AppDb {\n @collection static users: Documents<UserId, User>;\n @collection static likes: Counter<UserId>;\n}\n```\n\n- `@database` marks the class as a database. You can have more than one `@database` class; each is a separate namespace of collections.\n- Each `@collection` is one collection. Declare it as a **`static`** field with **no initializer**: you write the type, and the compiler wires up the actual handle for you.\n- The field's **type is its family**: `Documents<K, V>`, `Counter<K>`, `Events<K, V>`, `Unique<K, V>`, `Membership<K, M>`, `Capacity<K>`, or `View<K, V>`. The compiler reads the family straight from this type, so getting it right here is how you pick a family (see [Choosing a family](./README.md#choosing-a-family-the-decision-guide)).\n\nYou reach a collection through the class, statically: `AppDb.users.get(...)`, `AppDb.likes.add(...)`. There is nothing to instantiate.\n\n### Reaching collections from a handler\n\nAny backend function can read and write collections by referencing them on the database class. What that function is allowed to do depends on its **kind**, covered next.\n\n## How access is gated: `@query`, `@action`, and friends\n\nToilDB will not let every function do everything. Each backend function runs as one **function kind**, and each kind is allowed a different slice of database operations. This is a safety rail: a read-only endpoint physically cannot write, and an expensive scan cannot run on the hot request path.\n\nYou rarely write these decorators by hand, because routes get a sensible kind automatically:\n\n- A **`@get`** route (a safe, read-only HTTP method) runs as a **Query**.\n- A **`@post`** route (a mutating method) runs as an **Action**.\n- A plain RPC **`@remote`** method defaults to a **Query** (read-only) because it has no HTTP method to infer from. Tag it `@action` if it writes.\n\nYou can override the default with `@query` or `@action` on the method when the automatic choice is wrong (for example, a `@get` that genuinely needs to write, though that is unusual).\n\nWhat each kind may do:\n\n| Kind | Set by | May do | May **not** do |\n| --- | --- | --- | --- |\n| **Query** | `@get`, plain `@remote`, or `@query` | Point reads: `get`, `getMany`, `exists`, `lookup`, `contains`, counter `get`, view `get`, Events `get`/`last`, capacity `available`. | Any write. Any scan. |\n| **Action** | `@post` or `@action` | Everything a Query can, plus bounded writes: `create`, `patch`, `delete`, `getDelete`, `enqueue`, `append`, `appendOnce`, counter `add`, membership `add`/`remove`, unique `claim`/`release`, capacity `reserve`/`confirm`/`cancel`. | Scans. Publishing a View. |\n| **Derive / Job** | Host dispatches Derive / Job; compiler checks `@derive` / `@job` | Reads including **scans** (`latest`, membership `list`), plus `publish` a View. | (Run off the request path; see below.) |\n\n**The host determines the execution kind.** An unannotated daemon `onStart` or\nscheduled tick runs as **Action**. A `@scheduled` method tagged `@job` runs as\n**Job**, including scans and `View.publish`; this requires toilscript 0.1.65,\ntoiljs 0.0.126, and a v2-capable native host. Annotating `onStart` itself with\n`@job` also gives startup **Job** permissions, using toilscript 0.1.66,\ntoiljs 0.0.128, and daemon catalog v3. Older hosts reject unsupported catalogs\nrather than silently downgrade permissions. Tagging a helper `@job` does not\nchange its caller's runtime permissions. See\n[startup with Job permissions](../background/daemons.md#startup-with-job-permissions).\n\nTwo rules trip people up, so they are worth stating plainly:\n\n- **Scans are barred from request handlers.** Reading \"the newest N events\" (`events.latest`) or \"the members of this set\" (`membership.list`) can fan out across many rows, so a `@get` or `@post` cannot call them. Do the scan in a `@derive` (a small function that recomputes a snapshot off the request path) and have the request read the snapshot. See [Views](./views.md) and [@derive](../background/derive.md).\n- **Only a call executing as Derive or Job may `publish` a View.** A `@job` annotation on code called from an Action does not change the caller's execution kind.\n\nBoth gates are enforced twice: the compiler rejects an illegal call at build time, and the edge rejects it again at runtime, so a hand-edited module cannot sneak past. For the decorator catalog, see [Decorators](../concepts/decorators.md).\n\n## No manual provisioning: how it actually gets set up\n\nYou never create a table or run a migration. Here is the machinery, so the \"it just works\" is not a mystery.\n\nWhen toilscript compiles your backend, it scans every `@database` class and writes a small catalog into the `.wasm` file: for each collection, its name, its family, its key and value type names, and the value's schema version. This catalog rides *inside* the compiled module.\n\nThen, wherever your backend runs, the host reads that catalog once at startup and builds your collections to match:\n\n- Under **`toiljs dev`**, the host is an in-process emulator. It reads the catalog and stands up all seven families, persisting development data under `.toil/devdata.json` across restarts. This is a single-process, single-tenant development store, so you can test ToilDB behavior with no services to run.\n- On the **Dacely edge**, the host is the real ToilDB, with durable, distributed storage. It reads the *same* catalog and serves the *same* operations, now durable and worldwide.\n\nBecause both sides read the same catalog, **the same code runs unchanged in dev and in production.** There is no connection string to swap and no provisioning step to run.\n\n```mermaid\nflowchart TD\n SRC[\"@database AppDb<br/>@collection static users: Documents...<br/>@data UserId / User\"]\n SRC -->|toilscript compile| WASM[\"server.wasm<br/>(with an embedded<br/>toildb catalog section)\"]\n WASM -->|toiljs dev reads the catalog| DEV[\"Dev store<br/>(one process, local snapshot)\"]\n WASM -->|edge reads the same catalog| EDGE[(\"ToilDB on the Dacely edge<br/>(worldwide, durable)\")]\n```\n\n## Gotchas\n\n- **Declare collections as `static` fields with no initializer.** Do not try to `new` a collection or assign a handle yourself; the compiler owns that.\n- **Every `@data` field needs a default, and value types must be default-constructible.** A missing default fails to compile.\n- **Dev storage is local.** The `toiljs dev` snapshot survives restarts but is not a production backup or a distributed store. Delete `.toil/devdata.json` to reset it. Direct test-host instances stay in memory unless configured for persistence.\n- **Changing a `@data` type is a format change.** Reordering fields or changing a field's type changes the stored layout. Add new fields at the end, and use a migration when you evolve a stored type. See [data types](../backend/data.md).\n- **Pick the family at the type.** The family is read from the collection's declared type, so `Counter<K>` versus `Documents<K, V>` is a real, load-bearing choice, not a hint. Revisit [Choosing a family](./README.md#choosing-a-family-the-decision-guide) if unsure.\n\n## Related\n\n- [ToilDB overview](./README.md): the seven families and how to choose.\n- [Documents](./documents.md): the general-purpose record family (a good first collection).\n- [Data types (`@data`)](../backend/data.md): keys, values, and the codec.\n- [Decorators](../concepts/decorators.md): `@database`, `@collection`, `@query`, `@action`, `@derive`.\n- [@derive](../background/derive.md): recompute snapshots and run scans off the request path.\n",
36
37
  "database/unique.md": "# Unique\n\nThe **Unique** family enforces that a value is claimed by only one owner across the entire world. It is how you make usernames, email addresses, and URL slugs one-of-a-kind, safely, even when two people try to grab the same one at the same instant.\n\n## What and why\n\nA **Unique collection** maps a `@data` **claim key** (the thing that must be unique, like a username) to a `@data` **owner value** (who or what claimed it, like a user id). At any moment a claim key is either **unclaimed** or **owned by exactly one owner**. The family lets you look up one or several owners, claim a key, and release it.\n\nReach for Unique whenever a value must be globally singular:\n\n- usernames or handles\n- email addresses\n- URL slugs or workspace names\n- any \"reserve this name for me\" scenario\n\nWhy not just check a Documents record first? Because a check-then-write has a race: two requests can both check \"is `alice` free?\", both see yes, and both create it. Unique closes that gap. The claim is decided at the key's single **home** (see [consistency](./README.md#eventual-consistency-in-plain-words)), where claims are processed one at a time, so exactly one of the two racers wins.\n\nDeclare one by typing a `@collection` as `Unique<ClaimKey, OwnerValue>`:\n\n```ts\n@data\nclass Username {\n name: string = '';\n constructor(name: string = '') { this.name = name; }\n}\n\n@data\nclass OwnerId {\n userId: string = '';\n constructor(userId: string = '') { this.userId = userId; }\n}\n\n@database\nclass AppDb {\n @collection static usernames: Unique<Username, OwnerId>;\n}\n```\n\n## The operations\n\n`K` is the claim-key type, `V` the owner value type.\n\n| Operation | Signature | Returns | Use it to |\n| --- | --- | --- | --- |\n| `lookup` | `lookup(key: K): V \\| null` | the current owner, or `null` if unclaimed | find out who owns a name |\n| `claim` | `claim(key: K, value: V): ClaimResult<V>` | a `ClaimResult` (see below) | try to take a name for an owner |\n| `release` | `release(key: K, value: V): void` | nothing; **traps** if you are not the owner | give a name back |\n\n`lookup` is a read, so it works in any function. `claim` and `release` are writes, so they need an **Action** (a `@post` route or an `@action`); see [Setup](./setup.md#how-access-is-gated-query-action-and-friends).\n\n### `ClaimResult`\n\n`claim` returns a small object that tells you what happened:\n\n```ts\nclass ClaimResult<V> {\n claimed: bool; // true if YOU own the key now\n owner: V | null; // when claimed is false, who owns it instead\n}\n```\n\n- **`claimed == true`**: you own the key. This covers both a fresh claim and an **idempotent re-claim**: if you claim a key you already own (same owner value), you still get `true`, so retrying a claim is safe. `owner` is `null` in this case.\n- **`claimed == false`**: someone else got there first. `owner` is their value, so you can tell the user \"that name is taken.\"\n\n### `lookup`\n\n`lookup` just reads the current owner without changing anything:\n\n```ts\nconst owner = AppDb.usernames.lookup(new Username('alice'));\nif (owner == null) {\n // 'alice' is free\n} else {\n // owner.userId currently holds 'alice'\n}\n```\n\nNote that `lookup` is subject to [eventual consistency](./README.md#eventual-consistency-in-plain-words): a claim made moments ago in another region may not show up in a far-away `lookup` yet. Do not use `lookup` as your uniqueness guard. `lookup` is for display (\"this name is taken by ...\"); the real guarantee comes from `claim`, which is decided at the home and cannot race.\n\n### `lookupMany`\n\n`lookupMany(keys)` returns owners in input order, with `null` for unclaimed keys.\nIt uses one database operation for the batch and the same tenant isolation and\nconsistency rules as `lookup`. The host enforces its batch-size limit (32 keys for queries, 64 for actions); split larger lists into bounded pages. The batch is not a transaction\nor a consistent snapshot across keys. It never replaces `claim` as a uniqueness\ncheck.\n\n```ts\nconst owners = AppDb.usernames.lookupMany([new Username('alice'), new Username('bob')]);\n```\n\n### `claim`\n\n`claim` is the operation that actually enforces uniqueness. You pass the key and the owner value:\n\n```ts\nconst result = AppDb.usernames.claim(new Username('alice'), new OwnerId('u_123'));\nif (result.claimed) {\n // 'alice' is now yours\n} else {\n // taken; result.owner is the current owner\n}\n```\n\nBecause claims are serialized at the key's home, this is race-safe. If two requests anywhere in the world call `claim('alice', ...)` at the same moment, the home applies them in order: the first gets `claimed: true`, the second gets `claimed: false` with the first as `owner`. There is no window where both win.\n\n### `release`\n\n`release` gives a claim back so the key becomes available again. Only the **current owner** may release: you pass both the key and the owner value, and if that value is not the current owner, `release` **traps** (aborts the request). This prevents one user from releasing another user's name.\n\n```ts\nAppDb.usernames.release(new Username('alice'), new OwnerId('u_123'));\n```\n\nRelease when a name is being changed or an account is deleted, so the name returns to the pool.\n\n## The claim / release lifecycle\n\nA claim is a small state machine: unclaimed, owned, and back to unclaimed.\n\n```mermaid\nstateDiagram-v2\n [*] --> Unclaimed\n Unclaimed --> Owned: claim(key, me) -> claimed: true\n Owned --> Owned: claim(key, me) again -> claimed: true (idempotent)\n Owned --> Owned: claim(key, someoneElse) -> claimed: false, owner: me\n Owned --> Unclaimed: release(key, me)\n```\n\nThe key insight: **claiming is the guard, releasing is cleanup.** You claim to reserve, you release to free. A claim that is never released stays owned forever (there is no automatic expiry; if you want time-limited holds, that is what the [Capacity](./capacity.md) family's TTL reservations are for).\n\n## Worked example: reserving a username on signup\n\nThe safe signup pattern is: claim the username first, then create the account, and if creating the account fails, release the claim so the name is not stranded.\n\n```ts\nimport { Response } from 'toiljs/server/runtime';\n\n@data\nclass Username {\n name: string = '';\n constructor(name: string = '') { this.name = name; }\n}\n\n@data\nclass OwnerId {\n userId: string = '';\n constructor(userId: string = '') { this.userId = userId; }\n}\n\n@data\nclass UserId {\n id: string = '';\n constructor(id: string = '') { this.id = id; }\n}\n\n@data\nclass User {\n id: string = '';\n username: string = '';\n}\n\n@data\nclass SignupInput {\n username: string = '';\n userId: string = '';\n}\n\n@database\nclass AppDb {\n @collection static usernames: Unique<Username, OwnerId>;\n @collection static users: Documents<UserId, User>;\n}\n\n@rest('signup')\nclass Signup {\n // POST /signup (Action: may claim and write)\n @post('/')\n public signup(input: SignupInput): Response {\n const owner = new OwnerId(input.userId);\n\n // 1. Claim the username. This is the uniqueness guard.\n const claim = AppDb.usernames.claim(new Username(input.username), owner);\n if (!claim.claimed) {\n return Response.text('username taken', 409);\n }\n\n // 2. Create the account. If this fails, undo the claim so the name is free.\n const user = new User();\n user.id = input.userId;\n user.username = input.username;\n if (!AppDb.users.create(new UserId(input.userId), user)) {\n AppDb.usernames.release(new Username(input.username), owner);\n return Response.text('could not create account', 409);\n }\n\n return Response.json(user.toJSON().toString());\n }\n}\n```\n\nTwo things make this correct:\n\n- **The claim happens before the account write**, so uniqueness is decided up front.\n- **The claim is released if the follow-up write fails**, so a failed signup does not permanently burn a username.\n\nBecause `claim` is idempotent for the same owner, a client that retries the whole request after a network hiccup does not get a false \"taken\" error: the second `claim('alice', u_123)` returns `claimed: true` again.\n\n## Consistency notes\n\n- **`claim` and `release` are strongly consistent at the key's home.** Two callers can never both own the same key; the home serializes claims. This is the whole point of the family.\n- **`lookup` is eventually consistent.** It reads a possibly-nearby copy, so a very recent claim from elsewhere may not appear yet. Never gate uniqueness on `lookup`; gate it on the result of `claim`.\n- **Claims do not expire.** A claim stays until someone releases it. Use [Capacity](./capacity.md) if you need holds that auto-release after a timeout.\n\n## Gotchas\n\n- **Do not use `lookup` as the uniqueness check.** Its answer can be stale. Call `claim` and trust its `claimed` flag.\n- **Release on failure and on account deletion.** A claim you forget to release stays owned forever, quietly blocking that name.\n- **`release` traps for a non-owner.** Pass the correct owner value, or you abort the request. If you are not sure you own it, `lookup` first (for display) but expect `release` to enforce ownership regardless.\n- **The owner value is data you choose.** Store enough in it (a user id, say) to know who holds the claim, so you can display and release it later.\n\n## Related\n\n- [ToilDB overview](./README.md): the seven families and how to choose.\n- [Setup](./setup.md): declaring the collection and which function kinds may claim.\n- [Documents](./documents.md): the account record you create alongside a claim.\n- [Capacity](./capacity.md): time-limited holds that auto-release (a different kind of \"reserve\").\n- [Data types (`@data`)](../backend/data.md): the claim key and owner value.\n",
37
38
  "database/views.md": "# Views (materialized views)\n\nA `View` collection is a **precomputed, read-optimized result** that you publish\nonce and read many times. Reads are a single cheap keyed lookup, no scanning, no\nrecomputing.\n\n## What and why\n\nA \"materialized view\" is a fancy name for a simple idea: instead of computing an\nanswer every time someone asks, you compute it **once**, store the finished\nanswer, and just hand it out on each request. \"Materialized\" means the result is\nmade real and saved (as opposed to computed on the fly). \"View\" means it is a\nread-friendly projection of your underlying data.\n\nThink of a leaderboard. Computing \"the top 10 players by score\" means scanning\nevery player and sorting. You do not want to do that on every page load. So you\ncompute it in the background, save the finished top-10 list as a view, and every\npage load just reads that saved list. Fast, cheap, and it does not get slower as\nyou add players.\n\nUse a `View` when:\n\n- A page needs a result that is **expensive to compute** (a scan, a sort, a fold\n over many rows).\n- That result is **read far more often than it changes** (a home page, a feed, a\n leaderboard, a \"latest N\" list, a rendered summary).\n\nThe rule of thumb: if a route wants \"the newest N of something\" or \"the top N of\nsomething\", that is a scan, and scans are barred on the request path. A `View`\nis how you serve that result without scanning per request.\n\n```mermaid\nflowchart LR\n subgraph off[\"Off the request path (@derive)\"]\n S[(\"Source data<br/>events / counters / records\")] --> D[\"@derive: scan + compute\"]\n D --> P[\"publish(key, result)\"]\n end\n P --> V[(\"View\")]\n subgraph on[\"On the request path (@get)\"]\n G[\"view.get(key)\"] --> V\n end\n```\n\n## The type\n\nA `View` has two type parameters: the **key** (which view) and the **value**\n(the precomputed result).\n\n```ts\nView<K, V>\n```\n\n- `K` is the key type: it picks *which* view to read or publish. For a single\n global leaderboard, the key can be a fixed constant like `'main'`.\n- `V` is the value type: the finished result you serve. Both are\n [`@data`](../concepts/types.md) classes.\n\nDeclare it as a `@collection` field inside a `@database` class, alongside the\nsources it is built from:\n\n```ts\n@database\nclass BoardDb {\n @collection static scores: Events<GameKey, ScoreEvent>; // a source\n @collection static board: View<GameKey, Leaderboard>; // the view\n}\n```\n\n## Operations\n\nA `View` has exactly two operations you use directly (plus `require`, a\nconvenience wrapper). Exact signatures:\n\n| Operation | Signature | What it does |\n| --- | --- | --- |\n| `get` | `get(key: K): V \\| null` | Read the published view, or `null` if nothing has been published yet. |\n| `require` | `require(key: K): V` | Like `get`, but traps (aborts the request) if nothing is published. |\n| `publish` | `publish(key: K, value: V): void` | Overwrite the view for `key` with a fresh result. |\n| `delete` | `delete(key: K): void` | Remove a projection key, idempotently; allowed in Action, Derive, or Job. |\n\n### `delete`: remove a projection key\n\n`AppDb.pages.delete(key)` removes the current projection and invalidates the\nlocal read cache. The delete is tenant-scoped, owner-routed, and replicated with\nits own authenticated operation. It does not retrigger the view's materializer.\nRemove or redact the corresponding source data as part of the same cleanup;\na later source write can otherwise rebuild and republish the key. A failed\ndelete aborts with the host status rather than reporting successful erasure.\n\n### `get`\n\nA plain keyed read. It is cheap and is allowed from **any** handler, including a\nread-only `@get` route.\n\n```ts\nconst board = BoardDb.board.get(new GameKey('main'));\nif (board == null) {\n // Nothing published yet (e.g. brand-new game). Serve an empty default.\n return new Leaderboard();\n}\nreturn board;\n```\n\nAlways handle the `null` case: until a `@derive` (or `@job`) has published at\nleast once, `get` returns `null`.\n\n### `publish`\n\nOverwrites the stored view with a new value. This is how the view gets its\ncontent.\n\n```ts\nBoardDb.board.publish(new GameKey('main'), freshBoard);\n```\n\n`publish` is **restricted**: you may only call it from a\n[`@derive`](../background/derive.md) or a `@job` (a background task), never from a\nrequest handler (`@get`/`@post`/...). The compiler enforces this, and so does the\nedge at runtime. The reason: a view is meant to be maintained off the request\npath from the source of truth, not written ad hoc by whichever request happens to\nrun.\n\n### How `publish` differs from a Documents write\n\nA `View`'s `publish` looks like writing a value, but it is not the same as a\n[Documents](./documents.md) `patch`/`create`. The differences matter:\n\n| | `Documents` write (`create` / `patch`) | `View` `publish` |\n| --- | --- | --- |\n| Who may call it | Any action handler (`@post`, ...) | Only a `@derive` or `@job` |\n| Meaning | The record IS the source of truth | The view is a **copy** derived from a source |\n| Version control | You may version-check (optimistic concurrency) | The host assigns the version; a later publish always wins (last writer wins) |\n| Read path | Standard keyed read | A read-optimized fast path (views are heavily read) |\n| Who owns correctness | You (each writer edits the true value) | The derive (it recomputes from the source, so the view always converges) |\n\nIn short: a Document is the truth; a View is a saved snapshot of a computation\nover the truth. If the view is ever wrong or stale, the derive just recomputes and\nrepublishes it. You never hand-edit a view from a route.\n\n## Automatic maintenance with `@derive`\n\nYou rarely call `publish` by hand. The normal pattern is a\n[`@derive`](../background/derive.md): a method on your `@database` class that\nreads the sources, builds the value, and publishes it. The runtime runs it for\nyou:\n\n- **Right after a write to a source.** When a request writes one of the\n database's source collections (an `append`, a `counter.add`, a record write),\n the database's derives run right after the response is produced. So the view\n reflects the new data on the next read.\n- **On box load.** When the server starts or reloads, the views are rebuilt from\n their sources before the first read is served.\n\nYou never call a derive yourself, and a derive's own `publish` never re-triggers\nit. See [`@derive`](../background/derive.md) for the full rules.\n\n## Worked example: a leaderboard\n\nA game appends score events; a derive folds them into a top-10 list; a route\nserves that list with a single `get`.\n\n```ts\nimport { ScoreEvent } from '../models/ScoreEvent';\nimport { Leaderboard } from '../models/Leaderboard';\nimport { GameKey } from '../models/GameKey';\nimport { NewScore } from '../models/NewScore';\n\n@database\nclass BoardDb {\n // The source of truth: every score, appended as it happens.\n @collection static scores: Events<GameKey, ScoreEvent>;\n // The materialized view: the current top entries, ready to serve.\n @collection static board: View<GameKey, Leaderboard>;\n\n // Off the request path: scan the recent scores, sort, publish the top 10.\n @derive\n rebuild(): void {\n const key = new GameKey('main');\n const recent = BoardDb.scores.latest(key, 500); // a scan, allowed in a derive\n const board = new Leaderboard();\n board.entries = topTen(recent); // your own sort/aggregate\n BoardDb.board.publish(key, board);\n }\n}\n\n@rest('leaderboard')\nclass LeaderboardRoutes {\n // GET reads the precomputed view: one keyed read, no scan.\n @get('/')\n public top(): Leaderboard {\n const board = BoardDb.board.get(new GameKey('main'));\n return board == null ? new Leaderboard() : board;\n }\n\n // POST records a score. The @derive rebuilds `board` right after.\n @post('/')\n public submit(input: NewScore): Leaderboard {\n BoardDb.scores.append(new GameKey('main'), new ScoreEvent(input.player, input.score));\n return new Leaderboard(); // ack; the GET serves the updated board from the view\n }\n}\n```\n\nThe models:\n\n```ts\n@data\nexport class ScoreEvent {\n player: string = '';\n score: u64 = 0;\n}\n\n@data\nexport class Leaderboard {\n entries: ScoreEvent[] = [];\n}\n```\n\nA \"latest N\" view is the same shape: the derive calls `latest(key, N)` and\npublishes the list. See the [Events](./events.md) page for that variant end to\nend.\n\n## Consistency\n\n- **Last writer wins.** The host assigns each `publish` a version, and a later\n publish always supersedes an earlier one. Because a derive recomputes the whole\n view from the source of truth, the view converges to a correct snapshot; you do\n not need to coordinate concurrent publishes.\n- **A view can be briefly stale.** ToilDB is worldwide, and a view is published\n at its home then copied to other regions in the background (asynchronous\n replication). A read from a far region can lag the newest publish by a moment.\n This is usually fine for the things views hold (feeds, leaderboards, summaries):\n a leaderboard that is a second behind is still a good leaderboard.\n- **`get` returns `null` until the first publish.** Always default the empty case.\n\n## Gotchas\n\n- **`publish` is derive/job only.** You cannot publish from a route. If you need\n to update a view in response to a request, write the *source* (append an event,\n add to a counter) from the action and let the `@derive` republish.\n- **Handle `null` from `get`.** A never-published view reads as `null`, not as an\n empty value. Return a sensible default.\n- **A view is a copy, not the truth.** Never store data *only* in a view. Keep\n the real data in a source family (Documents, Events, Counters) and treat the\n view as a disposable, recomputable projection.\n- **Keep views bounded.** A view value is read whole on every request, so build\n it from a bounded read (top N, latest N, a total), not the entire history.\n\n## Related\n\n- [`@derive`](../background/derive.md): the normal way a view is maintained.\n- [Events](./events.md): the append-only log a view is often folded from.\n- [Counters](./counters.md): another common source for a view (totals).\n- [Documents](./documents.md): mutable source-of-truth records (and how a write\n differs from a publish).\n- [Data types (`@data`)](../concepts/types.md): how view keys and values are stored.\n",
38
39
  "frontend/components.md": "# Components\n\nA toiljs frontend is a normal React app, so the components you write are just React components: functions that return JSX, hold state with hooks, and compose however you like. There is no toiljs-specific base class, no decorator, and no registration step. On top of your own components, toiljs ships a small set of ready-made ones on the `Toil` global (an image, a script loader, a form, and a few more) for the jobs a plain React app makes you wire up by hand. This page covers both: how your components fit in, and a reference for every `Toil.*` component.\n\n## Writing your own components\n\nAnything you already know about writing React components applies unchanged. You write ordinary functions, use `useState` / `useEffect` / `useMemo` and any hooks you like, and return JSX:\n\n```tsx\n// client/components/Counter.tsx\nimport { useState } from 'react';\n\nexport default function Counter({ start = 0 }: { start?: number }) {\n const [n, setN] = useState(start);\n return <button onClick={() => setN(n + 1)}>Clicked {n} times</button>;\n}\n```\n\nYour reusable components live in `client/components/`, and you import them the normal way from anywhere in `client/`:\n\n```tsx\n// client/routes/index.tsx\nimport Counter from '../components/Counter';\n\nexport default function Home() {\n return (\n <main>\n <h1>Welcome</h1>\n <Counter start={10} />\n </main>\n );\n}\n```\n\nA few things are worth spelling out, because they are the parts that are handled for you rather than by you:\n\n- **Route files must `export default` a component.** A file under `client/routes/` becomes a page only if it default-exports a component (see [Routing](./routing.md)). Files under `client/components/` have no such rule; export them however you please (default or named).\n- **The `Toil.*` globals need no import.** `Toil.Link`, `Toil.useParams()`, `Toil.Image`, and everything else on `Toil` are ambient. The compiler generates a `toil-env.d.ts` that types the global, so your editor autocompletes `Toil.` and type-checks it with no `import` line. The same goes for `Server` (the typed backend client) and the `FastMap` / `DataWriter` data utilities. See the [Frontend overview](./README.md) for the whole ambient surface.\n- **The JSX runtime is configured for you.** You do not write `import React from 'react'` at the top of every file. The build sets up the automatic JSX runtime, so JSX just works. Import named hooks and types from `react` when you need them (`import { useState, type ReactNode } from 'react'`), but the bare React import for JSX is unnecessary.\n\nIn other words, a component in a toiljs app is indistinguishable from a component in any React app. Two things are genuinely special, and both are opt-in.\n\n### Special case 1: components inside an SSR route\n\nIf a route opts into server rendering with `export const ssr = true`, its component tree is rendered once at build time into a template, then filled per request on the edge (see [Rendering and SSR](./rendering.md)). For that to work, any part of the JSX that changes per request (a value from the URL, a list from a loader, a block of user HTML) has to be wrapped in one of the [SSR marker primitives](#ssr-marker-primitives) below, or isolated in a `Toil.Island`. Anything you leave unwrapped gets frozen into the template at its build-time value.\n\nYou do not have to get this perfect: if an SSR route (or a layout above it) cannot render on the server, toiljs skips SSR for that route at build, prints a warning telling you what to move, and falls back to plain client rendering. So the route still works, it just loses its server first paint until you address the warning.\n\n### Special case 2: importing images and other assets\n\nImporting an image with the `?toil` suffix gives you an object carrying the resolved URL, the intrinsic width and height, and an auto-generated blur placeholder (a `blurDataURL`), ready to hand straight to `Toil.Image`:\n\n```tsx\nimport hero from './hero.webp?toil';\n// hero is { src, width, height, blurDataURL }\n\n<Toil.Image src={hero} alt=\"Our office\" />;\n```\n\nPassing the whole object lets `Toil.Image` reserve the correct aspect ratio and paint the blur while the real image loads, with no extra props. See [Images](./images.md) for the full treatment.\n\nPlain asset imports are typed for you as well. A bare `import logo from './logo.svg'` (or `.png`, `.webp`, and so on) resolves to the hashed URL string, and the vite-imagetools query forms (`?url`, `?as=srcset`, `?as=metadata`) are typed too, so you get autocomplete and type-checking on all of them without declaring any modules yourself.\n\n## The toiljs component primitives\n\nThese are the components toiljs provides on the `Toil` global. They cover the framework-level jobs a plain React app leaves to you. All are ambient (no import), and all are fully typed.\n\n| Component | What it is | Renders |\n| --- | --- | --- |\n| `Toil.Image` | Layout-shift-free `<img>` replacement with lazy-load and blur placeholder. | An `<img>` (optionally wrapped in a sizing box). |\n| `Toil.Script` | One-time external or inline `<script>` loader with a load strategy. | Nothing (`null`). |\n| `Toil.Form` | A `<form>` that runs an action on submit and revalidates loader data. | A `<form>`. |\n| `Toil.Slot` | Renders a named parallel-route slot for the current URL. | The slot's route tree, or a fallback. |\n| `Toil.Head` | Declarative `<head>` contribution (title, meta, link). | Nothing (`null`). |\n| `Toil.Metadata` | Declarative route-style metadata applied from any component. | Nothing (`null`). |\n\nThe [SSR marker primitives](#ssr-marker-primitives) (`Toil.Hole`, `Toil.Repeat`, `Toil.RawHtml`, `Toil.attr`, `Toil.Island`) are a separate group, covered in their own section below.\n\n### `Toil.Image`\n\nA drop-in `<img>` replacement that prevents layout shift and lazy-loads by default. You give it `width` and `height` (or `fill`) so it reserves space before the image arrives, it decodes asynchronously, it lazy-loads unless you mark it `priority`, and it can fade in from a blur placeholder. It accepts either a string URL or a `?toil` import object (which auto-fills the size and blur):\n\n```tsx\nimport hero from './hero.webp?toil';\n\nexport default function Home() {\n return (\n <>\n <Toil.Image src={hero} alt=\"Our office\" priority placeholder=\"blur\" />\n <Toil.Image src=\"/team.jpg\" alt=\"The team\" width={800} height={600} />\n </>\n );\n}\n```\n\nKey props are `src`, `alt` (required, pass `alt=\"\"` for a decorative image), `width` / `height` or `fill`, `priority` (for an above-the-fold hero), and `placeholder` (`'empty'` or `'blur'`). It also accepts any standard `<img>` attribute. This is kept brief on purpose: [Images](./images.md) covers sizing, `fill`, blur placeholders, and how it stops layout shift in full.\n\n### `Toil.Script`\n\nLoads an external or inline `<script>` exactly once for the whole life of the app (even across client-side navigations), and lets you choose when it runs with a `strategy` prop. Use it instead of a hand-written `<script>` tag for third-party snippets like analytics or chat widgets, which a plain `<script>` in a single-page app runs unreliably or twice:\n\n```tsx\n// client/layout.tsx\nexport default function Layout({ children }: { children?: React.ReactNode }) {\n return (\n <div className=\"app\">\n <Toil.Script src=\"https://cdn.example-analytics.com/analytics.js\" />\n {children}\n </div>\n );\n}\n```\n\nThe `strategy` is `afterInteractive` (default), `lazyOnload`, or `beforeInteractive`, and there are `onLoad` / `onReady` / `onError` callbacks. `Toil.Script` renders nothing. See [Scripts](./scripts.md) for the strategies, inline scripts, dedup rules, and the full prop table.\n\n### `Toil.Form`\n\nA `<form>` that submits without reloading the page. On submit it runs your `action` (which receives the form's `FormData`), tracks pending and error state, and on success revalidates the current route's loader data so the page reflects the write. It is the convenient front end of the loader/action data loop:\n\n```tsx\n// A guestbook that refreshes its list after a successful sign.\nexport default function Guestbook() {\n const entries = Toil.useLoaderData<typeof loader>();\n\n const sign = async (data: FormData) => {\n const author = String(data.get('author'));\n const message = String(data.get('message'));\n await Server.REST.guestbook.sign({ body: new NewMessage(author, message) });\n };\n\n return (\n <Toil.Form action={sign} resetOnSuccess>\n {({ pending, error }) => (\n <>\n <input name=\"author\" placeholder=\"Your name\" />\n <textarea name=\"message\" />\n <button disabled={pending}>{pending ? 'Signing...' : 'Sign'}</button>\n {error ? <p className=\"err\">Could not sign, try again.</p> : null}\n </>\n )}\n </Toil.Form>\n );\n}\n```\n\nPass a render function as the child to read the live submit state: it receives `{ pending, error, data }`, which is how you disable the button while pending or show an error. The props:\n\n| Prop | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `action` | `(data: FormData) => void \\| Promise<void>` | (required) | Runs on submit, receiving the form's `FormData`. May be async. |\n| `revalidate` | `RevalidateTarget` | `true` | Which loader data to refetch after a successful submit. `true` is the current route. |\n| `onSuccess` | `() => void` | (none) | Called after a successful submit. |\n| `onError` | `(error: unknown) => void` | (none) | Called when the action throws. |\n| `resetOnSuccess` | `boolean` | `false` | Reset the form fields after a successful submit. |\n| `className` | `string` | (none) | Class on the `<form>` element. |\n| `children` | `ReactNode` or `(state) => ReactNode` | (none) | Form contents. A function child receives `{ pending, error, data }`. |\n\nFor writes that are not form submits (a delete button, a like toggle), reach for the underlying `Toil.useAction` hook instead. Both are covered in [Fetching data](./data-fetching.md).\n\n### `Toil.Slot`\n\nRenders the named parallel-route slot for the current URL. A folder starting with `@` (like `@modal`) under `client/routes/` is a whole second route tree that matches the URL independently of the main page; placing `<Toil.Slot name=\"modal\" />` is where that tree renders. If no slot route matches the current URL, it renders the `fallback` (nothing by default):\n\n```tsx\n// client/routes/gallery/layout.tsx\nexport default function GalleryLayout({ children }: { children?: React.ReactNode }) {\n return (\n <div>\n {children}\n <Toil.Slot name=\"modal\" fallback={null} />\n </div>\n );\n}\n```\n\n| Prop | Type | Default | What it does |\n| --- | --- | --- | --- |\n| `name` | `string` | (required) | The slot name: the `@name` directory under `routes/`, without the `@`. |\n| `fallback` | `ReactNode` | `null` | Rendered when no slot route matches the current URL. |\n\nParallel slots and the intercepting routes that fill them (the \"click a photo, open it in a modal\" pattern) are explained in [Routing](./routing.md).\n\n### `Toil.Head`\n\nA declarative way for any component (a page, a layout, a deep child) to contribute to the document `<head>`: a title, `<meta>` tags, and `<link>` tags. It renders nothing; it just applies its head entries for the lifetime of the component and reverts them on unmount. Entries compose across the tree, with later or deeper ones winning per key:\n\n```tsx\nexport default function ArticlePage() {\n const post = Toil.useLoaderData<typeof loader>();\n return (\n <>\n <Toil.Head\n title={post.title}\n meta={[\n { name: 'description', content: post.summary },\n { property: 'og:title', content: post.title },\n ]}\n link={[{ rel: 'canonical', href: `https://example.com/blog/${post.id}` }]}\n />\n <article>{/* ... */}</article>\n </>\n );\n}\n```\n\n`<Toil.Head>` takes `title`, `meta` (an array of `{ name | property, content }` tags), and `link` (an array of `{ rel, href }` tags). The hook form `Toil.useHead(spec)` and the shorthand `Toil.useTitle(title)` do the same job imperatively. See [Metadata and SEO](./metadata.md).\n\n### `Toil.Metadata`\n\nThe declarative, convenience-shaped cousin of `Toil.Head`. Instead of raw meta and link arrays, you pass a route-style metadata object (the same shape a route file's `export const metadata` uses), and toiljs expands the convenience fields (`description`, `keywords`, `canonical`, `openGraph`, and so on) into the right tags. It renders nothing, and applies for the component's lifetime. Use it to set metadata from a component that is not itself a route file (a rendered article, a widget):\n\n```tsx\n<Toil.Metadata\n title=\"Our pricing\"\n description=\"Simple, flat pricing for teams of any size.\"\n openGraph={{ title: 'Pricing', image: 'https://example.com/og/pricing.png' }}\n/>\n```\n\nBecause a route's own `metadata` export is applied last (highest priority), `Toil.Metadata` fills in for routes that declare none and yields to a route that sets the same key. The full field list lives in [Metadata and SEO](./metadata.md).\n\n## SSR marker primitives\n\nThese five primitives matter only for routes with `export const ssr = true`. They are how you tell the build which parts of a server-rendered page are dynamic (filled per request) versus static (baked into the template once). On a client-only route they do nothing special, so you never need them unless you opt a route into SSR.\n\n**The mental model.** In the browser these markers are transparent: `<Toil.Hole>` renders its children, `<Toil.Repeat>` maps its rows, `<Toil.RawHtml>` renders a raw-HTML wrapper, and `Toil.attr(id, value)` returns the value unchanged. Your client-side app runs exactly as written. But under the build-time SSR extractor, each marker instead emits a sentinel token that marks an insertion point. The extractor strips those tokens and records their positions, producing a static template with numbered holes. Per request, your compiled backend fills only the hole values, and the edge splices them into the template. Because the static scaffold around each hole is React's own rendering output and the hole values are escaped exactly as React escapes them, the browser hydrates the result byte-for-byte, with no mismatch.\n\n| Marker | Use it for | Shape |\n| --- | --- | --- |\n| `Toil.Hole` | A single dynamic **text** value. | `<Toil.Hole id=\"...\">{value}</Toil.Hole>` |\n| `Toil.Repeat` | A **list**: one row template repeated over an `each` array. | `<Toil.Repeat id=\"...\" each={rows}>{(item, i) => ...}</Toil.Repeat>` |\n| `Toil.RawHtml` | A block of **trusted, pre-rendered HTML**. | `<Toil.RawHtml id=\"...\" html={s} as=\"section\" />` |\n| `Toil.attr` | A dynamic value in **attribute position** (an `href`, a `class`). | `href={Toil.attr('id', value)}` (a function call) |\n| `Toil.Island` | Content that must render **only in the browser** (escape hatch). | `<Toil.Island>{children}</Toil.Island>` |\n\nA few rules that keep the template valid:\n\n- **Every marker needs a stable `id`**, a short name unique within the page. The build maps each id to a numbered slot, so keep the ids constant across builds.\n- **`Toil.Repeat` needs at least one row at build time.** It captures that first row as the sub-template for every row, so the build render must see a sample with one or more items. An empty `each` gives it nothing to capture.\n- **`Toil.RawHtml` renders inside a wrapper element** (a `<div>` by default, `as=\"section\"` to change the tag), and you own sanitising that HTML, exactly like React's `dangerouslySetInnerHTML`.\n- **`Toil.attr` is a function, not an element.** An attribute is not a child node, so it cannot be a JSX element. You call `Toil.attr(id, value)` right where the attribute value goes, and it composes with literal text around it (`` className={`btn ${Toil.attr('kind', d.kind)}`} ``).\n- **`Toil.Island` renders nothing on the server and on the first (hydration) render**, then reveals its children after mount. So an island gets no server first paint and no SEO, by design. It is the place for anything that genuinely cannot run on the server (reads `window`, calls `Date.now()`, depends on the live URL).\n\nHere is a compact SSR route wiring several of them together. The title, tag list, and author link all come from the route's `loader`:\n\n```tsx\n// client/routes/blog/[id].tsx\nexport const ssr = true;\n\nexport const loader = async ({ params }: Toil.LoaderArgs) => {\n // Illustrative shape: { title, tags, authorUrl }.\n return Server.REST.blog.get({ params: { id: params.id } });\n};\n\nexport default function BlogPost() {\n const post = Toil.useLoaderData<typeof loader>();\n return (\n <article>\n <h1>\n <Toil.Hole id=\"title\">{post.title}</Toil.Hole>\n </h1>\n\n {/* A dynamic attribute: call attr() in attribute position. */}\n <a href={Toil.attr('authorUrl', post.authorUrl)}>By the author</a>\n\n {/* A list: one row template, stamped once per item on the server. */}\n <ul>\n <Toil.Repeat id=\"tags\" each={post.tags}>\n {(tag) => <li key={tag}>{tag}</li>}\n </Toil.Repeat>\n </ul>\n </article>\n );\n}\n```\n\nFor the whole SSR story (the template extraction flow, keeping a route SSR-safe, and the current SSR limitations), see [Rendering and SSR](./rendering.md).\n\n## Related\n\n- [Rendering and SSR](./rendering.md): how SSR routes render, hydrate, and use the marker primitives.\n- [Images](./images.md): the full `Toil.Image` reference, blur placeholders, and layout shift.\n- [Scripts](./scripts.md): `Toil.Script` strategies, inline scripts, and dedup.\n- [Fetching data](./data-fetching.md): `Toil.Form`, `useAction`, loaders, and the typed backend clients.\n- [Metadata and SEO](./metadata.md): `Toil.Head`, `Toil.Metadata`, and per-route metadata.\n- [Routing](./routing.md): pages, layouts, and the parallel slots `Toil.Slot` renders.\n",
@@ -49,7 +50,7 @@ export const TOIL_DOCS = {
49
50
  "frontend/testing.md": "# Testing and coverage\n\nEvery new toiljs project includes Vitest 5, real Chrome tests through WebdriverIO,\nand V8 coverage. The `app`, `minimal`, and `agent` templates install the tooling\nalongside the other development dependencies. Tests run without starting or building\nany backend.\n\n## Run the starter examples\n\n```bash\nnpm test # Node unit tests\nnpm run test:watch # Watch unit tests\nnpm run test:browser # Real Chrome component tests\nnpm run test:all # Unit and browser projects together\nnpm run test:coverage # Both projects with coverage\n```\n\nThe starter includes `client/lib/Greeting.ts` and `tests/Greeting.test.ts`:\n\n```ts\nimport { expect, test } from 'vitest';\nimport { Greeting } from '../client/lib/Greeting';\n\ntest('trims the supplied name', (): void => {\n expect(Greeting.message(' Ada ')).toBe('Hello, Ada!');\n});\n```\n\n`tests/TestCounter.browser.test.tsx` renders a React component, clicks its button\nwith `page` from `vitest/browser`, and checks that its count changes. It also uses\n`Toil.Link`, so the example verifies framework globals in a real browser.\n\n## Configuration and globals\n\nThe generated `vitest.config.ts` uses the framework preset:\n\n```ts\nimport { defineTestConfig } from 'toiljs/vitest';\n\nexport default defineTestConfig();\n```\n\nThe preset installs the React Vite plugin, `client` and `shared` aliases, and two\nindependent projects:\n\n| Project | Files | Runtime |\n| --- | --- | --- |\n| `unit` | `*.test.ts`, `*.test.tsx`, `*.spec.ts`, `*.spec.tsx` under `client/`, `tests/`, or `test/`, excluding browser files | Node |\n| `browser` | `*.browser.test.ts`, `*.browser.test.tsx`, `*.browser.spec.ts`, `*.browser.spec.tsx` under those folders | Chrome, headless by default |\n\nThe setup registers `Toil`, `Server`, `FastMap`, `FastSet`, `DataWriter`, `DataReader`,\nand `parseError`. It does not mount the app or launch a server. Mock typed backend\ncalls with Vitest mocks or `vi.stubGlobal('Server', yourTypedMock)` when a component\nneeds data. AssemblyScript backend code requires separate WebAssembly integration\ntests; this preset covers JavaScript and React code.\n\nPass `root`, `headless`, `chromeArgs`, `unitInclude`, or `browserInclude` to\n`defineTestConfig` to change its defaults. Use `mergeConfig` from `vitest/config`\nfor other settings, such as coverage thresholds or additional aliases. A custom\nconfiguration can import `toiljs/vitest/setup` as a setup file to register globals.\n\nThe preset uses WebDriver Classic for compatibility with Vitest iframe control on\nWebdriverIO 10. WebdriverIO discovers Chrome and manages ChromeDriver automatically. To use specific\nbinaries, set `TOIL_TEST_BROWSER_BINARY` and `TOIL_TEST_CHROMEDRIVER` independently.\nBrowser tests need Chrome and its OS libraries installed; downloads need network\naccess on the first run. A Linux container running as root may need explicit\n`chromeArgs: ['--no-sandbox']` in its test config.\n\n## Coverage reports\n\n`npm run test:coverage` produces terminal, HTML, JSON, and LCOV reports under\n`coverage/`. Open `coverage/index.html` for the HTML report. Client and shared\nTypeScript files are included, with declarations, tests, and generated\n`shared/server.ts` excluded. The `coverage/` directory is gitignored.\n\n```bash\nnpx toiljs test --coverage # Unit coverage only\nnpx toiljs test --browser --coverage # Browser coverage only\nnpx toiljs test --all --coverage --coverage.thresholds.lines=80\n```\n\n## Existing projects\n\nAfter updating toiljs, run `npx toiljs test`. It adds missing test scripts and installs\nmissing Vitest, WebdriverIO, and coverage packages using your project's package\nmanager. If no Vitest or Vite config exists, it also writes the preset and examples,\npreserving any files already at those paths. Existing custom configs and scripts\nare preserved. Keep Vitest and `@vitest/coverage-v8` on matching versions; the native\npreset requires Vitest 5.\n\nOther Vitest options and file filters pass through:\n\n```bash\nnpx toiljs test Greeting\nnpx toiljs test --browser TestCounter\nnpx toiljs test --all --reporter=verbose\nnpx toiljs test --root ./apps/dashboard --watch\n```\n\nWith the native preset, `toiljs test` selects `unit`, `--browser` selects `browser`,\nand `--all` runs both. An explicit `--project` selects your requested project.\nA custom configuration keeps its own project selection; `--browser` is forwarded\nto Vitest. Failed tests return a nonzero exit status for CI.\n\n## Diagnose and repair setup\n\n`npx toiljs doctor` has a Testing report covering actual installed versions, declared\nranges, matching Vitest and coverage releases, config presence, and scripts.\nUnconfigured legacy projects get warnings; broken configured packages fail the check.\n`--json` includes the same Testing group for CI.\n\n`npx toiljs doctor --fix` repairs missing tooling, scripts, config, and examples;\nadds tests to plain JSON TypeScript includes; and ignores test reports. It preserves\ncustom configs, existing files, nonempty scripts, and explicit dependency sources.\nInstall afterward, or run `npx toiljs test` to install missing packages. Doctor never\nlaunches a browser or installs packages itself.\n\n`npx toiljs update --yes` includes testing setup and installation even when no package\nupdates are available. Native updates retain supported runner/browser majors and\nkeep Vitest and V8 coverage on matching releases. Interactive updates add setup only\nwhen updates are accepted.\n",
50
51
  "frontend/toil-global.md": "# The Toil global (reference)\n\nAlmost the entire toiljs client API hangs off one global object, `Toil`, so your route files need no imports for the everyday things. This page is the full index: every `Toil.*` member, its TypeScript signature, and a one-line description, grouped by area. Reach for it when you know roughly what you want and just need the exact name or shape; the deeper guides (linked per section) explain the concepts.\n\n`Toil` is not a hand-written object. It is the module namespace of the `toiljs/client` package, exposed as a global. The compiler writes a `toil-env.d.ts` at your project root containing `declare const Toil: typeof import('toiljs/client')`, so `Toil` is typed as the whole package and every member autocompletes with no import. Put another way: anything you could `import { X } from 'toiljs/client'` is reachable as `Toil.X`.\n\nA few members are also bare globals, handed to you the same way. `Server` (the typed backend client) and `parseError` are global on their own and additionally live under `Toil` (so `Server` and `Toil.Server` are the same value, likewise `parseError`). `FastMap`, `FastSet`, `DataWriter`, and `DataReader` (the fast collections and compact binary codec from `toiljs/io`, see [Data types](../backend/data.md)) are bare globals only: they are not under `Toil`, so write `new DataWriter()`, never `new Toil.DataWriter()`.\n\n## Components (JSX)\n\nDrop-in components you render in JSX. See [Images](./images.md), [Scripts](./scripts.md), [Fetching data](./data-fetching.md), and [Metadata and SEO](./metadata.md) for the detail.\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.Image` | `Image(props: ImageProps): ReactNode` | A drop-in `<img>` that reserves space (no layout shift), lazy-loads, and can fade in from a blur placeholder. See [Images](./images.md). |\n| `Toil.Script` | `Script(props: ScriptProps): ReactNode` | Loads an external or inline `<script>` with a load `strategy`, deduplicated so it runs at most once. Renders nothing. See [Scripts](./scripts.md). |\n| `Toil.Form` | `Form(props: FormProps): ReactNode` | A `<form>` that runs an action on submit (no reload) and revalidates loader data on success. See [Fetching data](./data-fetching.md). |\n| `Toil.Slot` | `Slot(props: SlotProps): ReactNode` | Renders the parallel-route slot named `props.name` (`{ name: string; fallback?: ReactNode }`) for the current URL. See [Routing](./routing.md). |\n| `Toil.Head` | `Head(props: HeadSpec): null` | Declarative form of `useHead`: `<Toil.Head title=\"...\" meta={[...]} />`. Renders nothing. See [Metadata and SEO](./metadata.md). |\n| `Toil.Metadata` | `Metadata(props: Metadata): null` | Declarative form of `useMetadata`: `<Toil.Metadata title=\"...\" openGraph={...} />`. Renders nothing. See [Metadata and SEO](./metadata.md). |\n| `Toil.Router` | `Router(props: { routes; layout?; notFound?; globalError?; slots? }): ReactNode` | The app router element. `Toil.mount` renders this for you, so you rarely use it directly. |\n\n## SSR marker primitives\n\nThese mark a route's dynamic bits so the edge can server-render it (the compiler's template extractor finds them deterministically). They are transparent at runtime: in the browser they render exactly the normal tree. See [Components](./components.md) and [Rendering and SSR](./rendering.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.Hole` | `Hole(props: HoleProps): ReactNode` | A scalar text hole (`{ id: string; children?: ReactNode }`); renders `children` in the browser, a text insertion point under the SSR extractor. |\n| `Toil.Repeat` | `Repeat<T>(props: RepeatProps<T>): ReactNode` | A repeat region (`{ id; each: readonly T[]; children: (item: T, index: number) => ReactNode }`); `each.map(children)` in the browser. |\n| `Toil.RawHtml` | `RawHtml(props: RawHtmlProps): ReactNode` | A raw-HTML block hole (`{ id; html; as? }`); sanitizes HTML in the browser and wraps it in a host element (default `div`). Sanitize server data before rendering. |\n| `Toil.attr` | `attr(id: string, value: string): string` | An attribute-value hole, used in attribute position (`href={Toil.attr('u', d.url)}`); returns `value` unchanged in the browser. |\n| `Toil.Island` | `Island(props: IslandProps): ReactNode` | A client-only escape hatch (`{ children? }`); renders nothing on the server and first paint, then reveals `children` after mount (so no SSR / SEO, by design). |\n\n`Toil.sanitizeHtml(html: string): string | TrustedHTML` sanitizes HTML in browser code for React or DOM sinks. It returns a Trusted Types value when supported and throws without a browser DOM.\n\n## Navigation\n\nClient-side links and imperative navigation. Detailed guide: [Navigation](./navigation.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.Link` | `Link(props: LinkProps): ReactNode` | A client-side navigation `<a>`: no full reload, prefetches on hover/focus, falls through to the browser for external / `target` / `download` / `#hash` links. |\n| `Toil.NavLink` | `NavLink(props: NavLinkProps): ReactNode` | A `Link` that adds an active class (default `\"active\"`) and `aria-current=\"page\"` when it points at the current page. |\n| `Toil.matchActive` | `matchActive(linkPath: string, currentPath: string, end: boolean): boolean` | Whether a link to `linkPath` is active for `currentPath` (the pure rule behind `NavLink`). |\n| `Toil.navigate` | `navigate(href: Href, options?: NavigateOptions): void` | Navigate in code (no hook needed), pushing history or replacing with `{ replace: true }`. |\n| `Toil.back` | `back(): void` | Go back one history entry. |\n| `Toil.forward` | `forward(): void` | Go forward one history entry. |\n| `Toil.refresh` | `refresh(): void` | Re-render the current route and re-run its loader (its `loading.tsx` shows while it re-fetches). |\n| `Toil.href` | `href(path: string): Href` | Assert a runtime-built string is a valid `Href`. Escape hatch for a path assembled from data. |\n| `Toil.prefetch` | `prefetch(href: string): void` | Warm a route's chunk ahead of navigation; a no-op for external, unknown, or already-warmed targets. |\n| `Toil.setViewTransitions` | `setViewTransitions(enabled: boolean): void` | Enable animated View Transitions for navigation (normally set once from `client.viewTransitions`). |\n| `Toil.setTransitions` | `setTransitions(enabled: boolean): void` | Keep the current page visible until the next route is ready (normally set once from `client.transitions`). |\n\n## Routing and location hooks\n\nHooks a component uses to read where it is and to get a router handle.\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.useParams` | `useParams<T extends RouteParams = RouteParams>(): T` | Read the dynamic route params, e.g. `{ id }` for `/blog/[id]`. Values are always strings. |\n| `Toil.useNavigate` | `useNavigate(): (href: Href, options?: NavigateOptions) => void` | Returns the bare `navigate` function. |\n| `Toil.useRouter` | `useRouter(): RouterInstance` | Returns the router handle (`push` / `replace` / `back` / `forward` / `refresh` / `revalidate` / `prefetch`). |\n| `Toil.useLocation` | `useLocation(): string` | The current pathname, re-read on each navigation (an alias of `usePathname`). |\n| `Toil.usePathname` | `usePathname(): string` | The current pathname, e.g. `\"/blog/42\"`. |\n| `Toil.useSearchParams` | `useSearchParams(): URLSearchParams` | The query string as a `URLSearchParams`, re-read on each navigation. |\n| `Toil.useNavigationPending` | `useNavigationPending(): boolean` | `true` while a navigation is in flight (drives a top loading bar). |\n| `Toil.matchRoute` | `matchRoute(pattern: string, pathname: string): RouteParams \\| null` | Pure route matcher: extract params, or `null` if the pattern does not match. |\n\n## Route data and mutations\n\nLoaders read data on navigation, actions write it. See [Fetching data](./data-fetching.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.useLoaderData` | `useLoaderData<L extends LoaderFunction>(loader: L): Awaited<ReturnType<L>>` | Read the data the current route's `loader` returned. Passing `loader` infers the type; the no-arg `useLoaderData<T>()` returns `unknown` unless you supply `T`. |\n| `Toil.revalidate` | `revalidate(href?: string): void` | Invalidate loader data and re-render so the active route (or a given href) re-fetches. Call after a mutation; usable outside React. |\n| `Toil.invalidateLoaderData` | `invalidateLoaderData(href?: string): void` | Drop cached loader data (all routes, or one href) without re-rendering. |\n| `Toil.useAction` | `useAction<TInput = void, TData = unknown>(fn: (input: TInput) => TData \\| Promise<TData>, options?: UseActionOptions<TData>): ActionHandle<TInput, TData>` | Run a mutation with pending / error / result tracking; revalidates loader data on success. |\n\n## Head and metadata\n\nSet the document `<head>` from a component or resolve a route's metadata. See [Metadata and SEO](./metadata.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.useHead` | `useHead(spec: HeadSpec): void` | Apply a title / `<meta>` / `<link>` contribution for the component's lifetime (reverts on unmount, composes across the tree). |\n| `Toil.useTitle` | `useTitle(title: string): void` | Set `document.title` for the component's lifetime. |\n| `Toil.mergeHead` | `mergeHead(specs: readonly HeadSpec[]): ResolvedHead` | Merge head specs in order: the last `title` wins, `meta` dedupes by name/property, `link` by rel+href. |\n| `Toil.useMetadata` | `useMetadata(metadata: Metadata): void` | Apply a route-style `Metadata` object from inside any component (the runtime counterpart of a route's `metadata` export). |\n| `Toil.resolveMetadata` | `resolveMetadata(metadata: Metadata): HeadSpec` | Expand a `Metadata` object into a title plus concrete `<meta>` / `<link>` tags. |\n\n## Page search\n\nQuery the statically-baked index of your pages' metadata. See [Search](./search.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.searchPages` | `searchPages(query: string, options?: PageSearchOptions): PageSearchResult[]` | Rank the registered page index against a query (pure, framework-agnostic; AND semantics across terms). |\n| `Toil.usePageSearch` | `usePageSearch(query: string, options?: PageSearchOptions): PageSearch` | React binding for `searchPages`, memoized, with a `goTo` helper that navigates to a match. |\n| `Toil.registerPages` | `registerPages(pages: readonly PageMeta[]): void` | Replace the live page index. Called once at startup by the generated bundle; rarely called by user code. |\n| `Toil.getPages` | `getPages(): readonly PageMeta[]` | The registered page index (every page, including dynamic ones). Empty before registration. |\n| `Toil.pagePath` | `pagePath(target: string \\| PageMeta \\| PageSearchResult): string` | Normalize a result / page / raw path to its route path string. |\n\n## Realtime\n\nOpen a channel or a typed stream to the backend. See [Channels](../realtime/channels.md) and [Streams](../realtime/streams.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.connectChannel` | `connectChannel(onMessage: (data: ChannelData) => void, options?: ChannelOptions): Channel` | Open a WebSocket channel to the backend, invoking `onMessage` per frame; returns `send` / `close`. |\n| `Toil.useChannel` | `useChannel(options?: ChannelOptions): ChannelHook` | React hook over `connectChannel`: connects on mount, tracks `connected` + `messages`, exposes `send`. |\n| `Toil.resolveChannelUrl` | `resolveChannelUrl(path?: string, location?: { protocol: string; host: string }): string` | Derive the channel's `ws(s)://` URL from the current page location. |\n| `Toil.makeStreamClient` | `makeStreamClient(routes: Record<string, string>, origin?: string, encoders?: Record<string, (msg: never) => Uint8Array>): StreamClient` | Build the `Server.Stream` client from the generated route map. Used by generated code; rarely called directly. |\n\n## Backend client, errors, bootstrap\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.Server` | `Server.REST.<controller>.<route>(args)` / `Server.Stream.<class>.connect(path?)` / `Server.<service>.<method>(args)` | The typed backend surface. Its shape is generated into `shared/server.ts`; this global is the runtime behind it. See [Fetching data](./data-fetching.md). |\n| `Toil.parseError` | `parseError(err: unknown): string` | Extract a human-readable message from an unknown thrown value: `Error.message`, else `String(err)`. |\n| `Toil.mount` | `mount(routes: RouteDef[], layout?: LayoutLoader, notFound?: NotFoundLoader, globalError?: ErrorComponentLoader, slots?: Record<string, RouteDef[]>): void` | Boot the app into `#root` and start idle link prefetching. Called by the generated entry file; you rarely call it yourself. |\n\n## Auth\n\nThe whole password-auth client lives under `Toil.Auth`, and its error family is exposed on `Toil.*` (and mirrored under `Toil.Auth.*`) so you can branch on it. The password never leaves the browser. See [Auth](../auth/README.md).\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.Auth.register` | `register(username: string, password: string, email: string, opts?: AuthOptions): Promise<void>` | Create an account (only a derived public key is ever sent). Throws `UsernameTakenError` / `EmailInUseError` on conflict. |\n| `Toil.Auth.login` | `login(username: string, password: string, opts?: AuthOptions): Promise<Uint8Array>` | Log in with mutual authentication; resolves to the opaque session token. |\n| `Toil.Auth.confirmEmail` | `confirmEmail(token: string, opts?: AuthOptions): Promise<void>` | Confirm an account from the one-time token in the emailed link. |\n| `Toil.Auth.resendConfirmation` | `resendConfirmation(email: string, opts?: AuthOptions): Promise<void>` | Ask the server to re-send the confirmation email (never reveals whether the address exists). |\n| `Toil.Auth.requestPasswordReset` | `requestPasswordReset(email: string, opts?: AuthOptions): Promise<void>` | Begin a password reset by emailing a link (anti-enumeration: always resolves). |\n| `Toil.Auth.resetPassword` | `resetPassword(token: string, newPassword: string, opts?: AuthOptions): Promise<void>` | Complete a reset from the token plus a new password. |\n| `Toil.Auth.verifyTwoFactor` | `verifyTwoFactor(twoFaId: string, code: string, opts?: AuthOptions): Promise<Uint8Array>` | Finish a 2FA login by submitting the code for `twoFaId`; resolves to the session token. |\n| `Toil.Auth.setupTwoFactor` | `setupTwoFactor(method: number, opts?: AuthOptions): Promise<void>` | Begin enabling or disabling 2FA for the current session user (pass a `TwoFactorMethod` value). |\n| `Toil.Auth.confirmTwoFactorSetup` | `confirmTwoFactorSetup(code: string, opts?: AuthOptions): Promise<void>` | Confirm a pending `setupTwoFactor` with the delivered code. |\n| `Toil.Auth.twoFactorStatus` | `twoFactorStatus(opts?: AuthOptions): Promise<number>` | The current user's 2FA method (a `TwoFactorMethod` value; `0` means off). |\n| `Toil.Auth.TwoFactorMethod` | `{ None: 0, Email: 1 }` | The 2FA method values, mirroring the server enum. |\n\nThe typed error surface (each error carries a stable `code`, and every subclass maps 1:1 to an `AuthErrorCode`):\n\n| Member | Signature | Description |\n| --- | --- | --- |\n| `Toil.AuthError` | `class AuthError extends Error { readonly code: AuthErrorCode }` | Base class for every auth error. `err instanceof Toil.AuthError` narrows the whole family; `err.code` discriminates within it. |\n| `Toil.AuthErrorCode` | `enum AuthErrorCode` (string values) | The stable, machine-readable discriminant carried as `err.code`. Branch on this, never on `err.message` or `err.name`. |\n| `Toil.UsernameTakenError` | `class UsernameTakenError extends AuthError` | register: the username is already registered (`AuthErrorCode.UsernameTaken`). |\n| `Toil.EmailInUseError` | `class EmailInUseError extends AuthError` | register: the email is already in use (`AuthErrorCode.EmailInUse`). |\n| `Toil.InvalidCredentialsError` | `class InvalidCredentialsError extends AuthError` | login: wrong username or password (`AuthErrorCode.InvalidCredentials`). |\n| `Toil.EmailNotConfirmedError` | `class EmailNotConfirmedError extends AuthError` | login: valid credential, but the email is not confirmed (`AuthErrorCode.EmailNotConfirmed`). |\n| `Toil.TwoFactorRequiredError` | `class TwoFactorRequiredError extends AuthError { readonly twoFaId: string }` | login: a second factor is required; echo `err.twoFaId` to `verifyTwoFactor` (`AuthErrorCode.TwoFactorRequired`). |\n| `Toil.ServerAuthFailedError` | `class ServerAuthFailedError extends AuthError` | login/2fa: the server failed to prove its identity, possible MITM (`AuthErrorCode.ServerAuthFailed`). |\n| `Toil.TwoFactorCodeError` | `class TwoFactorCodeError extends AuthError` | 2fa: the code was wrong, expired, or already used (`AuthErrorCode.TwoFactorCodeInvalid`). |\n| `Toil.ConfirmationInvalidError` | `class ConfirmationInvalidError extends AuthError` | confirm: the confirmation link was invalid or expired (`AuthErrorCode.ConfirmationInvalid`). |\n| `Toil.PasswordResetInvalidError` | `class PasswordResetInvalidError extends AuthError` | reset: the reset link was invalid or expired (`AuthErrorCode.PasswordResetInvalid`). |\n\nThe `AuthErrorCode` string values:\n\n```ts\nenum AuthErrorCode {\n RequestFailed = 'request_failed',\n ProtocolError = 'protocol_error',\n UsernameTaken = 'username_taken',\n EmailInUse = 'email_in_use',\n RegistrationRejected = 'registration_rejected',\n InvalidCredentials = 'invalid_credentials',\n EmailNotConfirmed = 'email_not_confirmed',\n TwoFactorRequired = 'two_factor_required',\n ServerAuthFailed = 'server_auth_failed',\n TwoFactorCodeInvalid = 'two_factor_code_invalid',\n TwoFactorSetupFailed = 'two_factor_setup_failed',\n ConfirmationInvalid = 'confirmation_invalid',\n PasswordResetInvalid = 'password_reset_invalid',\n}\n```\n\nCatch by class for the common branches, or on `err.code` for a precise check:\n\n```tsx\ntry {\n const token = await Toil.Auth.login(username, password);\n // ... persist the session token and redirect\n} catch (err) {\n if (err instanceof Toil.EmailNotConfirmedError) return promptEmailConfirmation();\n if (err instanceof Toil.TwoFactorRequiredError) return promptTwoFactorCode(err.twoFaId);\n if (err instanceof Toil.AuthError && err.code === Toil.AuthErrorCode.InvalidCredentials) {\n return setError('Incorrect username or password.');\n }\n throw err;\n}\n```\n\n## A note on types\n\nEvery member above is a value, and values on `Toil.*` need no import: `Toil.Link`, `Toil.useParams`, `Toil.Auth.login`. Types are different. In type position, only a small set are namespaced as `Toil.<Type>`, because the generated `toil-env.d.ts` aliases exactly these under a `declare namespace Toil` block:\n\n`LoaderArgs`, `LoaderFunction`, `Revalidate`, `Metadata`, `GenerateMetadata`, `GenerateStaticParams`, `StaticParams`, `RouteErrorProps`, `Href`, `RoutePath`, `PageMeta`, `SearchHints`.\n\nSo a loader can annotate its argument with no import:\n\n```tsx\nexport const loader = async ({ params }: Toil.LoaderArgs) => { /* ... */ };\n```\n\nEvery other exported type (for example `LinkProps`, `NavLinkState`, `NavigateOptions`, `RouterInstance`, `ImageProps`, `ScriptProps`, `FormProps`, `ActionState`) is not in that namespace, so it must be imported from the package:\n\n```tsx\nimport type { ImageProps } from 'toiljs/client';\n```\n\n## Related\n\n- [Navigation](./navigation.md): links, active state, and navigating in code.\n- [Components](./components.md): the built-in components and the SSR marker primitives.\n- [Fetching data](./data-fetching.md): the `Server` client, loaders, actions, and forms.\n- [Metadata and SEO](./metadata.md): titles, descriptions, and social-share tags per route.\n- [Auth](../auth/README.md): the full password-auth client and its error handling.\n",
51
52
  "getting-started/create-project.md": "# Create a project\n\nScaffold a brand-new toiljs app with one command. The CLI asks a few questions, writes the files, and (optionally) installs dependencies for you.\n\n## Why and when\n\n`toiljs create` is how every project starts. It wires up the enforced toiljs presets (TypeScript 7, Oxlint + tsgolint, and Prettier config), the file-based routing, and a working client and server, so you get a project that builds and runs on the first try. Use it for a new app. To bring an **existing** React app into toiljs instead, see [Migrating](./migrating.md).\n\n## The command\n\n```sh\ntoiljs create my-app\n```\n\nReplace `my-app` with your project name (it becomes the folder name). If you leave the name off, the wizard asks for one.\n\nBy default this runs an interactive wizard. To skip every question and accept the defaults (handy for scripts and CI), add `--yes`:\n\n```sh\ntoiljs create my-app --yes\n```\n\n## What the wizard asks\n\nRunning `toiljs create` walks you through these prompts. Each one has a flag you can pass instead, so you can answer some or all of them up front.\n\n| Prompt | What it decides | Flag | Default |\n| --- | --- | --- | --- |\n| Project name | The folder and package name | (the first argument) | `my-toil-app` |\n| Which template? | How much starter code you get | `-t, --template <app\\|minimal>` | `app` |\n| Styling | The CSS flavor for `client/` | `--style <css\\|sass\\|less\\|stylus>` | `css` |\n| Add Tailwind CSS? | Adds Tailwind on top of the styling | `--tailwind` / `--no-tailwind` | off |\n| AI assistant files | Editor hint files for Claude, Cursor, Codex, Copilot | `--no-ai` (to skip) | all |\n| Optimize images at build time? | Resize and compress imported images | `--images` / `--no-images` | on |\n| Initialize a git repository? | Runs `git init` and stages the files | `--git` / `--no-git` | on |\n| Install dependencies now? | Runs your package manager's install | `--install` / `--no-install` | on |\n\nTwo more flags do not have a prompt:\n\n- `--pm <npm\\|pnpm\\|yarn\\|bun>` picks the package manager to install with (default `npm`).\n- `-y, --yes` accepts every default and runs without any prompts.\n\n### The two templates\n\n- **`app`** (default) is the full starter: a landing page, a shared layout, styles, and a set of demo routes that show off HTTP routes, typed RPC, cookies, auth, and a ToilDB-backed guestbook. Great for learning by reading real, working code.\n- **`minimal`** is the bare minimum: a layout, a single home page, and a tiny server handler with one example endpoint. Great when you want a clean slate.\n\nA fully non-interactive example:\n\n```sh\ntoiljs create my-app --yes --template minimal --style css --no-tailwind --pm pnpm\n```\n\n## What gets scaffolded\n\nHere is the shape of a new **`app`** project. The exact set of demo routes may grow over time, so this is trimmed for readability.\n\n```text\nmy-app/\n package.json scripts + dependencies (toiljs, react, toilscript, ...)\n toil.config.ts client/build config (SEO, images, page transitions)\n toilconfig.json server (wasm) build config for toilscript\n tsconfig.json TypeScript config for the client\n oxlint.config.ts linting preset\n .prettierrc formatting preset\n .gitignore ignores build output, generated files, and .env files\n toil-env.d.ts generated editor types for client globals (Toil.*)\n toil-routes.d.ts generated typed-route names (filled in on first build)\n README.md\n CLAUDE.md / AGENTS.md AI assistant hint files (if you kept them)\n\n client/ your React app (runs in the browser)\n toil.tsx the client entry: mounts routes + layout\n layout.tsx the root layout that wraps every page\n 404.tsx the not-found page\n global-error.tsx the top-level error page\n routes/ file-based pages (index.tsx = \"/\", about.tsx = \"/about\", ...)\n components/ shared React components\n styles/main.css global styles\n public/ static files served as-is (favicon, robots.txt, images)\n\n server/ your backend (compiled to wasm, runs on the edge)\n main.ts the entry: wires the handler + imports your surface modules\n tsconfig.json server-only TS config (dialect checked by toilscript builds)\n toil-server-env.d.ts generated editor types for server globals (Cookie, crypto, ...)\n core/ your top-level request handler and shared logic\n models/ @data classes (the typed wire types)\n routes/ @rest controllers (HTTP endpoints)\n services/ @service classes and @remote functions (typed RPC)\n migrations/ ToilDB schema migrations (README explains the convention)\n scheduled/ reserved for scheduled tasks\n\n shared/ (created by the build)\n server.ts GENERATED typed client: the Server proxy + @data codecs\n```\n\nThe **`minimal`** template is the same layout with far fewer files: `client/` has just `layout.tsx`, `routes/index.tsx`, and `styles/main.css`; `server/` has `main.ts` and `core/AppHandler.ts` with a single example endpoint.\n\nA few files are worth calling out now, and the next page ([Project structure](./project-structure.md)) walks through all of them:\n\n- **`shared/server.ts` does not exist yet** in a fresh project. It is generated the first time you run `toiljs dev` or `toiljs build`. That is normal and expected.\n- **`toil-routes.d.ts`** starts as a stub and gets filled in with your real route names on the first build, which is what makes `Toil.Link` route names type-check.\n- **`.env` and `.env.secrets` are not created** for you. You add them yourself when you need local environment variables or secrets. They are already listed in `.gitignore` so you never commit them. See [Environment and secrets](../services/environment.md).\n\n## Run it\n\nOnce scaffolding (and install) finishes, the CLI prints your next steps:\n\n```sh\ncd my-app\nnpm run dev\n```\n\n`npm run dev` runs `toiljs dev`, which builds your server to wasm, generates `shared/server.ts`, and starts the dev server with hot reload. Open the printed URL (by default `http://localhost:3000`) and you have a live app.\n\nIf you told the wizard **not** to install dependencies, run `npm install` first.\n\nInstall the **Oxc** plugin for VS Code or WebStorm using the [editor setup instructions](./installation.md#editor-setup).\nThe generated README includes the steps. WebStorm requires **Enable type aware rules** to be\nchecked under **Settings → Tools → Oxlint**, even though the project preset enables them.\n\n## Gotchas and notes\n\n- **Scaffolding into a non-empty folder** asks for confirmation in interactive mode, and fails in `--yes` mode. Create into a fresh, empty directory.\n- **The project name must be a valid package name** and must stay inside the current directory (no `..`, no absolute paths).\n- **Git init is best-effort.** If `git` is not installed, the CLI skips that step and keeps going.\n- **You do not run `toilscript` yourself.** It is added as a dependency and driven by `toiljs dev` / `toiljs build`.\n\n## Related\n\n- [Project structure](./project-structure.md)\n- [Your first app](./first-app.md)\n- [The CLI reference](../cli/README.md)\n- [Configuration](../concepts/config.md)\n- [Styling](../frontend/styling.md)\n",
52
- "getting-started/deploy.md": "# Deploying a toiljs app\n\nThis page is an honest look at how you get a toiljs app in front of real users. There are two paths, and it helps to be clear about which one exists today.\n\n- **Self-host it yourself.** You build the app and run it on a machine you control, with `toiljs build` then `toiljs start`. This works right now, on your laptop, a VPS, or any server that can run Node.js.\n- **Run it on the managed Dacely edge.** This is the platform toiljs is built for: a worldwide fleet of servers that runs your compiled backend close to every user. It is the target the whole framework is designed around.\n\nOne thing up front, so you do not go looking for it: **there is no `toiljs deploy` command.** The CLI can build and self-host; pushing a build onto the managed edge is a platform step, not a CLI subcommand. The rest of this page covers what you can do today (self-hosting) and what the managed edge gives you.\n\n## The one build powers both\n\nBoth paths serve the exact same artifacts. `toiljs build` produces them once:\n\n```mermaid\nflowchart LR\n A[\"Your project\"] -->|toiljs build| B[\"build/client/<br/>(HTML, JS, CSS, assets)\"]\n A -->|toiljs build| C[\"build/server/release.wasm<br/>(your backend)\"]\n B --> H[\"toiljs start<br/>(self-host)\"]\n C --> H\n B --> E[\"managed Dacely edge<br/>(worldwide)\"]\n C --> E\n```\n\nSo you never build differently for the two targets. You build once, then either run it yourself or hand the same output to the edge.\n\n## Self-hosting with `toiljs start`\n\n`toiljs start` runs your built app on a fast production HTTP server. It serves your static client, dispatches dynamic requests into your `release.wasm`, does server-side rendering, runs daemons, and exposes a `/_toil` websocket channel. Use it to put your app on your own machine or server instead of the managed edge.\n\n### Step 1: build\n\n`start` serves whatever is in `build/`, so you must build first. If there is no build, `start` exits with an error (it looks for `build/client/index.html`).\n\n```bash\nnpm run build\n```\n\n### Step 2: start\n\n```bash\n# Serve on http://127.0.0.1:3000 (loopback only, one worker per CPU).\nnpx toiljs start\n\n# Accept outside connections, on port 8080, with 4 worker processes.\nnpx toiljs start --host 0.0.0.0 --port 8080 --threads 4\n```\n\n### start flags\n\n| Flag | Meaning |\n| --- | --- |\n| `--port <n>` | Port to listen on. Default `3000` (or `client.port` from your config). |\n| `--host <host>` | Address to bind. Default `127.0.0.1`, which is **loopback only** (reachable just from the same machine). Pass `0.0.0.0` to accept connections from other machines. |\n| `--threads <n>` | Number of HTTP worker processes. Default is automatic (one per available CPU). Pass `1` to disable the worker pool. `--workers` is an accepted alias, and you can also set `server.threads` in your config or the `TOILJS_THREADS` environment variable. |\n| `--root <dir>` | Run against a project in another directory instead of the current one. |\n\nThese flags are verified against the CLI. Note that `--host` and `--threads` are `start`-only: `toiljs dev` always binds locally and does not take them. For the full command reference, see [the CLI](../cli/README.md#toiljs-start).\n\n### A realistic self-host\n\nOn a small server (say a VPS), a minimal run looks like this:\n\n```bash\n# Install and build.\nnpm ci\nnpm run build\n\n# Bind on all interfaces so a reverse proxy or the public can reach it.\nnpx toiljs start --host 0.0.0.0 --port 8080 --threads 4\n```\n\nThen put a reverse proxy (nginx, Caddy) in front for TLS and a real hostname, pointing it at `http://127.0.0.1:8080`. Keep the process alive with your usual tool (systemd, pm2, a container restart policy).\n\n### Self-host gotchas\n\n- **`start` needs a fresh build.** It serves `build/`, not your source. After any code change, run `toiljs build` again before restarting.\n- **The default bind is loopback.** With no `--host`, only the same machine can reach it. Set `--host 0.0.0.0` (usually behind a reverse proxy) to serve real traffic.\n- **Self-host is one place, not the whole world.** You get one server (or however many you run yourself). The latency and worldwide reach of the managed edge is exactly the thing self-hosting does not give you.\n- **The database is different.** Self-hosting runs the built server, but ToilDB's worldwide data layer is an edge feature. Treat self-host as a way to run and test your build, not as a substitute for the managed edge's global database.\n\n## Default browser security\n\nSee [Security](../concepts/security.md#default-browser-security) for the complete policy, configuration examples, Trusted Types usage, and deployment checks.\n\n`toiljs build` and `toiljs start` enable browser security without application configuration:\n\n- An enforced **Content-Security-Policy** authorizes scripts with build-time hashes and Subresource Integrity, including static imports and lazy route chunks. It blocks inline event handlers, `eval`, plugin objects, and changes to the document base URL. WebAssembly compilation remains available for client password hashing.\n- **Cross-Origin-Opener-Policy: same-origin** isolates the window from cross-origin openers and popups. Integrations that require a cross-origin popup to keep its opener must account for this policy.\n- **Trusted Types** enforcement blocks raw strings at DOM injection sinks in supporting browsers. Toil uses a private script URL policy for `Toil.Script`, and DOMPurify for `Toil.RawHtml`. There is no permissive default policy. In browser code, `Toil.sanitizeHtml(html)` returns sanitized HTML suitable for React's `dangerouslySetInnerHTML`, including `TrustedHTML` when supported. Server code must sanitize raw HTML before rendering it.\n\nThe policy permits React inline styles, same-origin connections, and local images/fonts (including data/blob image URLs). Add third-party resource origins through `client.cspSources` in `toil.config.ts`, for example `cspSources: { 'connect-src': ['https://api.example.com'], 'img-src': ['https://images.example.com'], 'frame-src': ['https://widget.example.com'] }`. These additions apply to both the headers and meta policy, in development and production. Script trust and Trusted Types enforcement remain enabled. See [Scripts](../frontend/scripts.md) for loading intentional application scripts. A backend handler can supply its own CSP or COOP with `Response.setHeader`; defaults fill missing headers case-insensitively.\n\n`toiljs dev` applies the same protections using fresh per-request script nonces and permits WebSocket connections for HMR. Production uses stable hashes, so HTML remains cacheable. SSR policy comes from the trusted template before request values are inserted.\n\nThe build includes `build/client/_headers` with the production CSP and COOP for static hosts that support this format. Other hosts, including managed edge integrations, must apply these headers when serving the build. The HTML also carries a CSP meta fallback; **COOP and `frame-ancestors` require HTTP headers**. Native backend response envelopes include default CSP and COOP themselves. HSTS is left to the deployment's TLS configuration.\n\nTo run the browser security regression suite with Chrome installed:\n\n```bash\nnpm run build\nTOILJS_BROWSER_TESTS=1 npx vitest run test/security-browser.test.ts\n```\n\nSet `CHROME_BIN` if Chrome is installed outside `/usr/bin/google-chrome`.\n\n## The managed Dacely edge\n\nThe managed **Dacely edge** is the platform toiljs targets: a fleet of servers in many cities that runs your compiled backend as close to each user as possible, backed by the worldwide **ToilDB** database. You write one project, and the build already decides which part of your code belongs to which layer of the edge.\n\nYour backend runs across four **compute tiers**, from a per-request handler at the very edge up to a single worldwide coordinator:\n\n| Tier | Name | Where it runs | Typical code |\n| --- | --- | --- | --- |\n| **L1** | Hot / edge | The node nearest the user, fresh per request | `@rest`, `@service` / `@remote` |\n| **L2** | Regional | One box per connection, per region | `@stream` (Regional) |\n| **L3** | Continental | One box per connection, per continent | `@stream` (Continental) |\n| **L4** | Global / daemon | Exactly one leader worldwide | `@daemon`, `@scheduled` |\n\nBecause the same `toiljs build` output feeds the edge, everything you built and tested with `toiljs dev` and `toiljs start` is what runs there. The edge decides each server's role for you; you do not configure tiers by hand. For the full picture of what each tier means and how to write for it, see [Compute tiers (L1 to L4)](../concepts/tiers.md).\n\n## Related\n\n- [The CLI](../cli/README.md): the full reference for `build` and `start` and every flag.\n- [Configuration (`toil.config.ts`)](../concepts/config.md): `server.threads` and the other self-host knobs.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): how your code maps onto the managed edge.\n- [Getting started](./README.md): the path from install to a running feature.\n",
53
+ "getting-started/deploy.md": "# Deploying a toiljs app\n\nThis page is an honest look at how you get a toiljs app in front of real users. There are two paths, and it helps to be clear about which one exists today.\n\n- **Self-host it yourself.** You build the app and run it on a machine you control, with `toiljs build` then `toiljs start`. This works right now, on your laptop, a VPS, or any server that can run Node.js.\n- **Run it on the managed Dacely edge.** This is the platform toiljs is built for: a worldwide fleet of servers that runs your compiled backend close to every user. It is the target the whole framework is designed around.\n\nOne thing up front, so you do not go looking for it: **there is no `toiljs deploy` command.** The CLI can build and self-host; pushing a build onto the managed edge is a platform step, not a CLI subcommand. The rest of this page covers what you can do today (self-hosting) and what the managed edge gives you.\n\n## The one build powers both\n\nBoth paths serve the exact same artifacts. `toiljs build` produces them once:\n\n```mermaid\nflowchart LR\n A[\"Your project\"] -->|toiljs build| B[\"build/client/<br/>(HTML, JS, CSS, assets)\"]\n A -->|toiljs build| C[\"build/server/release.wasm<br/>(your backend)\"]\n B --> H[\"toiljs start<br/>(self-host)\"]\n C --> H\n B --> E[\"managed Dacely edge<br/>(worldwide)\"]\n C --> E\n```\n\nSo you never build differently for the two targets. You build once, then either run it yourself or hand the same output to the edge.\n\n## Self-hosting with `toiljs start`\n\n`toiljs start` runs your built app on a fast production HTTP server. It serves your static client, dispatches dynamic requests into your `release.wasm`, does server-side rendering, runs daemons, and exposes a `/_toil` websocket channel. Use it to put your app on your own machine or server instead of the managed edge.\n\n### Step 1: build\n\n`start` serves whatever is in `build/`, so you must build first. If there is no build, `start` exits with an error (it looks for `build/client/index.html`).\n\n```bash\nnpm run build\n```\n\n### Step 2: start\n\n```bash\n# Serve on http://127.0.0.1:3000 (loopback only, one worker per CPU).\nnpx toiljs start\n\n# Accept outside connections, on port 8080, with 4 worker processes.\nnpx toiljs start --host 0.0.0.0 --port 8080 --threads 4\n```\n\n### start flags\n\n| Flag | Meaning |\n| --- | --- |\n| `--port <n>` | Port to listen on. Default `3000` (or `client.port` from your config). |\n| `--host <host>` | Address to bind. Default `127.0.0.1`, which is **loopback only** (reachable just from the same machine). Pass `0.0.0.0` to accept connections from other machines. |\n| `--threads <n>` | Number of HTTP worker processes. Default is automatic (one per available CPU). Pass `1` to disable the worker pool. `--workers` is an accepted alias, and you can also set `server.threads` in your config or the `TOILJS_THREADS` environment variable. |\n| `--root <dir>` | Run against a project in another directory instead of the current one. |\n\nThese flags are verified against the CLI. Note that `--host` and `--threads` are `start`-only: `toiljs dev` always binds locally and does not take them. For the full command reference, see [the CLI](../cli/README.md#toiljs-start).\n\n### A realistic self-host\n\nOn a small server (say a VPS), a minimal run looks like this:\n\n```bash\n# Install and build.\nnpm ci\nnpm run build\n\n# Bind on all interfaces so a reverse proxy or the public can reach it.\nnpx toiljs start --host 0.0.0.0 --port 8080 --threads 4\n```\n\nThen put a reverse proxy (nginx, Caddy) in front for TLS and a real hostname, pointing it at `http://127.0.0.1:8080`. Keep the process alive with your usual tool (systemd, pm2, a container restart policy).\n\n### Self-host gotchas\n\n- **`start` needs a fresh build.** It serves `build/`, not your source. After any code change, run `toiljs build` again before restarting.\n- **The default bind is loopback.** With no `--host`, only the same machine can reach it. Set `--host 0.0.0.0` (usually behind a reverse proxy) to serve real traffic.\n- **Self-host is one place, not the whole world.** You get one server (or however many you run yourself). The latency and worldwide reach of the managed edge is exactly the thing self-hosting does not give you.\n- **The database is different.** Self-hosting runs the built server, but ToilDB's worldwide data layer is an edge feature. Treat self-host as a way to run and test your build, not as a substitute for the managed edge's global database.\n\n## Default browser security\n\nSee [Security](../concepts/security.md#default-browser-security) for the complete policy, configuration examples, Trusted Types usage, and deployment checks.\n\n`toiljs build` and `toiljs start` enable browser security without application configuration:\n\n- An enforced **Content-Security-Policy** authorizes scripts with build-time hashes and Subresource Integrity, including static imports and lazy route chunks. It blocks inline event handlers, `eval`, plugin objects, and changes to the document base URL. WebAssembly compilation remains available for client password hashing.\n- **Cross-Origin-Opener-Policy: same-origin** isolates the window from cross-origin openers and popups. Integrations that require a cross-origin popup to keep its opener must account for this policy.\n- **Trusted Types** enforcement blocks raw strings at DOM injection sinks in supporting browsers. Toil uses a private script URL policy for `Toil.Script`, and DOMPurify for `Toil.RawHtml`. There is no permissive default policy. In browser code, `Toil.sanitizeHtml(html)` returns sanitized HTML suitable for React's `dangerouslySetInnerHTML`, including `TrustedHTML` when supported. Server code must sanitize raw HTML before rendering it.\n\nThe policy permits React inline styles, same-origin connections, and local images/fonts (including data/blob image URLs). Add third-party resource origins through `client.cspSources` in `toil.config.ts`, for example `cspSources: { 'connect-src': ['https://api.example.com'], 'img-src': ['https://images.example.com'], 'frame-src': ['https://widget.example.com'] }`. These additions apply to both the headers and meta policy, in development and production. Script trust and Trusted Types enforcement remain enabled unless explicitly overridden for compatibility; see [Allowing additional resources](../concepts/security.md#allowing-additional-resources) for the options and security tradeoffs. See [Scripts](../frontend/scripts.md) for loading intentional application scripts. A backend handler can supply its own CSP or COOP with `Response.setHeader`; defaults fill missing headers case-insensitively.\n\n`toiljs dev` applies the same protections using fresh per-request script nonces and permits WebSocket connections for HMR. Production uses stable hashes, so HTML remains cacheable. SSR policy comes from the trusted template before request values are inserted.\n\nThe build includes `build/client/_headers` with the production CSP and COOP for static hosts that support this format. Other hosts, including managed edge integrations, must apply these headers when serving the build. The HTML also carries a CSP meta fallback; **COOP and `frame-ancestors` require HTTP headers**. Native backend response envelopes include default CSP and COOP themselves. HSTS is left to the deployment's TLS configuration.\n\n`toiljs build` prints the actual generated header rules after a successful client\nbuild, with copyable Cloudflare expressions, header values, and operations. It\nreads the completed `_headers` file so project-specific policies and route\nexceptions are included. See [Deployment headers](../concepts/security.md#deployment-headers).\n\nTo run the browser security regression suite with Chrome installed:\n\n```bash\nnpm run build\nTOILJS_BROWSER_TESTS=1 npx vitest run test/security-browser.test.ts\n```\n\nSet `CHROME_BIN` if Chrome is installed outside `/usr/bin/google-chrome`.\n\n## The managed Dacely edge\n\nThe managed **Dacely edge** is the platform toiljs targets: a fleet of servers in many cities that runs your compiled backend as close to each user as possible, backed by the worldwide **ToilDB** database. You write one project, and the build already decides which part of your code belongs to which layer of the edge.\n\nYour backend runs across four **compute tiers**, from a per-request handler at the very edge up to a single worldwide coordinator:\n\n| Tier | Name | Where it runs | Typical code |\n| --- | --- | --- | --- |\n| **L1** | Hot / edge | The node nearest the user, fresh per request | `@rest`, `@service` / `@remote` |\n| **L2** | Regional | One box per connection, per region | `@stream` (Regional) |\n| **L3** | Continental | One box per connection, per continent | `@stream` (Continental) |\n| **L4** | Global / daemon | Exactly one leader worldwide | `@daemon`, `@scheduled` |\n\nBecause the same `toiljs build` output feeds the edge, everything you built and tested with `toiljs dev` and `toiljs start` is what runs there. The edge decides each server's role for you; you do not configure tiers by hand. For the full picture of what each tier means and how to write for it, see [Compute tiers (L1 to L4)](../concepts/tiers.md).\n\n## Related\n\n- [The CLI](../cli/README.md): the full reference for `build` and `start` and every flag.\n- [Configuration (`toil.config.ts`)](../concepts/config.md): `server.threads` and the other self-host knobs.\n- [Compute tiers (L1 to L4)](../concepts/tiers.md): how your code maps onto the managed edge.\n- [Getting started](./README.md): the path from install to a running feature.\n",
53
54
  "getting-started/first-app.md": "# Your first app\n\nBuild a tiny feature end to end: a page with a \"Like\" button that reads and writes a real number in ToilDB, so the count survives page reloads and restarts. Along the way you meet the typed client, an HTTP route, and the database, the three pieces you use in almost every toiljs app.\n\n## What you will build\n\nA `/likes` page that shows a running like count and a button to add one. The count lives in ToilDB, so it is shared by everyone and it persists.\n\n```mermaid\nsequenceDiagram\n participant B as Browser (/likes page)\n participant SH as shared/server.ts (typed client)\n participant W as server.wasm (@rest route)\n participant DB as ToilDB (counter)\n B->>SH: Server.REST.likes.add()\n SH->>W: POST /likes\n W->>DB: counter.add(key, 1)\n W-->>SH: { count: 43 }\n SH-->>B: typed LikeCount\n B->>B: show \"43 likes\"\n```\n\n## Before you start\n\nYou need a project. If you do not have one yet, create one and start the dev server:\n\n```sh\ntoiljs create my-app\ncd my-app\nnpm run dev\n```\n\nLeave `npm run dev` running in a terminal. It rebuilds your server, regenerates the typed client, and hot-reloads the browser every time you save. The app is at `http://localhost:3000`.\n\n## Why the database (and not a variable)\n\nYour first instinct might be to keep the count in a normal variable on the server. That will not work, and it is worth understanding why now.\n\n**The server runs a fresh copy of your `.wasm` for every request, and wipes its memory when the request ends.** So a variable you set while handling one request is gone by the next request. Anything that must outlive a single request, a counter, a user, a post, has to go into a store. toiljs ships one: **ToilDB**, a database built into the edge.\n\nToilDB offers a few specialized shapes called **families**. For a running total, the right one is a **counter**: a value you can atomically add to and read back. (Others include documents, events, and views. See [Database overview](../database/README.md).)\n\n## Step 1: add a data type for the response\n\nYour server and client talk in typed messages called `@data` classes. A `@data` class can cross the wire and be parsed into a real typed object on the other side. Create one to hold the count.\n\nCreate `server/models/LikeCount.ts`:\n\n```ts\n// The response our route returns: just the current like count.\n@data\nexport class LikeCount {\n count: i64 = 0;\n constructor(count: i64 = 0) {\n this.count = count;\n }\n}\n```\n\nTwo things to notice:\n\n- `@data` is a decorator that marks this class as a wire type. You use it with no import (it is a compiler built-in). See [Data types](../backend/data.md).\n- The field type is `i64`, a 64-bit integer. The server uses precise integer types like `i64` and `u64`. On the client side these arrive as JavaScript `bigint`. More on this in [Types](../concepts/types.md).\n\n## Step 2: add the HTTP route\n\nNow the backend endpoint. Create `server/routes/Likes.ts`:\n\n```ts\nimport { RouteContext } from 'toiljs/server/runtime';\n\nimport { LikeCount } from '../models/LikeCount';\n\n// The KEY that names one counter. A counter is a map from a key to a number,\n// so a single fixed key (\"home\") gives us one global tally.\n@data\nclass LikeKey {\n page: string = 'home';\n constructor(page: string = 'home') {\n this.page = page;\n }\n}\n\n// A @database declares your ToilDB collections. Each @collection is one named\n// store. Here we declare a single counter keyed by LikeKey.\n@database\nclass LikesDb {\n @collection static likes: Counter<LikeKey>;\n}\n\n// A @rest controller exposes HTTP endpoints. 'likes' is the URL prefix, so the\n// routes below live under /likes.\n@rest('likes')\nclass Likes {\n // GET /likes -> read the current count.\n // A @get handler is a \"query\": it may read but not write. Reading one\n // counter by its key is a point read, which queries are allowed to do.\n @get('/')\n public show(): LikeCount {\n const key = new LikeKey('home');\n return new LikeCount(LikesDb.likes.get(key));\n }\n\n // POST /likes -> add one, then return the new count.\n // A @post handler is an \"action\": it may write. `add` bumps the counter.\n // (A body-less POST takes the RouteContext; we do not need it here.)\n @post('/')\n public add(_ctx: RouteContext): LikeCount {\n const key = new LikeKey('home');\n LikesDb.likes.add(key, 1);\n return new LikeCount(LikesDb.likes.get(key));\n }\n}\n```\n\nWhat each decorator does:\n\n- **`@rest('likes')`** turns the class into an HTTP controller mounted at `/likes`.\n- **`@get('/')`** and **`@post('/')`** map a method to a verb and path. A `@get` is a read-only **query**; a `@post` is a write-capable **action**. This split is how toiljs keeps expensive or unsafe operations out of read paths.\n- **`@database`** and **`@collection`** declare your ToilDB stores. `Counter<LikeKey>` is a counter you look up by a `LikeKey`.\n\nThe counter gives you two operations: `add(key, delta)` to change it and `get(key)` to read it. See [Counters](../database/counters.md) and [HTTP routes](../backend/rest.md) for the full API.\n\n## Step 3: register the route\n\nOpen `server/main.ts` and add an import for your new route, next to the others:\n\n```ts\nimport './routes/Likes';\n```\n\nThe build actually discovers decorated files under `server/` on its own, but importing them from `main.ts` is the convention: it keeps a direct `toilscript` build finding the same code. (Every `app` project already imports its demo routes this way.)\n\nSave. Watch the terminal: `toiljs dev` recompiles the server to wasm and regenerates `shared/server.ts`. A moment later your new endpoint exists, fully typed.\n\n## Step 4: add the client page\n\nNow the frontend. Create `client/routes/likes.tsx`. The file name is the URL, so this page is at `/likes`.\n\n```tsx\nimport { useEffect, useState } from 'react';\n\nexport default function LikesPage() {\n // The count is a bigint because the server field is i64.\n const [count, setCount] = useState(0n);\n\n // Read the current count once, when the page first loads.\n useEffect(() => {\n Server.REST.likes.show().then((res) => setCount(res.count));\n }, []);\n\n // Add a like, then update the UI with the fresh count the server returns.\n const like = async () => {\n const res = await Server.REST.likes.add();\n setCount(res.count);\n };\n\n return (\n <main>\n <h1>{String(count)} likes</h1>\n <button onClick={like}>Like</button>\n </main>\n );\n}\n```\n\nThe magic here is `Server.REST.likes`. You never wrote it. toiljs generated it into `shared/server.ts` from your `@rest` controller, so:\n\n- `Server.REST.likes.show()` returns a `Promise<LikeCount>`, and `res.count` is typed for you.\n- `Server.REST.likes.add()` sends the POST and returns the updated `LikeCount`.\n- `Server` is a global in client code, so you do not import it. Its types come from the generated file.\n\nIf you rename the route or change its return type on the server, this client code stops type-checking until you fix it. That is the whole point: the browser and the backend cannot silently disagree.\n\n## Step 5: try it\n\nOpen `http://localhost:3000/likes`. You should see \"0 likes\" and a button. Click **Like** a few times and the number climbs.\n\nNow the important test: **reload the page.** The count is still there. Stop the dev server, start it again, reload: still there. That is ToilDB persisting your counter, exactly as it would on the real edge. The same code that ran against the local dev database runs against the worldwide database in production, with no connection string to configure.\n\n## What just happened\n\n```mermaid\nflowchart LR\n M[\"server/models/LikeCount.ts<br/>@data\"] --> GEN\n R[\"server/routes/Likes.ts<br/>@rest + @database\"] --> GEN\n GEN[\"toiljs dev<br/>compiles + generates\"] --> WASM[\"release.wasm\"]\n GEN --> SS[\"shared/server.ts<br/>(typed Server.REST.likes)\"]\n SS --> P[\"client/routes/likes.tsx<br/>calls Server.REST.likes\"]\n```\n\nYou wrote three small files. toiljs compiled the server to WebAssembly, generated a typed client from your route, and your React page called it with full type safety. The like count lives in ToilDB, so it persists.\n\n## Gotchas and notes\n\n- **`res.count` is a `bigint`, not a `number`.** That is why the page uses `useState(0n)` and `String(count)`. Server integer types map to `bigint` on the client. See [Types](../concepts/types.md).\n- **A `@get` cannot write, and a `@post` can.** If you try to call `.add(...)` from a `@get`, the compiler rejects it. Reads that scan many rows are also blocked in handlers; a single-key `get` is fine.\n- **You do not edit `shared/server.ts`.** It is regenerated on every server build. Change the route, and the client updates itself.\n- **If the editor does not know `Server.REST.likes` yet**, it is because the server has not rebuilt since you added the route. Save a server file (or restart `toiljs dev`) to regenerate `shared/server.ts`.\n- **The counter is global.** Everyone hitting `/likes` shares the same \"home\" tally, because we used one fixed key. Use a different key per page or per user to split the count.\n\n## Where to go next\n\n- Return richer objects and lists: [Data types](../backend/data.md) and [HTTP routes](../backend/rest.md).\n- Call the server without URLs, as plain function calls: [Typed RPC](../backend/rpc.md).\n- Store more than a number: [Documents](../database/documents.md), [Events](../database/events.md), and [Views](../database/views.md).\n- Add login and sessions: [Auth](../auth/README.md).\n- Style your pages: [Styling](../frontend/styling.md) and [Routing](../frontend/routing.md).\n\n## Related\n\n- [Project structure](./project-structure.md)\n- [Database overview](../database/README.md)\n- [Counters](../database/counters.md)\n- [Backend overview](../backend/README.md)\n",
54
55
  "getting-started/installation.md": "# Installation\n\nInstall the toiljs command-line tool (CLI) so you can create and run projects. This takes a couple of minutes.\n\n## Why and when\n\nYou need the toiljs CLI once, before you create your first project. The CLI is the single tool you use to scaffold, run, build, and check toiljs apps. After a project exists, the same CLI is also installed inside that project, so day-to-day you can run it through your package scripts (`npm run dev`) without a global install.\n\n## Prerequisites\n\nYou need **Node.js version 24.0.0 or newer**. Node.js is the JavaScript runtime that powers the toiljs CLI, the dev server, and the build. (Your backend does not run on Node.js, but the tools that build it do.)\n\nCheck your version:\n\n```sh\nnode --version\n```\n\nIf it prints `v24.0.0` or higher, you are set. If it is older or the command is not found, install a current Node.js from [nodejs.org](https://nodejs.org), or use a version manager like [nvm](https://github.com/nvm-sh/nvm) or [fnm](https://github.com/Schniz/fnm):\n\n```sh\n# with nvm\nnvm install 24\nnvm use 24\n```\n\nYou also need a package manager. **npm** comes with Node.js, so you already have it. toiljs also supports **pnpm**, **yarn**, and **bun** if you prefer one of those.\n\n### TypeScript 7\n\ntoiljs requires **TypeScript 7** (`>=7.0.2 <8.0.0`). The native compiler is shipped in the\n`typescript` package and still uses the `tsc` command. Vite 8 bundles the React 19 frontend.\nRoute metadata and search indexing use Oxc parsing; they do not need the old JavaScript compiler API.\n\nFor an existing project:\n\n```sh\nnpm uninstall eslint typescript-eslint @typescript-eslint/utils @eslint/js @eslint-react/eslint-plugin eslint-plugin-react-refresh\nnpm install -D typescript@^7.0.2 oxlint@latest oxlint-tsgolint@latest\n```\n\nReplace `eslint.config.js` with `oxlint.config.ts`:\n\n```ts\nimport toiljs from 'toiljs/oxlint';\nexport default toiljs;\n```\n\nSet `lint` to `oxlint --type-aware client` and keep `typecheck` as `tsc --noEmit`.\nThe shared preset retains the former strict TypeScript rules, severities, React Hooks checks,\nFast Refresh export exceptions, blank-line rule, and custom byte-array rule. Built-in semantic\nrules run in tsgolint; the custom byte-array Oxlint plugin queries the TypeScript 7 native checker.\nSee [toolchain migration](./typescript7.md) for custom configurations and editor setup.\n\n`toiljs doctor` checks the installed compiler, the declared version range, and type-aware lint\nconfiguration. `doctor --fix` migrates TypeScript declarations to `^7.0.2`. Reinstall afterward.\n`toiljs update` only applies TypeScript ranges confined to supported 7.x versions, including when\nusing `--target patch` on an older project.\n\n## Install the CLI\n\nThe package is called `toiljs`, and it provides a command named `toiljs`. You have two ways to use it.\n\n### Option A: run it on demand with npx (no install)\n\n`npx` comes with npm and runs a package without installing it globally. This is the quickest way to create your first project:\n\n```sh\nnpx toiljs create my-app\n```\n\n### Option B: install it globally\n\nIf you plan to create projects often, install it once so `toiljs` is always on your path:\n\n```sh\nnpm install -g toiljs\n```\n\nThen you can run `toiljs` directly:\n\n```sh\ntoiljs create my-app\n```\n\nBoth options end up at the same place. The rest of these docs write `toiljs <command>`; if you did not install globally, just put `npx` in front (`npx toiljs <command>`).\n\n## Editor setup\n\nAfter creating your project, run `npm install` inside it. The **Oxc** editor plugin uses the\nproject's `oxlint` and `oxlint-tsgolint` dependencies to show lint diagnostics and fixes. Use\nNode 26 for editor tooling to match toiljs CI. Installing npm dependencies does not install\nthe editor plugin.\n\n### VS Code\n\n1. Open Extensions and install [Oxc](https://marketplace.visualstudio.com/items?itemName=oxc.oxc-vscode),\n with identifier `oxc.oxc-vscode`. Alternatively, run `code --install-extension oxc.oxc-vscode`.\n2. Merge this setting into your project's `.vscode/settings.json`:\n\n ```json\n {\n \"oxc.typeAware\": true\n }\n ```\n\n3. If you installed dependencies while the editor was open, run **Oxc: Restart oxlint Server**\n from the Command Palette. Check the **Oxc (Lint)** output channel if it does not start.\n\nNew toiljs projects already recommend the extension and enable type-aware linting; you still\nneed to install the extension. Optional lint fixes on save can be enabled with\n`\"editor.codeActionsOnSave\": { \"source.fixAll.oxc\": \"explicit\" }`.\n\n### WebStorm\n\n1. Open **Settings → Plugins → Marketplace**, search for [Oxc](https://plugins.jetbrains.com/plugin/27061-oxc),\n and install it. Restart the IDE if prompted.\n2. Set the project's Node.js interpreter to Node 26.\n3. Open **Settings → Tools → Oxlint**, select **Automatic configuration**, and check\n **Enable type aware rules**.\n4. Apply the settings, then run **Restart Oxlint Server** through Find Action.\n\nThe plugin has its own type-aware checkbox, which defaults to off. Its explicit value\n[overrides `options.typeAware` in the project config](https://oxc.rs/docs/guide/usage/linter/lsp-config-reference#typeaware),\nso installing the plugin alone does not enable tsgolint checks.\n\nIf automatic detection does not start the server, select **Manual configuration** and set\n**Path to Oxlint Language Server** to `<project>/node_modules/oxlint/bin/oxlint`. Check\n**Add --lsp CLI argument** and keep **Enable type aware rules** checked. Use the JavaScript\nlauncher at that path so `oxlint.config.ts` and the custom JavaScript rules can load.\n\nLeave **Path to Oxlint Config** blank when opening the whole toiljs repository, and leave\n**Disable nested config lookups** unchecked, so both examples use their own configurations.\nFor a standalone app whose config is not discovered, select that app's `oxlint.config.ts`.\n\nThe [Oxc editor guide](https://oxc.rs/docs/guide/usage/linter/editors) covers supported editors.\nRun `npm run lint` to check the same project rules from a terminal.\n\n## Verify it works\n\nCheck the version:\n\n```sh\ntoiljs --version\n```\n\nYou should see a version number printed (for example, `0.0.86`).\n\nTo see every command and flag, run help:\n\n```sh\ntoiljs --help\n```\n\nInside a project, there is a deeper health check called **doctor**. It inspects your setup and dependencies and tells you exactly what to fix. You will use it after you create a project, but it is good to know it exists:\n\n```sh\ntoiljs doctor\n```\n\n`toiljs doctor` reads your project (its `package.json`, config, routes, and build output), runs a series of checks, and prints a grouped report. One of the first checks is your Node.js version against the required `>=24.0.0`, so if your Node is too old, doctor will say so. Add `--fix` to let it repair the things it can (such as the typed-RPC wiring), or `--json` for machine-readable output in a CI pipeline.\n\n## How the tooling fits together\n\nThe `toiljs` CLI is a friendly front end over two underlying tools. You rarely call them directly, but it helps to know they exist.\n\n```mermaid\nflowchart LR\n CLI[\"toiljs CLI\"] --> TS[\"toilscript<br/>(compiles server/ to wasm)\"]\n CLI --> VITE[\"Vite<br/>(bundles client/ React)\"]\n TS --> W[\"build/server/release.wasm\"]\n VITE --> B[\"build/client/\"]\n```\n\nWhen you create a project, both `toiljs` and `toilscript` are added to it as dependencies, so everything is pinned to versions that work together. You do not install `toilscript` separately.\n\n## Gotchas and notes\n\n- **\"command not found: toiljs\"** after a global install usually means npm's global bin folder is not on your `PATH`. Either fix your `PATH` or just use `npx toiljs ...` instead.\n- **Node too old** is the most common first-time failure. WebAssembly tooling and the build depend on features in Node 24 and up. Upgrade before creating a project.\n- **Every command checks for updates.** On each run, the CLI quietly checks npm for a newer toiljs and prints a note if you are behind. It never blocks the command. To turn it off, set the environment variable `TOILJS_NO_UPDATE_CHECK=1`.\n- You do **not** need to install a database, a Docker container, or any cloud account to develop locally. The dev server includes a local ToilDB so your data-backed features run out of the box.\n\n## Related\n\n- [Create a project](./create-project.md)\n- [The CLI reference](../cli/README.md)\n- [Getting started overview](./README.md)\n",
55
56
  "getting-started/migrating.md": "# Migrating an existing React app\n\nHow to bring a React app you already have into toiljs. The frontend usually moves over with small changes. The backend is the real work, because a toiljs server is not Node.js, and this page is honest about what that means.\n\n## Why and when\n\nMove to toiljs when you want your frontend and backend in one typed repo, deployed to the edge, with a built-in global database, and you are willing to rewrite your server logic against toiljs's rules. If you only want a React bundler, toiljs is more than you need. If you want the full-stack, typed, edge model, this is the payoff.\n\nThe safest approach is **not** to convert your old project in place. Instead, scaffold a fresh toiljs project and move code into it piece by piece. A fresh project comes with the required presets, config, and routing already wired, so you spend your time on your code, not on plumbing.\n\n```sh\ntoiljs create my-app\ncd my-app\n```\n\n## The big picture: what moves where\n\n```mermaid\nflowchart LR\n subgraph OLD[\"Your current app\"]\n FE[\"React components,<br/>pages, styles, assets\"]\n BE[\"Node/Express backend,<br/>DB access, npm libs\"]\n end\n FE -->|\"mostly copy\"| C[\"toiljs client/\"]\n BE -->|\"rewrite\"| S[\"toiljs server/\"]\n C -.->|\"generated typed client\"| S\n S --> DB[(\"ToilDB\")]\n```\n\n- Your **React frontend** copies into `client/` with modest changes (routing and asset paths).\n- Your **backend** is **rewritten** into `server/` as toilscript, because it compiles to WebAssembly, not Node.\n\n## The frontend: what changes\n\n`client/` is a normal Vite + React app, so most of your frontend works as is. The common adjustments:\n\n- **Routing becomes file-based.** toiljs has no `<Routes>`/`<Route>` config. A file at `client/routes/about.tsx` is the `/about` page; `client/routes/blog/[slug].tsx` is `/blog/:slug`. Move each page component to the matching file and delete your router setup. Use `Toil.Link` for navigation instead of your router's `Link`. See [Routing](../frontend/routing.md).\n- **Static assets move to `client/public/`.** Files there are served as is (images at `/images/...`, plus `favicon` and `robots.txt`).\n- **Global styles move to `client/styles/`**, and are imported from `client/toil.tsx`. See [Styling](../frontend/styling.md).\n- **Your React npm packages are fine.** The client is regular JavaScript, so component libraries, state managers, and browser APIs all work.\n- **Data fetching changes** if you want the typed client: replace hand-written `fetch('/api/...')` calls with the generated `Server.REST.*` methods. You can keep raw `fetch` too, but you lose the type safety. See [Fetching data](../frontend/data-fetching.md).\n\nMetadata and SEO that you used a helmet library for is built in: set a `metadata` export per route, or use `Toil.Head`. See [Metadata and SEO](../frontend/metadata.md).\n\n## The backend: the honest part\n\nThis is where migration takes real effort. Read this section carefully before you plan the work.\n\nYour toiljs server is compiled by **toilscript** into WebAssembly. toilscript accepts a **strict subset of TypeScript**. It looks like TypeScript, but treat it as a small, separate language that happens to share the syntax. The practical consequences:\n\n### What is NOT available on the server\n\n- **No arbitrary npm packages.** You cannot `import` a library from `node_modules` into `server/`. There is no `express`, no `pg`, no `stripe` SDK, no `lodash`. If your route logic leans on npm libraries, that logic has to be reworked.\n- **No Node.js APIs.** No `fs`, `http`, `process`, `Buffer`, `path`, or other Node built-ins. The server runs in a sandbox, not in Node.\n- **No DOM or browser APIs**, because it is not a browser either.\n- **No connecting to your existing database.** There is no connection string and no driver. Your data moves to **ToilDB**, the built-in database.\n\n### What you use instead\n\ntoiljs replaces the common needs with built-in globals and decorators, so you rarely miss the missing libraries:\n\n| You used to reach for | On the toiljs server you use |\n| --- | --- |\n| `express` routes / a router | `@rest` controllers with `@get` / `@post` ([HTTP routes](../backend/rest.md)) |\n| A REST client between services | `@service` / `@remote` typed RPC ([RPC](../backend/rpc.md)) |\n| Postgres / Mongo / Redis | [ToilDB](../database/README.md) families (documents, counters, events, views) |\n| `jsonwebtoken`, session middleware | Built-in [auth](../auth/README.md) and cookies |\n| `crypto` from Node | the `crypto` global (synchronous Web Crypto) ([Crypto](../services/crypto.md)) |\n| `nodemailer` / an email SDK | the built-in email service ([Email](../services/email.md)) |\n| `process.env` | `Environment.get()` / `Environment.getSecure()` ([Environment](../services/environment.md)) |\n| `Date.now()`, timers | the `Time` global ([Time](../services/time.md)) |\n\n### Type system differences\n\ntoilscript uses precise, explicit numeric types instead of JavaScript's single `number`. You will write `i32`, `u64`, `f64`, and even `u256`, and be explicit about integer sizes. Values that must cross the wire are `@data` classes with concrete fields, not free-form objects. There is no `any`-style duck typing to lean on. The full rules, and how server types map to `bigint` and friends on the client, are in [Types](../concepts/types.md).\n\n### Two behaviors to design around\n\n- **Memory resets every request.** Each request gets a fresh `.wasm` instance and its memory is wiped afterward. A module-level variable does not persist. Anything durable goes in ToilDB. (This is the same rule you met in [Your first app](./first-app.md).)\n- **Reads and writes are split.** A `@get` is a read-only query; a `@post` is a write action. Operations that scan unbounded data are not allowed in a request handler; they move to a [`@derive`](../background/derive.md) or a background [daemon](../background/daemons.md).\n\n## Configuration\n\nTwo config files replace the various configs you may have had:\n\n- **`toil.config.ts`** is your client and build config: SEO defaults, image optimization, page transitions, and dev-server options. It uses `defineConfig`. See [Configuration](../concepts/config.md).\n- **`toilconfig.json`** is the low-level server (wasm) build config. The scaffold sets sensible defaults, and you usually leave it alone.\n\nEnvironment variables move from a `.env` you read with `process.env` to `.env` / `.env.secrets` files you read with `Environment.get()` / `Environment.getSecure()`. Secrets and plain vars are kept in separate buckets. See [Environment and secrets](../services/environment.md).\n\n## Step by step\n\n1. **Scaffold a fresh project** with `toiljs create` and get it running with `npm run dev`. Start from something that works.\n2. **Move the frontend.** Copy components into `client/components/`, turn each page into a file under `client/routes/`, move styles into `client/styles/`, and static assets into `client/public/`. Swap your router's `Link` for `Toil.Link`. Install your client-side npm dependencies.\n3. **Get the client rendering** against the routes, even if the data is still stubbed or points at your old backend. Fix routing and asset paths first.\n4. **Rebuild the backend, one route at a time.** For each old endpoint, add a `@data` model in `server/models/`, a `@rest` controller in `server/routes/`, and move its data into a ToilDB family. Import each new route in `server/main.ts`. This is the bulk of the effort; go endpoint by endpoint.\n5. **Move persistence to ToilDB.** Map each table or collection to a ToilDB family (a document store, a counter, an event log, or a view). See [Database overview](../database/README.md) for choosing a family.\n6. **Switch the client to the typed client.** Replace `fetch('/api/...')` calls with `Server.REST.*` (or `Server.<service>.*` for RPC). Now a backend change that breaks the contract shows up as a client type error.\n7. **Run the doctor.** `toiljs doctor` checks your wiring (routes, RPC generation, config, dependencies) and points at anything still off. Add `--fix` to let it repair what it can.\n\n## When toiljs is not the right move\n\nBe honest with yourself about the backend rewrite. Migration is a poor fit if:\n\n- Your server depends heavily on npm libraries or Node-only APIs that have no toiljs equivalent, and rewriting them is not worth it.\n- Your hot request path requires synchronous calls to an external database or service, and you cannot move that work into an integration server or background daemon. Other servers can send results to private ToilJS HTTP endpoints protected with authentication, shared secrets, and an IP allowlist at the firewall or reverse proxy; outbound network I/O stays off the hot path to keep it responsive under load.\n- You need long-lived in-process server state that does not fit the per-request, database-backed model.\n\nIn those cases, you can still adopt toiljs for the frontend and keep your existing backend, calling it with plain `fetch`. You just give up the single-repo, end-to-end-typed benefits for that part.\n\n## Gotchas and notes\n\n- **Do not try to `import` server code into the client or vice versa.** They compile with different rules. The only bridge is the generated `shared/server.ts`.\n- **One `@data` type per file** under `models/` matches the tooling's expectations.\n- **`shared/server.ts` is generated**, so it will not exist until your first build, and you never edit it.\n- **Plan the backend as a rewrite, not a port.** The frontend moves; the backend is re-expressed in toiljs's model. Budget for that.\n\n## Related\n\n- [Getting started overview](./README.md)\n- [Backend overview](../backend/README.md)\n- [Types](../concepts/types.md)\n- [Database overview](../database/README.md)\n- [The CLI reference](../cli/README.md)\n- [Configuration](../concepts/config.md)\n",