@vielzeug/codex 26.11.17 → 26.11.18

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.
@@ -6,7 +6,18 @@
6
6
  "usage": "---\ntitle: 'Archive: Usage Guide'\ndescription: 'Define a collection, initialize fresh D1 databases, deploy the Workers, and wire your client and observation policy.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nA deployment is a collection definition plus one factory call. Put the definition in a\nmodule both sides import — the browser needs the composed schemas, the Worker needs\nthe collection itself.\n\n```ts\n// recipes-collection.ts — the one content contract, shared by both sides.\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst payloadSchema = s.object({\n cuisine: s.enum(['italian', 'japanese']),\n ingredients: s.array(s.string().trim().min(1).max(64)).min(1).max(20),\n name: s.string().trim().min(1).max(32),\n});\n\nexport const recipesCollection = defineArchiveCollection({\n // Ingredient order is not identity: the canonical form sorts, so reordered\n // content hashes identically and updates as a no-op.\n canonicalize: (payload) => ({ ...payload, ingredients: [...payload.ingredients].sort() }),\n contentVersion: 1,\n filters: ['italian', 'japanese'],\n index: (payload) => ({\n filter: payload.cuisine,\n tags: [payload.ingredients.length <= 5 ? 'quick' : 'involved'],\n title: payload.name,\n }),\n name: 'recipes',\n payloadSchema,\n tags: ['quick', 'involved'],\n});\n```\n\nThe Worker entry imports the collection and exports the built handler:\n\n```ts\n// backend/src/index.ts — the whole deployment.\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { recipesCollection } from './recipes-collection';\n\nconst worker = createArchiveWorker([recipesCollection]);\n\n// One sanitized log line per request: ids, codes and route classes only.\nworker.tap((event) => console.log(JSON.stringify(event)));\n\nexport default worker;\n```\n\nThe browser imports the same collection for its schemas — never the worker subpath:\n\n```ts\nimport { recipesCollection } from './recipes-collection';\nimport { archiveIdentitySchema, PUBLISHER_HEADER } from '@vielzeug/archive';\n\nconst response = await fetch('/api/v1/collections/recipes/entries');\nif (!response.ok) throw new Error('Archive unavailable');\nconst page = recipesCollection.contract.page.parse(await response.json());\nconst meResponse = await fetch('/api/v1/me', { credentials: 'same-origin' });\nif (!meResponse.ok) throw new Error('Identity unavailable');\nconst me = archiveIdentitySchema.parse(await meResponse.json());\nif (me === null) throw new Error('Register a publisher first');\nconst mineResponse = await fetch('/api/v1/me/publications?collection=recipes', {\n credentials: 'same-origin',\n headers: { [PUBLISHER_HEADER]: me.id },\n});\nif (!mineResponse.ok) throw new Error('Own publications unavailable');\nconst owned = recipesCollection.contract.ownedEntries.parse(await mineResponse.json());\nconsole.log(page.entries, owned.entries);\n```\n\n## The collection contract\n\n`defineArchiveCollection` is the only place content knowledge lives. The definition is\nvalidated at registration — a bad `name`, `contentVersion`, or any vocabulary value\n(well-formed text, 1..`vocabChars` chars) throws there, never mid-request — and every\nordinary invalid content returns `null` → `422 invalid-payload`. Collection\nimplementation faults instead throw `ArchiveDerivationError` → sanitized\n`500 internal`:\n\n- **Parse** — accept stable JSON objects only; schema outputs must remain JSON.\n- **Canonicalize** — optional; a result that leaves the payload schema throws, so a\n broken normalizer can never store invalid content.\n- **Index** — the returned `filter` must be declared in `filters`, every `tag` in\n `tags` (duplicates collapse), and the `title` is trimmed and bounded\n (`titleChars`, well-formed text). A derivation outside the declared vocabulary\n would store a row no list query can reach — it throws instead.\n- **Size** — the canonical JSON must fit `payloadBytes`.\n- **Identity** — the content hash is SHA-256 over `{contentVersion, payload}`:\n identical content hashes identically, a real edit always re-identifies, and the\n core owns the envelope so collections cannot drift it.\n\nDeclare vocabularies with readonly arrays (`['fire', 'ice']`) for automatic\nliteral-union inference. Const generics retain the version literal and vocabulary\nunions; `NoInfer` prevents the index callback from widening them. Omitted arrays\nmean empty vocabularies: return `null` for\nthe filter and no tags. Object keys are recursively sorted by the core; schema\ntransformations must stabilize and `canonicalize` must be pure and idempotent.\nNon-JSON input returns `null`. Unexpected callback, schema or hashing failures,\nunstable transformations, non-idempotent canonicalization and index mutation throw\n`ArchiveDerivationError`; its `stage` identifies the failing phase.\nLossy or non-JSON schema output and invalid index-result shapes also throw.\n\n`contentVersion` participates in content identity. Request handling validates\nonly the current collection definition; it does not interpret historical schemas.\nArchive provides no content-upgrade APIs: a new definition never reinterprets\nstored rows.\n\nFilters, tags and searchable titles are persisted data derived at publish/update\ntime. Editing `index` or its vocabularies does not recompute existing projections.\nKeep the active definition and dataset consistent. For a development\ndeployment, deliberately reset and reseed a fresh database when you change payload\nor projection semantics; the package does not supply a migration framework.\nResetting destroys existing data. Perform it only as an explicit, deliberate\ndevelopment operation, not automatically during startup or deployment.\n\n**Payloads carry decisions, not content.** The payload schema should accept\nuser-authored choices expressed as IDs plus user-written text — never the content's\nown copyrighted expression (card text, artwork, rules), never more than the game's\nown identifiers. For games with paid or DLC content this is the whole answer:\nownership resolves on each viewer's device against their own library, the service\nnever learns what anyone owns, and the strict schema is the enforcement seam —\nuse a strict schema that rejects unknown fields, so a collection that only models IDs cannot\naccidentally start shipping paid content. For example, published game builds can\nreference cards, equipment and potions by ID plus a user-written name. The client\nrenders pieces the viewer does not own as unavailable. Keep the browser-safe\npublication contract in a shared domain module consumed by both the frontend and\nits backend, without importing frontend application code into the Worker.\n\n## The Worker and its environment\n\n`createArchiveWorker(collections)` returns the full handler: anonymous public reads,\ncookie-authenticated mutations behind exact-origin and request-marker guards, local\nRS256/JWKS verification followed by an uncached issuer session-version check,\nper-IP read limits and per-subject write limits keyed by peppered HMACs, the\n30-second anonymous cache on public entry lists only, operator moderation, and a\nscheduled expiry sweep for retired publish retry keys and revocation tombstones.\nHealth sits outside the rate-limit and session pipelines: probes never burn the\nanonymous read budget or call the issuer.\n\nThe Worker reads its environment fail-closed — every binding must be present and\nwell-formed, or the route answers 503 without naming what is missing:\n\n| Variable | Meaning |\n| ---------------------------------------------- | ----------------------------------------------------------------------------------------- |\n| `APP_ENV` | `local` or `production` (transport rules and the pepper policy) |\n| `ALLOWED_ORIGINS` | Exact canonical origins; never wildcards |\n| `JWT_ISSUER` / `JWT_AUDIENCE` / `JWT_JWKS_URL` | Exact issuer claim, audience and issuer JWKS endpoint URL |\n| `AUTH_ISSUER_SERVICE` | Required issuer service binding for signing-key retrieval and live session-version checks |\n| `LIKES_ENABLED` / `PUBLISHING_ENABLED` | Feature flags |\n| `RATE_LIMIT_KEY_SECRET` | HMAC pepper. Required ≥ 32 chars in production; local may fall back |\n| `DB` / `READ_LIMIT` / `WRITE_LIMIT` | D1 + rate-limit bindings |\n\nBoth limiter bindings must run 60-second windows (`simple` limiters:\n`period: 60`): the platform binding does not expose its period at runtime, so the\nWorker's 429 `Retry-After` header is fixed at 60 seconds — a longer window would\nmake the header lie. The read limit keys on `cf-connecting-ip`, which Cloudflare\nsets authoritatively for requests that reach the Worker through its network. Keep\nthat network path: never front the Worker with a proxy that forwards a\nclient-supplied header of the same name.\n\nGenerated Env types (wrangler's `worker-configuration.d.ts`) satisfy the package's\nstructural `ArchiveWorkerEnv` — no `@cloudflare/workers-types` dependency, no casts.\n\nSigning keys are fetched from `JWT_JWKS_URL` through `AUTH_ISSUER_SERVICE`, not\nglobal `fetch`. Point the URL at the bound issuer's `/api/v1/auth/jwks.json`\nroute; retain the HTTPS production or loopback HTTP local configuration rules.\nThis transport supports Workers on the same Cloudflare zone without a public\nWorker-to-Worker fetch. JOSE caches signing keys, but every private request still\nchecks the current issuer session version. A signing-key provider failure is\n`503 auth-unavailable`, not a reason to clear the browser's signed-in state.\n\n## The auth issuer\n\n`createAuthWorker()` from `@vielzeug/archive/auth` is the reference passwordless\nidentity issuer a deployment runs beside the catalog Worker: one POST with an email\nsends a single-use magic link, and explicitly confirming it sets the `archive_session`\ncookie. The catalog verifies the JWT locally, then calls the issuer through\n`AUTH_ISSUER_SERVICE` to check the account's current session version. Requests create\npending account rows; explicit link redemption atomically stamps the account's\nsign-in time and claims the token. The issuer's D1 schema ships at\n`node_modules/@vielzeug/archive/migrations/auth/`; point the issuer's\n`migrations_dir` there. The catalog's `JWT_ISSUER` and `JWT_JWKS_URL` must identify\nthe issuer, and its audience must match the issuer's `AUDIENCE`.\n\n| Variable | Meaning |\n| ------------------------------- | ----------------------------------------------------------------------------------------- |\n| `APP_NAME` | The app's display name in magic-link email and escaped confirmation-page branding |\n| `ALLOWED_ORIGINS` | Exact origins allowed to trigger unsafe routes (the app origin(s)) |\n| `APP_ENV` | `local` or `production` — production requires HTTPS and sets Secure cookies |\n| `AUDIENCE` / `AUTH_ISSUER` | The claims every minted session carries; the catalog verifies the same pair |\n| `AUTH_DB` / `AUTH_EMAIL` | The issuer's D1 and send-email bindings |\n| `AUTH_ARCHIVE` | Required service binding to the catalog Worker; deletion calls its profile-erasure route |\n| `AUTH_JWT_PRIVATE_JWK` | The RS256 private key as a JWK JSON string: a wrangler secret in production |\n| `AUTH_JWT_PREVIOUS_PUBLIC_JWKS` | Optional retired public RS256 JWKS; publish during rotation until old sessions expire |\n| `OPERATOR_EMAILS` | Comma-separated emails whose newly minted sessions carry the operator role |\n| `PUBLIC_ORIGIN` | App origin for links, confirmation POST origin checks and client navigation after sign-in |\n| `SENDER_ADDRESS` | The address magic links come from: a domain onboarded to Cloudflare Email Service |\n\nUnder `wrangler dev` the send-email binding is simulated — the link prints to the\nissuer's console, so that console is the inbox. Demo-only Alice/Bob routes are\ndeployment wrappers, not package APIs.\n\nThe issuer first admits sign-in requests through its singleton durable\n`auth_sign_in_budget` table: 20 requests per 60 seconds before creating accounts\nor delivering email. No rate-limiter binding is required. It then\npermits three sign-in emails per email in an hourly durable window.\nThose durable budgets guard `POST /auth/sign-in` and `POST /auth/device/sign-in`.\n`POST /auth/verify`, the device approval and claim routes, and\n`GET /auth/session` stay public: tokens are 256-bit, single-use and expire in\n15 minutes, so guessing is not the risk — but every request still costs the\nissuer: the verify GET renders the confirmation page, the verify POST performs a\nD1 token write, and the session check performs an RS256 verification plus an\naccount read for a well-formed signed token. Put per-client-IP Cloudflare\nrate-limit rules (or an equivalent edge control) in front of those routes in\nproduction. Prefer a block action: applications check `GET /auth/session` with\na `fetch`, and a fetch cannot solve a challenge interstitial, so challenging\nthat route breaks legitimate sign-in. The verify GET is a browser navigation\nopened from the email link, so a challenge is solvable there if you want one.\nSet thresholds with CGNAT headroom (shared mobile/office egress IPs) and tune\nfrom observed traffic.\nLater database or delivery failures do not refund global admission.\nUsing or expiring a link never refunds sends; failed delivery also spends the\nallowance. Links expire after 15 minutes. Operator sessions expire after 60 minutes\n(3600 seconds), ordinary sessions after at most 30 days. Retain retired public keys during\nrotation; the active private key signs every new session. Sign-in input trims and\nlowercases email before validation. `SENDER_ADDRESS` must already be canonical;\n`OPERATOR_EMAILS` entries are trimmed and lowercased before validation.\n\nThe scheduled sweep deletes expired links and closed per-user send windows, then\npending accounts only when neither a link nor send-budget row still references\nthem. Failed delivery deletes the unusable token but retains the spent allowance;\nit does not immediately remove the pending account. Verified accounts stay until\nexplicit erasure. The singleton admission row remains and resets its window on a\nlater admitted request.\n\nOpening `GET /auth/verify?token=…` renders a no-store confirmation page and does\nnot consume the link or change the session, so email scanners cannot sign in by\nfetching it. A deliberate click sends `POST /auth/verify` with JSON `{ token }`,\nthe request marker and an exact allowed origin or `PUBLIC_ORIGIN`.\nSuccess is 204 with Set-Cookie; the page then navigates to the fixed\n`${PUBLIC_ORIGIN}/signed-in` destination. Your application must serve that page;\nthe issuer only serves the confirmation endpoint. The redemption update and\naccount sign-in stamp are trigger-backed and atomic.\nThe page removes the token from the address bar, loads no external assets, and\nsets a restrictive CSP and `Referrer-Policy: no-referrer`. Its inline CSS and\nscript use a fresh nonce, never `unsafe-inline`. The page follows light/dark\npreferences, supports reduced motion, focuses the confirmation action and\nannounces pending, success and recovery states. Without JavaScript it links to\n`${PUBLIC_ORIGIN}/account` as “Request a new sign-in link” and does not pretend\nto complete sign-in.\n\n### Sign in an isolated installed app\n\nWhen the app and email browser do not share cookies, generate a random 32-byte\nbase64url proof in the app and compute the SHA-256 hex digest of the proof's\nUTF-8 text. Send `{ email, challenge }` to `POST /auth/device/sign-in` with the\nrequest marker. Show the first eight uppercase characters of the digest in the\napp: the approval page shows the same code, and users should approve only when\nthey match. The link's GET is non-destructive; its confirmation POST authorizes\nthe app but does not sign in the browser.\n\nThe app sends `{ token: proof }` to `POST /auth/device/claim` with credentials,\nthe request marker and an allowed origin. `202 { ok: false }` means no claimable\napproval; `204` sets the normal cookie in the app. Poll only while needed and\nwhile the app is visible, stop after 15 minutes, and serialize a claim with\naccount changes so a late cookie cannot overwrite another choice. Clear the\nproof on cancellation or completion. Do not log the proof or approval URL.\nAn existing valid session returns 409 without consuming the proof; recheck the\nsession rather than replacing that account.\nPending requests share the usual email budgets and are revoked by account\ndeletion or sign-out-all. Add edge rate limits for device approval and claim\nbefore enabling the feature; block rather than challenge the programmatic claim.\n\nArchive only serves the confirmation endpoint. Your application must serve its\nsign-in entry at the fixed `${PUBLIC_ORIGIN}/account` recovery destination and\nthe success page at `${PUBLIC_ORIGIN}/signed-in`. These are reference issuer\nroute conventions, not configurable destinations. The initial “Back to app”\nexit links to `${PUBLIC_ORIGIN}/`. No query parameter supplies a destination.\nExpired or already-used links (POST 410) require a new link rather than a retry.\nHTTP 429 enables manual retry after a `Retry-After` cooldown bounded to 1-300\nseconds, accepting unsigned integer seconds or valid HTTP-date syntax and\ndefaulting to 30 seconds for missing or invalid values, including negative or\nfractional numbers. HTTP 503 and network failures offer a retry button and a\nsecondary “Request a new sign-in link” action; invalid or expired links make\nthat recovery action primary. The page never\nautomatically retries, aborts stalled requests after 15 seconds and releases\nrequests/timers when you leave it. Response bodies, including stale responses,\nare cancelled without waiting, and completed attempts abort their controllers.\n\nWith valid issuer configuration, malformed GET links return HTTP 400 with branded\nrecovery HTML rather than the JSON error envelope. POST errors retain the JSON\nerror schema. A well-formed expired token still gets GET 200 confirmation: its\nredemption status is determined only by the deliberate POST.\n\n`GET /auth/account` exports account metadata only. For full erasure, call\n`DELETE /auth/account` with `ACCOUNT_HEADER` (`X-Archive-Account`) set to the\nissuer account UUID captured from `GET /auth/account` before confirmation.\nThe issuer rejects missing or invalid UUIDs with 400 and a different signed-in\naccount with 409 `account-changed`, before any erasure. This guard applies even\nbefore publisher registration and must stay pinned across retries.\nThe issuer forwards the caller's session and publisher\nprecondition through `AUTH_ARCHIVE` to `DELETE /me/account`, requires exactly 204,\nthen deletes its\nown user and clears the cookie. Failure preserves the session for retry. Direct\n`DELETE /me` removes only the Archive profile and leaves the cookie intact.\n\nSeveral game frontends can share one issuer and catalog. Keep the cookie\nhost-only on the central API host, use `credentials: 'include'` from same-site\nHTTPS game subdomains, and allow each exact frontend origin in both Workers.\nDo not share cookies through a parent-domain `Domain` attribute. The\n[multi-collection recipe](./examples/multi-collection-deployment.md) describes\nthe topology, session revalidation and platform-wide account boundary.\n\n`DELETE /me/account` atomically revokes the issuer/subject and cascades profile\ndeletion. Its tombstone lasts 30 days plus ten seconds; old sessions cannot read\nprivate data or register again, including a racing registration. The dedicated\naccount-erasure route alone may bypass the issuer lookup, and only to retry with\nthe same principal's original signed session while its existing tombstone is\nvalid; signature and claims are still verified, and initial erasure validates the\nissuer. The issuer's `DELETE /auth/account` checks the current version before\nstarting erasure; after completed erasure a retry there returns 401. A fresh\nissuer account gets a new UUID subject. External issuers must use a new subject to\nre-enroll during the revocation window. Profile-only deletion does not revoke the\nsubject and permits re-registration with existing credentials.\n\nEach JWT also carries the issuer account's required safe-integer `sessionVersion`.\nThe issuer compares it with `auth_users.session_version` on every ordinary\nauthenticated route. A JWT with an old version is unauthenticated even before its\nexpiry; the catalog asks the issuer on every private request and does not cache a\nsuccessful verdict. A valid local JWT with an unavailable, malformed, 5xx or\ntimed-out (fixed 5000 ms, including body decoding) issuer response becomes\n`503 auth-unavailable`, not anonymous identity.\n\n## The database\n\nThe package ships the canonical catalog migration:\n`node_modules/@vielzeug/archive/migrations/0001_community_archive.sql` — the whole schema,\nmoderation included, as one designed file. The runtime SQL in the package is\nwritten against exactly this schema, and the package's own integration suite runs\nagainst the same file. Point wrangler at the directory:\n\n```jsonc\n// wrangler.jsonc — the deployment owns its D1 database, not its DDL.\n{\n \"d1_databases\": [\n {\n \"binding\": \"DB\",\n \"database_name\": \"my-app\",\n \"migrations_dir\": \"./node_modules/@vielzeug/archive/migrations\"\n }\n ]\n}\n```\n\nThe issuer points to\n`node_modules/@vielzeug/archive/migrations/auth/0001_auth.sql`. Both files are\nfresh-database initialization definitions, not upgrades. The issuer DDL initializes\n`auth_users.session_version` to `0` and stamps `auth_schema_meta.applied` as\n`AUTH_SCHEMA_VERSION` (`1`). Neither file automatically deletes or resets data.\nArchive's canonical initial schemas are edited directly. Reset and reseed a\ndevelopment database deliberately when its schema or collection semantics no\nlonger match; reapplying the initial file does not update an existing dataset.\nThe initialization file also stamps the storage schema\n(`archive_schema_meta`) at `ARCHIVE_SCHEMA_VERSION`, and health reads it back: a\ndatabase with a mismatched stamp answers `status: 'degraded'` with the\nobserved `dbSchemaVersion` and HTTP 503 (`reason: 'schema-mismatch'`).\nAn unavailable database produces HTTP 503 with `dbSchemaVersion: null` and\n`reason: 'database-unavailable'`. The debut storage stamp is `1`. A unit\ntest pins the shipped DDL's `CHECK` bounds to `ARCHIVE_LIMITS`, so the two can never\ndrift silently. The stamp does not detect changes in your collection's payload\nschema, vocabulary or indexing function; you own that dataset consistency.\n\n## Routes and wire names\n\n```\nGET /api/v1/health\nPOST /api/v1/sign-out\nGET /api/v1/auth/health\nGET /api/v1/auth/session (internal issuer check)\nPOST /api/v1/auth/sign-out-all (revoke every session)\nGET /api/v1/collections/:collection (self-description)\nGET /api/v1/collections/:collection/entries (author, filter, tag, search, sort, cursor, limit)\nPOST /api/v1/collections/:collection/entries\nGET /api/v1/collections/:collection/entries/:id\nPUT /api/v1/collections/:collection/entries/:id (expectedRevision)\nDELETE /api/v1/collections/:collection/entries/:id\nPUT /api/v1/collections/:collection/entries/:id/like\nDELETE /api/v1/collections/:collection/entries/:id/like\nPOST /api/v1/collections/:collection/entries/:id/report (reason)\nPUT /api/v1/collections/:collection/entries/:id/hidden (operator)\nDELETE /api/v1/collections/:collection/entries/:id/hidden (operator)\nGET /api/v1/collections/:collection/reports (operator: status, cursor, limit)\nPUT /api/v1/collections/:collection/reports/:id/resolved (operator: report ID)\nDELETE /api/v1/publishers/:id (operator: erase any publisher)\nGET /api/v1/moderation-log (operator: cursor, limit)\nGET /api/v1/me POST /me PUT /me DELETE /me\nGET /api/v1/me/publications?collection=:collection GET /api/v1/me/likes[?ids=…]\nGET /api/v1/me/reports (cursor, limit)\nGET /api/v1/auth/account\nGET /api/v1/auth/jwks.json\nPOST /api/v1/auth/sign-in (email)\nPOST /api/v1/auth/device/sign-in (email and challenge)\nGET /api/v1/auth/device/approve?token=… (confirmation only)\nPOST /api/v1/auth/device/approve (authorizes device)\nPOST /api/v1/auth/device/claim (proof, then session cookie)\nDELETE /api/v1/auth/account (coordinated full erasure)\nDELETE /api/v1/me/account (issuer erasure seam; revokes subject)\nGET /api/v1/auth/verify?token=… (confirmation only)\nPOST /api/v1/auth/verify (guarded {token} redemption)\n```\n\nPublishing is bounded by `maxPublications` live entries per `(collection, owner)`.\nThe quota check runs inside the guarded insert.\n\nEvery list — entry pages, `/me/likes` without `ids`, `/me/reports`, operator\nreports and `/moderation-log` — pages forward-only: follow `cursor` until `null`,\npreserving query context; a cursor minted for another query is a 400. `limit`\ndefaults to `pageSize` and is at most `maxPageSize`; there is no total export\nbound. `/me/likes?ids=…` remains a subset lookup returning `{ ids }`, not a\npage, and cannot combine `ids` with `cursor` or `limit`.\n\nShared wire names live in the package — `archive_session` cookie,\n`x-archive-publisher` and `x-archive-request` headers, `ARCHIVE_ERROR_CODES`, and\n`ARCHIVE_LIMITS` — so a client and the Worker cannot drift. Parse failures with the\ncollection's composed schemas; parse errors with `archiveErrorResponseSchema`, the\nsign-out body with `archiveOkSchema`, a collection's self-description with\n`archiveCollectionMetaSchema` and the operator queue with `archiveReportsSchema`.\nEvery entry's `schemaVersion` is the archive contract's version, not the\ncollection's; the collection's own format version lives in its hash envelope and in\neach entry's `contentVersion`.\n\nOnly anonymous entry lists carry a 30-second edge-cache contract\n(`publicCacheSeconds`). Detail is always `no-store`. Any Cookie or Authorization\nheader disables caching, regardless of validity; metadata, private and error\nresponses also use `no-store`.\n\nImplement UI ownership checks in your application by comparing the current\npublisher ID to the entry's `author.id`; there is no package action-policy helper.\nServer mutations remain authoritative.\n\n`POST /api/v1/sign-out` is deliberately local: it clears only this browser's\ncookie and does not contact the issuer or revoke copied sessions. To revoke every\nsession, post to `/api/v1/auth/sign-out-all` with the mutation marker, an exact\nallowed `Origin`, and the issuer account UUID captured from\n`GET /api/v1/auth/account` in `X-Archive-Account`. The issuer returns 409\n`account-changed` if the active subject differs. On success it atomically increments\n`session_version`, deletes outstanding links, preserves account and catalog data,\nand returns `{ ok: true }` with an expired cookie. Requests authorized before\nrevocation may finish; there is no cross-database cancellation guarantee.\n\n`GET /api/v1/auth/health` is public and read-only. It validates issuer\nconfiguration, key signing/verification, binding shapes, the `auth_schema_meta`\nstamp and expected tables, columns and triggers, returns `AuthHealth` through\n`archiveAuthHealthSchema`, and answers 503 `degraded` for configuration,\ndatabase or schema failures. It never writes, sends email or probes the catalog.\n\n## Moderation\n\nOperator authority is the session token's optional `roles` claim carrying\n`ARCHIVE_OPERATOR_ROLE` (`'archive-operator'`) — minted by your issuer, verified with\nthe same signature, audience and issuer checks as any session, and never a separate\ncredential. Mint operator sessions with a lifetime of at most\n`OPERATOR_SESSION_MAX_AGE_SECONDS` (3600 seconds): the catalog rejects any token\ncarrying the operator role whose signed lifetime or age exceeds it, so reusing the\nordinary long session expiry 401s operator sessions immediately. Moderation routes\nadditionally require a registered publisher row: one accountable identity per action.\n\n- **Report** — any registered publisher reports a visible entry with a bounded\n free-text reason (`reportReasonChars`). Idempotent per (entry, reporter): the same\n report twice is the same 204. Missing or hidden entries answer 404 — there is\n nothing left to report.\n- **Hide** — an operator removes an entry from every public surface (list, detail,\n likes) with a soft-hide: the row, its likes and its retry key stay intact. The\n owner still sees the entry in `/me/publications` with `hidden: true`, edits and\n key replay are frozen (403), removal stays allowed, and unhiding restores\n everything. Already hidden or already visible answer the same 204.\n- **Queue** — the operator pages newest reports with entry title and reporter\n identity; `status` is `unresolved` (default) or `resolved`. Each report has its\n own `id` and nullable `resolvedAt`. Resolve it with\n `PUT /collections/:collection/reports/:id/resolved`; repeating is a 204 no-op.\n- **Log** — every effective moderation action (hide, unhide, removal, publisher\n erasure) appends one accountability row in the same transaction that applies it,\n and `GET /api/v1/moderation-log` pages the newest actions to\n operators. Rows carry only ids, the action kind and the time — no names (they\n change), no content — and no foreign keys: the audit must outlive the erasures it\n records. Idempotent repeats (hiding an already-hidden entry, erasing an\n already-erased publisher) answer the same 204 with no new row, including\n concurrent repeats: audit insertion tests the effective state inside the batch.\n\nLike and unlike both require a visible entry. Their SQL guards visibility during\nthe mutation, and the response checks it again; hiding or deleting an entry\ncannot turn a racing unlike into a successful response for unavailable content.\n\n## Observability\n\nThe core never logs. `worker.tap(handler, { signal? })` emits one `ArchiveEvent` per\nrequest — `{ type: 'request', code, ms, requestId, route, status, diagnostic? }` —\nand successful sweep — `{ type: 'scheduled', status: 'ok', removed }`. Failed\nsweeps emit `{ type: 'scheduled', status: 'failed', diagnostic }` and rethrow so\nthe runtime sees failure. Cache failures emit `{ type: 'cache-error', diagnostic }`.\nThe Worker swallows observer errors so\nobservability cannot affect the Worker. With no handlers registered there is zero\nwork. Route is a finite class like `/collections/:collection/entries`, never a\nraw path; no event carries a URL, cookie, subject, alias or token. Diagnostics are\ntyped sanitized categories, not raw exceptions. A pre-aborted tap signal is inert.\nThe sweep's `removed` counts expired retry keys and revocation tombstones together.\n\nThe issuer also exposes `tap()` with `AuthEvent` from `@vielzeug/archive/auth`.\nIt never logs directly. Events contain finite route labels, codes, counts,\nduration and sanitized `AuthDiagnostic` categories, never emails, tokens or raw\nexceptions. Scheduled failures emit then rethrow; pre-aborted taps are inert.\nIssuer sweep counts include expired tokens, closed per-user send windows and\nremoved pending accounts; the singleton admission row is not removed.\n\n```ts\nimport { createLogger } from '@vielzeug/rune';\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { recipesCollection } from './recipes-collection';\n\nconst log = createLogger({ namespace: 'recipes' });\nconst worker = createArchiveWorker([recipesCollection]);\nworker.tap((event) => log.debug(event, `archive:${event.type}`));\nexport default worker;\n```\n\n## Testing\n\nThe package proves itself against real workerd + local D1:\n\n```sh\nbun x vitest run packages/archive/src/__tests__/ # fast unit suite\nbun run --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage\nbun run --filter @vielzeug/archive test:types # strict types over src and the integration suite\n```\n\nProve your own collection the way the reference deployment does: a slim deployment\nsuite that publishes over your real vocabulary and asserts the derivation, plus the\npackage's generic suite for the core behavior. A collection with an `index` that can\ndrift out of vocabulary should unit-test `derive` directly: ordinary invalid input\nreturns `null`, while implementation faults throw `ArchiveDerivationError`.\nDirect DDL tests exercise the shipped schema rather than a duplicate schema.\n\n## Framework Integration\n\nThe root entry is plain TypeScript with no framework coupling; Vue, React and Svelte\napps all consume the composed schemas the same way. A Vue 3 composable that pages a\ncollection:\n\n```ts\n// useRecipes.ts — one collection's typed client in any component tree.\nimport { recipesCollection } from './recipes-collection';\nimport { ref, shallowRef } from 'vue';\n\nexport function useRecipes() {\n const entries = shallowRef<ReturnType<typeof recipesCollection.contract.entry.parse>[]>([]);\n const cursor = ref<string | null>(null);\n async function load(sort: 'liked' | 'recent') {\n const params = new URLSearchParams({ sort });\n if (cursor.value !== null) params.set('cursor', cursor.value);\n const response = await fetch(`/api/v1/collections/recipes/entries?${params}`);\n if (!response.ok) throw new Error('The archive is unavailable.');\n const page = recipesCollection.contract.page.parse(await response.json());\n entries.value = [...entries.value, ...page.entries];\n cursor.value = page.cursor;\n }\n return { cursor, entries, load };\n}\n```\n\n## Working with Other Vielzeug Libraries\n\n- [Spell](/spell/) — the payload schema a collection declares; the core composes the\n envelope schemas from it, so the wire and the types cannot drift.\n- [Courier](/courier/) — the HTTP client shape an app's frontend mirrors to consume\n these routes: strict response schemas over one typed port.\n- [Rune](/rune/) — the structured logger a deployment points `tap()` events at.\n\n## Best Practices\n\n- Compose client schemas from `collection.contract`; never hand-write the envelope.\n- Declare exactly the vocabulary your `index` derives, with union types where you\n have them; a value outside it rejects loudly.\n- Keep `canonicalize` pure and schema-true: reordered lists in, canonical form out.\n- Initialize fresh databases with the shipped DDL and deliberately reset/reseed\n development data when collection or storage semantics change.\n- Treat `ARCHIVE_ERROR_CODES` and `archiveErrorResponseSchema` as one tested contract.\n- Pin the expected-publisher header from the identity you captured at sign-in, never from storage alone.\n- Grant the operator role claim only through your issuer, and only to accounts that\n are also registered publishers.\n- Wire a sanitized `tap()` sink and register the rate-limit pepper as a production secret.\n- Rate-limit the issuer's public `verify` and `session` routes at the edge; the\n durable budgets cover sign-in admission only.\n",
7
7
  "examples": "---\ntitle: 'Archive: Examples'\ndescription: 'Task-oriented recipes for @vielzeug/archive, from first deployment to erasure.'\n---\n\n- [Stand Up a Content Archive](./examples/stand-up-a-content-archive.md)\n- [Content Identity and Versions](./examples/content-identity-and-versions.md)\n- [Multi-Collection Deployment](./examples/multi-collection-deployment.md)\n- [Moderate Content](./examples/moderate-content.md)\n- [Client Error Mapping](./examples/client-error-mapping.md)\n- [GDPR Erasure and Export](./examples/gdpr-erasure-and-export.md)\n"
8
8
  },
9
- "examples": [],
9
+ "examples": [
10
+ {
11
+ "id": "contract-schemas",
12
+ "code": "import { s } from '@vielzeug/spell'\nimport { defineArchiveCollection } from '@vielzeug/archive'\n\nconst notes = defineArchiveCollection({\n contentVersion: 1,\n index: (p) => ({ filter: null, tags: [], title: p.text }),\n name: 'notes',\n payloadSchema: s.object({ text: s.string().min(1).max(200) }),\n})\n\n// contract exposes the exact schemas client and Worker share.\nconst publish = notes.contract.publishInput.safeParse({\n clientKey: '5f0d4d1a-2f1e-4b6c-9a3d-7e8c1b2a3f4d',\n payload: { text: 'hello archive' },\n})\nconsole.log('publish input valid:', publish.success)\n\n// The publish envelope is strict: a malformed retry key is rejected.\nconst bad = notes.contract.publishInput.safeParse({ clientKey: 'nope', payload: { text: 'hi' } })\nconsole.log('bad clientKey rejected:', !bad.success)\n\n// The emitted-entry schema pins the wire and content versions.\nconst entry = notes.contract.entry.safeParse({\n author: { id: 'a1', name: 'Ada' },\n contentHash: '0'.repeat(64),\n contentVersion: 1,\n id: '5f0d4d1a-2f1e-4b6c-9a3d-7e8c1b2a3f4d',\n likeCount: 0,\n payload: { text: 'hello archive' },\n publishedAt: '2026-01-01T00:00:00.000Z',\n revision: 1,\n schemaVersion: 1,\n updatedAt: '2026-01-01T00:00:00.000Z',\n})\nconsole.log('entry schema accepts a well-formed entry:', entry.success)",
13
+ "name": "Shared Contract Schemas"
14
+ },
15
+ {
16
+ "id": "define-collection",
17
+ "code": "import { s } from '@vielzeug/spell'\nimport { defineArchiveCollection } from '@vielzeug/archive'\n\n// A collection declares its payload schema plus how to index it; the core\n// derives canonical bytes, the content hash, and every wire schema.\nconst recipes = defineArchiveCollection({\n contentVersion: 1,\n filters: ['breakfast', 'dinner'],\n index: (p) => ({ filter: p.meal, tags: [...p.tags], title: p.name }),\n name: 'recipes',\n payloadSchema: s.object({\n meal: s.enum(['breakfast', 'dinner']),\n name: s.string().min(1).max(80),\n tags: s.array(s.string().min(1).max(24)),\n }),\n tags: ['quick', 'festive'],\n})\n\nconsole.log('collection:', recipes.name, '| filters:', recipes.filters.join(','))\n\n// derive() validates, canonicalizes, and hashes in one async step.\nconst ok = await recipes.derive({ meal: 'dinner', name: 'Risotto', tags: ['festive'] })\nconsole.log('derived title:', ok.title, '| revision bytes pinned:', ok.canonicalJson)\nconsole.log('contentHash:', ok.contentHash.slice(0, 16) + '...')\n\n// Identical content hashes identically, whatever key order it arrives in.\nconst again = await recipes.derive({ tags: ['festive'], name: 'Risotto', meal: 'dinner' })\nconsole.log('stable hash:', again.contentHash === ok.contentHash)\n\n// Invalid content returns null (the Worker answers 422), never throws.\nconsole.log('bad payload:', await recipes.derive({ meal: 'lunch', name: '', tags: [] }))",
18
+ "name": "Define A Collection"
19
+ }
20
+ ],
10
21
  "typeSignatures": {
11
22
  "ArchiveIndexing": "export interface ArchiveIndexing<F extends string = string, T extends string = string> {\n /** One scalar-filter value from the declared vocabulary, or null for \"no filter\". */\n filter: F | null;\n /** Tag values from the declared vocabulary; duplicates collapse in first-seen order. */\n tags: readonly T[];\n /** The searchable title; the core trims and bounds it. */\n title: string;\n}",
12
23
  "ArchiveCollectionDefinition": "export interface ArchiveCollectionDefinition<\n P extends object,\n C extends number,\n F extends string = never,\n T extends string = never,\n> {\n /**\n * Normalizes a parsed payload to its storage form — fixed key order, sorted\n * order-insensitive lists — so equivalent content hashes identically. Omit when\n * the payload is already canonical; a result that leaves the payload schema is\n * a derivation fault at derive time, never stored. Must be idempotent.\n */\n canonicalize?(payload: P): P;\n /** The collection's payload-format version; stored and re-emitted with every entry. */\n contentVersion: C;\n /** Valid scalar-filter values; a query param outside the vocabulary is 400. */\n filters?: readonly F[];\n /** Derives the list dimensions and the searchable title from the canonical payload. */\n index(payload: P): ArchiveIndexing<NoInfer<F>, NoInfer<T>>;\n /** The URL + storage dimension this collection owns: lowercase `[a-z0-9-]`, at most 32 chars. */\n name: string;\n /** The strict payload schema: the whole content contract, parsed before anything derives. */\n payloadSchema: Schema<P, unknown>;\n /** Valid tag values. */\n tags?: readonly T[];\n}",
@@ -6,7 +6,18 @@
6
6
  "usage": "---\ntitle: 'Assay: Usage Guide'\ndescription: Scoped DOM queries, exact event dispatch, and cancellable waiting with @vielzeug/assay.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`within(root)` is Assay's query API. It accepts an element, document fragment, or shadow root and keeps every lookup\nin that scope. Use `get*` when a match is required and nullable `query*` methods when absence is part of the assertion.\n\n```ts\nimport { within } from '@vielzeug/assay';\n\nconst view = within(panel.shadowRoot!);\n\nconst save = view.get<HTMLButtonElement>('button.save');\nconst status = view.queryByText('Saved');\n\nexpect(view.query('.error')).toBeNull();\nexpect(view.getByTestId('summary').textContent).toContain('Complete');\n```\n\n`get()`, `getByText()`, and `getByTestId()` throw `AssayQueryError` with the lookup and a bounded rendering of the\nscoped DOM. This keeps a failed required lookup diagnosable without non-null assertions.\n\nUse the cross-boundary helpers for custom elements:\n\n```ts\nimport { getSlotted, queryAllInShadow, queryPart } from '@vielzeug/assay';\n\nconst trigger = queryPart(menu, 'trigger');\nconst options = queryAllInShadow(menu, '[role=\"option\"]');\nconst footerActions = getSlotted(dialog, 'footer');\n```\n\n## Exact event dispatch\n\nAssay dispatches the platform event class named by each helper. It does not model browser activation, focus\nmanagement, or form defaults. `fireFocus()` and `fireBlur()` use their non-bubbling platform defaults; use\n`focusin`/`focusout` events when testing delegated focus listeners. Use `element.click()` when native activation is\nthe behavior under test; use Assay when testing an event listener or a controlled state transition.\n\n```ts\nimport { fireClick, fireCustom, fireInput, fireKeyDown } from '@vielzeug/assay';\n\ninput.value = 'Ada';\nfireInput(input);\n\nfireKeyDown(input, { key: 'Enter' });\nfireClick(saveButton);\nfireCustom(panel, 'value-change', { detail: { value: 42 } });\n```\n\nEvery helper returns `dispatchEvent()`'s boolean result. `dispatch(target, event)` is available when an existing\nevent instance is the clearest expression of the test.\n\n## Waiting\n\nChoose the waiting primitive by the test's assertion shape:\n\n```ts\nimport { delay, eventually, waitForEvent, waitUntil } from '@vielzeug/assay';\n\nawait waitUntil(() => panel.querySelector('.status')?.textContent === 'Ready');\n\nawait eventually(\n () => {\n expect(onSave).toHaveBeenCalledOnce();\n },\n { message: 'save callback did not run' },\n);\n\nconst completed = waitForEvent<CustomEvent<{ id: string }>>(panel, 'save-complete', {\n signal: AbortSignal.timeout(1000),\n});\nfireClick(saveButton);\nexpect((await completed).detail.id).toBeDefined();\n\nawait delay(100); // real timer dependency, such as a debounce\n```\n\n`waitUntil()` polls a boolean predicate. `eventually()` retries a throwing assertion and can include a diagnostic `message`. Both enforce one hard deadline while asynchronous callbacks are pending. Abort rejects immediately with the signal reason, but cannot stop callback-owned work; forward an application signal into that work when needed.\n\nTimeouts reject with `AssayTimeoutError`. Timeout and delay values must be finite and non-negative; polling intervals must be finite and positive. All durations must fit the platform timer limit of 2,147,483,647 ms.\n\n## Testing custom elements\n\nUse Ore for component mounting and Assay for generic DOM concerns:\n\n```ts\nimport { fireClick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { mount } from '@vielzeug/ore/testing';\n\nconst fixture = await mount(\n () => html`\n <button @click=${onSave}>Save</button>\n `,\n);\n\nfireClick(fixture.get('button'));\nawait fixture.flush();\n\nexpect(onSave).toHaveBeenCalledOnce();\n```\n\nRefine's testing entry point contains only Refine-specific assertions and typed mount wrappers. Import Assay helpers\ndirectly instead of routing generic DOM operations through another package.\n\nWhen a suite tests a form-associated custom element (one built on `useField()` from `@vielzeug/ore`), install the\nform-internals polyfill in the setup file so jsdom gains the `ElementInternals` API it lacks:\n\n```ts\n// vitest.setup.ts\nimport { installFormInternalsPolyfill } from '@vielzeug/assay';\nimport { install } from '@vielzeug/ore/testing';\nimport { afterAll, afterEach } from 'vitest';\n\ninstall(afterEach);\nafterAll(installFormInternalsPolyfill());\n```\n\n## Traverse slotted content in jsdom\n\nUse `walkFlatTree()` when a test must visit descendants assigned through slots. It expands each slot into its assigned\nelements, including nested slots, instead of relying on jsdom's light-DOM-only `querySelectorAll()`.\n\n```ts\nimport { walkFlatTree } from '@vielzeug/assay';\n\nconst named: HTMLElement[] = [];\nwalkFlatTree(form, (element) => {\n if (element.hasAttribute('name')) named.push(element);\n});\n```\n\nThe callback receives descendants in the flat tree, not the root element or slot elements themselves. Browsers already\nuse the flat tree for DOM algorithms; this helper is for test code that needs equivalent traversal in jsdom.\n\n## Best Practices\n\n- Scope multiple assertions with `within()` rather than repeatedly querying the document.\n- Prefer `get*` for required controls and `query*` for intentional absence checks.\n- Make form state and event boundaries explicit: assign `.value`, then call `fireInput()` or `fireChange()`.\n- Use browser integration tests for focus, disabled activation, pointer capture, and other browser-default behavior.\n- Use `waitForEvent()` for an emitted event, `waitUntil()` for a condition, and `eventually()` for assertions.\n- Add a diagnostic `message` to waits whose final assertion does not identify the tested workflow.\n",
7
7
  "examples": "---\ntitle: 'Assay: Examples'\ndescription: Practical examples and recipes for assay.\n---\n\n## Examples\n\n- [Custom Element Interaction](./examples/custom-element-interaction.md)\n- [Waiting for Async Updates](./examples/waiting-for-async-updates.md)\n"
8
8
  },
9
- "examples": [],
9
+ "examples": [
10
+ {
11
+ "id": "scoped-queries",
12
+ "code": "import { fireClick, fireInput, within } from '@vielzeug/assay'\n\n// Build a small app DOM to probe (the REPL runs inside the sandbox iframe).\ndocument.body.innerHTML = `\n <form id=\"signup\">\n <input data-testid=\"email\" placeholder=\"email\" />\n <button type=\"submit\">Sign up</button>\n <p class=\"status\" hidden></p>\n </form>`\n\n// within() keeps every lookup scoped to one root.\nconst view = within(document.getElementById('signup'))\nconst email = view.getByTestId('email')\nconst status = view.get('.status')\n\nemail.value = 'ada@example.com'\nfireInput(email)\n\nview.getByText('Sign up').addEventListener('click', () => {\n status.hidden = false\n status.textContent = 'Welcome, ' + email.value\n})\n\nfireClick(view.getByText('Sign up'))\nconsole.log('status after click:', status.textContent)\n\n// get* throws AssayQueryError when a required match is missing;\n// query* returns null instead.\nconsole.log('missing element:', view.query('.error'))\ntry {\n view.get('.error')\n} catch (e) {\n console.log('get threw:', e.name)\n}",
13
+ "name": "Scoped Queries And Events"
14
+ },
15
+ {
16
+ "id": "waiting",
17
+ "code": "import { eventually, waitForEvent, waitUntil } from '@vielzeug/assay'\n\nconst box = document.createElement('div')\nbox.textContent = 'idle'\ndocument.body.appendChild(box)\n\n// Simulate async work that settles later.\nsetTimeout(() => { box.textContent = 'ready' }, 120)\n\n// waitUntil polls until the predicate passes.\nawait waitUntil(() => box.textContent === 'ready')\nconsole.log('waitUntil settled on:', box.textContent)\n\n// eventually retries an assertion until it stops throwing.\nsetTimeout(() => { box.classList.add('done') }, 120)\nawait eventually(() => {\n if (!box.classList.contains('done')) throw new Error('not yet')\n})\nconsole.log('eventually saw .done:', box.classList.contains('done'))\n\n// waitForEvent resolves with the next matching event.\nsetTimeout(() => { box.dispatchEvent(new CustomEvent('ping', { detail: 7 })) }, 120)\nconst ping = await waitForEvent(box, 'ping')\nconsole.log('waitForEvent detail:', ping.detail)",
18
+ "name": "Cancellable Waiting"
19
+ }
20
+ ],
10
21
  "typeSignatures": {
11
22
  "walkFlatTree": "export { walkFlatTree } from './dom';",
12
23
  "AssayError": "export { AssayError, AssayQueryError, AssayTimeoutError } from './errors';",
@@ -0,0 +1,38 @@
1
+ {
2
+ "apiSource": "// Public root surface of @vielzeug/bard. Every public export goes through this file.\nexport { createBard } from './bard';\nexport { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';\nexport type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';\n",
3
+ "docs": {
4
+ "index": "---\ntitle: 'Bard'\ndescription: 'Lifecycle-owned Web Audio mixing: buses with ducking, buffered SFX and sprites, procedural synth, streamed tracks, and crossfading music decks'\npackage: bard\ncategory: utilities\nkeywords: [web-audio, audio, sfx, soundboard, crossfade, ducking, audio-sprites]\nrelated: [necromancer]\nexports: [createBard, BardError, BardLoadError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"bard\" />\n\n## Why Bard?\n\nThe Web Audio API gives you nodes and params but no lifecycle: nothing stops voices, removes gesture listeners, or closes the context when your feature unmounts. Bard wraps a lazily created `AudioContext` in one disposable engine with named buses, ducking, voice caps, and a crossfading music deck.\n\n```ts\n// Before: hand-rolled graph, listeners, and teardown you must remember\nconst ctx = new AudioContext();\nconst source = ctx.createBufferSource();\nsource.connect(ctx.destination);\n// ...who disconnects this on unmount?\n\n// After\nconst bard = createBard({ ducking: [{ source: 'voice', target: 'music', gain: 0.3 }] });\nawait bard.load({ confirm: '/confirm.wav' });\nbard.play('confirm');\nbard.dispose(); // stops voices, removes listeners, closes the context\n```\n\n| Feature | Native Web Audio | Bard | Howler.js |\n| ----------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"bard\" type=\"size\" /> | ~30 kB |\n| Root dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Lifecycle | Manual node teardown | `dispose()` + `Symbol.dispose` | Per-sound unload |\n| Mixing | Hand-built gain graph | Named buses, ducking rules, voice caps | Per-sound volume only |\n| Music transitions | Manual crossfade scheduling | `deck.transition()` with loop points, queue | Not built in |\n\n<div class=\"decision-callout\">\n\n**Use Bard when** an interactive app needs owned audio: UI SFX with voice caps, narration that ducks music, or game-state music transitions with crossfades and loop points.\n\n**Consider a plain `HTMLAudioElement` when** you need one background track with no mixing, sprites, or lifecycle requirements.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/bard\n```\n\n```sh [npm]\nnpm install @vielzeug/bard\n```\n\n```sh [yarn]\nyarn add @vielzeug/bard\n```\n\n:::\n\n## Quick Start\n\nCreate the engine once per app, load assets, and dispose it when the owning feature unmounts. Nothing touches `AudioContext` or the DOM until the first call that needs audio, so server rendering is safe.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({\n ducking: [{ source: 'voice', target: 'music', gain: 0.3 }],\n});\n\nawait bard.load({\n music: { src: '/theme.mp3', stream: true },\n dice: { src: '/sfx.wav', sprites: { roll: [0, 1.2] } },\n});\n\nconst deck = bard.createDeck();\ndeck.transition('music', { loop: true });\nbard.play('dice:roll', { detune: [-60, 60] });\n\nbard.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createBard()`**: one disposable owner for the context, buses, voices, and decks.\n- **`bus()`**: named gain buses (`music`, `sfx`, `voice`) with click-free volume ramps.\n- **`ducking`**: declarative rules that ramp a target bus while a source bus has active voices.\n- **`play()`**: buffered playback with sprites, voice caps, oldest-first stealing, and detune/rate variance.\n- **`synth()`**: zero-asset oscillator and noise voices with ADSR and frequency sweeps.\n- **`createDeck()`**: two-slot crossfader with loop points, queue with shuffle, and opt-in Media Session.\n- **`tap()`**: observability events for state changes, steals, ducks, and track changes.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Necromancer](/necromancer/): pair visual transitions with deck music transitions from the same game-state change.\n- [Arsenal](/arsenal/): general-purpose utilities used across the monorepo.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Bard: API Reference'\ndescription: Public API of @vielzeug/bard.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ---------------------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------ |\n| `createBard` | Creates the disposable audio engine | Sync | Context is still created lazily on first audio use |\n| `BardError` | Base error for invalid keys, buses, regions | — | Subclasses: `BardLoadError`, `BardDisposedError`, `BardUnsupportedError` |\n| `BardLoadError` | A manifest entry failed to fetch or decode | — | Original failure is in `cause` |\n| `BardDisposedError` | A method ran after `dispose()` | — | Thrown by every engine method except `dispose` |\n| `BardUnsupportedError` | No `AudioContext` in the runtime | — | `unlock()` rejects with it on servers without Web Audio |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | --------------------------------------- |\n| `@vielzeug/bard` | Complete public Bard API |\n| `@vielzeug/bard/testing` | Deterministic Web Audio fakes for tests |\n\n## Engine\n\n### createBard\n\n```ts\nfunction createBard(options?: BardOptions): Bard;\n```\n\nCreates the engine. Touches no browser global until the first method that needs audio.\n\n| Option | Type | Default | Notes |\n| --------------------- | ------------------------ | --------------------------- | --------------------------------------------------------------------------- |\n| `buses` | `readonly string[]` | `['music', 'sfx', 'voice']` | `'master'` is reserved and throws if declared |\n| `volume` | `number` | `1` | Master volume, linear 0..1 |\n| `ducking` | `readonly DuckingRule[]` | `[]` | See Ducking |\n| `maxVoices` | `number` | `32` | Engine-wide concurrent voice cap |\n| `autoUnlock` | `boolean` | `true` | Gesture listeners resume a suspended context |\n| `autoSuspendOnHidden` | `boolean` | `false` | Suspend on page hide, resume on show (only resumes its own suspends) |\n| `context` | `() => AudioContext` | lazy `new AudioContext()` | Injection seam for tests; injected contexts are never closed by `dispose()` |\n\nReturns the `Bard` engine.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard({ volume: 0.9 });\n```\n\n### Bard\n\n| Member | Signature | Notes |\n| ----------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |\n| `state` | `'idle' \\| 'suspended' \\| 'running' \\| 'interrupted' \\| 'closed'` | `'idle'` until first lazy context creation; `'interrupted'` occurs on iOS calls |\n| `context` | `AudioContext \\| null` | Native context for advanced graph work |\n| `unlock()` | `() => Promise<void>` | Creates and resumes the context |\n| `load(manifest, options?)` | `(AssetManifest, { signal? }) => Promise<void>` | Deduplicates concurrent fetches per URL |\n| `unload(keys?)` | `(string \\| readonly string[]) => void` | Stops active voices for the dropped keys |\n| `has(key)` | `(string) => boolean` | Resolves `'key:sprite'` to its parent asset |\n| `play(key, options?)` | `(string, PlayOptions?) => SoundHandle` | Throws `BardError` for unknown keys and streamed assets |\n| `synth(options)` | `(SynthOptions) => SoundHandle` | Procedural voice, self-cleaning |\n| `bus(name)` | `(string) => BusController` | `'master'` is valid; unknown names throw |\n| `createDeck(options?)` | `(DeckOptions?) => MusicDeck` | Multiple decks share the engine |\n| `suspend()` / `resume()` | `() => Promise<void>` | Engine-wide pause for the whole context |\n| `tap(handler, options?)` | `(BardEvent) => void` → unsubscribe | Handler errors are swallowed; auto-detaches on `signal` |\n| `dispose()` | `() => void` | Stops voices and decks, aborts loads, removes listeners, closes an owned context; idempotent |\n| `disposed` / `disposalSignal` | `boolean` / `AbortSignal` | Standard disposal contract |\n\n---\n\n## Playback\n\n### SoundHandle\n\nReturned by `play()` and `synth()`.\n\n| Member | Signature | Notes |\n| --------------------------------------------- | -------------------------------- | ------------------------------------------- |\n| `stop(options?)` | `(FadeOptions?) => void` | Fades (default 15 ms micro-fade) then stops |\n| `setVolume(volume, options?)` | `(number, FadeOptions?) => void` | Ramped, never clicks |\n| `setPan(pan)` | `(-1..1) => void` | No-op when the voice has no panner |\n| `finished` | `Promise<void>` | Resolves on natural end, stop, or dispose |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Immediate stop and node release |\n\n### PlayOptions\n\n| Option | Type | Default | Notes |\n| ----------------------- | ---------------------- | ------------- | -------------------------------------- |\n| `bus` | `string` | `'sfx'` | Destination bus |\n| `volume` | `number` | `1` | Linear 0..1 |\n| `pan` | `number` | — | -1..1; adds a `StereoPannerNode` |\n| `loop` | `boolean` | `false` | Loops the buffer or sprite region |\n| `loopStart` / `loopEnd` | `number` | — | Absolute buffer seconds |\n| `offset` | `number` | `0` | Start offset in seconds |\n| `detune` | `number \\| [min, max]` | — | Cents; ranges sampled per voice |\n| `rate` | `number \\| [min, max]` | — | Playback rate; shifts pitch on buffers |\n| `maxVoices` | `number` | — | Per-key cap; oldest copy is stolen |\n| `fadeIn` | `number` | — | Seconds from 0 to `volume` |\n| `random` | `() => number` | `Math.random` | Deterministic sampling in tests |\n\n### SynthOptions\n\n| Option | Type | Default | Notes |\n| ---------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------- |\n| `type` | `'sine' \\| 'square' \\| 'sawtooth' \\| 'triangle' \\| 'noise'` | `'sine'` | `'noise'` uses a cached white-noise buffer |\n| `freq` | `number \\| [from, to]` | `440` | Tuple sweeps exponentially; maps to filter cutoff for `'noise'` |\n| `duration` | `number` | `0.3` | Total seconds including release; must be positive |\n| `envelope` | `SynthEnvelope` | `{ attack: 0.005, decay: 0.05, sustain: 0.6, release: 0.1 }` | ADSR; `sustain` is a level |\n| `filter` | `SynthFilter` | — | Biquad stage before the envelope |\n| `bus` / `volume` / `pan` / `detune` / `random` | as in `PlayOptions` | | |\n\n---\n\n## Mixing\n\n### DuckingRule\n\n```ts\ninterface DuckingRule {\n readonly source: string;\n readonly target: string;\n readonly gain: number; // duck level, linear 0..1\n readonly attack?: number; // seconds, default 0.2\n readonly release?: number; // seconds, default 0.8\n}\n```\n\nWhile the `source` bus has active voices, `target` ramps to `gain`; when they end it ramps back to 1. Multiple rules on one target take the lowest active gain.\n\n### BusController\n\n| Member | Notes |\n| ----------------------------------- | -------------------------------------- |\n| `name` | Bus name |\n| `volume` / `setVolume(v, options?)` | User volume stage, ramped |\n| `muted` / `mute()` / `unmute()` | Ramped mute |\n| `duckLevel` | Current duck multiplier (1 = unducked) |\n\n---\n\n## Music Deck\n\n### MusicDeck\n\n| Member | Signature | Notes |\n| --------------------------------------------- | --------------------------------------------- | ----------------------------------------------- |\n| `current` | `string \\| null` | Active track key |\n| `playing` | `boolean` | `false` while paused or stopped |\n| `transition(key, options?)` | `(string, TransitionOptions?) => SoundHandle` | Crossfades; same key returns the current handle |\n| `queue(keys, options?)` | `(readonly string[], QueueOptions?) => void` | Replaces the queue and starts its first track |\n| `next()` / `previous()` | `() => void` | No-op without a queue |\n| `pause()` / `play()` | `() => void` | `play()` resumes from the paused offset |\n| `stop(options?)` | `(FadeOptions?) => void` | Stops and clears queue and slot |\n| `dispose()` / `disposed` / `[Symbol.dispose]` | | Releases a Media Session claim |\n\n`TransitionOptions`: `fade`, `loop`, `loopStart`, `loopEnd`, `offset`.\n`QueueOptions`: `shuffle`, `crossfade`, `repeat`, `random`.\n\n### DeckOptions\n\n| Option | Type | Default | Notes |\n| -------------- | --------- | --------- | ------------------------------------------------------ |\n| `bus` | `string` | `'music'` | Destination bus |\n| `mediaSession` | `boolean` | `false` | Claims `navigator.mediaSession`; a second claim throws |\n| `fade` | `number` | `2` | Default crossfade seconds |\n\n---\n\n## Assets\n\n### AssetManifest\n\n```ts\ntype AssetManifest = Readonly<Record<string, string | AssetDefinition>>;\n\ninterface AssetDefinition {\n readonly src: string;\n readonly sprites?: Readonly<Record<string, readonly [start: number, duration: number]>>;\n readonly stream?: boolean; // deck-only playback via an owned <audio> element\n readonly meta?: AssetMeta; // Media Session metadata\n}\n```\n\nA bare string is shorthand for `{ src }`. Sprite regions are `[startSeconds, durationSeconds]` and play as `'key:sprite'`; out-of-bounds regions throw `BardError`.\n\n---\n\n## Observability\n\n### BardEvent\n\n| Event | Payload | Fires |\n| ------------ | ---------------------- | ---------------------------------------- |\n| `state` | `state` | Context lifecycle changes |\n| `load` | `key` | A manifest entry finished loading |\n| `load-error` | `key`, `error` | A load failed |\n| `steal` | `key` | A voice was stolen past a cap |\n| `duck` | `bus`, `level`, `ramp` | A bus duck level changed |\n| `track` | `key \\| null` | The deck changed tracks |\n| `dispose` | — | Emitted once at the start of `dispose()` |\n\n---\n\n## Testing\n\n`@vielzeug/bard/testing` exports `FakeAudioContext` (manual clock via `advance(seconds)`, recorded `FakeAudioParam` automation), `FakeMediaElement`, `FakeMediaSession`, and `flush()`. Inject the fake with `createBard({ context: () => fake })`.\n\n---\n\n## Errors\n\n| Error | Trigger | Notes |\n| ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------- |\n| `BardError` | Unknown key/bus/sprite, reserved bus name, streamed-asset misuse | Base class |\n| `BardLoadError` | Fetch or `decodeAudioData` failure | `cause` carries the original error or `{ status }` |\n| `BardDisposedError` | Engine use after `dispose()` | Also `BardUnsupportedError` when no `AudioContext` exists |\n",
6
+ "usage": "---\ntitle: 'Bard: Usage Guide'\ndescription: Play sounds, mix buses with ducking, generate synth SFX, and crossfade music with @vielzeug/bard.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one engine per app, load a manifest, and play through a bus. Dispose the engine when its owning feature unmounts.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = createBard();\nawait bard.load({ click: '/click.wav', boom: '/boom.wav' });\n\nconst handle = bard.play('boom', { volume: 0.8, pan: -0.3 });\nawait handle.finished;\nbard.dispose();\n```\n\n`play()` returns a `SoundHandle` immediately; audio starts once the browser allows it. `finished` resolves when the voice ends, is stopped, or is disposed.\n\n## Unlocking Audio\n\nBrowsers start the `AudioContext` suspended until a user gesture. Bard attaches capture-phase listeners for `pointerup`, `touchend`, `keydown`, and `click` and resumes the context inside the first one. All listeners are removed once the context is running.\n\n```ts\nconst bard = createBard(); // listeners attach on first audio use\nawait bard.unlock(); // or resume programmatically inside your own handler\n```\n\n`autoUnlock: false` skips the gesture listeners entirely; call `resume()` from your own gesture handler instead.\n\n## Buses and Volume\n\nVoices route to a named bus: `voice -> [pan] -> bus -> master -> destination`. The defaults are `music`, `sfx`, and `voice`; override with `buses`. Volume changes always ramp, so they never click.\n\n```ts\nconst music = bard.bus('music');\nmusic.setVolume(0.6, { fade: 0.5 });\nmusic.mute();\nmusic.unmute();\n```\n\n`bard.bus('master')` controls the output stage for every bus.\n\n## Ducking\n\nA ducking rule ramps a target bus down while the source bus has active voices, and back up when they end. Narration over music is the canonical case.\n\n```ts\nconst bard = createBard({\n ducking: [{ source: 'voice', target: 'music', gain: 0.3, attack: 0.2, release: 0.8 }],\n});\n\nawait bard.load({ announce: '/announce.wav' });\nconst voice = bard.play('announce', { bus: 'voice' });\n// music is now at 30% until the announcement ends\nawait voice.finished; // music ramps back to 100%\n```\n\nDucking uses its own gain stage per bus, so it never fights user volume automation.\n\n## Sound Sprites\n\nBundle many short SFX into one file and address regions with `key:sprite`. The region is `[startSeconds, durationSeconds]`.\n\n```ts\nawait bard.load({\n ui: { src: '/ui.wav', sprites: { open: [0, 0.4], close: [0.5, 0.4] } },\n});\n\nbard.play('ui:open');\nbard.play('ui:close', { bus: 'sfx' });\n```\n\n## Voice Caps and Variance\n\n`maxVoices` caps concurrent copies of one key; the oldest copy is stolen with a micro-fade. The engine-wide cap is `maxVoices` in `createBard` (default 32). Ranges for `detune` and `rate` keep repeated hits from sounding identical.\n\n```ts\nfor (let i = 0; i < 10; i += 1) {\n bard.play('ui:open', { maxVoices: 3, detune: [-100, 100], rate: [0.95, 1.05] });\n}\n```\n\nNote: `rate` shifts pitch on buffer sources. Pitch-preserving playback belongs on a streamed `HTMLAudioElement`.\n\n## Procedural Synth\n\n`synth()` builds an oscillator or noise burst with an ADSR envelope and optional filter, and disconnects itself when done. No assets required.\n\n```ts\n// countdown tick\nbard.synth({ type: 'square', freq: 880, duration: 0.08 });\n\n// descending error buzz with a lowpass\nbard.synth({\n type: 'sawtooth',\n freq: [220, 55],\n duration: 0.6,\n filter: { type: 'lowpass', frequency: [2400, 400] },\n});\n```\n\n## Music Deck\n\nA deck crossfades between two slots. Transition to game states, loop the body of a track after its intro, or queue continuous playback.\n\n```ts\nconst deck = bard.createDeck({ fade: 2.5 });\n\n// intro plays once, then the region loops seamlessly\ndeck.transition('bossTheme', { loop: true, loopStart: 12.5 });\n\n// later: crossfade to the victory track\ndeck.transition('victory', { fade: 4 });\n\n// continuous ambient playback with deterministic shuffle\ndeck.queue(['forest', 'cave', 'village'], { shuffle: true, crossfade: 6, repeat: true });\ndeck.next();\n```\n\n`pause()` then `play()` resumes from the paused position. A manual `transition()` takes over from the queue.\n\n## Streaming Long Tracks\n\nMark an asset `stream: true` to play it through an owned `<audio>` element instead of decoding it into an `AudioBuffer`. Mobile devices never spike RAM on ten-minute ambient tracks. Streamed assets are deck-only; `play()` on them throws.\n\n```ts\nawait bard.load({\n ambient: { src: 'https://cdn.example.com/forest.mp3', stream: true },\n});\nbard.createDeck().transition('ambient', { loop: true });\n```\n\nThe element requests CORS (`crossOrigin: 'anonymous'`); a CDN without CORS headers plays silent through Web Audio. Streamed loops cover the whole file: `loopStart`/`loopEnd` throw.\n\n## Media Session\n\n`mediaSession: true` claims `navigator.mediaSession` for one deck: metadata from the asset's `meta`, hardware play/pause/next/previous. A second claim throws instead of stealing controls; disposing the deck releases the claim.\n\n```ts\nawait bard.load({\n theme: { src: '/theme.mp3', meta: { title: 'Hunt Theme', artist: 'Bard' } },\n});\nconst deck = bard.createDeck({ mediaSession: true });\ndeck.transition('theme');\n```\n\n## Testing\n\n`@vielzeug/bard/testing` ships deterministic fakes: a context with a manual clock, recorded param automation, and fake media elements. Bard's own suite uses them.\n\n```ts\nimport { createBard } from '@vielzeug/bard';\nimport { FakeAudioContext } from '@vielzeug/bard/testing';\n\nconst ctx = new FakeAudioContext();\nconst bard = createBard({ context: () => ctx });\nawait bard.load({ ping: '/ping.wav' });\nbard.play('ping');\nctx.advance(2); // clock moves, sources past their stop time fire 'ended'\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport { createBard, type Bard } from '@vielzeug/bard';\n\nexport function useBard() {\n const [bard, setBard] = useState<Bard | null>(null);\n useEffect(() => {\n const engine = createBard();\n setBard(engine);\n return () => engine.dispose();\n }, []);\n return bard;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, shallowRef } from 'vue';\nimport { createBard } from '@vielzeug/bard';\n\nconst bard = shallowRef<ReturnType<typeof createBard> | null>(null);\nonMounted(() => (bard.value = createBard()));\nonUnmounted(() => bard.value?.dispose());\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createBard } from '@vielzeug/bard';\n import { onDestroy } from 'svelte';\n\n const bard = createBard();\n onDestroy(() => bard.dispose());\n</script>\n```\n\n:::\n\nCreate the engine in a mount hook, not at module scope: only mount lifecycle proves a browser runtime exists.\n\n## Best Practices\n\n- Create one engine per app and pass it down; contexts are a limited hardware resource.\n- Dispose the engine with its owning feature; `using` works via `Symbol.dispose`.\n- Keep streamed assets for tracks longer than a few minutes; buffers are better for SFX.\n- Give narration its own `voice` bus and duck `music` from it, rather than fading tracks by hand.\n- Inject `random` in tests so detune, rate, and shuffle are deterministic.\n- Watch `tap()` events (`steal`, `duck`, `load-error`) in development to catch mixing problems early.\n- Call `unlock()` from your own first-gesture UI when you want audio live before the next interaction.\n",
7
+ "examples": "---\ntitle: 'Bard Examples'\ndescription: Practical sound, ducking, and music-transition recipes for @vielzeug/bard.\n---\n\n## Examples\n\n- [Game-State Music Transitions](./examples/game-state-music-transitions.md)\n- [Duck Music Under Narration](./examples/duck-music-under-narration.md)\n- [UI SFX Without Assets](./examples/ui-sfx-without-assets.md)\n"
8
+ },
9
+ "examples": [],
10
+ "typeSignatures": {
11
+ "createBard": "export { createBard } from './bard';",
12
+ "BardDisposedError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
13
+ "BardError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
14
+ "BardLoadError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
15
+ "BardUnsupportedError": "export { BardDisposedError, BardError, BardLoadError, BardUnsupportedError } from './errors';",
16
+ "AssetDefinition": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
17
+ "AssetManifest": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
18
+ "AssetMeta": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
19
+ "Bard": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
20
+ "BardEvent": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
21
+ "BardOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
22
+ "BardState": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
23
+ "BusController": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
24
+ "DeckOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
25
+ "DuckingRule": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
26
+ "FadeOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
27
+ "MediaImage": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
28
+ "MusicDeck": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
29
+ "PlayOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
30
+ "QueueOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
31
+ "SoundHandle": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
32
+ "SynthEnvelope": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
33
+ "SynthFilter": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
34
+ "SynthOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
35
+ "SynthWaveform": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';",
36
+ "TransitionOptions": "export type {\n AssetDefinition,\n AssetManifest,\n AssetMeta,\n Bard,\n BardEvent,\n BardOptions,\n BardState,\n BusController,\n DeckOptions,\n DuckingRule,\n FadeOptions,\n MediaImage,\n MusicDeck,\n PlayOptions,\n QueueOptions,\n SoundHandle,\n SynthEnvelope,\n SynthFilter,\n SynthOptions,\n SynthWaveform,\n TransitionOptions,\n} from './types';"
37
+ }
38
+ }
@@ -42,6 +42,11 @@
42
42
  "code": "import { createForm } from '@vielzeug/forge'\n\nconst form = createForm({\n initialValues: { password: '', passwordConfirmation: '' },\n validate: (value) => {\n const issues: { path: (string | number)[]; message: string }[] = []\n\n if (value.password.length < 8) issues.push({ path: ['password'], message: 'Use at least eight characters' })\n if (value.password !== value.passwordConfirmation) {\n issues.push({ path: ['passwordConfirmation'], message: 'Passwords must match' })\n }\n\n return issues\n },\n})\n\nform.field('password').set('short')\nconsole.log(await form.validate())\n\nform.field('password').set('strong-password')\nform.field('passwordConfirmation').set('strong-password')\nconsole.log(await form.validate())",
43
43
  "name": "Whole-Value Validation"
44
44
  },
45
+ {
46
+ "id": "refine-elements",
47
+ "code": "import { createForm } from '@vielzeug/forge'\n// Importing refine registers its ore-* custom elements and applies theme tokens.\n// The REPL loads the bundle for every @vielzeug package your code imports,\n// so this works from the forge tab without switching libraries.\nimport '@vielzeug/refine'\n\nconst form = createForm({ initialValues: { name: '', initiative: 7 } })\n\nconst host = document.createElement('div')\nhost.style.cssText = 'display: flex; flex-direction: column; gap: 0.75rem; max-width: 320px'\nhost.innerHTML = `\n <ore-input label=\"Player name\"></ore-input>\n <ore-slider max=\"20\" value=\"7\">Initiative</ore-slider>\n <ore-button color=\"primary\">Submit</ore-button>\n <output id=\"state\"></output>\n`\ndocument.body.append(host)\n\nconst nameInput = host.querySelector('ore-input')\nconst slider = host.querySelector('ore-slider')\nconst stateOut = host.querySelector('#state')\n\nconst render = () => {\n stateOut.textContent = JSON.stringify(form.value)\n}\nnameInput.addEventListener('input', () => form.field('name').set(nameInput.value))\nslider.addEventListener('input', () => form.field('initiative').set(Number(slider.value)))\nhost.querySelector('ore-button').addEventListener('click', () => {\n console.log('submitted', form.value)\n render()\n})\nrender()",
48
+ "name": "Forge state + Refine elements"
49
+ },
45
50
  {
46
51
  "id": "scoped-sub-forms",
47
52
  "code": "import { createForm } from '@vielzeug/forge'\n\nconst form = createForm({ initialValues: { shipping: { city: '', street: '' } } })\nconst shipping = form.field('shipping')\n\nshipping.field('street').set('123 Main Street')\nshipping.field('city').set('Portland')\nconsole.log(shipping.value)\nconsole.log(form.value.shipping)",
@@ -6,7 +6,18 @@
6
6
  "usage": "---\ntitle: 'Ore: Usage Guide'\ndescription: Practical Ore usage patterns for components, props, templates, slots, context, forms, Sentinel integration, and tests.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`define(tag, definition)` creates and registers a custom element. Call it from the module or browser bootstrap responsible for registration.\n\nYour `setup()` function receives typed prop signals and returns an `HTMLResult` directly. Its state belongs to the\ncurrent connection: disconnect disposes it, and reconnecting the same element runs setup again.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('status-chip', {\n setup() {\n const online = signal(true);\n\n return html`\n <button @click=${() => (online.value = !online.value)}>${() => (online.value ? 'Online' : 'Offline')}</button>\n `;\n },\n});\n```\n\nEverything besides `props`: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, getHost, html, bind, useEmit, useSlots } from '@vielzeug/ore';\n\ndefine('my-widget', {\n setup(_props) {\n const el = getHost(); // the host HTMLElement\n const emit = useEmit<{ close: undefined }>(); // typed event emitter\n const slots = useSlots<'header'>(); // reactive slot observation\n\n bind({ attr: { role: 'group' } }); // host binding helper (attr, class, style, on)\n\n return html`<slot></slot>`;\n },\n});\n```\n\n## signals and effects\n\nOre does not re-export ripple primitives: import them directly from `@vielzeug/ripple`.\n\n```ts\nimport { batch, computed, effect, signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst doubled = computed(() => count.value * 2);\n\neffect(() => {\n console.log('doubled =', doubled.value);\n});\n\nwatch(count, (next, prev) => {\n console.log('count changed', prev, '->', next);\n});\n\nbatch(() => {\n count.value = 1;\n count.value = 2;\n});\n```\n\n## onMounted and lifecycle\n\nUse `onMounted()` for DOM-dependent initialization that must run after the template is mounted. Use `onElement(ref, cb)` for work tied to a specific DOM node. `onEvent()` attaches a listener that is automatically removed on disconnect.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, onElement, onEvent, onMounted, ref, useSlots } from '@vielzeug/ore';\n\ndefine('deferred-init', {\n setup(_props) {\n const tabIndex = signal(0);\n const inputRef = ref<HTMLInputElement>();\n const slots = useSlots<'items'>();\n\n onMounted(() => {\n const items = slots.elements('items').value;\n console.log('Found', items.length, 'items');\n });\n\n onElement(inputRef, (input) => {\n input.focus();\n });\n\n onEvent(window, 'keydown', (e: KeyboardEvent) => {\n if (e.key === 'Escape') tabIndex.value = 0;\n });\n\n return html`<div><slot name=\"items\"></slot><input ref=${inputRef} /></div>`;\n },\n});\n```\n\n## prop definitions\n\nUse `prop.*` helpers for common cases, or raw `PropDef` objects for custom parsing or `reflect: false`.\n\n```ts\nimport { define, html, prop } from '@vielzeug/ore';\n\ndefine('x-button', {\n props: {\n label: prop.string('Button'),\n disabled: prop.bool(false),\n variant: prop.oneOf(['primary', 'secondary'] as const, 'primary'),\n count: prop.number(0),\n },\n setup(props) {\n return html`\n <button ?disabled=${props.disabled} data-variant=${props.variant}>${props.label} (${props.count})</button>\n `;\n },\n});\n```\n\n## template bindings\n\n`html` supports text, attributes, booleans, properties, events, refs, and nested templates. Event bindings accept\n`.stop`, `.prevent`, `.once`, and `.capture`: the first two apply before the handler runs, while the latter two use\nnative listener options. Unknown modifiers throw while Ore compiles the template.\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { define, html, model, ref } from '@vielzeug/ore';\n\ndefine('profile-name', {\n setup() {\n const name = signal('Alice');\n const inputRef = ref<HTMLInputElement>();\n\n return html`\n <label title=${computed(() => 'Current: ' + name.value)}>Name</label>\n <input\n ref=${inputRef}\n value=${model(name)}\n aria-label=${() => 'Current name ' + name.value} />\n <p>Hello ${name}</p>\n `;\n },\n});\n```\n\n## directives\n\nOre exports `each`, `classMap`, `styleMap`, `when`, `live`, `model`, and `unsafeHtml` from `@vielzeug/ore`.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { classMap, define, each, html, styleMap, when } from '@vielzeug/ore';\n\ndefine('task-list', {\n setup() {\n const tasks = signal([{ id: 1, text: 'Write tests' }]);\n const active = signal(true);\n\n return html`\n <ul\n class=\"${classMap({ ready: () => tasks.value.length > 0 })}\"\n style=${styleMap({ opacity: () => (active.value ? 1 : 0.5) })}>\n ${when(\n () => active.value,\n () => html`<li>Active</li>`,\n () => html`<li>Paused</li>`,\n )}\n ${each(\n tasks,\n (task) => task.id,\n (task) => html`<li>${() => task.value.text}</li>`,\n )}\n </ul>\n `;\n },\n});\n```\n\n### each() API\n\n`each(source, key, render, fallback?)` takes positional arguments:\n\n- **source**: signal, getter, or plain array\n- **key**: function returning a unique string or number per item; number and string keys remain distinct\n- **render**: receives reactive `item` and `index` signals\n- **fallback**: optional, rendered when the list is empty\n\n```ts\neach(\n items,\n (item) => item.id,\n (item, index) => html`<li>#${index}: ${() => item.value.label}</li>`,\n () => html`<li>No items</li>`,\n);\n```\n\nEach reactive reconciliation is transactional. Ore creates missing entries before committing updates or removing stale\nentries; if a render callback throws, entries created during that pass are rolled back and the last successful list\nremains on screen. Ore reports the failure through `ore:error` with phase `each-reconcile`.\n\nReused items keep their DOM nodes in place: when the surviving items stay in the same relative order (prepend, append,\ninterleaved inserts, or replacing list contents), `each()` never moves a reused node, so CSS transitions, animations,\nfocus, and nested component state survive the update untouched. Only genuine reorders move nodes, and a moved item\ntravels with everything its inner directives rendered. New items are built detached and inserted exactly once at their\nfinal position, so each item's custom elements connect a single time per render.\n\n## model: two-way form bindings\n\nUse `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and\nwrites user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`\notherwise).\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, model } from '@vielzeug/ore';\n\ndefine('live-search', {\n setup() {\n const query = signal('');\n const agree = signal(false);\n\n return html`\n <input value=${model(query)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n `;\n },\n});\n```\n\nA native text input's `value` is always a string, so pass a `get` reader to keep a numeric signal numeric, and an\n`event` name for custom controls that emit their own change event:\n\n```ts\nconst count = signal(0);\n\nhtml`\n <input type=\"number\" value=${model(count, { get: (el) => Number(el.value) })} />\n <my-picker value=${model(pick, { event: 'pick-change', get: (el) => (el as MyPicker).selection })} />\n`;\n```\n\n`model()` also guards in-progress edits: while the control holds a value the signal has not received yet, a stale\napp-state write to the signal is skipped instead of clobbering what the user is typing.\n\n## host bindings\n\n`bind()` wires reactive attrs, classes, styles, and events to the host element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html } from '@vielzeug/ore';\n\ndefine('x-toggle', {\n setup(_props) {\n const open = signal(false);\n\n bind({\n attr: { 'aria-expanded': () => String(open.value), role: 'button', tabindex: 0 },\n class: { 'is-open': open },\n on: { click: () => (open.value = !open.value) },\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nThe `bind` config supports `attr`, `class`, `style`, and `on` sections.\n\n## ARIA bindings\n\nUse explicit `aria-*` keys in `bind({ attr: config }, { target })` to reactively sync ARIA attributes to any element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onMounted } from '@vielzeug/ore';\n\ndefine('x-disclosure', {\n setup(_props) {\n const open = signal(false);\n const panelId = 'disclosure-panel';\n\n bind({\n attr: { role: 'button', tabindex: 0 },\n on: { click: () => (open.value = !open.value) },\n });\n\n onMounted(() => {\n const trigger = document.querySelector('#trigger') as HTMLElement;\n if (trigger) {\n // bind() registers cleanup automatically when called inside setup\n bind(\n {\n attr: {\n 'aria-controls': panelId,\n 'aria-expanded': () => String(open.value),\n 'aria-haspopup': 'region',\n },\n },\n { target: trigger },\n );\n }\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nStatic values are applied once. Getter functions create reactive effects. Setting a value to `null`, `undefined`, or `false` removes the attribute.\n\n`bind()` always returns a cleanup function. Use it to stop syncing early when a trigger element can be swapped out:\n\n```ts\nonMounted(() => {\n const trigger = document.querySelector('#trigger') as HTMLElement;\n const stopAria = bind({ attr: { 'aria-expanded': () => String(open.value) } }, { target: trigger });\n\n // Stop syncing when the trigger is replaced\n onCleanup(stopAria);\n});\n```\n\n### Binding a non-host element with `bind()`\n\nPass `{ target: el }` as a second argument to bind attributes, classes, styles, or events to any element:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onMounted, ref } from '@vielzeug/ore';\n\ndefine('button-wrapper', {\n setup(_props) {\n const visible = signal(false);\n const btnRef = ref<HTMLButtonElement>();\n\n onMounted(() => {\n const btn = btnRef.value;\n if (!btn) return;\n\n bind(\n {\n attr: { 'aria-pressed': () => String(visible.value) },\n on: { click: () => (visible.value = !visible.value) },\n },\n { target: btn },\n );\n });\n\n return html`<button ref=${btnRef}>Toggle</button>`;\n },\n});\n```\n\n## slots and emits\n\n```ts\nimport { define, html, useEmit, useSlots } from '@vielzeug/ore';\n\ndefine('card-with-footer', {\n setup(_props) {\n const slots = useSlots<'header' | 'footer'>();\n const emit = useEmit<{ action: undefined }>();\n\n return html`\n <div class=\"card\">\n <slot name=\"header\"></slot>\n <slot></slot>\n <footer ?hidden=${() => !slots.has('footer').value}><slot name=\"footer\"></slot></footer>\n </div>\n <button @click=${() => emit('action')}>Go</button>\n `;\n },\n});\n```\n\nPass a `SlotNames` type parameter to `useSlots<SlotNames>()` to get typed `slots.has()` and `slots.elements()` calls.\n\nKeep the `<slot>` rendered and toggle its wrapper with `slots.has()`: presence is read from rendered slots, so a `<slot>` inside `when(slots.has(...))` would never appear.\n\n## context provide/inject\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { createContext, define, html, injectStrict, provide } from '@vielzeug/ore';\n\nconst COUNT_CTX = createContext<ReturnType<typeof signal<number>>>('count');\n\ndefine('count-provider', {\n setup(_props) {\n const count = signal(0);\n provide(COUNT_CTX, count);\n\n return html`<button @click=${() => count.value++}><slot></slot></button>`;\n },\n});\n\ndefine('count-consumer', {\n setup() {\n const count = injectStrict(COUNT_CTX);\n\n return html`<p>Count: ${count}</p>`;\n },\n});\n```\n\n`provide()` registers cleanup automatically: context keys are removed from the registry when the providing component disconnects. On reconnect, `setup()` runs fresh and `provide()` re-registers without spurious \"overwriting\" warnings. Provide a `Readable` (signal/computed) rather than a raw value if descendants need to observe later changes: `inject()` resolves and caches the value once per consumer connection.\n\n## form-associated elements\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, prop } from '@vielzeug/ore';\nimport { useField } from '@vielzeug/ore';\n\ndefine('rating-input', {\n formAssociated: true,\n setup() {\n const value = signal(0);\n const field = useField({ value });\n\n return html`\n <button @click=${() => (value.value = 1)}>1</button>\n <button @click=${() => (value.value = 2)}>2</button>\n <button @click=${() => (value.value = 3)}>3</button>\n <button @click=${() => field.reportValidity()}>Validate</button>\n <p>Current: ${value}</p>\n `;\n },\n});\n```\n\n## Sentinel Observers\n\nUse `@vielzeug/sentinel` for subscribable browser and DOM observations. Create element-dependent Sentinels inside `onMounted()` and dispose them with the component.\n\n```ts\nimport { define, html, onCleanup, onMounted, ref, watchEffect } from '@vielzeug/ore';\nimport { fromSubscribable } from '@vielzeug/ripple';\nimport { createElementSize, SentinelUnavailableError } from '@vielzeug/sentinel';\n\ndefine('x-observed', {\n setup(_props) {\n const boxRef = ref<HTMLDivElement>();\n\n onMounted(() => {\n const element = boxRef.value;\n if (!element) return;\n\n try {\n const size = createElementSize(element);\n const sizeState = fromSubscribable(size, { signal: size.disposalSignal });\n\n watchEffect(() => {\n console.log(sizeState.value?.width);\n });\n\n onCleanup(() => size.dispose());\n } catch (error) {\n if (!(error instanceof SentinelUnavailableError)) throw error;\n }\n });\n\n return html`<div ref=${boxRef}>Observe me</div>`;\n },\n});\n```\n\n## testing utilities\n\nImport from `@vielzeug/ore/testing`.\n\n```ts\nimport { afterEach, describe, expect, it } from 'vitest';\nimport { signal } from '@vielzeug/ripple';\nimport { fireClick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { cleanup, mount } from '@vielzeug/ore/testing';\n\ndescribe('my-counter', () => {\n afterEach(cleanup);\n\n it('increments on click', async () => {\n let count!: ReturnType<typeof signal<number>>;\n const { query, act } = await mount(() => {\n count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n });\n\n expect(query('button')?.textContent).toBe('0');\n\n await act(() => fireClick(query('button')!));\n\n expect(query('button')?.textContent).toBe('1');\n });\n});\n```\n\n## Framework Integration\n\nOre components are standard custom elements and work natively in any framework.\n\n::: code-group\n\n```tsx [React]\n// React 19+ supports custom elements natively.\nimport './x-toggle'; // wherever define('x-toggle', { ... }) is called\n\nfunction App() {\n return <x-toggle aria-label=\"Open menu\" />;\n}\n```\n\n```ts [Vue 3]\n<script setup lang=\"ts\">\nimport './x-toggle'; // wherever define('x-toggle', { ... }) is called\nimport { ref } from 'vue';\n\nconst open = ref(false);\n</script>\n\n<template>\n <x-toggle :aria-label=\"'Open menu'\" @click=\"open = !open\" />\n</template>\n```\n\n```svelte [Svelte]\n<script>\n import './x-toggle'; // wherever define('x-toggle', { ... }) is called\n\n function handleClick() {\n console.log('toggled');\n }\n</script>\n\n<x-toggle aria-label=\"Open menu\" on:click={handleClick} />\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Ripple\n\nImport ripple primitives directly from `@vielzeug/ripple` for standalone reactive state outside components.\n\n```ts\nimport { signal, computed } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\n// Shared state created outside any component\nconst theme = signal<'light' | 'dark'>('light');\nconst isDark = computed(() => theme.value === 'dark');\n\ndefine('theme-toggle', {\n setup() {\n return html`\n <button @click=${() => (theme.value = isDark.value ? 'light' : 'dark')}>\n ${() =>\n isDark.value ? '<ore-icon name=\"sun\" size=\"16\"></ore-icon>' : '<ore-icon name=\"moon\" size=\"16\"></ore-icon>'}\n </button>\n `;\n },\n});\n```\n\n### With Forge\n\nUse `@vielzeug/forge` for typed form state. `useField()` remains intentionally narrow: it connects a form-associated\ncustom element to native `ElementInternals` without imposing submission, validation, or dirty-state policy.\n\n```ts\nimport { createForm } from '@vielzeug/forge';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('signup-form', {\n setup(_props) {\n const form = createForm({ initialValues: { email: '' } });\n\n return html`\n <form\n @submit=${(event: SubmitEvent) => {\n event.preventDefault();\n void form.submit(async (values) => {\n console.log(values);\n });\n }}>\n <slot></slot>\n </form>\n `;\n },\n});\n```\n\n## Best Practices\n\n- Setup returns `html\\`...\\`` directly: not a function wrapping the template.\n- Use `watchEffect()` for reactive subscriptions tied to component lifetime: it auto-registers cleanup on disconnect.\n- Use `onElement(ref, cb)` instead of `onMounted` when the work is tied to a single DOM node.\n- Bind host attributes and classes via `bind()` rather than mutating the element directly.\n- Provide context at the nearest ancestor: avoid global context singletons.\n- Call `onCleanup()` for every resource allocated in `setup()` (WebSockets, intervals, external subscriptions).\n- Use `model(signal)` for form inputs: it writes both ways and never clobbers an in-progress user edit.\n- Extract composable helper functions freely: `onMounted`/`onCleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.\n- Test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic DOM events, queries, and waits\n from `@vielzeug/assay`.\n",
7
7
  "examples": "---\ntitle: 'Ore: Examples'\ndescription: Practical examples and recipes for ore.\n---\n\n## Examples\n\n- [Counter Component](./examples/counter-component.md)\n- [Typed Props And Emits](./examples/typed-props-and-emits.md)\n- [Observers In onMounted()](./examples/observers-in-onmount.md)\n- [Search List With Directives](./examples/search-list-with-directives.md)\n- [Context Provider And Consumer](./examples/context-provider-and-consumer.md)\n- [Prop Helpers And Raw PropDef](./examples/propsof-builder-api.md)\n- [Form Associated Rating Input](./examples/form-associated-rating-input.md)\n- [Test Example With @vielzeug/ore/testing](./examples/test-example-at-vielzeug-ore-testing.md)\n"
8
8
  },
9
- "examples": [],
9
+ "examples": [
10
+ {
11
+ "id": "counter-chip",
12
+ "code": "import { define, html } from '@vielzeug/ore'\nimport { signal } from '@vielzeug/ripple'\n\n// define() registers a custom element: setup() returns a template whose\n// bindings track signals. No classes, no lifecycle boilerplate.\ndefine('counter-chip', {\n setup() {\n const count = signal(0)\n\n return html`\n <button style=\"padding: 8px 16px; border-radius: 8px; border: 1px solid currentColor; background: transparent; color: inherit; cursor: pointer; font: inherit\"\n @click=${() => count.value++}>\n clicked ${() => count.value} ×\n </button>\n `\n },\n})\n\nconst chip = document.createElement('counter-chip')\ndocument.body.appendChild(chip)\n\nconsole.log('mounted a <counter-chip> — click it, watch this log:')\nchip.addEventListener('click', () => console.log('chip clicked'))",
13
+ "name": "Counter chip"
14
+ },
15
+ {
16
+ "id": "todo-list",
17
+ "code": "import { define, each, html, when } from '@vielzeug/ore'\nimport { signal } from '@vielzeug/ripple'\n\n// each() renders lists, when() toggles blocks: both reactive against signals.\nconst todos = signal([\n { done: true, id: 1, text: 'Read the ore overview' },\n { done: false, id: 2, text: 'Build a component with define()' },\n { done: false, id: 3, text: 'Ship it' },\n])\n\ndefine('todo-list', {\n setup() {\n const toggle = (id: number) => {\n todos.value = todos.value.map((t) => (t.id === id ? { ...t, done: !t.done } : t))\n }\n\n return html`\n <ol style=\"padding-left: 1.25rem; margin: 0 0 0.5rem\">\n ${each(\n todos,\n (todo) => todo.id,\n (todo) => html`\n <li style=${() => (todo.value.done ? 'opacity: 0.5; text-decoration: line-through; cursor: pointer' : 'cursor: pointer')}\n @click=${() => toggle(todo.value.id)}>\n ${() => todo.value.text}\n </li>`,\n () => html`<li>Nothing to do</li>`,\n )}\n </ol>\n <p>${when(\n () => todos.value.every((t) => t.done),\n () => html`<strong>All done 🎉</strong>`,\n () => html`<span>${() => todos.value.filter((t) => !t.done).length} remaining — click an item to toggle</span>`,\n )}</p>\n `\n },\n})\n\ndocument.body.appendChild(document.createElement('todo-list'))",
18
+ "name": "Todo list"
19
+ }
20
+ ],
10
21
  "typeSignatures": {
11
22
  "ComponentDefinition": "export type { ComponentDefinition } from './component-types';",
12
23
  "createContext": "export { createContext, type InjectionKey, inject, injectStrict, provide } from './context';",
@@ -21,6 +21,11 @@
21
21
  "id": "merge-basic",
22
22
  "code": "import { diff, apply } from '@vielzeug/patchwork'\nimport { merge } from '@vielzeug/patchwork/merge'\n\nconst base = { price: 10, title: 'Doc', tags: ['a'] }\nconst local = { price: 10, title: 'My edit', tags: ['a', 'mine'] }\nconst remote = { price: 12, title: 'Doc', tags: ['a', 'theirs'] }\n\nconst { doc, conflicts } = merge(base, local, remote)\nconsole.log(JSON.stringify(doc))\nconsole.log(conflicts.length)\nconsole.log(JSON.stringify(apply(local, diff(local, doc))))",
23
23
  "name": "Merge - Three-way field-level reconciliation"
24
+ },
25
+ {
26
+ "id": "pointers-basic",
27
+ "code": "import { getIn, parsePointer, formatPointer } from '@vielzeug/patchwork'\n\nconst doc = { inventory: { 'iron/sword': { qty: 2 }, '~rare~': true } }\n\n// Read through a pointer without walking the object yourself\nconsole.log(getIn(doc, '/inventory/iron~1sword/qty'))\nconsole.log(getIn(doc, '/inventory/~0rare~0'))\nconsole.log(getIn(doc, '/inventory/missing'))\n\n// Pointers are data: split, transform, re-join\nconst tokens = parsePointer('/inventory/iron~1sword/qty')\nconsole.log(tokens.join(' -> '))\n\ntokens[1] = 'iron~1axe'\nconsole.log(formatPointer(tokens))",
28
+ "name": "getIn - JSON Pointer Round-Trips"
24
29
  }
25
30
  ],
26
31
  "typeSignatures": {
@@ -6,7 +6,18 @@
6
6
  "usage": "---\ntitle: 'Prism: Usage Guide'\ndescription: Create responsive SVG charts, update their data, handle interaction, and theme @vielzeug/prism.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate a host element with non-zero dimensions, then pass it to a chart factory. This example creates the host in JavaScript so the snippet can run as written.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\nimport '@vielzeug/prism/theme.css';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Revenue by month' },\n series: [\n {\n name: 'Revenue',\n data: [\n { key: 1, value: 10 },\n { key: 2, value: 16 },\n ],\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nEach factory appends an SVG to its container and returns a `ChartHandle`. Prism observes the container with `ResizeObserver`; if it has zero dimensions on creation, Prism uses a temporary `600 × 300` size and warns in development. Give the host its layout before creating the chart.\n\n## Updating Data\n\nKeep application state outside Prism and pass the next complete data value to `update()`. The update method replaces chart data synchronously; the default transition may animate the resulting SVG.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nlet series = [{ data: [{ key: 1, value: 10 }], name: 'Live' }];\nconst chart = createLineChart(container, { series });\n\nseries = [\n {\n data: [\n { key: 1, value: 10 },\n { key: 2, value: 20 },\n ],\n name: 'Live',\n },\n];\nchart.update(series);\nchart.dispose();\n```\n\n`update()` accepts the type shown by that factory's handle: a complete series array for line, area, scatter, bar, and radar charts; a slice array for pie charts; a `HeatmapData` object for heatmap charts; and a number or stack-segment array for sparklines. Chart options such as axes, variant, callbacks, and accessibility are set at creation. For example, radar axes and a pie chart's variant do not change through `update()`.\n\n## Line Charts\n\nLine and area series use number or `Date` keys. All series in one chart must use the same key kind. Use `curve` to choose interpolation, and enable markers with `showPoints`.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Revenue and expenses' },\n series: [\n {\n curve: 'monotone',\n data: [\n { key: 1, value: 100 },\n { key: 2, value: 150 },\n { key: 3, value: 130 },\n ],\n name: 'Revenue',\n showPoints: true,\n },\n {\n color: '#c2410c',\n data: [\n { key: 1, value: 70 },\n { key: 2, value: 95 },\n { key: 3, value: 110 },\n ],\n name: 'Expenses',\n },\n ],\n tooltip: true,\n xAxis: { label: 'Month' },\n yAxis: { grid: true, label: 'Dollars' },\n});\n\nchart.dispose();\n```\n\n### Independent Value Axes\n\nAssign a line series to the right axis when it uses a different value range. Both axes share the x-scale; `rightYAxis` configures the second axis and cannot configure its position or grid.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Health and damage by level' },\n rightYAxis: { label: 'Damage' },\n series: [\n {\n data: [\n { key: 1, value: 30 },\n { key: 2, value: 20 },\n ],\n name: 'Health',\n },\n {\n data: [\n { key: 1, value: 100 },\n { key: 2, value: 300 },\n ],\n name: 'Damage',\n yAxis: 'right',\n },\n ],\n yAxis: { grid: true, label: 'Health' },\n});\n\nchart.dispose();\n```\n\nWhen any series uses the right axis, the primary value axis is placed on the left. Grid lines belong to the primary `yAxis`. The independent numeric scales mean that curve crossings do not imply equal values.\n\n### Time-Based X Axis\n\nUse `Date` values for every key when plotting time. Line and area charts use a time scale whose domain fits the data instead of rounding outward to tick boundaries.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });\nconst chart = createLineChart(container, {\n a11y: { ariaLabel: 'Signups over time' },\n series: [\n {\n data: [\n { key: new Date('2026-09-01'), value: 50 },\n { key: new Date('2026-09-08'), value: 80 },\n { key: new Date('2026-09-15'), value: 120 },\n ],\n name: 'Signups',\n },\n ],\n xAxis: { tickFormat: (value) => (value instanceof Date ? formatter.format(value) : String(value)) },\n});\n\nchart.dispose();\n```\n\n`tickFormat` formats axis labels only. Tooltip content and accessibility announcements use the underlying keys and values. To render an exact set of ticks instead of scale-generated ones, pass `tickValues`; gridlines follow the same list. Values must match the axis's scale kind, and an off-scale value warns in development:\n\n```ts\n// Force a tick on the last month, which nice-stepped ticks can skip.\nconst chart = createLineChart(container, {\n series: [\n {\n data: [\n { key: 0, value: 90 },\n { key: 11, value: 128 },\n ],\n name: 'Costs',\n },\n ],\n xAxis: { tickValues: [0, 6, 11] },\n});\n```\n\nNumeric tick labels at a magnitude of `1e5` or above default to compact notation (`123K`, `1.23M`) so long numbers fit the default value-axis margin; pass `tickFormat: String` for raw labels. Supplying a partial value-axis config merges over its default, so `yAxis: { tickFormat }` alone keeps the default grid lines.\n\n## Bar Charts\n\nBar chart keys are string categories. The default `grouped` variant puts series side by side; the horizontal variants put categories on the y-axis and values on the x-axis.\n\n```ts\nimport { createBarChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createBarChart(container, {\n a11y: { ariaLabel: 'Sales by quarter' },\n series: [\n {\n data: [\n { key: 'Q1', value: 200 },\n { key: 'Q2', value: 350 },\n { key: 'Q3', value: 280 },\n ],\n name: 'Sales',\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nChoose `grouped`, `stacked`, `grouped-horizontal`, or `stacked-horizontal` in `variant`. Negative values in a stacked chart are clamped to zero and produce a development warning. Bars in stacked variants remain square; `borderRadius` applies to grouped bars.\n\nAxes render by default, with grid lines on the value axis. For horizontal variants, `xAxis` is the value axis and `yAxis` is the category axis. Configure `grid` on the value axis.\n\nSet `showValues: true` to paint each bar's value at its end so the chart reads without hover; `valueFormat` shapes the label text. Stacked variants label the stack total at the top of the stack, and labels that would overflow the plot flip inside the bar with a contrasting fill. The labels are decorative (`aria-hidden`) — the accessible read stays with the chart's data table.\n\n## Area Charts\n\nArea series use a gradient fill by default. Set `fill: 'solid'` for a flat fill, or set `fillOpacity` to override the theme opacity for that series.\n\n```ts\nimport { createAreaChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createAreaChart(container, {\n a11y: { ariaLabel: 'Visitors over time' },\n crosshair: true,\n series: [\n {\n curve: 'monotone',\n data: [\n { key: 1, value: 12 },\n { key: 2, value: 18 },\n { key: 3, value: 15 },\n ],\n fill: 'solid',\n fillOpacity: 0.2,\n name: 'Visitors',\n showLine: true,\n },\n ],\n});\n\nchart.dispose();\n```\n\n## Scatter Charts\n\nScatter charts treat every datum as an independent point: `key` is the numeric or `Date` x-value and `value` is the y-value. The scales fit the observed values rather than forcing the y-domain to include zero. Set `pointRadius` on a series to change its marker size (default `3`).\n\n```ts\nimport { createScatterChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createScatterChart(container, {\n a11y: { ariaLabel: 'Height against weight' },\n series: [\n {\n data: [\n { key: 160, value: 55 },\n { key: 175, value: 70 },\n { key: 190, value: 88 },\n ],\n name: 'Cohort A',\n pointRadius: 5,\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nScatter callbacks identify the nearest point in two dimensions and do not provide cross-series `values`, because points do not share a category key. Keyboard navigation visits every point across series in x order. With a tooltip, `titleFormat` formats the x-value and `valueFormat` the y-value, in both the visible row and the spoken summary.\n\n## Forecast and Emphasis Styling\n\nAdd `dash` or `opacity` to individual `Datum` objects when one part of a series needs distinct styling. These fields do not change interaction, tooltip, or accessibility behavior.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst values = [10, 13, 15, 18];\nconst chart = createLineChart(container, {\n series: [\n {\n data: values.map((value, index) => ({\n key: index + 1,\n value,\n ...(index >= 2 ? { dash: '5 5', opacity: 0.4 } : {}),\n })),\n name: 'Forecast',\n showPoints: true,\n },\n ],\n});\n\nchart.dispose();\n```\n\nFor line and area charts, each datum's `dash` styles the segment from that datum to the next; the final datum has no outgoing segment. Line opacity also fades the datum's marker. Area styling affects the top line, not the fill. Bar opacity and dashes apply to the individual bar; scatter opacity applies to its point and scatter dashes are ignored. Pie, radar, and sparkline ignore these two fields.\n\n## Pie, Donut, and Semi Charts\n\nUse `createPieChart()` for all three shapes. `variant` is fixed when the chart is created; `update()` replaces the slice data.\n\n```ts\nimport { createPieChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:320px;height:240px';\ndocument.body.append(container);\n\nconst chart = createPieChart(container, {\n a11y: { ariaLabel: 'Orders by channel' },\n data: [\n { label: 'Direct', value: 42 },\n { label: 'Organic', value: 28 },\n { label: 'Referral', value: 18 },\n { label: 'Social', value: 12 },\n ],\n legend: true,\n tooltip: true,\n variant: 'donut',\n});\n\nchart.dispose();\n```\n\nThe `pie` default has no inner radius. `donut` and `semi` default to an inner radius of 55% of the outer radius. `innerRadius` overrides that size in pixels. Slice labels are omitted when they do not fit; keep a tooltip or legend when small slices need identifying.\n\n## Radar Charts\n\nDefine at least three axes when creating a radar chart. Series data uses string keys that match `RadarAxisConfig.key`; `update()` replaces series but keeps axes and other configuration fixed.\n\n```ts\nimport { createRadarChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:400px;height:320px';\ndocument.body.append(container);\n\nconst axes = [\n { key: 'strength', label: 'Strength' },\n { key: 'agility', label: 'Agility' },\n { key: 'endurance', label: 'Endurance' },\n];\nconst chart = createRadarChart(container, {\n a11y: { ariaLabel: 'Hero stats' },\n axes,\n domain: [0, 10],\n series: [\n {\n data: [\n { key: 'strength', value: 8 },\n { key: 'agility', value: 6 },\n { key: 'endurance', value: 9 },\n ],\n name: 'Adam',\n },\n ],\n tooltip: true,\n});\n\nchart.dispose();\n```\n\nThe default shared domain starts at zero and uses a nice maximum; set `domain` to compare series on a fixed range. Per-axis `min` and `max` override the chart domain for that axis. Grid rings, bands, curves, fills, vertex dots, and values are configurable; see `RadarChartConfig` and `RadarGridConfig` in the API reference.\n\n## Heatmaps\n\nDefine `rows`, `columns`, and `cells`; each cell names its `row` and `column` labels. A cell with `value: null` (or no matching cell at all) renders in `emptyColor` without in-cell text. `rowSummary` adds a right-hand column of pre-formatted per-row texts (aligned with `rows`, with an optional header) — useful for a per-row rate the cells cannot show. `update()` replaces cells and may replace `rows`, `columns`, `domain`, and `rowSummary`.\n\n```ts\nimport { createHeatmapChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:400px;height:320px';\ndocument.body.append(container);\n\nconst chart = createHeatmapChart(container, {\n a11y: { ariaLabel: 'Win rate by hero and region' },\n bins: [50, 75],\n cells: [\n { column: 'Forest', row: 'Aria', value: 90 },\n { column: 'Swamp', row: 'Aria', value: 40 },\n { column: 'Forest', row: 'Brom', value: 20 },\n { column: 'Swamp', row: 'Brom', value: 75 },\n ],\n columns: ['Forest', 'Swamp'],\n rows: ['Aria', 'Brom'],\n tooltip: true,\n valueFormat: (value) => `${value}%`,\n});\n\nchart.dispose();\n```\n\nWithout `bins` the ramp is continuous over the data's `[min, max]` domain (or an explicit `domain`); with `bins` each value maps to a discrete step and a swatch legend appears. `colorRange` sets the ramp low → high, `valueFormat` shapes in-cell values, tooltip values, and bin labels, and `showValues: false` hides the in-cell text.\n\n## Sparklines\n\nSparklines omit axes, margins, and legends. Choose `line`, `area`, or `bar` for numeric arrays, and `stack` for an array of `StackSegment` objects.\n\n```ts\nimport { createSparkline } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:240px;height:48px';\ndocument.body.append(container);\n\nconst chart = createSparkline(container, {\n a11y: { ariaLabel: 'Weekly orders' },\n data: [10, 14, 12, 18, 22],\n variant: 'area',\n});\n\nchart.update([10, 14, 12, 18, 22, 25]);\nchart.dispose();\n```\n\nFor a stacked sparkline, each segment can set `value`, `color`, and `label`. Sparklines do not offer keyboard navigation, a tooltip, or a live value announcer. Add a visible value or summary when the trend conveys important information.\n\n## Interaction\n\nSet `tooltip: true` to show Prism's default tooltip, or pass a `TooltipConfig` to format its content. `titleFormat` and `valueFormat` shape the default comparison tooltip on line, area, and bar charts—the title from the focused key and each row's value—without rebuilding its markup, and the same formatting is applied to the tooltip's spoken summary. A `render` callback receives the active `Datum` and `Series` and replaces the whole body, taking precedence over the formatters. Returned strings are inserted as text; return a DOM `Node` for structured content.\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst compact = new Intl.NumberFormat(undefined, { notation: 'compact' });\nconst months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nconst chart = createLineChart(container, {\n series: [{ data: [{ key: 11, value: 128000 }], name: 'EC2' }],\n tooltip: {\n titleFormat: (key) => months[Number(key)] ?? String(key),\n valueFormat: (value) => compact.format(value),\n },\n});\n\nchart.dispose();\n```\n\n`onHover` receives an event while a point, category, slice, or radar axis is active, then `null` when the interaction clears. `onClick` receives the selected event. For line, area, and bar charts, `ChartEvent.values` contains each series' datum at that shared key; a missing datum is `undefined`. Scatter events are `ChartEvent` objects without `values`; pie, radar, and sparkline use their chart-specific event types.\n\n`crosshair` is available on line, area, and scatter charts. By default it shows a vertical guide and snaps the line to the nearest datum. Set `horizontal: true` to add a horizontal guide or `vertical: false` to hide the vertical one. Set `snap: false` to make the guide follow the pointer; tooltip and callback data still come from the nearest datum.\n\n### Keyboard and Announcements\n\nSet `a11y: { ariaLabel }` on an informative chart. Prism gives the SVG `role=\"img\"`, an accessible name, and keyboard focus. Arrow keys move among chart data; `Home` and `End` move to the first and last item where supported; `Enter` or `Space` activates an item when an `onClick` callback is configured; `Escape` clears the active selection. Sparklines do not support keyboard navigation.\n\nWhen `a11y` is omitted, or set to `{ decorative: true }`, the SVG is marked `aria-hidden=\"true\"` and does not enter the keyboard tab order. Only mark charts decorative when their information is available elsewhere. Interactive cartesian, pie, radar, and heatmap charts use the tooltip as a polite live region when enabled; otherwise they announce active values in `.prism-live`. Sparklines have no live value announcements, so provide an equivalent visible value or summary.\n\n## Animation\n\nChart motion is enabled by default, with a 300 ms duration per animated lane (radar uses 400 ms). Pass `transition: false` to render updates synchronously, or pass `true` to state the default explicitly.\n\n```ts\nimport { createBarChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createBarChart(container, {\n series: [\n {\n data: [\n { key: 'A', value: 4 },\n { key: 'B', value: 7 },\n ],\n name: 'Count',\n },\n ],\n transition: { duration: 500, easing: 'ease-out', preference: 'system' },\n});\n\nchart.dispose();\n```\n\nColumns grow together from their baseline by default over 300 ms. Lines trace their final curve over 420 ms, uncovering point markers along the way without fading or shifting the series. Line data updates retain the default 300 ms geometry transition; an explicit `duration` overrides both timings.\n\n`preference: 'system'` (the default) disables JavaScript motion when the user prefers reduced motion. Use `'always'` to ignore that preference or `'never'` to disable motion. `stagger` sets an optional delay between bars, entering scatter points (in x order), or radar series; bar and scatter charts cap the effective delay so many marks do not add unbounded time. Named easing values are `ease-in`, `ease-in-out`, `ease-out`, `back-out`, `expo-out`, and `linear`; you can also provide an easing function.\n\n## Responsive Layout and Lifecycle\n\nSize the host with CSS. Prism observes its content box and updates the SVG dimensions and chart layout when it changes. Bar, line, and scatter resize redraws apply immediately rather than animating between layout sizes; entrance animations and explicit data-update transitions remain enabled. The legend is rendered as container chrome outside the SVG and included in resize calculations.\n\nCall `dispose()` when the view no longer owns the chart. Disposal is idempotent: it removes the SVG, tooltip, legend, and resize observation, stops in-flight chart motion, and aborts `disposalSignal`. `chart[Symbol.dispose]()` calls the same cleanup method.\n\nUse `tap()` when external code needs resize or dispose notifications rather than observing the chart DOM itself:\n\n```ts\nimport { createLineChart } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nconst chart = createLineChart(container, {\n series: [{ data: [{ key: 1, value: 10 }], name: 'Revenue' }],\n});\nconst stopObserving = chart.tap((event) => {\n if (event.type === 'resize') console.log(event.width, event.height);\n if (event.type === 'dispose') console.log('chart disposed');\n});\n\nstopObserving();\nchart.dispose();\n```\n\n`tap()` returns an unsubscribe function and accepts `{ signal }` for automatic unsubscription. A listener exception is swallowed by the observer so it cannot interrupt chart rendering.\n\n## Theming\n\nImport the stylesheet once to load Prism's structural styles, default tokens, dark-mode rules, and reduced-motion CSS. You can override any CSS custom property on an ancestor of the chart.\n\n```css\n.dashboard-chart {\n --prism-color-1: #2563eb;\n --prism-color-2: #16a34a;\n --prism-grid-color: #94a3b8;\n --prism-line-width: 3;\n --prism-text-color: #172033;\n --prism-tooltip-bg: #111827;\n}\n```\n\n`setTheme()` provides a typed subset of theme properties. A scoped call writes inline values on the provided element; omit `scope` to write them to `document.documentElement`. Inline values override stylesheet tokens until reset.\n\n```ts\nimport { resetTheme, setTheme } from '@vielzeug/prism';\n\nconst container = document.createElement('div');\ncontainer.style.cssText = 'width:640px;height:320px';\ndocument.body.append(container);\n\nsetTheme({ colors: ['#2563eb', '#16a34a'], fontFamily: 'Inter, sans-serif' }, { scope: container });\n// Call resetTheme({ scope: container }) when this scoped theme is no longer needed.\nresetTheme({ scope: container });\n```\n\n### Available Tokens\n\nThe stylesheet defines defaults for the following token groups. Pie-label color and size are read with fallback values by the renderer but are not declared in the base token block. Set a token on the chart container or an ancestor to scope an override.\n\n| Group | CSS custom properties |\n| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Palette and surfaces | `--prism-color-1` through `--prism-color-8`, `--prism-bg`, `--prism-border-radius` |\n| Axes and grid | `--prism-axis-color`, `--prism-axis-width`, `--prism-grid-color`, `--prism-grid-width`, `--prism-grid-dash`, `--prism-grid-opacity` |\n| Text | `--prism-font-family`, `--prism-font-size`, `--prism-font-size-label`, `--prism-font-size-title`, `--prism-font-weight`, `--prism-font-weight-title`, `--prism-text-color`, `--prism-text-color-secondary` |\n| Tooltip | `--prism-tooltip-bg`, `--prism-tooltip-color`, `--prism-tooltip-border`, `--prism-tooltip-radius`, `--prism-tooltip-padding`, `--prism-tooltip-shadow`, `--prism-tooltip-font-size` |\n| Crosshair | `--prism-crosshair-color`, `--prism-crosshair-width`, `--prism-crosshair-dash`, `--prism-crosshair-opacity` |\n| Points | `--prism-point-radius`, `--prism-point-radius-hover`, `--prism-point-stroke-width`, `--prism-point-stroke` |\n| Bars | `--prism-bar-radius`, `--prism-bar-hover-opacity`, `--prism-bar-gap`, `--prism-bar-band-fill`, `--prism-bar-band-opacity`, `--prism-bar-dim-opacity` |\n| Areas and lines | `--prism-area-opacity`, `--prism-area-stroke-width`, `--prism-area-gradient-start`, `--prism-area-gradient-end`, `--prism-line-width`, `--prism-line-width-hover` |\n| Interaction | `--prism-dim-opacity`, `--prism-active-point-radius`, `--prism-point-ring`, `--prism-focus-color` |\n| Sparklines | `--prism-spark-fill-opacity`, `--prism-spark-gradient-start`, `--prism-spark-gradient-end` |\n| Radar | `--prism-radar-grid-color`, `--prism-radar-grid-opacity`, `--prism-radar-band-fill`, `--prism-radar-band-opacity`, `--prism-radar-spoke-color`, `--prism-radar-fill-opacity`, `--prism-radar-stroke-width`, `--prism-radar-point-radius`, `--prism-radar-point-radius-active`, `--prism-radar-label-color`, `--prism-radar-label-size`, `--prism-radar-value-color`, `--prism-radar-value-size`, `--prism-radar-dim-opacity` |\n| Heatmap | `--prism-heatmap-label-color`, `--prism-heatmap-label-size`, `--prism-heatmap-value-size`, `--prism-heatmap-highlight-color` |\n| Motion | `--prism-duration-fast`, `--prism-duration`, `--prism-duration-slow`, `--prism-ease`, `--prism-ease-spring`, `--prism-transition`, `--prism-transition-fast` |\n| Legend and pie labels | `--prism-legend-gap`, `--prism-legend-dot-size`, `--prism-legend-font-size`, `--prism-pie-label-color`, `--prism-pie-label-size` |\n\nThe default palette and structural colors adapt to `prefers-color-scheme: dark`, `html.dark`, or `[data-prism-theme='dark']` on an ancestor. Scoped inline values set with `setTheme()` take precedence in either mode. The stylesheet also provides `prefers-reduced-motion` overrides for CSS transitions.\n\n## Errors and Diagnostics\n\nPrism throws `PrismRenderError` when the container is not a DOM element, when initial rendering fails, or when `update()` is called on a disposed chart. A wrapped initial-render error exposes its cause. Use `PrismError` to catch all Prism-originated errors.\n\nEmpty or malformed data is not always an exception. Depending on the chart, Prism may draw nothing or emit a development-only `console.warn`; examples include an unknown `bandScale` category, negative values in stacked bars, and radar axes with fewer than three entries or duplicate keys. Correct the input rather than relying on a warning for validation.\n\n## Framework Integration\n\nPrism has no React, Vue, or Svelte adapter. In any framework, give Prism a host element after it is mounted, call `update()` when data changes, and call `dispose()` before the host is removed. This plain DOM pattern shows the ownership boundary without depending on a framework-specific lifecycle API:\n\n```ts\nimport { createLineChart, type LineSeriesConfig } from '@vielzeug/prism';\n\nfunction mountChart(host: HTMLElement, series: LineSeriesConfig[]) {\n const chart = createLineChart(host, { a11y: { ariaLabel: 'Revenue' }, series });\n\n return {\n update(next: LineSeriesConfig[]) {\n chart.update(next);\n },\n dispose() {\n chart.dispose();\n },\n };\n}\n\nconst host = document.createElement('div');\nhost.style.cssText = 'width:640px;height:320px';\ndocument.body.append(host);\nconst view = mountChart(host, [{ data: [{ key: 1, value: 10 }], name: 'Revenue' }]);\nview.update([\n {\n data: [\n { key: 1, value: 10 },\n { key: 2, value: 15 },\n ],\n name: 'Revenue',\n },\n]);\nview.dispose();\n```\n\nThe application owns its state and host; Prism owns only the SVG, observer, and optional overlay elements it creates.\n\n## Working with Other Vielzeug Libraries\n\nUse Refine components for dashboard controls and keep Prism in a sized host element. Map Refine theme tokens to Prism CSS custom properties or call `setTheme()` with a scoped element; Prism does not require a Refine adapter. Prism uses Orbit internally to place tooltips, so chart users do not need to create Orbit floating elements for the built-in tooltip.\n\n## Best Practices\n\n- Give the host a non-zero size before creating a chart.\n- Set `a11y.ariaLabel` when a chart communicates information.\n- Use `Date` or number keys consistently across each line or area chart.\n- Pass the complete new data value to `update()`.\n- Keep chart options fixed after creation; recreate the chart to change them.\n- Dispose the handle when its host leaves the owning view.\n- Use `transition: false` for deterministic synchronous rendering.\n- Prefer CSS custom properties for reusable theme overrides.\n",
7
7
  "examples": "---\ntitle: 'Prism: Examples'\ndescription: Focused recipes for creating, updating, interacting with, and theming Prism charts.\n---\n\n- [Create a line chart](./examples/line-chart.md)\n- [Plot a time series](./examples/time-series.md)\n- [Plot a scatter chart](./examples/scatter-chart.md)\n- [Compare categories with a bar chart](./examples/bar-chart.md)\n- [Render compact charts](./examples/compact-charts.md)\n- [Compare hero stats with a radar chart](./examples/radar-chart.md)\n- [Show a win-rate matrix with a heatmap](./examples/heatmap-chart.md)\n- [Update chart data](./examples/update-data.md)\n- [Sync a details panel with hover](./examples/hover-details.md)\n- [Render a custom tooltip](./examples/custom-tooltip.md)\n- [Match charts to your design system](./examples/theming.md)\n"
8
8
  },
9
- "examples": [],
9
+ "examples": [
10
+ {
11
+ "id": "bar-chart",
12
+ "code": "import { createBarChart } from '@vielzeug/prism'\n\nconst host = document.createElement('div')\nhost.style.cssText = 'width: 100%; max-width: 640px; height: 300px'\ndocument.body.append(host)\n\nconst chart = createBarChart(host, {\n a11y: { ariaLabel: 'Downloads per package' },\n legend: true,\n series: [\n { data: [{ key: 'ore', value: 420 }, { key: 'prism', value: 310 }, { key: 'refine', value: 505 }], name: 'This week' },\n { data: [{ key: 'ore', value: 380 }, { key: 'prism', value: 295 }, { key: 'refine', value: 440 }], name: 'Last week' },\n ],\n tooltip: true,\n})\n\nconsole.log('rendered a grouped bar chart — hover the bars')\nvoid chart",
13
+ "name": "Bar chart"
14
+ },
15
+ {
16
+ "id": "line-chart",
17
+ "code": "import { createLineChart } from '@vielzeug/prism'\n\n// Charts render into any element and update through the returned handle:\n// update() replaces the whole series array, transitions animate the delta.\nconst host = document.createElement('div')\nhost.style.cssText = 'width: 100%; max-width: 640px; height: 320px'\ndocument.body.append(host)\n\nconst months = [1, 2, 3, 4, 5, 6]\nconst revenue = [12, 19, 15, 25, 32, 30]\n\nconst chart = createLineChart(host, {\n a11y: { ariaLabel: 'Revenue and costs by month' },\n legend: true,\n series: [\n { curve: 'monotone', data: months.map((m, i) => ({ key: m, value: revenue[i] })), name: 'Revenue', showPoints: true },\n ],\n tooltip: true,\n})\n\n// Explicit updates: swap in a second series after a moment, like live data would.\nsetTimeout(() => {\n chart.update([\n { curve: 'monotone', data: months.map((m, i) => ({ key: m, value: revenue[i] })), name: 'Revenue', showPoints: true },\n { color: '#e05252', curve: 'monotone', data: months.map((m) => ({ key: m, value: m * 4 + 5 })), name: 'Costs' },\n ])\n console.log('added a second series via chart.update()')\n}, 1200)",
18
+ "name": "Line chart"
19
+ }
20
+ ],
10
21
  "typeSignatures": {
11
22
  "EasingFn": "export type { EasingFn, EasingName } from './animation/easing';",
12
23
  "EasingName": "export type { EasingFn, EasingName } from './animation/easing';",