@vielzeug/codex 26.10.9 → 26.10.11
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.
- package/data/catalog.json +43 -43
- package/data/llms-full.txt +325 -172
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +2 -2
- package/data/packages/refine.json +8 -4
- package/data/refine.json +2529 -2289
- package/data/search.json +6 -6
- package/package.json +2 -2
package/data/llms.txt
CHANGED
package/data/manifest.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"apiSource": "// Public root surface of @vielzeug/archive: the browser-safe contract — the wire\n// schemas and the collection seam. The Cloudflare Worker itself\n// lives behind the `@vielzeug/archive/worker` subpath so client bundles never\n// resolve worker machinery.\nexport * from './collection';\nexport * from './contract';\nexport * from './errors';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: Archive\ndescription: \"Community content publishing for Cloudflare Workers + D1: a hardened Worker core over per-collection payload schemas\"\npackage: archive\ncategory: utilities\nkeywords: [cloudflare, worker, d1, community, publishing, content, catalog, gdpr]\nrelated: [spell, courier, rune]\nexports: [defineArchiveCollection, createArchiveWorker, createAuthWorker, archiveAuthHealthSchema, ArchiveDerivationError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"archive\" />\n\n## Why Archive?\n\nYou can share content entries with ranked browsing, filters, likes and account\nerasure on Cloudflare Workers + D1. `defineArchiveCollection` supplies your JSON\npayload schema and indexing rules; the Worker supplies sessions, guards,\nidempotent publishing, cursors and rate limits.\n\n```ts\n// Before: each deployment repeats validation, indexing and route plumbing.\n\n// After: the deployment is one collection definition plus one factory call.\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes', contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createArchiveWorker([notes]);\n```\n\n| Feature | Archive | Hand-rolled Worker | BaaS (Firebase/Supabase) |\n| ------------------------------------ | -------------------------------------------------------- | ------------------------------------ | ------------------------------------- |\n| Bundle size (core) | <PackageInfo package=\"archive\" type=\"size\" /> | Depends on deployment code | Depends on selected SDK |\n| Zero dependencies | No — Spell and jose | Depends on implementation | No — client SDK |\n| Content knowledge in the core | <ore-icon name=\"check\" size=\"16\"></ore-icon> none — one collection seam | <ore-icon name=\"x\" size=\"16\"></ore-icon> baked in | <ore-icon name=\"x\" size=\"16\"></ore-icon> rules everywhere |\n| Canonical fresh-database D1 schema | <ore-icon name=\"check\" size=\"16\"></ore-icon> in the package | Deployment-owned | Not a D1 backend |\n| Idempotent publish w/ tombstones | <ore-icon name=\"check\" size=\"16\"></ore-icon> built-in | <ore-icon name=\"x\" size=\"16\"></ore-icon> rebuild it | <ore-icon name=\"x\" size=\"16\"></ore-icon> rebuild it |\n| GDPR erasure / export endpoints | <ore-icon name=\"check\" size=\"16\"></ore-icon> built-in | <ore-icon name=\"x\" size=\"16\"></ore-icon> rebuild it | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> partial |\n| Strict DTO re-validation on read | <ore-icon name=\"check\" size=\"16\"></ore-icon> every entry | <ore-icon name=\"x\" size=\"16\"></ore-icon> optional | <ore-icon name=\"x\" size=\"16\"></ore-icon> optional |\n\n<div class=\"decision-callout\">\n\n**Use Archive when** an app needs a shareable, ranked, liked community space for\ncontent entries on Cloudflare Workers + D1, and can express its content as one strict\npayload schema.\n**Consider alternatives when** you need rich queries beyond filter/tag/search, live\ncollaboration, or a backend you do not control — Archive is deliberately one narrow,\nhardened surface.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/archive @vielzeug/spell\n```\n\n```sh [npm]\nnpm install @vielzeug/archive @vielzeug/spell\n```\n\n```sh [yarn]\nyarn add @vielzeug/archive @vielzeug/spell\n```\n\n:::\n\n## Quick Start\n\nA deployment is one collection definition plus one factory call. The definition\nbrings the payload schema and what to index; everything else — the emitted-entry\nenvelope, the content hash, the wire contract, the routes — is composed for you.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\n// The collection's payload: one strict schema is the whole content contract.\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\nconst recipesCollection = defineArchiveCollection({\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// The whole Worker: routing, auth, guards, limits, SQL and DTO disciplines included.\nexport default createArchiveWorker([recipesCollection]);\n```\n\nThe browser side never imports worker machinery. The same collection's composed\nschemas parse what the routes emit:\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes', contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nconst response = await fetch('/api/v1/collections/notes/entries?sort=liked');\nif (!response.ok) throw new Error('Archive unavailable');\nconst parsed = notes.contract.page.parse(await response.json());\nconsole.log(parsed.entries);\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `defineArchiveCollection` — the one content seam: payload schema, canonicalization, filter/tag/title derivation, union-typed vocabularies\n- `createArchiveWorker` — the whole routes/auth/limits/SQL stack from registered collections\n- `collection.contract` — entry, page, publish/update input schemas shared by client and Worker\n- `ARCHIVE_LIMITS` + `archiveHealthSchema` — the application bounds, advertised by health and validated on both sides\n- `archiveAuthHealthSchema` + `AUTH_SCHEMA_VERSION` — typed issuer readiness checked against the issuer DDL stamp\n- `archiveErrorResponseSchema` — the one error envelope, code-typed across the wire\n- `createAuthWorker` — scanner-safe confirmation, live session-version enforcement, durable budgets, metadata export and coordinated erasure\n- `AUTH_ISSUER_SERVICE` — signing-key retrieval and an uncached issuer check after local catalog JWT verification\n- `ArchiveDerivationError` — distinguishes faulty collection code from invalid submitted content\n- Moderation — reader reports, the operator soft-hide and the report queue, keyed on a verified `roles` claim\n- `worker.tap()` / `issuer.tap()` — typed sanitized runtime events; neither core logs by default\n- `migrations/` — canonical fresh-database DDL with the storage stamp health reads back; no upgrade framework\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md) — stand up a collection, deploy the Worker, wire the client.\n- [API Reference](./api.md) — every export, all three entry points, the full route table.\n- [Examples](./examples.md) — recipes from first deployment to GDPR erasure.\n- [Migration](./migration.md) — breaking changes after the first release and\n fresh-database scope.\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Spell](/spell/) — every payload schema here is a spell schema; the core composes envelopes from it.\n- [Courier](/courier/) — the HTTP client shape an app's frontend mirrors to consume these routes.\n- [Rune](/rune/) — the structured logger a deployment points `worker.tap()` events at.\n\n</div>\n\n<!-- markdownlint-enable MD060 MD033 MD025 -->\n",
|
|
5
|
-
"api": "---\ntitle: \"Archive: API Reference\"\ndescription: \"Collection definitions, browser-safe wire schemas, Worker deployment, and identity issuance.\"\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `defineArchiveCollection` | Compose validation, indexing, identity and wire schemas | Sync | Invalid content derives to `null`; callback faults throw |\n| `createArchiveWorker` | Build the catalog Worker | Sync | Collection names must be unique |\n| `createAuthWorker` | Build the passwordless issuer | Sync | `AUTH_ARCHIVE` is required |\n| `worker.tap`, `issuer.tap` | Observe sanitized runtime outcomes | Sync | Neither core logs by default; observer exceptions are swallowed |\n| `ArchiveDerivationError` | Identify a collection implementation/runtime fault | Sync | Faults become sanitized 500s, not content-validation 422s |\n| `ARCHIVE_LIMITS` | Shared application bounds | Sync | Page bounds do not cap total exports |\n| `archiveErrorResponseSchema`, `archiveAuthHealthSchema` | Validate error and issuer-health responses | Sync | Unknown error codes and health states reject |\n| `ArchiveError`, `ArchiveDefinitionError` | Public base and invalid-definition errors | Sync | Thrown locally, not transmitted as error objects |\n| `sessionCookieValue` | Compose shared session-cookie attributes | Sync | Deployments must choose `secure` from their environment |\n| `isWellFormedText` | Check control characters and lone surrogates | Sync | Does not trim or impose a length bound |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/archive` | Browser-safe collections, constants, schemas and errors |\n| `@vielzeug/archive/worker` | Catalog factory, issuer signing-key/session service binding and event types |\n| `@vielzeug/archive/auth` | Issuer factory and binding types |\n\n## Collections\n\n### `defineArchiveCollection`\n\nCreates a frozen collection and its contract; malformed names, versions or vocabularies throw `ArchiveDefinitionError`.\n\n```ts\nfunction defineArchiveCollection<\n P extends object, const C extends number, const F extends string = never, const T extends string = never,\n>(definition: ArchiveCollectionDefinition<P, C, F, T>): ArchiveCollection<P, C>;\n```\n\n| Parameter | Contract |\n| --- | --- |\n| `name` | Lowercase `[a-z0-9-]{1,32}` |\n| `contentVersion` | Positive safe integer |\n| `payloadSchema` | Spell schema whose output is a stable JSON object |\n| `filters`, `tags` | Optional readonly arrays; omitted means empty vocabulary |\n| `canonicalize` | Optional pure, idempotent, schema-valid normalization |\n| `index` | Derive `filter`, `tags` and searchable `title` without mutating the payload |\n\n**Returns:** `ArchiveCollection<P, C>`.\n\n**Example:** define and derive one collection without Worker bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst recipes = defineArchiveCollection({\n name: 'recipes',\n contentVersion: 1,\n payloadSchema: s.object({ name: s.string().min(1).max(32) }),\n index: (payload) => ({ filter: null, tags: [], title: payload.name }),\n});\nconst derived = await recipes.derive({ name: 'Rice' });\nif (derived === null) throw new Error('Invalid recipe');\nconsole.log(derived.contentHash);\n```\n\n| Method / property | Result |\n| --- | --- |\n| `derive(raw)` | `Promise<ArchiveDerivation \\| null>` |\n| `contract.entry` | Public entry schema |\n| `contract.ownedEntry`, `ownedEntries` | Owner view with `clientKey` and `hidden` |\n| `contract.page` | Entries and the forward cursor |\n| `contract.publishInput`, `updateInput` | Publish and revision-guarded update request schemas |\n| `filters`, `tags` | Frozen vocabulary snapshots |\n\n`derive` returns `null` for invalid JSON objects, schema-invalid input, invalid titles, too many tags and oversized canonical payloads. Unexpected schema, callback or hashing failures throw `ArchiveDerivationError`. Non-idempotent or schema-invalid canonicalization, unstable schema transformations, index mutation and out-of-vocabulary projections are also derivation faults. Routes map `null` to 422 `invalid-payload` and faults to a sanitized 500 `internal`.\nSchema output that is lossy or no longer JSON is a derivation fault, not invalid\nsubmitted content. Invalid index-result shapes also throw.\n\nConst generics preserve the content-version literal and infer filter/tag unions from vocabulary arrays without `as const`. `NoInfer` prevents `index` from widening those unions; omitted arrays infer `never`, permitting only `filter: null` and empty tags.\n\nObjects serialize with recursively sorted keys; arrays preserve order unless your canonicalizer changes it. SHA-256 hashes the core-owned `{contentVersion, payload}` envelope. Stored payloads are canonical by construction, so the emitted entry schemas embed the plain payload schema.\n\n`filter`, tags and searchable title are persisted projections, not computed during reads. Changing `index` or its vocabulary does not update stored rows. The active definition and persisted dataset must remain consistent; Archive has no projection-update or historical-schema API.\n\n## Worker and Maintenance\n\n### `createArchiveWorker`\n\nReturns the catalog request/scheduled handler and its observation side channel.\n\n```ts\nfunction createArchiveWorker<E extends ArchiveWorkerEnv>(\n collections: readonly ArchiveCollection[],\n): ArchiveWorkerHandler<E>;\n```\n\n**Returns:** `ArchiveWorkerHandler<E>`; duplicate names throw `ArchiveDefinitionError` at registration.\n\n**Example:** export a deployable Worker using the package's structural bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes', contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createArchiveWorker<ArchiveWorkerEnv>([notes]);\n```\n\n| Method | Contract |\n| --- | --- |\n| `fetch(request, env, ctx)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx)` | Sweeps expired retry keys and revocation tombstones; emits failures and rethrows |\n| `tap(handler, { signal? }?)` | Returns unsubscribe; a pre-aborted signal registers nothing |\n\n`AUTH_ISSUER_SERVICE` is a required `fetch`-shaped service binding to the issuer.\nThe catalog fetches signing keys from the configured `JWT_JWKS_URL` through that\nbinding, not through global `fetch`. The URL still selects the issuer's JWKS\nroute and must satisfy the environment's transport rules. Key requests use GET\nwithout a session cookie and do not follow redirects.\nThe catalog verifies the signed JWT locally, then asks the issuer to validate its\ncurrent account session version. JOSE caches signing keys; the catalog does not\ncache successful issuer session verdicts.\nIf the service exchange fails or exceeds its fixed 5000 ms timeout (body decoding\nincluded), the catalog returns `503 auth-unavailable`; the timeout does not cancel\nwork already started by the issuer.\n\nOnly anonymous entry lists can use the 30-second edge cache. Any `Cookie` or `Authorization` header disables caching, even if invalid or empty. Detail, metadata, private and error responses are `no-store`. Public reads do not verify sessions.\n\n---\n\n### `worker.tap`\n\nObserves typed request, scheduled and cache-failure events without affecting request behavior.\n\n```ts\ntap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n```\n\n**Returns:** an unsubscribe function; abort detaches the observer. Diagnostics contain categories and trusted configuration field names, never raw errors, SQL, subjects, aliases, tokens or URLs.\n\n**Example:** observe a Worker and detach explicitly.\n\n```ts\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\n\nconst worker = createArchiveWorker<ArchiveWorkerEnv>([]);\nconst stop = worker.tap((event) => console.log(JSON.stringify(event)));\nstop();\n```\n\n---\n\n## Identity Issuer\n\n### `createAuthWorker`\n\nReturns the passwordless email issuer with account export and coordinated erasure.\n\n```ts\nfunction createAuthWorker<E extends AuthWorkerEnv>(): AuthWorkerHandler<E>;\n```\n\n**Returns:** `AuthWorkerHandler<E>`.\n\n**Example:** export an issuer configured through deployment bindings.\n\n```ts\nimport { createAuthWorker, type AuthWorkerEnv } from '@vielzeug/archive/auth';\n\nexport default createAuthWorker<AuthWorkerEnv>();\n```\n\n| Method | Contract |\n| --- | --- |\n| `fetch(request, env, ctx?)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx?)` | Removes expired links, closed send windows and unverified unreferenced accounts |\n| `tap(handler, { signal? }?)` | Observes typed `AuthEvent`; returns unsubscribe; pre-aborted signals are inert |\n\nMagic links expire after 15 minutes and work once. The durable per-email budget allows three sends per hour; consumption, expiration and send failure do not refund it. Ordinary sessions last at most 30 days. Operator sessions use `OPERATOR_SESSION_MAX_AGE_SECONDS` (900 seconds). `OPERATOR_EMAILS` controls newly minted role claims.\n\nThe issuer-global admission budget is durable D1 state in `auth_sign_in_budget`:\n20 requests per 60-second window before account creation or email delivery.\nThis supplements, rather than replaces, the durable per-email budget. No external\nrate-limiter binding is required.\nAdmission spends are not refunded after later database or email failures.\nRequest emails are trimmed and lowercased before validation. `SENDER_ADDRESS`\nmust already be canonical; `OPERATOR_EMAILS` entries are trimmed and lowercased\nbefore validation.\n\nSign-in requests create pending account rows with `lastSignInAt: null`. Successful\nredemption atomically claims the one-use link and stamps the account's sign-in\ntime. The sweep deletes expired links and closed per-user send windows, then\nunverified accounts with neither remaining links nor send-budget references.\nVerified accounts are retained until explicit account deletion.\n\n`OPERATOR_SESSION_MAX_AGE_SECONDS = 900` is part of the browser-safe root\ncontract; `/auth` exports the factory and issuer binding types.\n\n`AUTH_JWT_PREVIOUS_PUBLIC_JWKS` optionally publishes retired public RS256 keys and verifies sessions minted before rotation; private members reject configuration. The package has no demo sign-in routes.\n\nOpening a magic link performs a safe GET that displays a click-confirmation page,\nnot redemption. Only a marked POST from an exact allowed origin or\n`PUBLIC_ORIGIN` consumes `{ token }` and returns 204 with the session cookie. The\nconfirmation page navigates to `/signed-in` after success; the POST is not a\nredirect. Confirmation responses are `no-store` with no-referrer and restrictive\nCSP; the page removes the token from the address bar and loads no external assets.\nGET displays confirmation for any syntactically valid token, including a used\ntoken; only POST establishes whether the link is still redeemable. POST accepts\nexactly `{ token }` and rejects query parameters.\n\nThe issuer never logs directly. `tap` emits sanitized request and scheduled\noutcomes; observer failures are swallowed, abort detaches the observer and failed\nscheduled work emits then rethrows. `AuthDiagnostic` reports only a category.\n\n## HTTP Routes\n\nEvery route below is mounted under `/api/v1`. Mutation guards require an exact allowed `Origin` and `x-archive-request: 1`. Registered publishers pin `x-archive-publisher` to the identity captured when preparing private requests. The header is a freshness precondition, not authority.\n\n| Route | Contract |\n| --- | --- |\n| `GET /health` | Public catalog readiness; 200 `ok` or 503 `degraded` |\n| `POST /sign-out` | Catalog-local sign-out; `{ ok: true }` and expired session cookie, without issuer access |\n| `GET /collections/:collection` | Collection metadata |\n| `GET /collections/:collection/entries` | `author`, `filter`, `tag`, `search`, `sort`, `cursor`, `limit`; forward entry page |\n| `POST /collections/:collection/entries` | `{ clientKey, payload }`; 201 create or 200 replay |\n| `GET /collections/:collection/entries/:id` | Public entry; always `no-store` |\n| `PUT /collections/:collection/entries/:id` | Owner-only `{ expectedRevision, payload }` |\n| `DELETE /collections/:collection/entries/:id` | Owner or operator removal; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/like` | Like / unlike visible entries only; guarded write and response; like-state response |\n| `POST /collections/:collection/entries/:id/report` | `{ reason }`; idempotent per entry/reporter; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/hidden` | Operator hide / unhide; 204 |\n| `GET /collections/:collection/reports` | Operator page; `status=unresolved` (default) or `resolved`, `cursor`, `limit` |\n| `PUT /collections/:collection/reports/:id/resolved` | Operator resolves report by its unique report ID; idempotent 204 |\n| `DELETE /publishers/:id` | Operator erases Archive profile; not issuer account |\n| `GET /moderation-log` | Operator forward page; `cursor`, `limit` |\n| `GET` / `POST` / `PUT /me` | Identity, register with optional `{ name }`, rename with required `{ name }` |\n| `DELETE /me` | Profile-only cascade; 204; does not clear cookie |\n| `DELETE /me/account` | Revoke issuer/subject and atomically erase profile; 204; coordinated issuer-erasure seam |\n| `GET /me/publications?collection=…` | Owner entries including hidden state and retry keys |\n| `GET /me/likes` | Forward page `{ ids, cursor }`; `cursor`, `limit` |\n| `GET /me/likes?ids=…` | Subset lookup `{ ids }`; at most `likeStateIds` input IDs |\n| `GET /me/reports` | Own forward report page across collections; `cursor`, `limit` |\n| `GET /auth/health` | Public issuer readiness; typed `AuthHealth`, 200 `ok` or 503 `degraded`; no email or peer probe |\n| `GET /auth/session` | Internal issuer-session check for the catalog service binding; exact `{ ok: true }`, `no-store`, no PII; 401 for an invalid, stale or absent-account session |\n| `POST /auth/sign-out-all` | Requires marker, exact origin, session and captured `ACCOUNT_HEADER`; atomically increments `session_version`, deletes outstanding links, preserves account and catalog data; 200 `{ ok: true }` with an expired cookie only on durable success |\n| `GET /auth/jwks.json` | Active and configured retired public verification keys |\n| `POST /auth/sign-in` | `{ email }` (trimmed and lowercased); 202 `{ ok: true }` |\n| `GET /auth/verify?token=…` | Safe no-store click-confirmation page; no token consumption or session change |\n| `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |\n| `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |\n| `DELETE /auth/account` | Requires `ACCOUNT_HEADER` with the captured issuer account UUID; catalog `/me/account` via `AUTH_ARCHIVE`, require exact 204, then issuer user and cookie clear; 204 |\n\nForward pages are newest first with opaque context-bound keyset cursors. Keep the same query context when following a cursor; end at `cursor: null`. `maxPageSize` bounds each page, not the total number of liked IDs, reports or audit actions you can export. The subset-like query is not a page and cannot combine `ids` with `cursor` or `limit`.\n\nFull erasure creates an issuer/subject revocation tombstone for 30 days plus ten\nseconds and deletes the profile in the same transaction. Catalog authentication\nrejects that subject with 401 on ordinary private routes; registration also checks\nrevocation in SQL to prevent resurrection races. Only `DELETE /me/account` may\nbypass the issuer session lookup, and only to retry erasure with the original\nsigned session of the same principal while its existing revocation tombstone is\nvalid; JWT signature and claims are still verified. It is not a general\nstale-session exception: initial erasure validates the issuer session. The\nissuer-facing `DELETE /auth/account` always checks the current session version\nbefore calling the catalog, so retrying it after completed erasure returns 401\nbecause the account is absent.\nDirect profile-only `DELETE /me` allows later registration using the same session.\nThe sweep removes expired tombstones. Re-enrollment through the reference issuer\ncreates a fresh account UUID subject; an external issuer must issue a new subject\nto re-enroll during the revocation window.\n\nThe issuer stores `auth_users.session_version` as a safe non-negative integer,\ndefaulting to `0`. Every session JWT carries the current value as the required\n`sessionVersion` claim. Each ordinary issuer-authenticated route compares that\nclaim to the current account row; a mismatch is unauthenticated. `POST\n/api/v1/auth/sign-out-all` checks the captured issuer account UUID against the\nverified subject before atomically incrementing the version and deleting pending\nlinks. A changed account answers 409 `account-changed`; a failed request does not\nclear the cookie. This revokes all sessions, including the caller's, after a\nsuccessful response. Requests authorized before revocation may finish; there is\nno cross-database transactional or in-flight cancellation guarantee.\n\nThe catalog requires `AUTH_ISSUER_SERVICE`, a service binding to the issuer for\nboth JWKS retrieval and live session validation. Signing-key retrieval uses\n`JWT_JWKS_URL` through the binding, so it does not depend on a public same-zone\nWorker-to-Worker fetch. After local JWT signature/claims verification, it requests\n`GET /api/v1/auth/session` through that binding on every private request. Only a\nstrictly validated 401 `unauthenticated` remains a 401. Malformed, unexpected,\nprovider and 5xx responses become 503 `auth-unavailable`; there is no authority\ncache. Both service directions use a fixed 5000 ms timeout that includes body\ndecoding. The issuer's `/api/v1/auth/session` is an internal\nservice contract, not a frontend session API.\n\nIssuer readiness is independent of catalog readiness. `GET\n/api/v1/auth/health` returns `archiveAuthHealthSchema` as `AuthHealth`; its\nread-only probe checks configuration, a signing and verification key proof,\nbinding shapes, the singleton `auth_schema_meta` stamp against\n`AUTH_SCHEMA_VERSION`, and readability of expected tables, columns and triggers.\nIt does not write, send email or probe the catalog service. Responses are\nsanitized.\nConfiguration failure, database failure and schema mismatch return HTTP 503\nwith `status: 'degraded'` and the corresponding reason.\n\nEffective hide, unhide, operator removal and publisher erasure append audit rows atomically with the state transition. Concurrent idempotent no-ops append nothing. Audit rows contain opaque IDs, not names or content, and have no foreign keys so they outlive erasure. Resolving a report sets `resolvedAt`; it is not one of the four audit action kinds.\n\n## Constants and Schemas\n\n| Export | Value or parsed output |\n| --- | --- |\n| `ARCHIVE_CONTRACT_VERSION`, `ARCHIVE_SCHEMA_VERSION` | Both debut at `1`; wire and storage versions are independent |\n| `AUTH_SCHEMA_VERSION` | `1`; issuer DDL stamp checked by `/auth/health` |\n| `ARCHIVE_COLLECTION_NAME_PATTERN` | `/^[a-z0-9-]{1,32}$/` |\n| `ARCHIVE_OPERATOR_ROLE` | `'archive-operator'` |\n| `SESSION_COOKIE_NAME`, `SESSION_COOKIE_PATH` | `'archive_session'`, `'/api/v1'` |\n| `SESSION_MAX_AGE_SECONDS` | `2592000` |\n| `OPERATOR_SESSION_MAX_AGE_SECONDS` | `900`; shared root contract |\n| `ACCOUNT_HEADER` | `'X-Archive-Account'`; required issuer-account UUID on coordinated erasure |\n| `PUBLISHER_HEADER`, `REQUEST_MARKER_HEADER` | `'x-archive-publisher'`, `'x-archive-request'` |\n| `ILL_FORMED_TEXT`, `isWellFormedText(value: string): boolean` | Reject control characters and lone UTF-16 surrogates |\n| `uuidSchema`, `isoTimestampSchema`, `hex64Schema` | UUID, ISO timestamp, lowercase SHA-256 hex strings |\n| `archiveAliasSchema` | Trimmed, well-formed alias of at most 24 characters |\n| `archiveAuthorSchema` | `{ id: string; name: string }` |\n| `archiveIdentitySchema` | `ArchiveIdentity` |\n| `archiveAccountSchema` | `ArchiveAccount`; issuer metadata, excluding private fields |\n| `archiveLimitsSchema` | All numeric `ARCHIVE_LIMITS` fields |\n| `archiveHealthSchema` | `ArchiveHealth` |\n| `archiveAuthHealthSchema` | `AuthHealth` |\n| `archiveErrorResponseSchema` | `ArchiveErrorResponse` |\n| `archiveOkSchema` | `{ ok: true }` |\n| `archiveCollectionMetaSchema` | `ArchiveCollectionMeta` |\n| `archiveLikedIdsSchema` | `{ ids: string[] }` subset response |\n| `archiveLikesPageSchema` | `ArchiveLikesPage` |\n| `archiveLikeStateSchema` | `{ id: string; likeCount: number; liked: boolean }` |\n| `archiveReportsSchema`, `archiveOwnReportsSchema` | `ArchiveReports`, `ArchiveOwnReports` |\n| `archiveModerationLogSchema` | `ArchiveModerationLog` |\n| `archiveSortSchema` | `ArchiveSort` |\n| `ARCHIVE_ERROR_CODES` | Values of `ArchiveErrorCode` below |\n| `ARCHIVE_MODERATION_ACTIONS` | `['hide', 'unhide', 'remove', 'erase-publisher']` |\n\n### `sessionCookieValue`\n\nComposes a session cookie using the shared security attributes.\n\n```ts\nfunction sessionCookieValue(token: string, options: { maxAgeSeconds: number; secure: boolean }): string;\n```\n\n| Parameter | Contract |\n| --- | --- |\n| `token` | Session token, or empty string when clearing |\n| `options.maxAgeSeconds` | Cookie lifetime; `0` clears it |\n| `options.secure` | Include `Secure` for production HTTPS |\n\n**Returns:** the `Set-Cookie` value with `HttpOnly`, `SameSite=Strict`, the shared path and optional `Secure`.\n\n**Example:** clear the production cookie.\n\n```ts\nimport { sessionCookieValue } from '@vielzeug/archive';\n\nconst expiredCookie = sessionCookieValue('', { maxAgeSeconds: 0, secure: true });\nconsole.log(expiredCookie);\n```\n\n---\n\n### `isWellFormedText`\n\nChecks text for control characters and lone UTF-16 surrogates.\n\n```ts\nfunction isWellFormedText(value: string): boolean;\n```\n\n**Returns:** `true` when `ILL_FORMED_TEXT` does not match; it does not trim or impose bounds.\n\n**Example:** validate text independently of the alias schema.\n\n```ts\nimport { isWellFormedText } from '@vielzeug/archive';\n\nconsole.log(isWellFormedText('Rice'), isWellFormedText('\\u0000'));\n```\n\n### `ARCHIVE_LIMITS`\n\n`ARCHIVE_LIMITS` is frozen with these values:\n\n```ts\nconst limits = {\n aliasChars: 24, cursorChars: 1024, idempotencyRetentionMs: 172800000,\n likeStateIds: 50, maxPageSize: 50, maxPublications: 50, pageSize: 10,\n payloadBytes: 8192, publicCacheSeconds: 30, reportReasonChars: 256,\n requestBytes: 12288, searchChars: 64, searchTerms: 6, tagsPerEntry: 16,\n titleChars: 128, vocabChars: 64,\n};\n```\n\n## Types\n\nThe following definitions use `Schema` from `@vielzeug/spell`. Schema-derived aliases show their complete output shape.\n\n```ts\ninterface ArchiveIndexing<F extends string = string, T extends string = string> {\n filter: F | null;\n tags: readonly T[];\n title: string;\n}\ninterface ArchiveCollectionDefinition<\n P extends object, C extends number, F extends string = never, T extends string = never,\n> {\n canonicalize?(payload: P): P;\n contentVersion: C;\n filters?: readonly F[];\n index(payload: P): ArchiveIndexing<NoInfer<F>, NoInfer<T>>;\n name: string;\n payloadSchema: Schema<P, unknown>;\n tags?: readonly T[];\n}\ninterface ArchiveDerivation {\n canonicalJson: string;\n contentHash: string;\n contentVersion: number;\n filter: string | null;\n tags: readonly string[];\n title: string;\n}\ninterface ArchiveEntry<P = unknown, C extends number = number> {\n author: { id: string; name: string };\n contentHash: string;\n contentVersion: C;\n id: string;\n likeCount: number;\n payload: P;\n publishedAt: string;\n revision: number;\n schemaVersion: typeof ARCHIVE_CONTRACT_VERSION;\n updatedAt: string;\n}\ninterface ArchiveOwnedEntry<P = unknown, C extends number = number> extends ArchiveEntry<P, C> {\n clientKey: string;\n hidden: boolean;\n}\ninterface ArchiveContract<P = unknown, C extends number = number> {\n entry: Schema<ArchiveEntry<P, C>>;\n ownedEntries: Schema<{ entries: ArchiveOwnedEntry<P, C>[] }>;\n ownedEntry: Schema<ArchiveOwnedEntry<P, C>>;\n page: Schema<ArchivePage<ArchiveEntry<P, C>>>;\n publishInput: Schema<{ clientKey: string; payload: P }, unknown>;\n updateInput: Schema<{ expectedRevision: number; payload: P }, unknown>;\n}\ninterface ArchiveCollection<P extends object = object, C extends number = number> {\n readonly contentVersion: C;\n readonly contract: ArchiveContract<P, C>;\n readonly derive: (raw: unknown) => Promise<ArchiveDerivation | null>;\n readonly filters: readonly string[];\n readonly name: string;\n readonly tags: readonly string[];\n}\ninterface ArchivePage<T> {\n cursor: string | null;\n entries: readonly T[];\n}\ntype ArchiveSort = 'liked' | 'recent';\ntype ArchiveDerivationStage = 'canonicalize' | 'hash' | 'index' | 'schema';\ntype ArchiveIdentity = { id: string; name: string; operator: boolean } | null;\ntype ArchiveAccount = {\n id: string; email: string; createdAt: string; lastSignInAt: string | null;\n};\ntype ArchiveCollectionMeta = { filters: string[]; name: string; tags: string[] };\ntype ArchiveLikesPage = { cursor: string | null; ids: string[] };\ntype ArchiveErrorCode =\n | 'account-changed' | 'auth-unavailable' | 'bad-request' | 'conflict' | 'forbidden' | 'gone'\n | 'internal' | 'invalid-payload' | 'likes-disabled' | 'method-not-allowed'\n | 'not-found' | 'publisher-changed' | 'publishing-disabled' | 'quota'\n | 'rate-limited' | 'record-unavailable' | 'timeout' | 'too-large'\n | 'unauthenticated' | 'unavailable' | 'unsupported-media';\ntype ArchiveErrorResponse = {\n error: { code: ArchiveErrorCode; message: string; requestId: string };\n};\ntype ArchiveHealth = {\n dbSchemaVersion: number | null;\n features: { likes: boolean; publishing: boolean };\n limits: {\n aliasChars: number; cursorChars: number; idempotencyRetentionMs: number;\n likeStateIds: number; maxPageSize: number; maxPublications: number;\n pageSize: number; payloadBytes: number; publicCacheSeconds: number;\n reportReasonChars: number; requestBytes: number; searchChars: number;\n searchTerms: number; tagsPerEntry: number; titleChars: number; vocabChars: number;\n };\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype AuthHealth = {\n dbSchemaVersion: number | null;\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype ArchiveReports = {\n cursor: string | null;\n reports: {\n id: string; createdAt: string; entryId: string; entryTitle: string;\n reason: string; reporter: { id: string; name: string }; resolvedAt: string | null;\n }[];\n};\ntype ArchiveOwnReports = {\n cursor: string | null;\n reports: {\n collection: string; createdAt: string; entryId: string; id: string;\n reason: string; resolvedAt: string | null;\n }[];\n};\ntype ArchiveModerationAction = 'hide' | 'unhide' | 'remove' | 'erase-publisher';\ntype ArchiveModerationLog = {\n cursor: string | null;\n actions: {\n id: string; action: ArchiveModerationAction; collection: string | null;\n createdAt: string; operatorId: string; targetId: string;\n }[];\n};\n```\n\nWorker subpath types model only the binding methods the catalog calls.\n\n```ts\ninterface D1Statement {\n all<T>(): Promise<{ results?: T[] }>;\n bind(...params: (string | number | null)[]): D1Statement;\n first<T>(): Promise<T | null>;\n run(): Promise<{ meta?: { changes?: number } }>;\n}\ninterface D1Like {\n batch(statements: D1Statement[]): Promise<{ meta?: { changes?: number } }[]>;\n prepare(sql: string): D1Statement;\n}\ninterface RateLimiterBinding {\n limit(input: { key: string }): Promise<{ success: boolean }>;\n}\ninterface ArchiveWorkerEnv {\n AUTH_ISSUER_SERVICE: AuthIssuerServiceBinding;\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n DB: D1Like;\n JWT_AUDIENCE: string;\n JWT_ISSUER: string;\n JWT_JWKS_URL: string;\n LIKES_ENABLED: string;\n PUBLISHING_ENABLED: string;\n RATE_LIMIT_KEY_SECRET: string;\n READ_LIMIT: RateLimiterBinding;\n WRITE_LIMIT: RateLimiterBinding;\n}\ninterface AuthIssuerServiceBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface ArchiveExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\ntype ArchiveDiagnostic =\n | { readonly kind: 'configuration'; readonly field: string }\n | { readonly kind: 'database' | 'record' | 'schema' | 'internal' | 'cache' | 'collection' };\ninterface ArchiveRequestEvent {\n code: ArchiveErrorCode | 'ok';\n diagnostic?: ArchiveDiagnostic;\n ms: number;\n requestId: string;\n route: string;\n status: number;\n type: 'request';\n}\ntype ArchiveScheduledEvent =\n | { removed: number; type: 'scheduled'; status: 'ok' }\n | { type: 'scheduled'; status: 'failed'; diagnostic: ArchiveDiagnostic };\ntype ArchiveEvent =\n | ArchiveRequestEvent\n | ArchiveScheduledEvent\n | { readonly type: 'cache-error'; readonly diagnostic: ArchiveDiagnostic };\ninterface ArchiveWorkerHandler<E extends ArchiveWorkerEnv = ArchiveWorkerEnv> {\n fetch(request: Request, env: E, ctx: ArchiveExecutionContext): Promise<Response>;\n scheduled?(controller: unknown, env: E, ctx: ArchiveExecutionContext): void | Promise<void>;\n tap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n```\n\nScheduled `removed` counts the combined expired retry-key and revocation rows.\n\nAuth subpath types describe the sibling issuer and its required service binding.\n\n```ts\ninterface SendEmail {\n send(message: { from: string; html?: string; subject: string; text: string; to: string }): Promise<unknown>;\n}\ninterface AuthArchiveBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface AuthWorkerEnv {\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n APP_NAME: string;\n AUDIENCE: string;\n AUTH_ARCHIVE: AuthArchiveBinding;\n AUTH_DB: D1Like;\n AUTH_EMAIL: SendEmail;\n AUTH_ISSUER: string;\n AUTH_JWT_PREVIOUS_PUBLIC_JWKS?: string;\n AUTH_JWT_PRIVATE_JWK: string;\n OPERATOR_EMAILS: string;\n PUBLIC_ORIGIN: string;\n SENDER_ADDRESS: string;\n}\ninterface AuthWorkerHandler<E extends AuthWorkerEnv = AuthWorkerEnv> {\n fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise<Response>;\n scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise<void>;\n tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\ntype AuthDiagnostic = {\n readonly kind: 'configuration' | 'database' | 'email' | 'catalog' | 'internal';\n};\ntype AuthEvent =\n | {\n readonly type: 'request';\n readonly requestId: string;\n readonly route:\n | '/auth/account'\n | '/auth/health'\n | '/auth/jwks.json'\n | '/auth/session'\n | '/auth/sign-in'\n | '/auth/sign-out-all'\n | '/auth/verify'\n | 'unmatched';\n readonly status: number;\n readonly code: ArchiveErrorCode | 'ok';\n readonly ms: number;\n readonly diagnostic?: AuthDiagnostic;\n }\n | { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }\n | { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };\n```\n\nIssuer scheduled `removed` counts expired token rows, closed per-user send windows\nand deleted unverified accounts. The singleton admission row is retained and its\nwindow resets atomically on a later sign-in request.\n\n## Errors\n\n| Exported class | Trigger | Properties |\n| --- | --- | --- |\n| `ArchiveError` | Base for public package errors | `name`, `message`, optional `cause` |\n| `ArchiveDefinitionError` | Invalid collection definition or duplicate registered collection names | Extends `ArchiveError` |\n| `ArchiveDerivationError` | Unexpected schema/canonicalization/index/hash fault or violated collection invariant | Extends `ArchiveError`; readonly `stage: ArchiveDerivationStage`; optional `cause` |\n\n`ArchiveError` and `ArchiveDefinitionError` accept `(message: string, opts?: ErrorOptions)`.\n`ArchiveDerivationError` accepts `(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions)`.\nIts message and cause are local diagnostics, not response content. Worker request\nfailures use the wire envelope, not these thrown classes. Internal `ApiError` and\n`AuthOperationError` are not exported.\n\nStored entries that fail the current wire schema return 503 `record-unavailable`.\nStored payloads are canonical by construction, so the emitted entry schemas embed\nthe plain payload schema: parsing a response re-runs that schema, and an\nexception from one of its callbacks becomes a sanitized 500.\n\nThe complete public error signatures are:\n\n```ts\nclass ArchiveError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\nclass ArchiveDefinitionError extends ArchiveError {}\nclass ArchiveDerivationError extends ArchiveError {\n readonly stage: ArchiveDerivationStage;\n constructor(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions);\n}\n```\n\nCatalog rate-limit responses use `Retry-After: 60`; configure catalog limiter periods to 60 seconds. Issuer admission/send-budget responses instead carry seconds until their durable window reopens. Health's degraded response is the health DTO, not an error envelope: schema mismatch reports the observed version; database unavailability reports `dbSchemaVersion: null`.\n",
|
|
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', 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.\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: the magic-link email's subject and copy name it |\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.\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 900\nseconds, 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 `/signed-in`. The\nredemption update and account 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`.\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)\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. Moderation routes additionally require a registered publisher row: one\naccountable 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\npnpm vitest run packages/archive/src/__tests__/ # fast unit suite\npnpm --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage\npnpm --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",
|
|
5
|
+
"api": "---\ntitle: 'Archive: API Reference'\ndescription: 'Collection definitions, browser-safe wire schemas, Worker deployment, and identity issuance.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------------------- | ------------------------------------------------------- | -------------- | --------------------------------------------------------------- |\n| `defineArchiveCollection` | Compose validation, indexing, identity and wire schemas | Sync | Invalid content derives to `null`; callback faults throw |\n| `createArchiveWorker` | Build the catalog Worker | Sync | Collection names must be unique |\n| `createAuthWorker` | Build the passwordless issuer | Sync | `AUTH_ARCHIVE` is required |\n| `worker.tap`, `issuer.tap` | Observe sanitized runtime outcomes | Sync | Neither core logs by default; observer exceptions are swallowed |\n| `ArchiveDerivationError` | Identify a collection implementation/runtime fault | Sync | Faults become sanitized 500s, not content-validation 422s |\n| `ARCHIVE_LIMITS` | Shared application bounds | Sync | Page bounds do not cap total exports |\n| `archiveErrorResponseSchema`, `archiveAuthHealthSchema` | Validate error and issuer-health responses | Sync | Unknown error codes and health states reject |\n| `ArchiveError`, `ArchiveDefinitionError` | Public base and invalid-definition errors | Sync | Thrown locally, not transmitted as error objects |\n| `sessionCookieValue` | Compose shared session-cookie attributes | Sync | Deployments must choose `secure` from their environment |\n| `isWellFormedText` | Check control characters and lone surrogates | Sync | Does not trim or impose a length bound |\n\n## Package Entry Point\n\n| Import | Purpose |\n| -------------------------- | --------------------------------------------------------------------------- |\n| `@vielzeug/archive` | Browser-safe collections, constants, schemas and errors |\n| `@vielzeug/archive/worker` | Catalog factory, issuer signing-key/session service binding and event types |\n| `@vielzeug/archive/auth` | Issuer factory and binding types |\n\n## Collections\n\n### `defineArchiveCollection`\n\nCreates a frozen collection and its contract; malformed names, versions or vocabularies throw `ArchiveDefinitionError`.\n\n```ts\nfunction defineArchiveCollection<\n P extends object,\n const C extends number,\n const F extends string = never,\n const T extends string = never,\n>(definition: ArchiveCollectionDefinition<P, C, F, T>): ArchiveCollection<P, C>;\n```\n\n| Parameter | Contract |\n| ----------------- | --------------------------------------------------------------------------- |\n| `name` | Lowercase `[a-z0-9-]{1,32}` |\n| `contentVersion` | Positive safe integer |\n| `payloadSchema` | Spell schema whose output is a stable JSON object |\n| `filters`, `tags` | Optional readonly arrays; omitted means empty vocabulary |\n| `canonicalize` | Optional pure, idempotent, schema-valid normalization |\n| `index` | Derive `filter`, `tags` and searchable `title` without mutating the payload |\n\n**Returns:** `ArchiveCollection<P, C>`.\n\n**Example:** define and derive one collection without Worker bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst recipes = defineArchiveCollection({\n name: 'recipes',\n contentVersion: 1,\n payloadSchema: s.object({ name: s.string().min(1).max(32) }),\n index: (payload) => ({ filter: null, tags: [], title: payload.name }),\n});\nconst derived = await recipes.derive({ name: 'Rice' });\nif (derived === null) throw new Error('Invalid recipe');\nconsole.log(derived.contentHash);\n```\n\n| Method / property | Result |\n| -------------------------------------- | --------------------------------------------------- |\n| `derive(raw)` | `Promise<ArchiveDerivation \\| null>` |\n| `contract.entry` | Public entry schema |\n| `contract.ownedEntry`, `ownedEntries` | Owner view with `clientKey` and `hidden` |\n| `contract.page` | Entries and the forward cursor |\n| `contract.publishInput`, `updateInput` | Publish and revision-guarded update request schemas |\n| `filters`, `tags` | Frozen vocabulary snapshots |\n\n`derive` returns `null` for invalid JSON objects, schema-invalid input, invalid titles, too many tags and oversized canonical payloads. Unexpected schema, callback or hashing failures throw `ArchiveDerivationError`. Non-idempotent or schema-invalid canonicalization, unstable schema transformations, index mutation and out-of-vocabulary projections are also derivation faults. Routes map `null` to 422 `invalid-payload` and faults to a sanitized 500 `internal`.\nSchema output that is lossy or no longer JSON is a derivation fault, not invalid\nsubmitted content. Invalid index-result shapes also throw.\n\nConst generics preserve the content-version literal and infer filter/tag unions from vocabulary arrays without `as const`. `NoInfer` prevents `index` from widening those unions; omitted arrays infer `never`, permitting only `filter: null` and empty tags.\n\nObjects serialize with recursively sorted keys; arrays preserve order unless your canonicalizer changes it. SHA-256 hashes the core-owned `{contentVersion, payload}` envelope. Stored payloads are canonical by construction, so the emitted entry schemas embed the plain payload schema.\n\n`filter`, tags and searchable title are persisted projections, not computed during reads. Changing `index` or its vocabulary does not update stored rows. The active definition and persisted dataset must remain consistent; Archive has no projection-update or historical-schema API.\n\n## Worker and Maintenance\n\n### `createArchiveWorker`\n\nReturns the catalog request/scheduled handler and its observation side channel.\n\n```ts\nfunction createArchiveWorker<E extends ArchiveWorkerEnv>(\n collections: readonly ArchiveCollection[],\n): ArchiveWorkerHandler<E>;\n```\n\n**Returns:** `ArchiveWorkerHandler<E>`; duplicate names throw `ArchiveDefinitionError` at registration.\n\n**Example:** export a deployable Worker using the package's structural bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes',\n contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createArchiveWorker<ArchiveWorkerEnv>([notes]);\n```\n\n| Method | Contract |\n| --------------------------------- | -------------------------------------------------------------------------------- |\n| `fetch(request, env, ctx)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx)` | Sweeps expired retry keys and revocation tombstones; emits failures and rethrows |\n| `tap(handler, { signal? }?)` | Returns unsubscribe; a pre-aborted signal registers nothing |\n\n`AUTH_ISSUER_SERVICE` is a required `fetch`-shaped service binding to the issuer.\nThe catalog fetches signing keys from the configured `JWT_JWKS_URL` through that\nbinding, not through global `fetch`. The URL still selects the issuer's JWKS\nroute and must satisfy the environment's transport rules. Key requests use GET\nwithout a session cookie and do not follow redirects.\nThe catalog verifies the signed JWT locally, then asks the issuer to validate its\ncurrent account session version. JOSE caches signing keys; the catalog does not\ncache successful issuer session verdicts.\nIf the service exchange fails or exceeds its fixed 5000 ms timeout (body decoding\nincluded), the catalog returns `503 auth-unavailable`; the timeout does not cancel\nwork already started by the issuer.\n\nOnly anonymous entry lists can use the 30-second edge cache. Any `Cookie` or `Authorization` header disables caching, even if invalid or empty. Detail, metadata, private and error responses are `no-store`. Public reads do not verify sessions.\n\n---\n\n### `worker.tap`\n\nObserves typed request, scheduled and cache-failure events without affecting request behavior.\n\n```ts\ntap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n```\n\n**Returns:** an unsubscribe function; abort detaches the observer. Diagnostics contain categories and trusted configuration field names, never raw errors, SQL, subjects, aliases, tokens or URLs.\n\n**Example:** observe a Worker and detach explicitly.\n\n```ts\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\n\nconst worker = createArchiveWorker<ArchiveWorkerEnv>([]);\nconst stop = worker.tap((event) => console.log(JSON.stringify(event)));\nstop();\n```\n\n---\n\n## Identity Issuer\n\n### `createAuthWorker`\n\nReturns the passwordless email issuer with account export and coordinated erasure.\n\n```ts\nfunction createAuthWorker<E extends AuthWorkerEnv>(): AuthWorkerHandler<E>;\n```\n\n**Returns:** `AuthWorkerHandler<E>`.\n\n**Example:** export an issuer configured through deployment bindings.\n\n```ts\nimport { createAuthWorker, type AuthWorkerEnv } from '@vielzeug/archive/auth';\n\nexport default createAuthWorker<AuthWorkerEnv>();\n```\n\n| Method | Contract |\n| ---------------------------------- | ------------------------------------------------------------------------------- |\n| `fetch(request, env, ctx?)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx?)` | Removes expired links, closed send windows and unverified unreferenced accounts |\n| `tap(handler, { signal? }?)` | Observes typed `AuthEvent`; returns unsubscribe; pre-aborted signals are inert |\n\nMagic links expire after 15 minutes and work once. The durable per-email budget allows three sends per hour; consumption, expiration and send failure do not refund it. Ordinary sessions last at most 30 days. Operator sessions use `OPERATOR_SESSION_MAX_AGE_SECONDS` (900 seconds). `OPERATOR_EMAILS` controls newly minted role claims.\n\nThe issuer-global admission budget is durable D1 state in `auth_sign_in_budget`:\n20 requests per 60-second window before account creation or email delivery.\nThis supplements, rather than replaces, the durable per-email budget. No external\nrate-limiter binding is required.\nAdmission spends are not refunded after later database or email failures.\nRequest emails are trimmed and lowercased before validation. `SENDER_ADDRESS`\nmust already be canonical; `OPERATOR_EMAILS` entries are trimmed and lowercased\nbefore validation.\n\nSign-in requests create pending account rows with `lastSignInAt: null`. Successful\nredemption atomically claims the one-use link and stamps the account's sign-in\ntime. The sweep deletes expired links and closed per-user send windows, then\nunverified accounts with neither remaining links nor send-budget references.\nVerified accounts are retained until explicit account deletion.\n\n`OPERATOR_SESSION_MAX_AGE_SECONDS = 900` is part of the browser-safe root\ncontract; `/auth` exports the factory and issuer binding types.\n\n`AUTH_JWT_PREVIOUS_PUBLIC_JWKS` optionally publishes retired public RS256 keys and verifies sessions minted before rotation; private members reject configuration. The package has no demo sign-in routes.\n\nOpening a magic link performs a safe GET that displays a click-confirmation page,\nnot redemption. Only a marked POST from an exact allowed origin or\n`PUBLIC_ORIGIN` consumes `{ token }` and returns 204 with the session cookie. The\nconfirmation page navigates to the fixed `${PUBLIC_ORIGIN}/signed-in` destination;\nyour application must serve that page because the issuer serves only the\nconfirmation endpoint. The POST is not a redirect. Confirmation responses are\n`no-store` with no-referrer and a restrictive CSP; inline script and styles\nrequire a fresh response nonce, with no\n`unsafe-inline`. The page removes the token from the address bar before rendering\nthe controls and loads no external assets. `APP_NAME` supplies escaped page and\nemail branding; the confirmation has keyboard focus, live status announcements,\n44-pixel minimum action heights, a warm near-white paper and copper light scheme,\na deep neutral dark scheme, serif headings, sans-serif body text and reduced-motion\nstyles. Without JavaScript, it links to `${PUBLIC_ORIGIN}/account` as “Request a\nnew sign-in link” but cannot redeem a link.\nGET displays confirmation for any syntactically valid token, including a used\ntoken; only POST establishes whether the link is still redeemable. POST accepts\nexactly `{ token }` and rejects query parameters. With valid issuer configuration,\ninvalid or missing GET tokens, duplicate token parameters and unsupported query\nparameters return HTTP 400 with branded HTML recovery, not a JSON error. POST\nerrors retain the JSON `ArchiveErrorResponse` schema and their HTTP status.\n\nThe button announces pending sign-in and blocks duplicate submissions. HTTP 410\nreplaces it with a new-link action; HTTP 400 also disables resubmission. Every\nfailure offers the fixed `${PUBLIC_ORIGIN}/account` recovery link labelled\n“Request a new sign-in link”. Like `/signed-in`, `/account` is a fixed reference\nissuer convention: the application must serve its sign-in entry there, not the issuer.\nRecovery is secondary while retry remains possible, and becomes the primary action\nfor invalid or expired links. It replaces the footer exit link to avoid duplicate\nnavigation. The initial “Back to app” footer links to `${PUBLIC_ORIGIN}/`.\nHTTP 429 delays manual retry using unsigned integer seconds or a syntactically valid\nHTTP-date `Retry-After`, rounded up\nand bounded to 1-300 seconds (30 seconds for missing or invalid values). HTTP 503\nand network failures offer explicit retry; no failure starts an automatic request.\nAll returned response bodies, including discarded stale responses, are cancelled\nwithout delaying recovery; cancellation failures are ignored. Each attempt aborts\nits controller on completion. Stalled requests abort after 15 seconds with a\ntimeout-specific message, distinct from connection failures. Leaving the page aborts its request and\nclears timers; bfcache restoration resumes only the remaining cooldown, not a\nrequest. Navigation after exact 204 success is fixed at\n`${PUBLIC_ORIGIN}/signed-in`; query input never controls either destination.\n\nThe issuer never logs directly. `tap` emits sanitized request and scheduled\noutcomes; observer failures are swallowed, abort detaches the observer and failed\nscheduled work emits then rethrows. `AuthDiagnostic` reports only a category.\n\n## HTTP Routes\n\nEvery route below is mounted under `/api/v1`. Mutation guards require an exact allowed `Origin` and `x-archive-request: 1`. Registered publishers pin `x-archive-publisher` to the identity captured when preparing private requests. The header is a freshness precondition, not authority.\n\n| Route | Contract |\n| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `GET /health` | Public catalog readiness; 200 `ok` or 503 `degraded` |\n| `POST /sign-out` | Catalog-local sign-out; `{ ok: true }` and expired session cookie, without issuer access |\n| `GET /collections/:collection` | Collection metadata |\n| `GET /collections/:collection/entries` | `author`, `filter`, `tag`, `search`, `sort`, `cursor`, `limit`; forward entry page |\n| `POST /collections/:collection/entries` | `{ clientKey, payload }`; 201 create or 200 replay |\n| `GET /collections/:collection/entries/:id` | Public entry; always `no-store` |\n| `PUT /collections/:collection/entries/:id` | Owner-only `{ expectedRevision, payload }` |\n| `DELETE /collections/:collection/entries/:id` | Owner or operator removal; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/like` | Like / unlike visible entries only; guarded write and response; like-state response |\n| `POST /collections/:collection/entries/:id/report` | `{ reason }`; idempotent per entry/reporter; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/hidden` | Operator hide / unhide; 204 |\n| `GET /collections/:collection/reports` | Operator page; `status=unresolved` (default) or `resolved`, `cursor`, `limit` |\n| `PUT /collections/:collection/reports/:id/resolved` | Operator resolves report by its unique report ID; idempotent 204 |\n| `DELETE /publishers/:id` | Operator erases Archive profile; not issuer account |\n| `GET /moderation-log` | Operator forward page; `cursor`, `limit` |\n| `GET` / `POST` / `PUT /me` | Identity, register with optional `{ name }`, rename with required `{ name }` |\n| `DELETE /me` | Profile-only cascade; 204; does not clear cookie |\n| `DELETE /me/account` | Revoke issuer/subject and atomically erase profile; 204; coordinated issuer-erasure seam |\n| `GET /me/publications?collection=…` | Owner entries including hidden state and retry keys |\n| `GET /me/likes` | Forward page `{ ids, cursor }`; `cursor`, `limit` |\n| `GET /me/likes?ids=…` | Subset lookup `{ ids }`; at most `likeStateIds` input IDs |\n| `GET /me/reports` | Own forward report page across collections; `cursor`, `limit` |\n| `GET /auth/health` | Public issuer readiness; typed `AuthHealth`, 200 `ok` or 503 `degraded`; no email or peer probe |\n| `GET /auth/session` | Internal issuer-session check for the catalog service binding; exact `{ ok: true }`, `no-store`, no PII; 401 for an invalid, stale or absent-account session |\n| `POST /auth/sign-out-all` | Requires marker, exact origin, session and captured `ACCOUNT_HEADER`; atomically increments `session_version`, deletes outstanding links, preserves account and catalog data; 200 `{ ok: true }` with an expired cookie only on durable success |\n| `GET /auth/jwks.json` | Active and configured retired public verification keys |\n| `POST /auth/sign-in` | `{ email }` (trimmed and lowercased); 202 `{ ok: true }` |\n| `GET /auth/verify?token=…` | Safe no-store click-confirmation HTML; with valid issuer configuration, invalid queries return 400 recovery HTML; no token consumption or session change |\n| `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |\n| `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |\n| `DELETE /auth/account` | Requires `ACCOUNT_HEADER` with the captured issuer account UUID; catalog `/me/account` via `AUTH_ARCHIVE`, require exact 204, then issuer user and cookie clear; 204 |\n\nForward pages are newest first with opaque context-bound keyset cursors. Keep the same query context when following a cursor; end at `cursor: null`. `maxPageSize` bounds each page, not the total number of liked IDs, reports or audit actions you can export. The subset-like query is not a page and cannot combine `ids` with `cursor` or `limit`.\n\nFull erasure creates an issuer/subject revocation tombstone for 30 days plus ten\nseconds and deletes the profile in the same transaction. Catalog authentication\nrejects that subject with 401 on ordinary private routes; registration also checks\nrevocation in SQL to prevent resurrection races. Only `DELETE /me/account` may\nbypass the issuer session lookup, and only to retry erasure with the original\nsigned session of the same principal while its existing revocation tombstone is\nvalid; JWT signature and claims are still verified. It is not a general\nstale-session exception: initial erasure validates the issuer session. The\nissuer-facing `DELETE /auth/account` always checks the current session version\nbefore calling the catalog, so retrying it after completed erasure returns 401\nbecause the account is absent.\nDirect profile-only `DELETE /me` allows later registration using the same session.\nThe sweep removes expired tombstones. Re-enrollment through the reference issuer\ncreates a fresh account UUID subject; an external issuer must issue a new subject\nto re-enroll during the revocation window.\n\nThe issuer stores `auth_users.session_version` as a safe non-negative integer,\ndefaulting to `0`. Every session JWT carries the current value as the required\n`sessionVersion` claim. Each ordinary issuer-authenticated route compares that\nclaim to the current account row; a mismatch is unauthenticated. `POST\n/api/v1/auth/sign-out-all` checks the captured issuer account UUID against the\nverified subject before atomically incrementing the version and deleting pending\nlinks. A changed account answers 409 `account-changed`; a failed request does not\nclear the cookie. This revokes all sessions, including the caller's, after a\nsuccessful response. Requests authorized before revocation may finish; there is\nno cross-database transactional or in-flight cancellation guarantee.\n\nThe catalog requires `AUTH_ISSUER_SERVICE`, a service binding to the issuer for\nboth JWKS retrieval and live session validation. Signing-key retrieval uses\n`JWT_JWKS_URL` through the binding, so it does not depend on a public same-zone\nWorker-to-Worker fetch. After local JWT signature/claims verification, it requests\n`GET /api/v1/auth/session` through that binding on every private request. Only a\nstrictly validated 401 `unauthenticated` remains a 401. Malformed, unexpected,\nprovider and 5xx responses become 503 `auth-unavailable`; there is no authority\ncache. Both service directions use a fixed 5000 ms timeout that includes body\ndecoding. The issuer's `/api/v1/auth/session` is an internal\nservice contract, not a frontend session API.\n\nIssuer readiness is independent of catalog readiness. `GET\n/api/v1/auth/health` returns `archiveAuthHealthSchema` as `AuthHealth`; its\nread-only probe checks configuration, a signing and verification key proof,\nbinding shapes, the singleton `auth_schema_meta` stamp against\n`AUTH_SCHEMA_VERSION`, and readability of expected tables, columns and triggers.\nIt does not write, send email or probe the catalog service. Responses are\nsanitized.\nConfiguration failure, database failure and schema mismatch return HTTP 503\nwith `status: 'degraded'` and the corresponding reason.\n\nEffective hide, unhide, operator removal and publisher erasure append audit rows atomically with the state transition. Concurrent idempotent no-ops append nothing. Audit rows contain opaque IDs, not names or content, and have no foreign keys so they outlive erasure. Resolving a report sets `resolvedAt`; it is not one of the four audit action kinds.\n\n## Constants and Schemas\n\n| Export | Value or parsed output |\n| ------------------------------------------------------------- | -------------------------------------------------------------------------- |\n| `ARCHIVE_CONTRACT_VERSION`, `ARCHIVE_SCHEMA_VERSION` | Both debut at `1`; wire and storage versions are independent |\n| `AUTH_SCHEMA_VERSION` | `1`; issuer DDL stamp checked by `/auth/health` |\n| `ARCHIVE_COLLECTION_NAME_PATTERN` | `/^[a-z0-9-]{1,32}$/` |\n| `ARCHIVE_OPERATOR_ROLE` | `'archive-operator'` |\n| `SESSION_COOKIE_NAME`, `SESSION_COOKIE_PATH` | `'archive_session'`, `'/api/v1'` |\n| `SESSION_MAX_AGE_SECONDS` | `2592000` |\n| `OPERATOR_SESSION_MAX_AGE_SECONDS` | `900`; shared root contract |\n| `ACCOUNT_HEADER` | `'X-Archive-Account'`; required issuer-account UUID on coordinated erasure |\n| `PUBLISHER_HEADER`, `REQUEST_MARKER_HEADER` | `'x-archive-publisher'`, `'x-archive-request'` |\n| `ILL_FORMED_TEXT`, `isWellFormedText(value: string): boolean` | Reject control characters and lone UTF-16 surrogates |\n| `uuidSchema`, `isoTimestampSchema`, `hex64Schema` | UUID, ISO timestamp, lowercase SHA-256 hex strings |\n| `archiveAliasSchema` | Trimmed, well-formed alias of at most 24 characters |\n| `archiveAuthorSchema` | `{ id: string; name: string }` |\n| `archiveIdentitySchema` | `ArchiveIdentity` |\n| `archiveAccountSchema` | `ArchiveAccount`; issuer metadata, excluding private fields |\n| `archiveLimitsSchema` | All numeric `ARCHIVE_LIMITS` fields |\n| `archiveHealthSchema` | `ArchiveHealth` |\n| `archiveAuthHealthSchema` | `AuthHealth` |\n| `archiveErrorResponseSchema` | `ArchiveErrorResponse` |\n| `archiveOkSchema` | `{ ok: true }` |\n| `archiveCollectionMetaSchema` | `ArchiveCollectionMeta` |\n| `archiveLikedIdsSchema` | `{ ids: string[] }` subset response |\n| `archiveLikesPageSchema` | `ArchiveLikesPage` |\n| `archiveLikeStateSchema` | `{ id: string; likeCount: number; liked: boolean }` |\n| `archiveReportsSchema`, `archiveOwnReportsSchema` | `ArchiveReports`, `ArchiveOwnReports` |\n| `archiveModerationLogSchema` | `ArchiveModerationLog` |\n| `archiveSortSchema` | `ArchiveSort` |\n| `ARCHIVE_ERROR_CODES` | Values of `ArchiveErrorCode` below |\n| `ARCHIVE_MODERATION_ACTIONS` | `['hide', 'unhide', 'remove', 'erase-publisher']` |\n\n### `sessionCookieValue`\n\nComposes a session cookie using the shared security attributes.\n\n```ts\nfunction sessionCookieValue(token: string, options: { maxAgeSeconds: number; secure: boolean }): string;\n```\n\n| Parameter | Contract |\n| ----------------------- | -------------------------------------------- |\n| `token` | Session token, or empty string when clearing |\n| `options.maxAgeSeconds` | Cookie lifetime; `0` clears it |\n| `options.secure` | Include `Secure` for production HTTPS |\n\n**Returns:** the `Set-Cookie` value with `HttpOnly`, `SameSite=Strict`, the shared path and optional `Secure`.\n\n**Example:** clear the production cookie.\n\n```ts\nimport { sessionCookieValue } from '@vielzeug/archive';\n\nconst expiredCookie = sessionCookieValue('', { maxAgeSeconds: 0, secure: true });\nconsole.log(expiredCookie);\n```\n\n---\n\n### `isWellFormedText`\n\nChecks text for control characters and lone UTF-16 surrogates.\n\n```ts\nfunction isWellFormedText(value: string): boolean;\n```\n\n**Returns:** `true` when `ILL_FORMED_TEXT` does not match; it does not trim or impose bounds.\n\n**Example:** validate text independently of the alias schema.\n\n```ts\nimport { isWellFormedText } from '@vielzeug/archive';\n\nconsole.log(isWellFormedText('Rice'), isWellFormedText('\\u0000'));\n```\n\n### `ARCHIVE_LIMITS`\n\n`ARCHIVE_LIMITS` is frozen with these values:\n\n```ts\nconst limits = {\n aliasChars: 24,\n cursorChars: 1024,\n idempotencyRetentionMs: 172800000,\n likeStateIds: 50,\n maxPageSize: 50,\n maxPublications: 50,\n pageSize: 10,\n payloadBytes: 8192,\n publicCacheSeconds: 30,\n reportReasonChars: 256,\n requestBytes: 12288,\n searchChars: 64,\n searchTerms: 6,\n tagsPerEntry: 16,\n titleChars: 128,\n vocabChars: 64,\n};\n```\n\n## Types\n\nThe following definitions use `Schema` from `@vielzeug/spell`. Schema-derived aliases show their complete output shape.\n\n```ts\ninterface ArchiveIndexing<F extends string = string, T extends string = string> {\n filter: F | null;\n tags: readonly T[];\n title: string;\n}\ninterface ArchiveCollectionDefinition<\n P extends object,\n C extends number,\n F extends string = never,\n T extends string = never,\n> {\n canonicalize?(payload: P): P;\n contentVersion: C;\n filters?: readonly F[];\n index(payload: P): ArchiveIndexing<NoInfer<F>, NoInfer<T>>;\n name: string;\n payloadSchema: Schema<P, unknown>;\n tags?: readonly T[];\n}\ninterface ArchiveDerivation {\n canonicalJson: string;\n contentHash: string;\n contentVersion: number;\n filter: string | null;\n tags: readonly string[];\n title: string;\n}\ninterface ArchiveEntry<P = unknown, C extends number = number> {\n author: { id: string; name: string };\n contentHash: string;\n contentVersion: C;\n id: string;\n likeCount: number;\n payload: P;\n publishedAt: string;\n revision: number;\n schemaVersion: typeof ARCHIVE_CONTRACT_VERSION;\n updatedAt: string;\n}\ninterface ArchiveOwnedEntry<P = unknown, C extends number = number> extends ArchiveEntry<P, C> {\n clientKey: string;\n hidden: boolean;\n}\ninterface ArchiveContract<P = unknown, C extends number = number> {\n entry: Schema<ArchiveEntry<P, C>>;\n ownedEntries: Schema<{ entries: ArchiveOwnedEntry<P, C>[] }>;\n ownedEntry: Schema<ArchiveOwnedEntry<P, C>>;\n page: Schema<ArchivePage<ArchiveEntry<P, C>>>;\n publishInput: Schema<{ clientKey: string; payload: P }, unknown>;\n updateInput: Schema<{ expectedRevision: number; payload: P }, unknown>;\n}\ninterface ArchiveCollection<P extends object = object, C extends number = number> {\n readonly contentVersion: C;\n readonly contract: ArchiveContract<P, C>;\n readonly derive: (raw: unknown) => Promise<ArchiveDerivation | null>;\n readonly filters: readonly string[];\n readonly name: string;\n readonly tags: readonly string[];\n}\ninterface ArchivePage<T> {\n cursor: string | null;\n entries: readonly T[];\n}\ntype ArchiveSort = 'liked' | 'recent';\ntype ArchiveDerivationStage = 'canonicalize' | 'hash' | 'index' | 'schema';\ntype ArchiveIdentity = { id: string; name: string; operator: boolean } | null;\ntype ArchiveAccount = {\n id: string;\n email: string;\n createdAt: string;\n lastSignInAt: string | null;\n};\ntype ArchiveCollectionMeta = { filters: string[]; name: string; tags: string[] };\ntype ArchiveLikesPage = { cursor: string | null; ids: string[] };\ntype ArchiveErrorCode =\n | 'account-changed'\n | 'auth-unavailable'\n | 'bad-request'\n | 'conflict'\n | 'forbidden'\n | 'gone'\n | 'internal'\n | 'invalid-payload'\n | 'likes-disabled'\n | 'method-not-allowed'\n | 'not-found'\n | 'publisher-changed'\n | 'publishing-disabled'\n | 'quota'\n | 'rate-limited'\n | 'record-unavailable'\n | 'timeout'\n | 'too-large'\n | 'unauthenticated'\n | 'unavailable'\n | 'unsupported-media';\ntype ArchiveErrorResponse = {\n error: { code: ArchiveErrorCode; message: string; requestId: string };\n};\ntype ArchiveHealth = {\n dbSchemaVersion: number | null;\n features: { likes: boolean; publishing: boolean };\n limits: {\n aliasChars: number;\n cursorChars: number;\n idempotencyRetentionMs: number;\n likeStateIds: number;\n maxPageSize: number;\n maxPublications: number;\n pageSize: number;\n payloadBytes: number;\n publicCacheSeconds: number;\n reportReasonChars: number;\n requestBytes: number;\n searchChars: number;\n searchTerms: number;\n tagsPerEntry: number;\n titleChars: number;\n vocabChars: number;\n };\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype AuthHealth = {\n dbSchemaVersion: number | null;\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype ArchiveReports = {\n cursor: string | null;\n reports: {\n id: string;\n createdAt: string;\n entryId: string;\n entryTitle: string;\n reason: string;\n reporter: { id: string; name: string };\n resolvedAt: string | null;\n }[];\n};\ntype ArchiveOwnReports = {\n cursor: string | null;\n reports: {\n collection: string;\n createdAt: string;\n entryId: string;\n id: string;\n reason: string;\n resolvedAt: string | null;\n }[];\n};\ntype ArchiveModerationAction = 'hide' | 'unhide' | 'remove' | 'erase-publisher';\ntype ArchiveModerationLog = {\n cursor: string | null;\n actions: {\n id: string;\n action: ArchiveModerationAction;\n collection: string | null;\n createdAt: string;\n operatorId: string;\n targetId: string;\n }[];\n};\n```\n\nWorker subpath types model only the binding methods the catalog calls.\n\n```ts\ninterface D1Statement {\n all<T>(): Promise<{ results?: T[] }>;\n bind(...params: (string | number | null)[]): D1Statement;\n first<T>(): Promise<T | null>;\n run(): Promise<{ meta?: { changes?: number } }>;\n}\ninterface D1Like {\n batch(statements: D1Statement[]): Promise<{ meta?: { changes?: number } }[]>;\n prepare(sql: string): D1Statement;\n}\ninterface RateLimiterBinding {\n limit(input: { key: string }): Promise<{ success: boolean }>;\n}\ninterface ArchiveWorkerEnv {\n AUTH_ISSUER_SERVICE: AuthIssuerServiceBinding;\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n DB: D1Like;\n JWT_AUDIENCE: string;\n JWT_ISSUER: string;\n JWT_JWKS_URL: string;\n LIKES_ENABLED: string;\n PUBLISHING_ENABLED: string;\n RATE_LIMIT_KEY_SECRET: string;\n READ_LIMIT: RateLimiterBinding;\n WRITE_LIMIT: RateLimiterBinding;\n}\ninterface AuthIssuerServiceBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface ArchiveExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\ntype ArchiveDiagnostic =\n | { readonly kind: 'configuration'; readonly field: string }\n | { readonly kind: 'database' | 'record' | 'schema' | 'internal' | 'cache' | 'collection' };\ninterface ArchiveRequestEvent {\n code: ArchiveErrorCode | 'ok';\n diagnostic?: ArchiveDiagnostic;\n ms: number;\n requestId: string;\n route: string;\n status: number;\n type: 'request';\n}\ntype ArchiveScheduledEvent =\n | { removed: number; type: 'scheduled'; status: 'ok' }\n | { type: 'scheduled'; status: 'failed'; diagnostic: ArchiveDiagnostic };\ntype ArchiveEvent =\n | ArchiveRequestEvent\n | ArchiveScheduledEvent\n | { readonly type: 'cache-error'; readonly diagnostic: ArchiveDiagnostic };\ninterface ArchiveWorkerHandler<E extends ArchiveWorkerEnv = ArchiveWorkerEnv> {\n fetch(request: Request, env: E, ctx: ArchiveExecutionContext): Promise<Response>;\n scheduled?(controller: unknown, env: E, ctx: ArchiveExecutionContext): void | Promise<void>;\n tap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n```\n\nScheduled `removed` counts the combined expired retry-key and revocation rows.\n\nAuth subpath types describe the sibling issuer and its required service binding.\n\n```ts\ninterface SendEmail {\n send(message: { from: string; html?: string; subject: string; text: string; to: string }): Promise<unknown>;\n}\ninterface AuthArchiveBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface AuthWorkerEnv {\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n APP_NAME: string;\n AUDIENCE: string;\n AUTH_ARCHIVE: AuthArchiveBinding;\n AUTH_DB: D1Like;\n AUTH_EMAIL: SendEmail;\n AUTH_ISSUER: string;\n AUTH_JWT_PREVIOUS_PUBLIC_JWKS?: string;\n AUTH_JWT_PRIVATE_JWK: string;\n OPERATOR_EMAILS: string;\n PUBLIC_ORIGIN: string;\n SENDER_ADDRESS: string;\n}\ninterface AuthWorkerHandler<E extends AuthWorkerEnv = AuthWorkerEnv> {\n fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise<Response>;\n scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise<void>;\n tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\ntype AuthDiagnostic = {\n readonly kind: 'configuration' | 'database' | 'schema' | 'email' | 'catalog' | 'internal';\n};\ntype AuthEvent =\n | {\n readonly type: 'request';\n readonly requestId: string;\n readonly route:\n | '/auth/account'\n | '/auth/health'\n | '/auth/jwks.json'\n | '/auth/session'\n | '/auth/sign-in'\n | '/auth/sign-out-all'\n | '/auth/verify'\n | 'unmatched';\n readonly status: number;\n readonly code: ArchiveErrorCode | 'ok';\n readonly ms: number;\n readonly diagnostic?: AuthDiagnostic;\n }\n | { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }\n | { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };\n```\n\nIssuer scheduled `removed` counts expired token rows, closed per-user send windows\nand deleted unverified accounts. The singleton admission row is retained and its\nwindow resets atomically on a later sign-in request.\n\n## Errors\n\n| Exported class | Trigger | Properties |\n| ------------------------ | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |\n| `ArchiveError` | Base for public package errors | `name`, `message`, optional `cause` |\n| `ArchiveDefinitionError` | Invalid collection definition or duplicate registered collection names | Extends `ArchiveError` |\n| `ArchiveDerivationError` | Unexpected schema/canonicalization/index/hash fault or violated collection invariant | Extends `ArchiveError`; readonly `stage: ArchiveDerivationStage`; optional `cause` |\n\n`ArchiveError` and `ArchiveDefinitionError` accept `(message: string, opts?: ErrorOptions)`.\n`ArchiveDerivationError` accepts `(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions)`.\nIts message and cause are local diagnostics, not response content. Worker request\nfailures use the wire envelope, not these thrown classes. Internal `ApiError` and\n`AuthOperationError` are not exported.\n\nStored entries that fail the current wire schema return 503 `record-unavailable`.\nStored payloads are canonical by construction, so the emitted entry schemas embed\nthe plain payload schema: parsing a response re-runs that schema, and an\nexception from one of its callbacks becomes a sanitized 500.\n\nThe complete public error signatures are:\n\n```ts\nclass ArchiveError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\nclass ArchiveDefinitionError extends ArchiveError {}\nclass ArchiveDerivationError extends ArchiveError {\n readonly stage: ArchiveDerivationStage;\n constructor(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions);\n}\n```\n\nCatalog rate-limit responses use `Retry-After: 60`; configure catalog limiter periods to 60 seconds. Issuer admission/send-budget responses instead carry seconds until their durable window reopens. Health's degraded response is the health DTO, not an error envelope: schema mismatch reports the observed version; database unavailability reports `dbSchemaVersion: null`.\n",
|
|
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.\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.\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 900\nseconds, 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\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)\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. Moderation routes additionally require a registered publisher row: one\naccountable 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\npnpm vitest run packages/archive/src/__tests__/ # fast unit suite\npnpm --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage\npnpm --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",
|
|
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
9
|
"examples": [],
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "/**\n * Refine components register through their explicit component entry points.\n *\n * Keeping the package root free of registration side effects makes dependency\n * ownership and bundle contents obvious to application code.\n */\nexport { RefineError } from './errors';\nexport { eventFieldChecked, eventFieldValue } from './inputs/shared/native-field-event';\n",
|
|
2
|
+
"apiSource": "/**\n * Refine components register through their explicit component entry points.\n *\n * Keeping the package root free of registration side effects makes dependency\n * ownership and bundle contents obvious to application code.\n */\n\nexport { RefineError } from './errors';\nexport type { IconAttributes, IconDefinition, IconElement } from './icons';\nexport { registerIcons } from './icons';\nexport { eventFieldChecked, eventFieldValue } from './inputs/shared/native-field-event';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Refine: Web component library'\ndescription: Accessible, themeable web components built with Ore for framework and vanilla DOM apps.\npackage: refine\ncategory: ui-components\nkeywords: [web-components, accessible, themeable, ui, components, design-system]\nrelated: [ore, orbit, forge, keymap]\nexports:\n [\n ore-accordion,\n ore-accordion-item,\n ore-alert,\n ore-async,\n ore-avatar,\n ore-avatar-group,\n ore-badge,\n ore-box,\n ore-breadcrumb,\n ore-breadcrumb-item,\n ore-button,\n ore-button-group,\n ore-calendar,\n ore-card,\n ore-carousel,\n ore-carousel-slide,\n ore-chat-message,\n ore-checkbox,\n ore-checkbox-group,\n ore-chip,\n ore-code-window,\n ore-column,\n ore-combobox,\n ore-combobox-option,\n ore-command-palette,\n ore-command-palette-item,\n ore-cookie-banner,\n ore-copy-command,\n ore-counter,\n ore-datagrid,\n ore-date-picker,\n ore-dialog,\n ore-drawer,\n ore-file-input,\n ore-grid,\n ore-grid-item,\n ore-icon,\n ore-input,\n ore-keyboard-key,\n ore-keyboard-shortcut,\n ore-list,\n ore-list-item,\n ore-marquee,\n ore-menu,\n ore-menu-item,\n ore-menu-separator,\n ore-message-composer,\n ore-navbar,\n ore-navbar-item,\n ore-navigation-menu,\n ore-navigation-menu-item,\n ore-navigation-menu-panel,\n ore-number-input,\n ore-otp-input,\n ore-pagination,\n ore-password-strength,\n ore-popover,\n ore-progress,\n ore-qr-code,\n ore-qr-scanner,\n ore-query-bar,\n ore-radio,\n ore-radio-group,\n ore-rating,\n ore-select,\n ore-separator,\n ore-sidebar,\n ore-sidebar-group,\n ore-sidebar-item,\n ore-skeleton,\n ore-slider,\n ore-speech-player,\n ore-stats,\n ore-step,\n ore-stepper,\n ore-switch,\n ore-tab-item,\n ore-tab-panel,\n ore-table,\n ore-tabs,\n ore-td,\n ore-text,\n ore-th,\n ore-tr,\n ore-textarea,\n ore-time-picker,\n ore-toast,\n ore-tooltip,\n ore-typing-indicator,\n ]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"refine\" />\n\n## Why Refine?\n\nEvery project needs UI primitives. Refine provides accessible web components that work natively anywhere HTML is rendered, no framework required.\n\n```html\n<!-- Before: roll your own button with ARIA -->\n<button class=\"btn btn-primary\" role=\"button\" aria-pressed=\"false\" tabindex=\"0\">\n <span class=\"btn-spinner\" aria-hidden=\"true\"></span>\n Save\n</button>\n\n<!-- After: Refine -->\n<ore-button variant=\"solid\" color=\"primary\" loading>Save</ore-button>\n```\n\n| Feature | Refine | Shoelace | Material Web |\n| ------------------ | ------------------------------------------- | ------------------------------------------ | ------------------------------------------ |\n| Bundle size | <PackageInfo package=\"refine\" type=\"size\" /> | ~145 kB | ~200 kB |\n| Built with | Ore | Lit | Lit |\n| Runtime dependencies | Vielzeug UI primitives + Lucide | Lit + utilities | Lit + Material foundations |\n| Accessible | WCAG AA | WCAG AA | WCAG AA |\n| Framework agnostic | <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\n<div class=\"decision-callout\">\n\n**Use Refine when** you want accessible web components that match the Vielzeug design system without a heavy framework dependency.\n\n**Consider Shoelace or Material Web** if your team is already standardized on those ecosystems and you need their established component catalogs.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/refine\n```\n\n```sh [npm]\nnpm install @vielzeug/refine\n```\n\n```sh [yarn]\nyarn add @vielzeug/refine\n```\n\n:::\n\n## Quick Start\n\n```ts\n// 1. Import global styles once\nimport '@vielzeug/refine/fouc.css'; // Hide unupgraded custom elements until first paint\nimport '@vielzeug/refine/tokens.css'; // Tokens, animations, cascade layers\n\n// 2. Register only the elements you need\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/card';\n```\n\n```html\n<ore-button variant=\"solid\" color=\"primary\">Save</ore-button>\n<ore-input label=\"Email\" type=\"email\" required></ore-input>\n<ore-card padding=\"lg\">\n <span slot=\"header\">Account</span>\n <p>Card content goes here.</p>\n</ore-card>\n```\n\n```ts\n```\n\n### CDN / Vanilla HTML\n\nUse the self-contained IIFE bundle to load Refine directly from a CDN in any HTML page: no build step required:\n\n```html\n<!-- 1. Styles -->\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/fouc.css\" />\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/tokens.css\" />\n\n<!-- 2. All components (IIFE: registers global Refine namespace) -->\n<script src=\"https://unpkg.com/@vielzeug/refine/dist/refine.iife.js\"></script>\n```\n\nFor bundler-based projects that still want a CDN URL, use the ESM bundle via an import map:\n\n```html\n<script type=\"importmap\">\n {\n \"imports\": {\n \"@vielzeug/refine\": \"https://esm.sh/@vielzeug/refine\",\n \"@vielzeug/refine/button\": \"https://esm.sh/@vielzeug/refine/button\",\n \"@vielzeug/refine/input\": \"https://esm.sh/@vielzeug/refine/input\"\n }\n }\n</script>\n\n<script type=\"module\">\n import '@vielzeug/refine/button';\n import '@vielzeug/refine/input';\n</script>\n```\n\n### Package Entry Points\n\n| Import | Purpose |\n| ------------------------ | ----------------------------------------- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Global design tokens and cascade layers |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser-default reset (includes FOUC suppression) |\n\nComponent registration happens through side-effect imports such as `@vielzeug/refine/button` and `@vielzeug/refine/dialog`.\n\n### Components\n\n**Content:** `ore-avatar`, `ore-avatar-group`, `ore-breadcrumb`, `ore-card`, `ore-carousel`, `ore-carousel-slide`, `ore-chat-message`, `ore-icon`, `ore-keyboard-key`, `ore-keyboard-shortcut`, `ore-list`, `ore-list-item`, `ore-marquee`, `ore-pagination`, `ore-qr-code`, `ore-separator`, `ore-stats`, `ore-step`, `ore-stepper`, `ore-table`, `ore-text`\n\n**Disclosure:** `ore-accordion`, `ore-accordion-item`, `ore-tabs`, `ore-tab-item`, `ore-tab-panel`\n\n**Feedback:** `ore-alert`, `ore-async`, `ore-badge`, `ore-chip`, `ore-cookie-banner`, `ore-password-strength`, `ore-progress`, `ore-skeleton`, `ore-toast`, `ore-typing-indicator`\n\n**Inputs:** `ore-button`, `ore-button-group`, `ore-calendar`, `ore-checkbox`, `ore-checkbox-group`, `ore-column`, `ore-combobox`, `ore-counter`, `ore-datagrid`, `ore-date-picker`, `ore-file-input`, `ore-input`, `ore-message-composer`, `ore-number-input`, `ore-otp-input`, `ore-qr-scanner`, `ore-query-bar`, `ore-radio`, `ore-radio-group`, `ore-rating`, `ore-select`, `ore-slider`, `ore-switch`, `ore-textarea`, `ore-time-picker`\n\n**Layout:** `ore-box`, `ore-grid`, `ore-grid-item`, `ore-navbar`, `ore-sidebar`\n\n**Overlay:** `ore-command-palette`, `ore-command-palette-item`, `ore-dialog`, `ore-drawer`, `ore-menu`, `ore-popover`, `ore-tooltip`\n\n## Component portfolio\n\nRefine keeps one public package and classifies components by composition level rather than stability. All listed components remain supported and tested.\n\n- **Foundations**: buttons, inputs, selection controls, disclosure, dialogs, menus, tooltips, layout primitives, and feedback indicators. Start here when building an application-specific interface.\n- **Composed patterns**: data grids, command palettes, navigation menus, steppers, calendars, date/time pickers, file inputs, and message composers. These package recurring accessibility and interaction behavior that is costly to rebuild correctly.\n- **Presentation patterns**: cards, chat messages, code windows, stats, marquees, avatars, badges, and skeletons. Use these when their product vocabulary matches the application; prefer foundations when it does not.\n\nClassification guides discovery and bundle selection. It is not a reason to remove working components or move them into unstable packages; per-component subpath imports remain the tree-shaking boundary.\n\n## Features\n\n<div class=\"features-grid\">\n\n- **Accessible**: keyboard navigation, ARIA wiring, and focus management across interactive components\n- **Themeable**: global tokens plus component-level CSS custom properties\n- **Framework agnostic**: works anywhere HTML can be rendered\n- **Tree-shakeable**: import only the component entry points you register\n- **Comprehensive surface**: inputs, content, disclosure, feedback, layout, and overlay primitives\n- **Native form integration**: form-associated controls submit values, validate supported required constraints, and reset with their form\n- **Typed framework declarations**: DOM, React, and Vue tags derive from the component property contracts\n\n</div>\n\n### Prerequisites\n\n- Browser runtime with Custom Elements support.\n- Import `@vielzeug/refine/fouc.css` and `@vielzeug/refine/tokens.css` before rendering components.\n- For SSR, render placeholders server-side and hydrate components only on the client.\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ore](/ore/): Web component runtime that powers Refine\n- [Orbit](/orbit/): Floating UI positioning used in Refine's overlays\n- [Forge](/forge/): Form state management for use with Refine inputs\n- [Keymap](/keymap/): Keyboard shortcut manager that powers the command palette's global trigger\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Refine: API Reference'\ndescription: Published component, stylesheet, framework type, and error entry points for @vielzeug/refine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `@vielzeug/refine/<component>` | Register one custom element and export its public types | Sync | Importing a type alone does not register the element |\n| `@vielzeug/refine/tokens.css` | Load required theme tokens, animations, and cascade layers | CSS | Import once before components render |\n| `@vielzeug/refine/fouc.css` | Hide unregistered `ore-*` elements until upgrade | CSS | Load before first paint |\n| `@vielzeug/refine/styles/preflight.css` | Apply the optional browser reset | CSS | The reset affects global elements |\n| `@vielzeug/refine/frameworks/elements` | Register typed DOM tag mappings | Types only | Import for side effects in TypeScript |\n| `@vielzeug/refine/frameworks/react` | Register typed React JSX elements | Types only | Does not provide runtime wrappers |\n| `@vielzeug/refine/frameworks/vue` | Register typed Vue global components | Types only | Does not install a Vue plugin |\n| `@vielzeug/refine/theme` | `createThemeController()`: light/dark/system document theme | Sync | Does not persist the preference or set an accent color |\n| `eventFieldValue()` / `eventFieldChecked()` | Read a form control's value/checked from `event.currentTarget` | Sync | Exported from the package root; guards non-field targets |\n| `RefineError` | Base class for package-defined public errors | Sync | Component configuration warnings do not throw this error |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/refine` | Export `RefineError` and the `eventFieldValue`/`eventFieldChecked` field readers without registering components |\n| `@vielzeug/refine/<component>` | Register one component and export its tag constant, props, events, and related types |\n| `@vielzeug/refine/theme` | `createThemeController()` and its theme types |\n| `@vielzeug/refine/tokens.css` | Required global design contract |\n| `@vielzeug/refine/fouc.css` | Optional pre-upgrade visibility rule |\n| `@vielzeug/refine/styles/*` | Focused theme, animation, layer, and preflight stylesheets |\n| `@vielzeug/refine/frameworks/*` | TypeScript augmentations for DOM, React, and Vue |\n\n## Styles\n\n```ts\nimport '@vielzeug/refine/fouc.css';\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n`tokens.css` is required. It defines tokens, animations, and cascade-layer order without resetting global elements. `preflight.css` is optional and includes FOUC suppression.\n\n| Import path | Purpose |\n| --- | --- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Tokens, animation helpers, and cascade layers |\n| `@vielzeug/refine/styles/theme.css` | Theme token declarations |\n| `@vielzeug/refine/styles/animation.css` | Animation helpers |\n| `@vielzeug/refine/styles/layers.css` | Cascade layer declarations |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser reset and FOUC suppression |\n\n## Components\n\nEach component uses one registration and type entry point:\n\n```ts\nimport '@vielzeug/refine/button';\nimport type { OreButtonProps } from '@vielzeug/refine/button';\n```\n\n| Area | Components |\n| --- | --- |\n| Content | `avatar`, `avatar-group`, `breadcrumb`, `card`, `carousel`, `chat-message`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `list-item`, `marquee`, `pagination`, `separator`, `speech-player`, `stats`, `step`, `stepper`, `table`, `text` |\n| Disclosure | `accordion`, `accordion-item`, `tabs`, `tab-item`, `tab-panel` |\n| Feedback | `alert`, `async`, `badge`, `chip`, `cookie-banner`, `password-strength`, `progress`, `skeleton`, `toast`, `typing-indicator` |\n| Inputs | `button`, `button-group`, `calendar`, `checkbox`, `checkbox-group`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `query-bar`, `radio`, `radio-group`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |\n| Layout | `box`, `grid`, `grid-item`, `navbar`, `sidebar` |\n| Overlays | `command-palette`, `dialog`, `drawer`, `menu`, `navigation-menu`, `popover`, `tooltip` |\n\nEach component page lists its attributes, JavaScript properties, events, slots, parts, and CSS custom properties.\n\n## Framework Types\n\n```ts\nimport type {} from '@vielzeug/refine/frameworks/elements';\nimport type {} from '@vielzeug/refine/frameworks/react';\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\nThe declarations cover every supported tag and derive component properties from Refine's authoritative `HTMLElementTagNameMap`. They provide types only; component registration still uses component subpaths.\n\n## Events and Form Controls\n\nForm controls expose `.value` or `.checked` and dispatch standard `input` and `change` events. Read the property from `event.currentTarget`.\n\nFinite-choice properties use Ore's `prop.oneOf()` parsing: values outside a component's documented options resolve to\nthe declared default, or `undefined` when no default is declared.\n\nForm-associated controls participate in native form submission, validity checks, and reset. A named control's value\nis available through `new FormData(form)`, and supported `required` constraints affect `form.checkValidity()`,\n`form.reportValidity()`, and submit blocking. The `error` property renders and announces feedback; it does not by\nitself set native constraint validity.\n\nStateful overlays expose controlled `open`, optional `default-open`, and an `open-change` custom event with `{ open, reason }` detail. Component pages define additional detail fields and reasons.\n\n## Utilities\n\n### `createThemeController(options?)`\n\n```ts\nimport { createThemeController } from '@vielzeug/refine/theme';\n\nconst theme = createThemeController(); // starts in 'system' mode\ntheme.setPreference('dark');\ntheme.dispose();\n```\n\nOwns the light/dark/system theme for the document: a reactive `preference` signal, the effective `resolved` mode (`'dark' | 'light'` after resolving `system` against the OS), and the DOM application `styles/theme.css` expects: the `.dark` class plus the `color-scheme` property on the root element, so every `light-dark()` token resolves to the right branch. While in `system` mode the controller tracks the OS `prefers-color-scheme` via sentinel's `createMediaQuery`.\n\nThe controller does **not** persist the preference or expose an accent color: those are consumer concerns (wire `watch(controller.preference, save)` for persistence; set `--color-primary-hue` yourself). Options: `initial` (starting preference, default `'system'`), `root` (element carrying the classes, default `document.documentElement`), `target` (window whose `matchMedia` backs `system`). The handle is disposable: `dispose()`, `disposed`, `disposalSignal`, `[Symbol.dispose]`.\n\n### `eventFieldValue(event)` / `eventFieldChecked(event)`\n\n```ts\nimport { eventFieldChecked, eventFieldValue } from '@vielzeug/refine';\n\ninput.addEventListener('input', (event) => {\n const value = eventFieldValue(event); // string | undefined: never a blind cast\n});\n```\n\nGuarded readers for the standard `input`/`change` event pattern above: they read `value`/`checked` from `event.currentTarget` only when the target actually carries it, so a handler wired to the wrong element yields `undefined`/`false` instead of a crash or a lie. Exported from the package root, which registers no components.\n\n## Types\n\nComponent props follow the `Ore<Component>Props` naming pattern. Event maps follow `Ore<Component>Events`. Import both from the component subpath that owns them.\n\n`RefineElementMap`, `RefineReactIntrinsicElements`, and `RefineVueGlobalComponents` are exported from their respective `frameworks/*` type entry points.\n\n## Errors\n\n### `RefineError`\n\n```ts\nclass RefineError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\n```\n\nBase class for public Refine errors. It preserves `cause` through `ErrorOptions`.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Refine: Usage Guide'\ndescription: Register Refine components, configure properties, handle events, compose slots, and integrate frameworks.\n---\n\n[[toc]]\n\n## Basic Usage\n\nLoad the global design contract once, then register only the components used by the page.\n\n```ts\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/dialog';\n\nconst input = document.querySelector('ore-input');\nconst save = document.querySelector('ore-button');\n\nif (!(input instanceof HTMLElement) || !(save instanceof HTMLElement)) {\n throw new Error('Expected Refine controls');\n}\n\nsave.addEventListener('click', () => {\n console.log((input as HTMLElement & { value: string }).value);\n});\n```\n\nAdd the browser reset only when the application owns global element styling:\n\n```ts\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n## Set Attributes and Properties\n\nUse attributes for serializable HTML state.\n\n```html\n<ore-button variant=\"outline\" color=\"secondary\" size=\"lg\" disabled>\n Save changes\n</ore-button>\n```\n\nUse JavaScript properties for arrays, objects, callbacks, and controlled state.\n\n```ts\nimport '@vielzeug/refine/datagrid';\nimport type { OreDataGridProps } from '@vielzeug/refine/datagrid';\n\nconst grid = document.querySelector('ore-datagrid') as HTMLElement & OreDataGridProps;\ngrid.columns = [\n { key: 'name', label: 'Name', sortable: true },\n { key: 'role', label: 'Role' },\n];\ngrid.rows = [\n { id: '1', name: 'Ada', role: 'Admin' },\n { id: '2', name: 'Linus', role: 'Editor' },\n];\n```\n\nEnumerated properties such as `variant`, `size`, and `color` accept the values listed on each component's reference\npage. An unsupported value resolves to the property's declared default (or `undefined` when it has no default).\n\nIn an Ore template, `model()` can bind a Refine field's `value` to a Ripple signal and write user input back:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { html, model } from '@vielzeug/ore';\nimport '@vielzeug/refine/input';\n\nconst email = signal('');\nconst field = html`<ore-input label=\"Email\" type=\"email\" value=${model(email)} />`;\n```\n\n## Handle Events\n\nForm controls dispatch standard `input` and `change` events. Read their current property from `event.currentTarget`.\n\n```ts\nconst input = document.querySelector('ore-input');\ninput?.addEventListener('input', (event) => {\n const target = event.currentTarget as HTMLElement & { value: string };\n console.log(target.value);\n});\n```\n\nCustom events use kebab-case names and typed detail objects.\n\n```ts\nimport type { OreDialogEvents } from '@vielzeug/refine/dialog';\n\nconst dialog = document.querySelector('ore-dialog');\ndialog?.addEventListener('open-change', (event: CustomEvent<OreDialogEvents['open-change']>) => {\n console.log(event.detail.open, event.detail.reason);\n});\n```\n\n## Native Form Validation\n\nRefine's form-associated controls integrate with native form submission, `FormData`, validity checks, and reset.\nUse `required` for a required-value constraint; setting `error` displays and announces feedback but does not, by\nitself, invalidate the form.\n\n```html\n<form id=\"profile-form\">\n <ore-input name=\"email\" type=\"email\" label=\"Email\" required></ore-input>\n <ore-select name=\"role\" label=\"Role\" required>\n <option value=\"\">Choose a role…</option>\n <option value=\"editor\">Editor</option>\n <option value=\"admin\">Admin</option>\n </ore-select>\n <ore-button type=\"submit\">Save</ore-button>\n</form>\n\n<script type=\"module\">\n import '@vielzeug/refine/input';\n import '@vielzeug/refine/select';\n import '@vielzeug/refine/button';\n\n const form = document.querySelector('#profile-form');\n form.addEventListener('submit', (event) => {\n event.preventDefault();\n console.log(new FormData(form).get('email'));\n });\n</script>\n```\n\nThe browser runs native validation before dispatching `submit`. Call `form.reportValidity()` to show validation\nfeedback directly, or `form.checkValidity()` for a boolean check without the browser's validation UI.\n\n## Compose Slots\n\nDefault slots hold primary content. Named slots identify component-owned regions.\n\n```html\n<ore-card>\n <span slot=\"header\">Account</span>\n <p>Profile settings</p>\n <div slot=\"footer\">\n <ore-button variant=\"ghost\">Cancel</ore-button>\n <ore-button>Save</ore-button>\n </div>\n</ore-card>\n```\n\nInput components commonly expose `prefix`, `suffix`, `label`, `helper`, and `error` slots. Each component reference lists its supported slots.\n\n## Load TypeScript Framework Declarations\n\nImport the declaration matching the framework once in an application type entry point.\n\n::: code-group\n\n```ts [DOM]\nimport type {} from '@vielzeug/refine/frameworks/elements';\n```\n\n```ts [React]\nimport type {} from '@vielzeug/refine/frameworks/react';\n```\n\n```ts [Vue]\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\n:::\n\nThese entry points provide typed tags and component properties. They do not register components or install runtime adapters.\n\n## Framework Integration\n\nRefine elements use native DOM properties, events, and slots. Frameworks differ only in how they forward custom-element properties and events.\n\n::: code-group\n\n```tsx [React 19]\nimport '@vielzeug/refine/button';\n\nexport function SaveButton() {\n return <ore-button variant=\"solid\">Save</ore-button>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport '@vielzeug/refine/button';\n</script>\n\n<template>\n <ore-button variant=\"solid\">Save</ore-button>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import '@vielzeug/refine/button';\n</script>\n\n<ore-button variant=\"solid\">Save</ore-button>\n```\n\n:::\n\nSee [Framework Integration](./frameworks.md) for custom events, controlled properties, SSR guards, and framework-specific configuration.\n\n## Working with Other Vielzeug Libraries\n\n### Ore\n\nUse Ore when authoring a custom element that composes Refine components.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('save-panel', {\n setup() {\n return html`<ore-button @click=${() => console.log('save')}>Save</ore-button>`;\n },\n});\n```\n\n### Ripple\n\nUse Ripple to drive component properties from application state.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst loading = signal(false);\nconst button = document.querySelector('ore-button') as HTMLElement & { loading?: boolean };\nconst loadingEffect = effect(() => {\n button.loading = loading.value;\n});\n\nloadingEffect.dispose();\n```\n\n## Best Practices\n\n- **Import** `tokens.css` once before rendering components.\n- **Register** components through explicit subpaths.\n- **Set** structured data and callbacks as JavaScript properties.\n- **Read** form state from the event target instead of custom event payloads.\n- **Provide** accessible labels for icon-only controls.\n- **Use** component reference pages for supported slots, parts, and CSS properties.\n- **Dispose** application-owned Ripple effects and service handles.\n- **Guard** DOM-dependent component registration during SSR.\n- **Working with AI agents?** Install the `vielzeug` skill (`npx -y @vielzeug/codex skills install`) so agents reach for Refine components and tokens instead of custom widgets: see the [Codex usage guide](../codex/usage.md#agent-skill).\n"
|
|
4
|
+
"index": "---\ntitle: 'Refine: Web component library'\ndescription: Accessible, themeable web components built with Ore for framework and vanilla DOM apps.\npackage: refine\ncategory: ui-components\nkeywords: [web-components, accessible, themeable, ui, components, design-system]\nrelated: [ore, orbit, forge, keymap]\nexports:\n [\n ore-accordion,\n ore-accordion-item,\n ore-alert,\n ore-async,\n ore-avatar,\n ore-avatar-group,\n ore-badge,\n ore-box,\n ore-breadcrumb,\n ore-breadcrumb-item,\n ore-button,\n ore-button-group,\n ore-calendar,\n ore-card,\n ore-carousel,\n ore-carousel-slide,\n ore-chat-message,\n ore-checkbox,\n ore-checkbox-group,\n ore-chip,\n ore-code-window,\n ore-column,\n ore-combobox,\n ore-combobox-option,\n ore-command-palette,\n ore-command-palette-item,\n ore-cookie-banner,\n ore-copy-command,\n ore-counter,\n ore-datagrid,\n ore-date-picker,\n ore-dialog,\n ore-drawer,\n ore-file-input,\n ore-grid,\n ore-grid-item,\n ore-icon,\n ore-input,\n ore-keyboard-key,\n ore-keyboard-shortcut,\n ore-list,\n ore-list-item,\n ore-marquee,\n ore-menu,\n ore-menu-item,\n ore-menu-separator,\n ore-message-composer,\n ore-navbar,\n ore-navbar-item,\n ore-navigation-menu,\n ore-navigation-menu-item,\n ore-navigation-menu-panel,\n ore-number-input,\n ore-otp-input,\n ore-pagination,\n ore-password-strength,\n ore-popover,\n ore-progress,\n ore-qr-code,\n ore-qr-scanner,\n ore-query-bar,\n ore-radio,\n ore-radio-group,\n ore-rating,\n ore-select,\n ore-separator,\n ore-sidebar,\n ore-sidebar-group,\n ore-sidebar-item,\n ore-skeleton,\n ore-slider,\n ore-speech-player,\n ore-stats,\n ore-step,\n ore-stepper,\n ore-switch,\n ore-tab-item,\n ore-tab-panel,\n ore-table,\n ore-tabs,\n ore-td,\n ore-text,\n ore-th,\n ore-tr,\n ore-textarea,\n ore-time-picker,\n ore-toast,\n ore-tooltip,\n ore-typing-indicator,\n ]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"refine\" />\n\n## Why Refine?\n\nEvery project needs UI primitives. Refine provides accessible web components that work natively anywhere HTML is rendered, no framework required.\n\n```html\n<!-- Before: roll your own button with ARIA -->\n<button class=\"btn btn-primary\" role=\"button\" aria-pressed=\"false\" tabindex=\"0\">\n <span class=\"btn-spinner\" aria-hidden=\"true\"></span>\n Save\n</button>\n\n<!-- After: Refine -->\n<ore-button variant=\"solid\" color=\"primary\" loading>Save</ore-button>\n```\n\n| Feature | Refine | Shoelace | Material Web |\n| ------------------ | ------------------------------------------- | ------------------------------------------ | ------------------------------------------ |\n| Bundle size | <PackageInfo package=\"refine\" type=\"size\" /> | ~145 kB | ~200 kB |\n| Built with | Ore | Lit | Lit |\n| Runtime dependencies | Vielzeug UI primitives; Lucide only for the opt-in full-library registrar | Lit + utilities | Lit + Material foundations |\n| Accessible | WCAG AA | WCAG AA | WCAG AA |\n| Framework agnostic | <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\n<div class=\"decision-callout\">\n\n**Use Refine when** you want accessible web components that match the Vielzeug design system without a heavy framework dependency.\n\n**Consider Shoelace or Material Web** if your team is already standardized on those ecosystems and you need their established component catalogs.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/refine\n```\n\n```sh [npm]\nnpm install @vielzeug/refine\n```\n\n```sh [yarn]\nyarn add @vielzeug/refine\n```\n\n:::\n\n## Quick Start\n\n```ts\n// 1. Import global styles once\nimport '@vielzeug/refine/fouc.css'; // Hide unupgraded custom elements until first paint\nimport '@vielzeug/refine/tokens.css'; // Tokens, animations, cascade layers\n\n// 2. Register only the elements you need\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/card';\n```\n\n```html\n<ore-button variant=\"solid\" color=\"primary\">Save</ore-button>\n<ore-input label=\"Email\" type=\"email\" required></ore-input>\n<ore-card padding=\"lg\">\n <span slot=\"header\">Account</span>\n <p>Card content goes here.</p>\n</ore-card>\n```\n\n```ts\n```\n\n### CDN / Vanilla HTML\n\nUse the self-contained IIFE bundle to load Refine directly from a CDN in any HTML page: no build step required:\n\n```html\n<!-- 1. Styles -->\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/fouc.css\" />\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/tokens.css\" />\n\n<!-- 2. All components (IIFE: registers global Refine namespace) -->\n<script src=\"https://unpkg.com/@vielzeug/refine/dist/refine.iife.js\"></script>\n```\n\nFor bundler-based projects that still want a CDN URL, use the ESM bundle via an import map:\n\n```html\n<script type=\"importmap\">\n {\n \"imports\": {\n \"@vielzeug/refine\": \"https://esm.sh/@vielzeug/refine\",\n \"@vielzeug/refine/button\": \"https://esm.sh/@vielzeug/refine/button\",\n \"@vielzeug/refine/input\": \"https://esm.sh/@vielzeug/refine/input\"\n }\n }\n</script>\n\n<script type=\"module\">\n import '@vielzeug/refine/button';\n import '@vielzeug/refine/input';\n</script>\n```\n\n### Package Entry Points\n\n| Import | Purpose |\n| ------------------------ | ----------------------------------------- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Global design tokens and cascade layers |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser-default reset (includes FOUC suppression) |\n\nComponent registration happens through side-effect imports such as `@vielzeug/refine/button` and `@vielzeug/refine/dialog`.\n\n### Components\n\n**Content:** `ore-avatar`, `ore-avatar-group`, `ore-breadcrumb`, `ore-card`, `ore-carousel`, `ore-carousel-slide`, `ore-chat-message`, `ore-icon`, `ore-keyboard-key`, `ore-keyboard-shortcut`, `ore-list`, `ore-list-item`, `ore-marquee`, `ore-pagination`, `ore-qr-code`, `ore-separator`, `ore-stats`, `ore-step`, `ore-stepper`, `ore-table`, `ore-text`\n\n**Disclosure:** `ore-accordion`, `ore-accordion-item`, `ore-tabs`, `ore-tab-item`, `ore-tab-panel`\n\n**Feedback:** `ore-alert`, `ore-async`, `ore-badge`, `ore-chip`, `ore-cookie-banner`, `ore-password-strength`, `ore-progress`, `ore-skeleton`, `ore-toast`, `ore-typing-indicator`\n\n**Inputs:** `ore-button`, `ore-button-group`, `ore-calendar`, `ore-checkbox`, `ore-checkbox-group`, `ore-column`, `ore-combobox`, `ore-counter`, `ore-datagrid`, `ore-date-picker`, `ore-file-input`, `ore-input`, `ore-message-composer`, `ore-number-input`, `ore-otp-input`, `ore-qr-scanner`, `ore-query-bar`, `ore-radio`, `ore-radio-group`, `ore-rating`, `ore-select`, `ore-slider`, `ore-switch`, `ore-textarea`, `ore-time-picker`\n\n**Layout:** `ore-box`, `ore-grid`, `ore-grid-item`, `ore-navbar`, `ore-sidebar`\n\n**Overlay:** `ore-command-palette`, `ore-command-palette-item`, `ore-dialog`, `ore-drawer`, `ore-menu`, `ore-popover`, `ore-tooltip`\n\n## Component portfolio\n\nRefine keeps one public package and classifies components by composition level rather than stability. All listed components remain supported and tested.\n\n- **Foundations**: buttons, inputs, selection controls, disclosure, dialogs, menus, tooltips, layout primitives, and feedback indicators. Start here when building an application-specific interface.\n- **Composed patterns**: data grids, command palettes, navigation menus, steppers, calendars, date/time pickers, file inputs, and message composers. These package recurring accessibility and interaction behavior that is costly to rebuild correctly.\n- **Presentation patterns**: cards, chat messages, code windows, stats, marquees, avatars, badges, and skeletons. Use these when their product vocabulary matches the application; prefer foundations when it does not.\n\nClassification guides discovery and bundle selection. It is not a reason to remove working components or move them into unstable packages; per-component subpath imports remain the tree-shaking boundary.\n\n## Features\n\n<div class=\"features-grid\">\n\n- **Accessible**: keyboard navigation, ARIA wiring, and focus management across interactive components\n- **Themeable**: global tokens plus component-level CSS custom properties\n- **Framework agnostic**: works anywhere HTML can be rendered\n- **Tree-shakeable**: import only the component entry points you register\n- **Comprehensive surface**: inputs, content, disclosure, feedback, layout, and overlay primitives\n- **Native form integration**: form-associated controls submit values, validate supported required constraints, and reset with their form\n- **Typed framework declarations**: DOM, React, and Vue tags derive from the component property contracts\n\n</div>\n\n### Prerequisites\n\n- Browser runtime with Custom Elements support.\n- Import `@vielzeug/refine/fouc.css` and `@vielzeug/refine/tokens.css` before rendering components.\n- For SSR, render placeholders server-side and hydrate components only on the client.\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ore](/ore/): Web component runtime that powers Refine\n- [Orbit](/orbit/): Floating UI positioning used in Refine's overlays\n- [Forge](/forge/): Form state management for use with Refine inputs\n- [Keymap](/keymap/): Keyboard shortcut manager that powers the command palette's global trigger\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Refine: API Reference'\ndescription: Published component, stylesheet, framework type, and error entry points for @vielzeug/refine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `@vielzeug/refine/<component>` | Register one custom element and export its public types | Sync | Importing a type alone does not register the element |\n| `@vielzeug/refine/tokens.css` | Load required theme tokens, animations, and cascade layers | CSS | Import once before components render |\n| `@vielzeug/refine/fouc.css` | Hide unregistered `ore-*` elements until upgrade | CSS | Load before first paint |\n| `@vielzeug/refine/styles/preflight.css` | Apply the optional browser reset | CSS | The reset affects global elements |\n| `@vielzeug/refine/frameworks/elements` | Register typed DOM tag mappings | Types only | Import for side effects in TypeScript |\n| `@vielzeug/refine/frameworks/react` | Register typed React JSX elements | Types only | Does not provide runtime wrappers |\n| `@vielzeug/refine/frameworks/vue` | Register typed Vue global components | Types only | Does not install a Vue plugin |\n| `@vielzeug/refine/theme` | `createThemeController()`: light/dark/system document theme | Sync | Does not persist the preference or set an accent color |\n| `eventFieldValue()` / `eventFieldChecked()` | Read a form control's value/checked from `event.currentTarget` | Sync | Exported from the package root; guards non-field targets |\n| `RefineError` | Base class for package-defined public errors | Sync | Component configuration warnings do not throw this error |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/refine` | Export `registerIcons`, icon definition types, `RefineError`, and the field readers without registering components |\n| `@vielzeug/refine/<component>` | Register one component and export its tag constant, props, events, and related types |\n| `@vielzeug/refine/theme` | `createThemeController()` and its theme types |\n| `@vielzeug/refine/tokens.css` | Required global design contract |\n| `@vielzeug/refine/fouc.css` | Optional pre-upgrade visibility rule |\n| `@vielzeug/refine/styles/*` | Focused theme, animation, layer, and preflight stylesheets |\n| `@vielzeug/refine/frameworks/*` | TypeScript augmentations for DOM, React, and Vue |\n\n## Icon Registration and Adapters\n\n`registerIcons(icons: Readonly<Record<string, IconDefinition>>): void` is available from `@vielzeug/refine/icons`, `@vielzeug/refine`, and `@vielzeug/refine/icon`. The common `icons` entry and root remain free of component registration side effects.\n\n`IconDefinition`, `IconElement`, and `IconAttributes` are exported from all three entries. Shared definition and registration modules live in `src/icons/`, alongside adapters and internal SVG helpers/defaults. Definitions contain a numeric `viewBox` tuple, optional presentation attributes, and recursive SVG children; they do not require a provider identity. Invalid registrations throw the root-exported `RefineError` atomically.\n\n| Entry | Export | Purpose |\n| --- | --- | --- |\n| `@vielzeug/refine/icons` | `registerIcons`, `IconDefinition`, `IconElement`, `IconAttributes` | Common library-neutral registration and definition API |\n| `@vielzeug/refine/icons/lucide` | `lucideIcons`, `LucideIconData` | Pure adapter for selected structural Lucide SVG data |\n| `@vielzeug/refine/icons/lucide/all` | Side-effect registration | Explicitly register the full installed Lucide library |\n| `@vielzeug/refine/icons/heroicons` | `heroiconsIcons`, `IconifyIcon` | Convert a caller-named map of individual Heroicons Iconify data |\n| `@vielzeug/refine/icons/tabler` | `tablerIcons`, `IconifyIcon` | Convert a caller-named map of individual Tabler Iconify data |\n| `@vielzeug/refine/icons/mdi` | `mdiIcons`, `IconifyIcon` | Convert a caller-named map of individual MDI Iconify data |\n| `@vielzeug/refine/icons/iconify` | `iconifyIcon`, `iconifyIcons` | Convert individual Iconify data or selected/complete collections |\n| `@vielzeug/refine/icons/iconify` | `IconifyIcon`, `IconifyAlias`, `IconifyCollection`, `IconifyTransform` | Structural data types; no Iconify dependency required |\n\nLucide is an optional peer, not a mandatory dependency. Only `icons/lucide/all` requires an installed `lucide` package; consumers selecting that entry declare it themselves. The structural `icons/lucide` adapter accepts supplied data without importing Lucide.\n\nThe standalone IIFE exposes `registerIcons`, `lucideIcons`, `heroiconsIcons`, `tablerIcons`, `mdiIcons`, `iconifyIcon`, and `iconifyIcons` under `Refine.components.content`. Neither the IIFE nor component entries import Lucide. Iconify conversion drops provider `class` metadata, validates finite numeric offsets and positive finite dimensions before transforms, and retains the strict SVG allowlist. See the [icon reference](./components/icon.md) for presentation overrides, local SVG ID rewriting, supported families, and licenses.\n\nThe three family adapters share this signature:\n\n```ts\nheroiconsIcons(icons: Readonly<Record<string, IconifyIcon>>): Record<string, IconDefinition>;\ntablerIcons(icons: Readonly<Record<string, IconifyIcon>>): Record<string, IconDefinition>;\nmdiIcons(icons: Readonly<Record<string, IconifyIcon>>): Record<string, IconDefinition>;\n```\n\nEach accepts individual Iconify SVG data, preserves input keys without adding a namespace, and returns definitions without registering them. They require `DOMParser`, preserve each icon's geometry/presentation/transforms, and throw `RefineError` for invalid Iconify data. They do not accept React/Vue components, collection JSON, or raw SVG path strings. Use `iconifyIcons(collection, names?)` for collections and alias resolution.\n\n## Styles\n\n```ts\nimport '@vielzeug/refine/fouc.css';\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n`tokens.css` is required. It defines tokens, animations, and cascade-layer order without resetting global elements. `preflight.css` is optional and includes FOUC suppression.\n\n| Import path | Purpose |\n| --- | --- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Tokens, animation helpers, and cascade layers |\n| `@vielzeug/refine/styles/theme.css` | Theme token declarations |\n| `@vielzeug/refine/styles/animation.css` | Animation helpers |\n| `@vielzeug/refine/styles/layers.css` | Cascade layer declarations |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser reset and FOUC suppression |\n\n## Components\n\nEach component uses one registration and type entry point:\n\n```ts\nimport '@vielzeug/refine/button';\nimport type { OreButtonProps } from '@vielzeug/refine/button';\n```\n\n| Area | Components |\n| --- | --- |\n| Content | `avatar`, `avatar-group`, `breadcrumb`, `card`, `carousel`, `chat-message`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `list-item`, `marquee`, `pagination`, `separator`, `speech-player`, `stats`, `step`, `stepper`, `table`, `text` |\n| Disclosure | `accordion`, `accordion-item`, `tabs`, `tab-item`, `tab-panel` |\n| Feedback | `alert`, `async`, `badge`, `chip`, `cookie-banner`, `password-strength`, `progress`, `skeleton`, `toast`, `typing-indicator` |\n| Inputs | `button`, `button-group`, `calendar`, `checkbox`, `checkbox-group`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `query-bar`, `radio`, `radio-group`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |\n| Layout | `box`, `grid`, `grid-item`, `navbar`, `sidebar` |\n| Overlays | `command-palette`, `dialog`, `drawer`, `menu`, `navigation-menu`, `popover`, `tooltip` |\n\nEach component page lists its attributes, JavaScript properties, events, slots, parts, and CSS custom properties.\n\n## Framework Types\n\n```ts\nimport type {} from '@vielzeug/refine/frameworks/elements';\nimport type {} from '@vielzeug/refine/frameworks/react';\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\nThe declarations cover every supported tag and derive component properties from Refine's authoritative `HTMLElementTagNameMap`. They provide types only; component registration still uses component subpaths.\n\n## Events and Form Controls\n\nForm controls expose `.value` or `.checked` and dispatch standard `input` and `change` events. Read the property from `event.currentTarget`.\n\nFinite-choice properties use Ore's `prop.oneOf()` parsing: values outside a component's documented options resolve to\nthe declared default, or `undefined` when no default is declared.\n\nForm-associated controls participate in native form submission, validity checks, and reset. A named control's value\nis available through `new FormData(form)`, and supported `required` constraints affect `form.checkValidity()`,\n`form.reportValidity()`, and submit blocking. The `error` property renders and announces feedback; it does not by\nitself set native constraint validity.\n\nStateful overlays expose controlled `open`, optional `default-open`, and an `open-change` custom event with `{ open, reason }` detail. Component pages define additional detail fields and reasons.\n\n## Utilities\n\n### `createThemeController(options?)`\n\n```ts\nimport { createThemeController } from '@vielzeug/refine/theme';\n\nconst theme = createThemeController(); // starts in 'system' mode\ntheme.setPreference('dark');\ntheme.dispose();\n```\n\nOwns the light/dark/system theme for the document: a reactive `preference` signal, the effective `resolved` mode (`'dark' | 'light'` after resolving `system` against the OS), and the DOM application `styles/theme.css` expects: the `.dark` class plus the `color-scheme` property on the root element, so every `light-dark()` token resolves to the right branch. While in `system` mode the controller tracks the OS `prefers-color-scheme` via sentinel's `createMediaQuery`.\n\nThe controller does **not** persist the preference or expose an accent color: those are consumer concerns (wire `watch(controller.preference, save)` for persistence; set `--color-primary-hue` yourself). Options: `initial` (starting preference, default `'system'`), `root` (element carrying the classes, default `document.documentElement`), `target` (window whose `matchMedia` backs `system`). The handle is disposable: `dispose()`, `disposed`, `disposalSignal`, `[Symbol.dispose]`.\n\n### `eventFieldValue(event)` / `eventFieldChecked(event)`\n\n```ts\nimport { eventFieldChecked, eventFieldValue } from '@vielzeug/refine';\n\ninput.addEventListener('input', (event) => {\n const value = eventFieldValue(event); // string | undefined: never a blind cast\n});\n```\n\nGuarded readers for the standard `input`/`change` event pattern above: they read `value`/`checked` from `event.currentTarget` only when the target actually carries it, so a handler wired to the wrong element yields `undefined`/`false` instead of a crash or a lie. Exported from the package root, which registers no components.\n\n## Types\n\nComponent props follow the `Ore<Component>Props` naming pattern. Event maps follow `Ore<Component>Events`. Import both from the component subpath that owns them.\n\n`RefineElementMap`, `RefineReactIntrinsicElements`, and `RefineVueGlobalComponents` are exported from their respective `frameworks/*` type entry points.\n\n## Errors\n\n### `RefineError`\n\n```ts\nclass RefineError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\n```\n\nBase class for public Refine errors. It preserves `cause` through `ErrorOptions`.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Refine: Usage Guide'\ndescription: Register Refine components, configure properties, handle events, compose slots, and integrate frameworks.\n---\n\n[[toc]]\n\n## Basic Usage\n\nLoad the global design contract once, then register only the components used by the page.\n\n```ts\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/dialog';\n\nconst input = document.querySelector('ore-input');\nconst save = document.querySelector('ore-button');\n\nif (!(input instanceof HTMLElement) || !(save instanceof HTMLElement)) {\n throw new Error('Expected Refine controls');\n}\n\nsave.addEventListener('click', () => {\n console.log((input as HTMLElement & { value: string }).value);\n});\n```\n\nAdd the browser reset only when the application owns global element styling:\n\n```ts\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n## Choose an Icon Library\n\nRefine includes only its internal component icons. Register application icons before mounting them: use `registerIcons` and neutral `IconDefinition` data from `@vielzeug/refine/icons`, the pure `@vielzeug/refine/icons/lucide` adapter for selected Lucide icons, or `@vielzeug/refine/icons/iconify` for local Heroicons, Tabler, and Material Design Icons data. Keep importing the component from `@vielzeug/refine/icon`. Lucide is an optional peer: install `lucide` yourself only when choosing its data or `@vielzeug/refine/icons/lucide/all`; core and structural adapters do not require it. The [icon reference](./components/icon.md) covers imports, licenses, and presentation behavior.\n\nFor selected individual Iconify data, use `heroiconsIcons`, `tablerIcons`, or `mdiIcons` from `@vielzeug/refine/icons/heroicons`, `/tabler`, or `/mdi`. For example, `registerIcons(heroiconsIcons({ Search, Home }))` preserves your app keys. Install the matching `@iconify-icons/<family>` data package yourself; these helpers do not accept framework components. Keep `iconifyIcons` for collection JSON and aliases.\n\n## Set Attributes and Properties\n\nUse attributes for serializable HTML state.\n\n```html\n<ore-button variant=\"outline\" color=\"secondary\" size=\"lg\" disabled>\n Save changes\n</ore-button>\n```\n\nUse JavaScript properties for arrays, objects, callbacks, and controlled state.\n\n```ts\nimport '@vielzeug/refine/datagrid';\nimport type { OreDataGridProps } from '@vielzeug/refine/datagrid';\n\nconst grid = document.querySelector('ore-datagrid') as HTMLElement & OreDataGridProps;\ngrid.columns = [\n { key: 'name', label: 'Name', sortable: true },\n { key: 'role', label: 'Role' },\n];\ngrid.rows = [\n { id: '1', name: 'Ada', role: 'Admin' },\n { id: '2', name: 'Linus', role: 'Editor' },\n];\n```\n\nEnumerated properties such as `variant`, `size`, and `color` accept the values listed on each component's reference\npage. An unsupported value resolves to the property's declared default (or `undefined` when it has no default).\n\nIn an Ore template, `model()` can bind a Refine field's `value` to a Ripple signal and write user input back:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { html, model } from '@vielzeug/ore';\nimport '@vielzeug/refine/input';\n\nconst email = signal('');\nconst field = html`<ore-input label=\"Email\" type=\"email\" value=${model(email)} />`;\n```\n\n## Handle Events\n\nForm controls dispatch standard `input` and `change` events. Read their current property from `event.currentTarget`.\n\n```ts\nconst input = document.querySelector('ore-input');\ninput?.addEventListener('input', (event) => {\n const target = event.currentTarget as HTMLElement & { value: string };\n console.log(target.value);\n});\n```\n\nCustom events use kebab-case names and typed detail objects.\n\n```ts\nimport type { OreDialogEvents } from '@vielzeug/refine/dialog';\n\nconst dialog = document.querySelector('ore-dialog');\ndialog?.addEventListener('open-change', (event: CustomEvent<OreDialogEvents['open-change']>) => {\n console.log(event.detail.open, event.detail.reason);\n});\n```\n\n## Native Form Validation\n\nRefine's form-associated controls integrate with native form submission, `FormData`, validity checks, and reset.\nUse `required` for a required-value constraint; setting `error` displays and announces feedback but does not, by\nitself, invalidate the form.\n\n```html\n<form id=\"profile-form\">\n <ore-input name=\"email\" type=\"email\" label=\"Email\" required></ore-input>\n <ore-select name=\"role\" label=\"Role\" required>\n <option value=\"\">Choose a role…</option>\n <option value=\"editor\">Editor</option>\n <option value=\"admin\">Admin</option>\n </ore-select>\n <ore-button type=\"submit\">Save</ore-button>\n</form>\n\n<script type=\"module\">\n import '@vielzeug/refine/input';\n import '@vielzeug/refine/select';\n import '@vielzeug/refine/button';\n\n const form = document.querySelector('#profile-form');\n form.addEventListener('submit', (event) => {\n event.preventDefault();\n console.log(new FormData(form).get('email'));\n });\n</script>\n```\n\nThe browser runs native validation before dispatching `submit`. Call `form.reportValidity()` to show validation\nfeedback directly, or `form.checkValidity()` for a boolean check without the browser's validation UI.\n\n## Compose Slots\n\nDefault slots hold primary content. Named slots identify component-owned regions.\n\n```html\n<ore-card>\n <span slot=\"header\">Account</span>\n <p>Profile settings</p>\n <div slot=\"footer\">\n <ore-button variant=\"ghost\">Cancel</ore-button>\n <ore-button>Save</ore-button>\n </div>\n</ore-card>\n```\n\nInput components commonly expose `prefix`, `suffix`, `label`, `helper`, and `error` slots. Each component reference lists its supported slots.\n\n## Load TypeScript Framework Declarations\n\nImport the declaration matching the framework once in an application type entry point.\n\n::: code-group\n\n```ts [DOM]\nimport type {} from '@vielzeug/refine/frameworks/elements';\n```\n\n```ts [React]\nimport type {} from '@vielzeug/refine/frameworks/react';\n```\n\n```ts [Vue]\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\n:::\n\nThese entry points provide typed tags and component properties. They do not register components or install runtime adapters.\n\n## Framework Integration\n\nRefine elements use native DOM properties, events, and slots. Frameworks differ only in how they forward custom-element properties and events.\n\n::: code-group\n\n```tsx [React 19]\nimport '@vielzeug/refine/button';\n\nexport function SaveButton() {\n return <ore-button variant=\"solid\">Save</ore-button>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport '@vielzeug/refine/button';\n</script>\n\n<template>\n <ore-button variant=\"solid\">Save</ore-button>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import '@vielzeug/refine/button';\n</script>\n\n<ore-button variant=\"solid\">Save</ore-button>\n```\n\n:::\n\nSee [Framework Integration](./frameworks.md) for custom events, controlled properties, SSR guards, and framework-specific configuration.\n\n## Working with Other Vielzeug Libraries\n\n### Ore\n\nUse Ore when authoring a custom element that composes Refine components.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('save-panel', {\n setup() {\n return html`<ore-button @click=${() => console.log('save')}>Save</ore-button>`;\n },\n});\n```\n\n### Ripple\n\nUse Ripple to drive component properties from application state.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst loading = signal(false);\nconst button = document.querySelector('ore-button') as HTMLElement & { loading?: boolean };\nconst loadingEffect = effect(() => {\n button.loading = loading.value;\n});\n\nloadingEffect.dispose();\n```\n\n## Best Practices\n\n- **Import** `tokens.css` once before rendering components.\n- **Register** components through explicit subpaths.\n- **Set** structured data and callbacks as JavaScript properties.\n- **Read** form state from the event target instead of custom event payloads.\n- **Provide** accessible labels for icon-only controls.\n- **Use** component reference pages for supported slots, parts, and CSS properties.\n- **Dispose** application-owned Ripple effects and service handles.\n- **Guard** DOM-dependent component registration during SSR.\n- **Working with AI agents?** Install the `vielzeug` skill (`npx -y @vielzeug/codex skills install`) so agents reach for Refine components and tokens instead of custom widgets: see the [Codex usage guide](../codex/usage.md#agent-skill).\n"
|
|
7
7
|
},
|
|
8
8
|
"examples": [],
|
|
9
9
|
"typeSignatures": {
|
|
10
10
|
"RefineError": "export { RefineError } from './errors';",
|
|
11
|
+
"IconAttributes": "export type { IconAttributes, IconDefinition, IconElement } from './icons';",
|
|
12
|
+
"IconDefinition": "export type { IconAttributes, IconDefinition, IconElement } from './icons';",
|
|
13
|
+
"IconElement": "export type { IconAttributes, IconDefinition, IconElement } from './icons';",
|
|
14
|
+
"registerIcons": "export { registerIcons } from './icons';",
|
|
11
15
|
"eventFieldChecked": "export { eventFieldChecked, eventFieldValue } from './inputs/shared/native-field-event';",
|
|
12
16
|
"eventFieldValue": "export { eventFieldChecked, eventFieldValue } from './inputs/shared/native-field-event';"
|
|
13
17
|
}
|