@vielzeug/codex 26.11.8 → 26.11.10

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/search.json CHANGED
@@ -959,8 +959,8 @@
959
959
  "description": "functional custom element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.",
960
960
  "docs": {
961
961
  "index": " \ntitle: 'ore: web component authoring with signals'\ndescription: functional custom element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.\npackage: ore\ncategory: ui primitives\nkeywords: [web components, custom elements, reactive, templates, signals, lifecycle]\nrelated: [ripple, refine, orbit]\nexports:\n [\n define,\n prop,\n html,\n css,\n ref,\n createcontext,\n inject,\n injectstrict,\n provide,\n onmounted,\n oncleanup,\n onevent,\n onelement,\n onformreset,\n watcheffect,\n useemit,\n useslots,\n gethost,\n bind,\n each,\n when,\n classmap,\n stylemap,\n live,\n model,\n unsafehtml,\n usefield,\n createid,\n oreerror,\n oreapierror,\n oreinternalerror,\n orelifecycleerror,\n attributebindings,\n bindoptions,\n maybereactive,\n ]\nenvironments: [browser]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"ore\" />\n\n## why ore?\n\nore keeps custom elements functional and signal driven while giving you direct control over templates, lifecycle hooks, host bindings, and form associated behavior.\n\n```ts\n// before: vanilla custom element boilerplate\nclass mycounter extends htmlelement {\n #count = 0;\n connectedcallback() {\n this.attachshadow({ mode: 'open' });\n this.#render();\n }\n #render() {\n this.shadowroot!.innerhtml = `<button>${this.#count}</button>`;\n this.shadowroot!.queryselector('button')!.onclick = () => {\n this.#count++;\n this.#render();\n };\n }\n}\ncustomelements.define('my counter', mycounter);\n\n// after: ore\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('my counter', {\n setup() {\n const count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n },\n});\n```\n\n| feature | ore | lit | stencil |\n| | | | |\n| bundle size | <packageinfo package=\"ore\" type=\"size\" /> | ~12 kb | ~60 kb+ toolchain |\n| signal first runtime | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> (separate signals package) | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| functional component setup | <ore icon name=\"check\" size=\"16\"></ore icon> | partial | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| typed prop helpers | <ore icon name=\"check\" size=\"16\"></ore icon> | partial | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| host binding helpers | <ore icon name=\"check\" size=\"16\"></ore icon> | partial | partial |\n| form associated helpers | <ore icon name=\"check\" size=\"16\"></ore icon> | manual | partial |\n| zero dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use ore when** you want typed, signal driven custom elements with minimal runtime overhead and no framework lock in.\n\n**consider lit when** you need a mature ecosystem with wide community adoption and don't need signal based reactivity.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/ore @vielzeug/ripple\n```\n\n```sh [npm]\nnpm install @vielzeug/ore @vielzeug/ripple\n```\n\n```sh [yarn]\nyarn add @vielzeug/ore @vielzeug/ripple\n```\n\n:::\n\n## quick start\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { bind, css, define, html, onmounted, prop } from '@vielzeug/ore';\n\ndefine('my counter', {\n props: {\n label: prop.string('count'),\n step: prop.number(1),\n },\n styles: [\n css`\n :host {\n display: inline grid;\n gap: 0.5rem;\n }\n `,\n ],\n setup(props) {\n const count = signal(0);\n const doubled = computed(() => count.value * 2);\n\n bind({ class: { 'is positive': () => count.value > 0 } });\n\n onmounted(() => console.log('mounted'));\n\n return html`\n <button @click=${() => (count.value += props.step.value)}>${props.label}: ${count}</button>\n <p>doubled: ${doubled}</p>\n `;\n },\n});\n```\n\n## features\n\n<div class=\"features grid\">\n\n signal first runtime with `signal`, `computed`, `watch`, `batch` from `@vielzeug/ripple`: import them directly\n functional component authoring via `define(tag, { props, setup, styles, formassociated })`\n props via `prop.*` helpers (`prop.string`, `prop.number`, `prop.bool`, `prop.oneof`, `prop.json`, `prop.data`) or raw `propdef` objects\n `setup(props)` takes only props and returns an `htmlresult` directly: `return html\\`...\\``\n lifecycle hooks: `onmounted`, `oncleanup`, `onevent`, `onelement`, `watcheffect`: plain functions imported from `@vielzeug/ore`, called directly from `setup()` or any composable it calls\n directives: `each` (transactional keyed list reconciliation), `classmap`, `stylemap`, `when`, `live`, `model`, `unsafehtml`\n host bindings via `bind({ attr, class, style, on })`: pass `{ target: el }` to bind any off host element\n reactive aria sync via explicit `aria *` keys in `bind({ attr }, { target })`, with automatic cleanup on disconnect\n context via `provide(key, value)` / `inject(key)`; typed emit/slots via `useemit<emits>()` / `useslots<slotnames>()`\n form associated `usefield()` and observer helpers are root exports\n testing utilities (`@vielzeug/ore/testing`): `mount`, `renderhook`, `flush`, `cleanup`\n generic testing utilities (scoped queries, named event dispatchers, and async waits) are exported by `@vielzeug/assay`\n\n</div>\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/ore` | all browser runtime apis: components, directives, `usefield`, and observers |\n| `@vielzeug/ore/testing` | ore specific mounting, lifecycle flushing, hooks, cleanup, and form internals |\n| `@vielzeug/assay` | generic dom events, scoped queries, and async waiting |\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [refine](../refine/index.md) for prebuilt accessible components powered by ore.\n [ripple](../ripple/index.md) for reactive state used inside ore components.\n [forge](../forge/index.md) for typed form state that integrates with ore.\n\n</div>\n\n<! markdownlint enable md025 md033 md060 >\n",
962
- "api": " \ntitle: 'ore: api reference'\ndescription: complete api reference for @vielzeug/ore and @vielzeug/ore/testing.\n \n\n[[toc]]\n\n## api overview\n\nall browser runtime symbols below are imported from `@vielzeug/ore`. lifecycle/context/binding functions (`onmounted`, `oncleanup`, `onevent`, `onelement`, `watcheffect`, `bind`, `provide`, `useemit`, `useslots`, `gethost`) resolve the active component through an implicit \"current component\" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window.\n\n> `watcheffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `define()` | create and register a custom element | sync | tag must contain a hyphen; call before first use |\n| `html` | tagged template literal returning htmlresult | sync | expressions must be signals, functions, or primitives |\n| `prop.*` | typed prop helpers (string, bool, number, …) | sync | prop values are signals: read `.value` |\n| `provide()`/`inject()` | context api for parent to descendant sharing | setup only | must be called synchronously during `setup()` |\n| `ref()` | reactive reference to a dom element | sync | value is null until after first mount |\n| `createcontext()` | create a unique typed injection key | sync | context is scoped to the component tree |\n| `each()` | keyed list rendering with dom diffing | sync | duplicate keys report `ore:error`; plain `t[]` is a one time static render |\n| `when()` | conditional branch rendering | sync | getter fn computed disposed on cleanup; static bool skips subscription |\n| `live(signal)` | one way binding that skips stale writes during input | sync | use for controlled inputs alongside a manual `@input` handler |\n| `model(signal)` | two way form control binding (value/checked + write back) | sync | plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |\n| `onmounted(fn)` | dom ready callback | setup only | must be called synchronously during `setup()` |\n| `oncleanup(fn)` | register teardown | setup only | called on component disconnect |\n| `onevent(target, …)` | scoped event listener with auto cleanup | setup only | no ops on null target; removed on disconnect |\n| `usefield(options)` | wire signal to form `elementinternals` | setup only | requires `formassociated: true` on the component definition |\n| `onformreset(fn)` | run work when the ancestor `<form>` resets | setup only | fires every reset (not one shot); only for `formassociated: true` components |\n| `useemit<emits>()` | typed `emit()` bound to the current host | setup only | call once per component; returns `dispatchevent`'s boolean (`false` if a listener called `preventdefault()`) |\n| `useslots<slotnames>()` | reactive slot presence/element signals | setup only | safe to call more than once: the underlying registry is created once |\n| `gethost()` | the current component's host element | setup only | prefer a higher level helper (`bind`, …) when one exists |\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/ore` | all browser runtime apis, including directives, fields, and lifecycle helpers |\n| `@vielzeug/ore/testing` | ore specific mounting, lifecycle, hook, cleanup, and form test support |\n| `@vielzeug/assay` | generic dom events, scoped queries, and async waiting |\n\n## core component api\n\n### `define(tag, definition)`\n\n```ts\ndefine<props>(tag: string, definition: componentdefinition<props>): customelementconstructor;\n```\n\nreturns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.\n\nthe `setup()` function receives only typed prop signals:\n\n```ts\nsetup(props) {\n return html`<div>${props.label}</div>`;\n}\n```\n\neverything else: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, html, onmounted, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my card', {\n setup(_props) {\n const emit = useemit<{ close: undefined }>();\n const slots = useslots<'header' | 'footer'>();\n\n onmounted(() => console.log('mounted'));\n\n // emit() returns dispatchevent's boolean: false if a listener called preventdefault()\n const notcancelled = emit('close');\n\n return html`${when(slots.has('header'), () => html`<slot name=\"header\"></slot>`)}`;\n },\n});\n```\n\n`useemit<emits>()` and `useslots<slotnames>()` are factory hooks: call them once per setup run to get a typed\n`emit`/`slots` bound to the current host. `useslots()` is safe to call more than once within that setup run.\n\n### componentdefinition\n\n```ts\ntype componentdefinition<props> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom (no shadow root)\n styles?: (string | cssstylesheet | cssresult)[];\n};\n```\n\n## runtime helpers\n\n`onmounted`, `oncleanup`, `onevent`, `onelement`, and `watcheffect` are plain functions imported from `@vielzeug/ore`. call them directly during `setup()`.\n\n```ts\nimport { html, oncleanup, onevent, onmounted } from '@vielzeug/ore';\n\nsetup(props) {\n onmounted(() => {\n // dom is ready; return a function for mount scoped cleanup\n return () => { /* cleanup on unmount */ };\n });\n\n oncleanup(() => { /* called on disconnect */ });\n\n onevent(window, 'keydown', (e) => { /* auto removed on disconnect */ });\n\n return html`...`;\n}\n```\n\nbecause these resolve the active component through an implicit context (rather than a value threaded through parameters), composable helper functions can call them directly too: no need to pass hooks in as options:\n\n```ts\nimport { oncleanup } from '@vielzeug/ore';\n\nfunction usemyhelper() {\n oncleanup(() => { /* teardown */ });\n}\n\n// in setup:\nsetup(_props) {\n usemyhelper();\n return html`...`;\n}\n```\n\n## props api\n\n| helper | signature | notes |\n| | | |\n| `prop.string(defaultvalue?)` | `propdef<string>` | reflects by default |\n| `prop.bool(defaultvalue?)` | `propdef<boolean>` | any non null attribute value other than `\"false\"` parses as `true`; `\"false\"` or absent attribute is `false` |\n| `prop.number(defaultvalue?)` | `propdef<number>` | returns default (not nan) and warns in dev when attribute is not a valid number |\n| `prop.oneof(allowed, defaultvalue?)` | `propdef<t>` | restricts to a fixed set of string or number members; `parse` falls back to `defaultvalue` (or `undefined` when omitted) for anything outside the set. numeric members match the attribute parsed as a number |\n| `prop.json(defaultvalue)` | `propdef<t>` | json.parse from attribute; `reflect: false` |\n| `prop.data<t>(defaultvalue?)` | `propdef<t>` | js only: never reads/writes an attribute; use for objects, arrays, callbacks, or any non serialisable value |\n\n> **choosing the right prop helper:**\n>\n> **`prop.oneof`**: the honest way to type a union valued prop: the restriction is enforced at runtime (`parse` falls back for anything outside the set), not just in a type parameter a raw attribute value could violate. pass an `as const` array of the allowed string or number members.\n> **`prop.json`**: value can be declared in html (`<my el config='{\"x\":1}'>`); attribute string is `json.parse`d.\n> **`prop.data`**: value is always set from javascript (objects, arrays, callbacks, class instances); the attribute is never read. use this for both data and function props.\n\nwhen you need custom parsing or `reflect: false`, use a raw `propdef` object:\n\n```ts\nprops: {\n items: { default: [], parse: () => [], reflect: false },\n}\n```\n\nuse `prop.data` for props that hold js only values (including callbacks) that cannot be serialised through an html attribute:\n\n```ts\ndefine('data grid', {\n props: {\n getrowkey: prop.data<(row: unknown) => string>(),\n columns: prop.data<datagridcolumn[]>([]),\n onsort: prop.data<(key: string) => void>(),\n },\n setup(props) {\n // set from js: grid.getrowkey = (row) => row.id\n return html`...`;\n },\n});\n```\n\n## template and directives\n\n### `html`\n\ntagged template literal that returns an `htmlresult`. supports text interpolation, ordinary attributes (`attr=`),\nboolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional\n`.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.\n\n`.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured\nvalues (arrays, objects, callbacks). prototype polluting names (`__proto__`, `constructor`, `prototype`) and\nraw html parsing names (`innerhtml`, `outerhtml`, `srcdoc`) are rejected at compile time: render sanitized\nhtml through the `unsafehtml()` directive instead of a property binding.\n\n`@event.stop`, `.prevent`, `.once`, and `.capture` are shorthand for the matching listener behavior\n(`stoppropagation`/`preventdefault` applied before the handler runs; `once`/`capture` passed as listener\noptions). an unknown modifier throws at compile time.\n\n### `css`\n\ntagged template literal that returns a `cssresult` for use in `styles`.\n\n### directives\n\n| directive | purpose |\n| | |\n| `each(source, key, render, fallback?)` | keyed reactive list; render receives `readable<t>` and `readable<number>`; plain `t[]` is a one time static snapshot |\n| `when(condition, truthy, falsy?)` | conditional rendering |\n| `classmap(record)` | reactive class string from object map |\n| `stylemap(record)` | reactive inline style string from object map |\n| `live(signal)` | one way binding that skips stale writes during active user input; use with `@input` handler |\n| `model(signal, options?)` | two way form control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |\n| `unsafehtml(value)` | html rendering sink; sanitize untrusted values before calling |\n\n`each()` treats number and string keys as distinct. a reconciliation failure (a duplicate key, or a render function that throws) reports `ore:error` and preserves the last valid list: entries created during the failed pass are rolled back, so the previous list stays exactly on screen.\n\n### `model(signal, options?)`\n\ntwo way binding for a form control: `value=${model(signal)}`. it writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and `<select>`; `'input'` otherwise). this is the complete controlled input loop that the `live()` + manual `@input` handler pair used to require.\n\n```ts\nconst text = signal('');\nconst agree = signal(false);\nconst count = signal(0);\n\nhtml`\n <input value=${model(text)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n`;\n```\n\n`options` overrides the defaults for non native controls: `event` sets the write back event name and `get` reads the current value out of the element (default `el.checked` for checkboxes/radios, `el.value` otherwise). because a native text input's `value` is always a string, pass a `get` like `(el) => number(el.value)` to keep a numeric signal numeric. `model()` can only drive a plain `value`/`checked` attribute binding; using it on a boolean (`?checked=`) or other attribute throws.\n\n### `unsafehtml`\n\n`unsafehtml()` is an explicit html injection sink. it has no global sanitizer: sanitize untrusted\ncontent before passing it to the directive, so the trust boundary remains at the call site.\n\n```ts\nimport { unsafehtml } from '@vielzeug/ore';\n\nconst safearticle = sanitize(usersuppliedarticle);\n\nreturn html`<article>${unsafehtml(safearticle)}</article>`;\n```\n\n## host bindings\n\n`bind(config, options?)` is a plain function imported from `@vielzeug/ore`:\n\n```ts\nbind({\n attr: { role: 'button', 'aria expanded': () => string(open.value) },\n class: { 'is open': open },\n style: { ' height': () => height.value + 'px' },\n on: { click: handleclick },\n});\n```\n\n`bind()` auto registers cleanup with the component scope: no manual `oncleanup` needed. returns a cleanup function for early teardown.\n\n### off host bindings\n\npass `{ target: el }` as a second argument to bind to any element other than the host:\n\n```ts\nbind({ attr: { 'aria expanded': () => string(isopen.value) } }, { target: triggerel });\n```\n\nevent listener options (`once`, `capture`, `passive`) are also accepted in the second argument. cleanup is auto registered with the component scope when called during setup.\n\n### reactive aria attributes\n\nuse explicit `aria *` keys in `bind({ attr }, { target })`:\n\n```ts\nconst stoparia = bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => isopen.value,\n 'aria haspopup': 'listbox',\n },\n },\n { target: triggerel },\n);\n```\n\nstatic values are applied once. getters and signals create reactive effects. calling `stoparia()` stops updates. values of `null`, `undefined`, or `false` remove the attribute.\n\n## slots\n\n `slots.has(name?)`: `readable<boolean>`: whether the named (or default) slot has assigned content\n `slots.elements(name?)`: `readable<element[]>`: the assigned elements for the slot\n\nslot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.\n\n## context api\n\n `createcontext<t>(description)`: create a unique typed injection key; the description is diagnostic only\n `provide(key, value)`: provide a value to descendants\n `inject(key)`: resolve from nearest ancestor; returns `undefined` if not found\n `inject(key, fallback)`: resolve with a fallback value\n `injectstrict(key)`: resolve or throw if absent\n\n`provide()` and `inject()` must be called synchronously during `setup()`. calling them outside a setup context throws\n`'lifecycle hooks must be called during component setup'`. context resolution walks the ancestor chain including shadow\ndom boundaries. `inject()` resolves and caches its result once per consumer: provide a `readable` (signal/computed)\nrather than a raw value if descendants need to observe later changes; re calling `provide()` with a new raw value\nafterward is not seen by consumers that already resolved it (a dev mode warning fires when a key is provided twice on\nthe same element). `provide()` registers cleanup automatically: context keys are removed from the registry when the\nproviding component disconnects, so reconnecting the same element runs `setup()` fresh without spurious \"overwriting\"\nwarnings or stale keys leaking to descendants.\n\n## utilities\n\n `ref<t>()`: create a `signal<t | null>` element reference. set to the element via `ref=` in templates.\n `createid(prefix = 'id')`: generate a collision resistant id with a semantic prefix, a per runtime tag, and a monotonic counter (for example, `'field a3k21'`).\n\n## form associated api\n\nimport from `@vielzeug/ore`.\n\n### `usefield(options)`\n\nwire a form associated element to `elementinternals`. requires `formassociated: true` on the component definition. the `disabled` state tracking via `internals.states` (customstateset) is skipped with a dev warning if the api is unavailable in the current environment.\n\n```ts\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t> = {\n disabled?: readable<boolean>;\n /**\n * when true, a null/undefined value is submitted as '' instead of null,\n * keeping the field's key present in formdata even when the value is absent.\n * only applies to the default toformvalue; ignored if toformvalue is provided.\n * @default false\n */\n emptystringfornull?: boolean;\n /** called when the ancestor <form> resets (see onformreset): restore local field state here. */\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n /**\n * recomputed reactively and passed straight to internals.setvalidity().\n * null (or omitted) = always valid. flags and message travel together because\n * the platform's setvalidity() contract couples them (flags without a\n * non empty message throw); a single { flags, message } | null input makes a\n * desynced pair unrepresentable.\n */\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity(): boolean;\n readonly internals: elementinternals;\n reportvalidity(): boolean;\n /** set (non empty message) or clear (empty string) a custom validity error. */\n setcustomvalidity(message: string): void;\n};\n```\n\npass a single `validity` signal to make `required` style constraints participate in native constraint validation\nthrough `checkvalidity()` and `reportvalidity()`. the `{ flags, message }` pair is the one validity input: the old\nsplit `validity` + `validationmessage` options are gone, since they could drift apart into a state the platform\nrejects.\n\n```ts\nconst isblank = (v: string) => v.trim() === '';\n\nusefield({\n validity: computed(() =>\n required.value && isblank(value.value)\n ? { flags: { valuemissing: true }, message: 'this field is required.' }\n : null,\n ),\n value,\n});\n```\n\n## testing apis\n\nimport from `@vielzeug/ore/testing`.\n\n| api | purpose |\n| | |\n| `mount(setup, options?)` | mount a component and return a test fixture |\n| `cleanup()` | remove all mounted elements and reset test state |\n| `install(aftereach)` | register auto cleanup after each test |\n| `flush(options?)` | drain reactive updates and animation frames |\n| `renderhook(setup)` | run lifecycle hooks in isolation; overload accepts `propdefs` as first arg for typed props |\n| `oretimeouterror` | error thrown when `flush()` cannot settle tracked ore work |\n\n> **test isolation:** `cleanup()` removes mounted elements and resets ore's cross test caches and counters. call it in `aftereach`, or use `install(aftereach)`.\n\nimport `within`, named dispatchers such as `fireclick`, and waits such as `waituntil` or `waitforevent` from\n`@vielzeug/assay`.\n\n> **form associated component testing:** jsdom implements none of the `elementinternals` form association api.\n> `@vielzeug/assay` exports `installforminternalspolyfill()` for this: it polyfills\n> `setformvalue`/`setvalidity`/`checkvalidity`/`reportvalidity`/`validationmessage`/`validity`/`states`, mixes\n> `checkvalidity`/`reportvalidity`/`validity`/`validationmessage` onto the host element itself (real browsers do\n> this for any `formassociated: true` element), makes `formdata` collect a form associated element's set value, and\n> makes `<form>.reset()` invoke `formresetcallback()`. every patch is a guarded no op when its target already\n> exists, and the function returns an `uninstall()` that restores every patched global. call it directly from a\n> test setup (alongside `install(aftereach)`) only when the suite tests form associated components: the patches\n> are global, so suites without them shouldn't carry them. a downstream package (e.g. a component library built\n> on `ore`) should rely on it instead of hand rolling its own copy.\n\n#### `fixture` interface\n\n```ts\ninterface fixture<t extends htmlelement = htmlelement> {\n [symbol.dispose](): void; // delegates to dispose(): enables `using` declarations\n element: t;\n readonly disposed: boolean; // true after dispose() has been called\n readonly shadow: shadowroot | null;\n get<e extends element>(selector: string): e;\n query<e extends element>(selector: string): e | null;\n queryall<e extends element>(selector: string): e[];\n getbytext<e extends element>(text: string, selector?: string): e;\n querybytext<e extends element>(text: string, selector?: string): e | null;\n queryallbytext<e extends element>(text: string, selector?: string): e[];\n getbytestid<e extends element>(testid: string): e;\n querybytestid<e extends element>(testid: string): e | null;\n queryallbytestid<e extends element>(testid: string): e[];\n attr(name: string, value: string | number | boolean): promise<void>;\n attrs(record: record<string, string | number | boolean>): promise<void>;\n flush(options?: flushoptions): promise<void>;\n act(fn: () => unknown): promise<void>;\n dispose(): void; // removes the component from the dom: idempotent\n}\n```\n\n#### `renderhook`\n\nuseful for testing composable lifecycle hooks (`onmounted`, `watcheffect`, `inject`, etc.) without a template. `onmounted`/`oncleanup`/`watcheffect`/... work exactly as inside a real `setup()`, since they resolve the same implicit current component context:\n\n```ts\n// without props\nconst { result, flush, dispose } = await renderhook(() => {\n const count = signal(0);\n onmounted(() => {\n count.value = 1;\n });\n return count;\n});\nexpect(result.value).tobe(1);\n\n// with typed props (prop defs overload)\nconst { result } = await renderhook({ label: prop.string('hello'), count: prop.number(0) }, (props) => props.label);\nexpect(result.value).tobe('hello');\n```\n\n## ripple primitives\n\nore does **not** re export reactive primitives. import them directly from `@vielzeug/ripple`:\n\n```ts\nimport { batch, computed, signal, watch } from '@vielzeug/ripple';\n```\n\nsee the [ripple documentation](/ripple/) for the full api.\n\n## lifecycle events\n\n| event | when |\n| | |\n| `ore:error` | when a lifecycle callback fails: bubbles, composed; detail is `orelifecycleerror` |\n\n## types\n\n```ts\ntype propdef<t> = {\n readonly default: t;\n readonly parse: (value: string | null) => t;\n reflect?: boolean;\n};\n\ntype propsdef<t extends record<string, unknown>> = {\n [k in keyof required<t>]: propdef<t[k & keyof t]>;\n};\n\ntype propinputdefs = record<string, propdef<unknown>>;\n\n/**\n * infer reactive props type from a propinputdefs map.\n * each entry becomes readable<t> keyed by prop name.\n */\ntype inferprops<d extends propinputdefs> = {\n readonly [k in keyof d] ?: readable<inferpropvalue<d[k]>>;\n};\n\n// runtime hooks: all plain functions imported from '@vielzeug/ore', not fields on an object.\ntype onmountedcallback = () => cleanup | undefined;\ntype onformresetcallback = () => void;\n\ndeclare function onmounted(fn: onmountedcallback): void; // dom ready callback; runs after each connection's render\ndeclare function oncleanup(fn: cleanup): void; // register teardown; called on disconnect\ndeclare function onelement<t extends htmlelement>(\n ref: readable<t | null>,\n callback: (el: t) => cleanup | undefined,\n): () => void;\ndeclare function onevent<k extends keyof htmlelementeventmap>(\n target: eventtarget | null | undefined,\n event: k,\n listener: (e: htmlelementeventmap[k]) => void,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onevent(\n target: eventtarget | null | undefined,\n event: string,\n listener: eventlistener,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onformreset(fn: onformresetcallback): void; // runs on every ancestor <form> reset; formassociated only\ndeclare function watcheffect(fn: () => cleanup | undefined): () => void; // scoped reactive effect; auto cleaned on disconnect\ndeclare function bind(config: hostbindconfig, options?: bindoptions): () => void; // bindings for host or any target element\ndeclare function provide<t>(key: injectionkey<t>, value: t): void; // register a context value on the host element\ndeclare function inject<t>(key: injectionkey<t>): t | undefined;\ndeclare function inject<t>(key: injectionkey<t>, fallback: t): t;\ndeclare function gethost(): htmlelement; // the current component's host element\ndeclare function useemit<emits extends record<string, unknown> = record<string, never>>(): emitfn<emits>;\ndeclare function useslots<slotnames extends string = string>(): componentslots<slotnames>;\n\ntype componentdefinition<props extends record<string, unknown> = record<never, never>> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom\n styles?: (string | cssstylesheet | cssresult)[];\n};\n\ntype maybereactive<t> = t | readable<t> | (() => t); // plain value, signal, or getter: accepted by when(), each(), classmap(), and bind()\n\ntype hostbindingvalue = maybereactive<string | number | boolean | null | undefined>;\n\ntype attributebindings = record<string, hostbindingvalue>;\n\ntype hostbindconfig = {\n attr?: attributebindings;\n class?: (() => record<string, boolean>) | record<string, readable<boolean> | (() => boolean) | boolean>;\n on?: record<string, ((event: event) => void) | undefined>;\n style?: record<string, hostbindingvalue>;\n};\n\ntype bindoptions = addeventlisteneroptions & {\n target?: element;\n};\n\ntype componentslots<s extends string = string> = {\n elements(name?: s): readable<element[]>;\n has(name?: s): readable<boolean>;\n};\n\ntype ref<t extends element> = signal<t | null>;\n\ntype refcallback<t extends element> = (el: t | null) => void;\n\ntype injectionkey<t> = symbol & { readonly __ore_injection_key?: t };\n\ninterface htmlresult {\n mount(parent: parentnode, anchor: node | null, registercleanup: (fn: () => void) => void): node[];\n}\n\ntype cssresult = {\n content: string;\n tostring(): string;\n};\n\ntype livebinding<t> = { readonly source: readable<t> };\n\ntype modeloptions<t = unknown> = {\n /** write back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */\n event?: string;\n /** value reader (default: el.checked for checkbox/radio, el.value otherwise). */\n get?: (el: htmlelement) => t;\n};\n\ntype emitfn<t extends record<string, unknown>> = {\n <k extends keyswithoutdetail<t>>(event: k): boolean;\n <k extends exclude<keyof t, keyswithoutdetail<t>>>(event: k, detail: t[k]): boolean;\n};\n// keyswithoutdetail is an internal helper type, not exported.\n\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t = unknown> = {\n disabled?: readable<boolean>;\n emptystringfornull?: boolean;\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity: () => boolean;\n readonly internals: elementinternals;\n reportvalidity: () => boolean;\n setcustomvalidity: (message: string) => void;\n};\n\n/** phase in which a oreerror occurred. */\ntype oreerrorphase = 'each reconcile' | 'form reset' | 'mounted' | 'setup';\n```\n\n## errors\n\n`oreerror` is the base class for every ore error class: `err instanceof oreerror` catches all of them.\n\n **`oreapierror`**: thrown when the `ore` api itself is misused: calling `define()` with a duplicate tag, calling a lifecycle hook (`inject`, `onmounted`, `oncleanup`, `onevent`, …) outside of `setup()`, or passing an invalid prop definition to `define()`.\n **`oreinternalerror`**: thrown when an ore invariant fails, indicating a package bug rather than invalid application code.\n **`orelifecycleerror`**: reported in the `ore:error` event when component `setup()`, a mounted callback, a form reset callback, or `each()` reconciliation fails. extends `oreerror` with:\n `component: string`: the element's local name\n `phase: oreerrorphase`: `'setup'` | `'mounted'` | `'form reset'` | `'each reconcile'`\n `cause: error`: the original error thrown by `setup()`\n **`oretimeouterror`**: thrown by `flush()` (from `@vielzeug/ore/testing`) when pending ore work does not settle before its timeout.\n\nlifecycle failures dispatch a bubbling, composed `ore:error` event whose `detail` is the `orelifecycleerror`. setup\nfailures still rethrow their original error; mounted and form reset callback failures are reported through the same\nevent so their remaining callbacks can continue.\n",
963
- "usage": " \ntitle: 'ore: usage guide'\ndescription: practical ore usage patterns for components, props, templates, slots, context, forms, sentinel integration, and tests.\n \n\n[[toc]]\n\n## basic usage\n\n`define(tag, definition)` creates and registers a custom element. call it from the module or browser bootstrap responsible for registration.\n\nyour `setup()` function receives typed prop signals and returns an `htmlresult` directly. its state belongs to the\ncurrent connection: disconnect disposes it, and reconnecting the same element runs setup again.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('status chip', {\n setup() {\n const online = signal(true);\n\n return html`\n <button @click=${() => (online.value = !online.value)}>${() => (online.value ? 'online' : 'offline')}</button>\n `;\n },\n});\n```\n\neverything besides `props`: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, gethost, html, bind, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my widget', {\n setup(_props) {\n const el = gethost(); // the host htmlelement\n const emit = useemit<{ close: undefined }>(); // typed event emitter\n const slots = useslots<'header'>(); // reactive slot observation\n\n bind({ attr: { role: 'group' } }); // host binding helper (attr, class, style, on)\n\n return html`<slot></slot>`;\n },\n});\n```\n\n## signals and effects\n\nore does not re export ripple primitives: import them directly from `@vielzeug/ripple`.\n\n```ts\nimport { batch, computed, effect, signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst doubled = computed(() => count.value * 2);\n\neffect(() => {\n console.log('doubled =', doubled.value);\n});\n\nwatch(count, (next, prev) => {\n console.log('count changed', prev, ' >', next);\n});\n\nbatch(() => {\n count.value = 1;\n count.value = 2;\n});\n```\n\n## onmounted and lifecycle\n\nuse `onmounted()` for dom dependent initialization that must run after the template is mounted. use `onelement(ref, cb)` for work tied to a specific dom node. `onevent()` attaches a listener that is automatically removed on disconnect.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, onelement, onevent, onmounted, ref, useslots } from '@vielzeug/ore';\n\ndefine('deferred init', {\n setup(_props) {\n const tabindex = signal(0);\n const inputref = ref<htmlinputelement>();\n const slots = useslots<'items'>();\n\n onmounted(() => {\n const items = slots.elements('items').value;\n console.log('found', items.length, 'items');\n });\n\n onelement(inputref, (input) => {\n input.focus();\n });\n\n onevent(window, 'keydown', (e: keyboardevent) => {\n if (e.key === 'escape') tabindex.value = 0;\n });\n\n return html`<div><slot name=\"items\"></slot><input ref=${inputref} /></div>`;\n },\n});\n```\n\n## prop definitions\n\nuse `prop.*` helpers for common cases, or raw `propdef` objects for custom parsing or `reflect: false`.\n\n```ts\nimport { define, html, prop } from '@vielzeug/ore';\n\ndefine('x button', {\n props: {\n label: prop.string('button'),\n disabled: prop.bool(false),\n variant: prop.oneof(['primary', 'secondary'] as const, 'primary'),\n count: prop.number(0),\n },\n setup(props) {\n return html`\n <button ?disabled=${props.disabled} data variant=${props.variant}>${props.label} (${props.count})</button>\n `;\n },\n});\n```\n\n## template bindings\n\n`html` supports text, attributes, booleans, properties, events, refs, and nested templates. event bindings accept\n`.stop`, `.prevent`, `.once`, and `.capture`: the first two apply before the handler runs, while the latter two use\nnative listener options. unknown modifiers throw while ore compiles the template.\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { define, html, model, ref } from '@vielzeug/ore';\n\ndefine('profile name', {\n setup() {\n const name = signal('alice');\n const inputref = ref<htmlinputelement>();\n\n return html`\n <label title=${computed(() => 'current: ' + name.value)}>name</label>\n <input\n ref=${inputref}\n value=${model(name)}\n aria label=${() => 'current name ' + name.value} />\n <p>hello ${name}</p>\n `;\n },\n});\n```\n\n## directives\n\nore exports `each`, `classmap`, `stylemap`, `when`, `live`, `model`, and `unsafehtml` from `@vielzeug/ore`.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { classmap, define, each, html, stylemap, when } from '@vielzeug/ore';\n\ndefine('task list', {\n setup() {\n const tasks = signal([{ id: 1, text: 'write tests' }]);\n const active = signal(true);\n\n return html`\n <ul\n class=\"${classmap({ ready: () => tasks.value.length > 0 })}\"\n style=${stylemap({ opacity: () => (active.value ? 1 : 0.5) })}>\n ${when(\n () => active.value,\n () => html`<li>active</li>`,\n () => html`<li>paused</li>`,\n )}\n ${each(\n tasks,\n (task) => task.id,\n (task) => html`<li>${() => task.value.text}</li>`,\n )}\n </ul>\n `;\n },\n});\n```\n\n### each() api\n\n`each(source, key, render, fallback?)` takes positional arguments:\n\n **source**: signal, getter, or plain array\n **key**: function returning a unique string or number per item; number and string keys remain distinct\n **render**: receives reactive `item` and `index` signals\n **fallback**: optional, rendered when the list is empty\n\n```ts\neach(\n items,\n (item) => item.id,\n (item, index) => html`<li>#${index}: ${() => item.value.label}</li>`,\n () => html`<li>no items</li>`,\n);\n```\n\neach reactive reconciliation is transactional. ore creates missing entries before committing updates or removing stale\nentries; if a render callback throws, entries created during that pass are rolled back and the last successful list\nremains on screen. ore reports the failure through `ore:error` with phase `each reconcile`.\n\n## model: two way form bindings\n\nuse `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and\nwrites user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`\notherwise). this replaces the `live()` + manual `@input` handler pair with one binding.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, model } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n const agree = signal(false);\n\n return html`\n <input value=${model(query)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n `;\n },\n});\n```\n\na native text input's `value` is always a string, so pass a `get` reader to keep a numeric signal numeric, and an\n`event` name for custom controls that emit their own change event:\n\n```ts\nconst count = signal(0);\n\nhtml`\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n <my picker value=${model(pick, { event: 'pick change', get: (el) => (el as mypicker).selection })} />\n`;\n```\n\n## live: one way bindings that preserve user edits\n\nuse `live(signal)` when a binding must skip a stale app state write while the user is mid edit, without writing\nuser input back. `model()` covers the common controlled input case; `live()` is for one way bindings that only\nneed the stale write guard.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, live } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n\n return html`\n <input value=${live(query)} @input=${(e: event) => (query.value = (e.target as htmlinputelement).value)} />\n `;\n },\n});\n```\n\n## host bindings\n\n`bind()` wires reactive attrs, classes, styles, and events to the host element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html } from '@vielzeug/ore';\n\ndefine('x toggle', {\n setup(_props) {\n const open = signal(false);\n\n bind({\n attr: { 'aria expanded': () => string(open.value), role: 'button', tabindex: 0 },\n class: { 'is open': open },\n on: { click: () => (open.value = !open.value) },\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nthe `bind` config supports `attr`, `class`, `style`, and `on` sections.\n\n## aria bindings\n\nuse explicit `aria *` keys in `bind({ attr: config }, { target })` to reactively sync aria attributes to any element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onmounted } from '@vielzeug/ore';\n\ndefine('x disclosure', {\n setup(_props) {\n const open = signal(false);\n const panelid = 'disclosure panel';\n\n bind({\n attr: { role: 'button', tabindex: 0 },\n on: { click: () => (open.value = !open.value) },\n });\n\n onmounted(() => {\n const trigger = document.queryselector('#trigger') as htmlelement;\n if (trigger) {\n // bind() registers cleanup automatically when called inside setup\n bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => string(open.value),\n 'aria haspopup': 'region',\n },\n },\n { target: trigger },\n );\n }\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nstatic values are applied once. getter functions create reactive effects. setting a value to `null`, `undefined`, or `false` removes the attribute.\n\n`bind()` always returns a cleanup function. use it to stop syncing early when a trigger element can be swapped out:\n\n```ts\nonmounted(() => {\n const trigger = document.queryselector('#trigger') as htmlelement;\n const stoparia = bind({ attr: { 'aria expanded': () => string(open.value) } }, { target: trigger });\n\n // stop syncing when the trigger is replaced\n oncleanup(stoparia);\n});\n```\n\n### binding a non host element with `bind()`\n\npass `{ target: el }` as a second argument to bind attributes, classes, styles, or events to any element:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onmounted, ref } from '@vielzeug/ore';\n\ndefine('button wrapper', {\n setup(_props) {\n const visible = signal(false);\n const btnref = ref<htmlbuttonelement>();\n\n onmounted(() => {\n const btn = btnref.value;\n if (!btn) return;\n\n bind(\n {\n attr: { 'aria pressed': () => string(visible.value) },\n on: { click: () => (visible.value = !visible.value) },\n },\n { target: btn },\n );\n });\n\n return html`<button ref=${btnref}>toggle</button>`;\n },\n});\n```\n\n## slots and emits\n\n```ts\nimport { define, html, useemit, useslots, when } from '@vielzeug/ore';\n\ndefine('card with footer', {\n setup(_props) {\n const slots = useslots<'header' | 'footer'>();\n const emit = useemit<{ action: undefined }>();\n\n return html`\n <div class=\"card\">\n <slot name=\"header\"></slot>\n <slot></slot>\n ${when(slots.has('footer'), () => html`<footer><slot name=\"footer\"></slot></footer>`)}\n </div>\n <button @click=${() => emit('action')}>go</button>\n `;\n },\n});\n```\n\npass a `slotnames` type parameter to `useslots<slotnames>()` to get typed `slots.has()` and `slots.elements()` calls.\n\n## context provide/inject\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { createcontext, define, html, injectstrict, provide } from '@vielzeug/ore';\n\nconst count_ctx = createcontext<returntype<typeof signal<number>>>('count');\n\ndefine('count provider', {\n setup(_props) {\n const count = signal(0);\n provide(count_ctx, count);\n\n return html`<button @click=${() => count.value++}><slot></slot></button>`;\n },\n});\n\ndefine('count consumer', {\n setup() {\n const count = injectstrict(count_ctx);\n\n return html`<p>count: ${count}</p>`;\n },\n});\n```\n\n`provide()` registers cleanup automatically: context keys are removed from the registry when the providing component disconnects. on reconnect, `setup()` runs fresh and `provide()` re registers without spurious \"overwriting\" warnings. provide a `readable` (signal/computed) rather than a raw value if descendants need to observe later changes: `inject()` resolves and caches the value once per consumer connection.\n\n## form associated elements\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, prop } from '@vielzeug/ore';\nimport { usefield } from '@vielzeug/ore';\n\ndefine('rating input', {\n formassociated: true,\n setup() {\n const value = signal(0);\n const field = usefield({ value });\n\n return html`\n <button @click=${() => (value.value = 1)}>1</button>\n <button @click=${() => (value.value = 2)}>2</button>\n <button @click=${() => (value.value = 3)}>3</button>\n <button @click=${() => field.reportvalidity()}>validate</button>\n <p>current: ${value}</p>\n `;\n },\n});\n```\n\n## sentinel observers\n\nuse `@vielzeug/sentinel` for subscribable browser and dom observations. create element dependent sentinels inside `onmounted()` and dispose them with the component.\n\n```ts\nimport { define, html, oncleanup, onmounted, ref, watcheffect } from '@vielzeug/ore';\nimport { fromsubscribable } from '@vielzeug/ripple';\nimport { createelementsize, sentinelunavailableerror } from '@vielzeug/sentinel';\n\ndefine('x observed', {\n setup(_props) {\n const boxref = ref<htmldivelement>();\n\n onmounted(() => {\n const element = boxref.value;\n if (!element) return;\n\n try {\n const size = createelementsize(element);\n const sizestate = fromsubscribable(size, { signal: size.disposalsignal });\n\n watcheffect(() => {\n console.log(sizestate.value?.width);\n });\n\n oncleanup(() => size.dispose());\n } catch (error) {\n if (!(error instanceof sentinelunavailableerror)) throw error;\n }\n });\n\n return html`<div ref=${boxref}>observe me</div>`;\n },\n});\n```\n\n## testing utilities\n\nimport from `@vielzeug/ore/testing`.\n\n```ts\nimport { aftereach, describe, expect, it } from 'vitest';\nimport { signal } from '@vielzeug/ripple';\nimport { fireclick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { cleanup, mount } from '@vielzeug/ore/testing';\n\ndescribe('my counter', () => {\n aftereach(cleanup);\n\n it('increments on click', async () => {\n let count!: returntype<typeof signal<number>>;\n const { query, act } = await mount(() => {\n count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n });\n\n expect(query('button')?.textcontent).tobe('0');\n\n await act(() => fireclick(query('button')!));\n\n expect(query('button')?.textcontent).tobe('1');\n });\n});\n```\n\n## framework integration\n\nore components are standard custom elements and work natively in any framework.\n\n::: code group\n\n```tsx [react]\n// react 19+ supports custom elements natively.\nimport './x toggle'; // wherever define('x toggle', { ... }) is called\n\nfunction app() {\n return <x toggle aria label=\"open menu\" />;\n}\n```\n\n```ts [vue 3]\n<script setup lang=\"ts\">\nimport './x toggle'; // wherever define('x toggle', { ... }) is called\nimport { ref } from 'vue';\n\nconst open = ref(false);\n</script>\n\n<template>\n <x toggle :aria label=\"'open menu'\" @click=\"open = !open\" />\n</template>\n```\n\n```svelte [svelte]\n<script>\n import './x toggle'; // wherever define('x toggle', { ... }) is called\n\n function handleclick() {\n console.log('toggled');\n }\n</script>\n\n<x toggle aria label=\"open menu\" on:click={handleclick} />\n```\n\n:::\n\n## working with other vielzeug libraries\n\n### with ripple\n\nimport ripple primitives directly from `@vielzeug/ripple` for standalone reactive state outside components.\n\n```ts\nimport { signal, computed } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\n// shared state created outside any component\nconst theme = signal<'light' | 'dark'>('light');\nconst isdark = computed(() => theme.value === 'dark');\n\ndefine('theme toggle', {\n setup() {\n return html`\n <button @click=${() => (theme.value = isdark.value ? 'light' : 'dark')}>\n ${() =>\n isdark.value ? '<ore icon name=\"sun\" size=\"16\"></ore icon>' : '<ore icon name=\"moon\" size=\"16\"></ore icon>'}\n </button>\n `;\n },\n});\n```\n\n### with forge\n\nuse `@vielzeug/forge` for typed form state. `usefield()` remains intentionally narrow: it connects a form associated\ncustom element to native `elementinternals` without imposing submission, validation, or dirty state policy.\n\n```ts\nimport { createform } from '@vielzeug/forge';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('signup form', {\n setup(_props) {\n const form = createform({ initialvalues: { email: '' } });\n\n return html`\n <form\n @submit=${(event: submitevent) => {\n event.preventdefault();\n void form.submit(async (values) => {\n console.log(values);\n });\n }}>\n <slot></slot>\n </form>\n `;\n },\n});\n```\n\n## best practices\n\n setup returns `html\\`...\\`` directly: not a function wrapping the template.\n use `watcheffect()` for reactive subscriptions tied to component lifetime: it auto registers cleanup on disconnect.\n use `onelement(ref, cb)` instead of `onmounted` when the work is tied to a single dom node.\n bind host attributes and classes via `bind()` rather than mutating the element directly.\n provide context at the nearest ancestor: avoid global context singletons.\n call `oncleanup()` for every resource allocated in `setup()` (websockets, intervals, external subscriptions).\n use `model(signal)` for two way form inputs; use `live(signal)` for a one way binding that must not clobber user in progress edits.\n extract composable helper functions freely: `onmounted`/`oncleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.\n test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic dom events, queries, and waits\n from `@vielzeug/assay`.\n",
962
+ "api": " \ntitle: 'ore: api reference'\ndescription: complete api reference for @vielzeug/ore and @vielzeug/ore/testing.\n \n\n[[toc]]\n\n## api overview\n\nall browser runtime symbols below are imported from `@vielzeug/ore`. lifecycle/context/binding functions (`onmounted`, `oncleanup`, `onevent`, `onelement`, `watcheffect`, `bind`, `provide`, `useemit`, `useslots`, `gethost`) resolve the active component through an implicit \"current component\" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window. the one exception is `bind()` with an explicit `options.target`: it also works outside setup (for example from an event handler), where only its returned disposer stops it.\n\n> `watcheffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `define()` | create and register a custom element | sync | tag must contain a hyphen; call before first use |\n| `html` | tagged template literal returning htmlresult | sync | expressions must be signals, functions, or primitives |\n| `prop.*` | typed prop helpers (string, bool, number, …) | sync | prop values are signals: read `.value` |\n| `provide()`/`inject()` | context api for parent to descendant sharing | setup only | must be called synchronously during `setup()` |\n| `ref()` | reactive reference to a dom element | sync | value is null until after first mount |\n| `createcontext()` | create a unique typed injection key | sync | context is scoped to the component tree |\n| `each()` | keyed list rendering with dom diffing | sync | duplicate keys report `ore:error`; plain `t[]` is a one time static render |\n| `when()` | conditional branch rendering | sync | getter fn computed disposed on cleanup; static bool skips subscription |\n| `model(signal)` | two way form control binding (value/checked + write back) | sync | plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |\n| `onmounted(fn)` | dom ready callback | setup only | must be called synchronously during `setup()` |\n| `oncleanup(fn)` | register teardown | setup only | called on disconnect, one microtask later, unless the element reconnects (a same turn move) |\n| `onevent(target, …)` | scoped event listener with auto cleanup | setup only | no ops on null target; removed on disconnect |\n| `usefield(options)` | wire signal to form `elementinternals` | setup only | requires `formassociated: true` on the component definition |\n| `onformreset(fn)` | run work when the ancestor `<form>` resets | setup only | fires every reset (not one shot); only for `formassociated: true` components |\n| `useemit<emits>()` | typed `emit()` bound to the current host | setup only | call once per component; returns `dispatchevent`'s boolean (`false` if a listener called `preventdefault()`) |\n| `useslots<slotnames>()` | reactive slot presence/element signals | setup only | safe to call more than once: the underlying registry is created once |\n| `gethost()` | the current component's host element | setup only | prefer a higher level helper (`bind`, …) when one exists |\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/ore` | all browser runtime apis, including directives, fields, and lifecycle helpers |\n| `@vielzeug/ore/testing` | ore specific mounting, lifecycle, hook, cleanup, and form test support |\n| `@vielzeug/assay` | generic dom events, scoped queries, and async waiting |\n\n## core component api\n\n### `define(tag, definition)`\n\n```ts\ndefine<props>(tag: string, definition: componentdefinition<props>): customelementconstructor;\n```\n\nreturns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.\n\nomit `props` to infer prop types from `props`. pass it explicitly when a public props type already exists: every key it\ndeclares must then have a definition in `props`.\n\nthe `setup()` function receives only typed prop signals:\n\n```ts\nsetup(props) {\n return html`<div>${props.label}</div>`;\n}\n```\n\neverything else: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, html, onmounted, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my card', {\n setup(_props) {\n const emit = useemit<{ close: undefined }>();\n const slots = useslots<'header' | 'footer'>();\n\n onmounted(() => console.log('mounted'));\n\n // emit() returns dispatchevent's boolean: false if a listener called preventdefault()\n const notcancelled = emit('close');\n\n // render the <slot> unconditionally: has() observes rendered slots, so gating the slot itself on has() never shows it.\n return html`<header ?hidden=${() => !slots.has('header').value}><slot name=\"header\"></slot></header>`;\n },\n});\n```\n\n`useemit<emits>()` and `useslots<slotnames>()` are factory hooks: call them once per setup run to get a typed\n`emit`/`slots` bound to the current host. `useslots()` is safe to call more than once within that setup run.\n\n### componentdefinition\n\n```ts\ntype componentdefinition<props> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom (no shadow root)\n styles?: (string | cssstylesheet | cssresult)[];\n};\n```\n\n## runtime helpers\n\n`onmounted`, `oncleanup`, `onevent`, `onelement`, and `watcheffect` are plain functions imported from `@vielzeug/ore`. call them directly during `setup()`.\n\n```ts\nimport { html, oncleanup, onevent, onmounted } from '@vielzeug/ore';\n\nsetup(props) {\n onmounted(() => {\n // dom is ready; return a function for mount scoped cleanup\n return () => { /* cleanup on unmount */ };\n });\n\n oncleanup(() => { /* called on disconnect */ });\n\n onevent(window, 'keydown', (e) => { /* auto removed on disconnect */ });\n\n return html`...`;\n}\n```\n\nbecause these resolve the active component through an implicit context (rather than a value threaded through parameters), composable helper functions can call them directly too: no need to pass hooks in as options:\n\n```ts\nimport { oncleanup } from '@vielzeug/ore';\n\nfunction usemyhelper() {\n oncleanup(() => { /* teardown */ });\n}\n\n// in setup:\nsetup(_props) {\n usemyhelper();\n return html`...`;\n}\n```\n\n## props api\n\n| helper | signature | notes |\n| | | |\n| `prop.string(defaultvalue?)` | `propdef<string>` | reflects by default |\n| `prop.bool(defaultvalue?)` | `propdef<boolean>` | any non null attribute value other than `\"false\"` parses as `true`; `\"false\"` or absent attribute is `false` |\n| `prop.number(defaultvalue?)` | `propdef<number>` | returns default (not nan) and warns in dev when attribute is not a valid number |\n| `prop.oneof(allowed, defaultvalue?)` | `propdef<t>` | restricts to a fixed set of string or number members; `parse` falls back to `defaultvalue` (or `undefined` when omitted) for anything outside the set. numeric members match the attribute parsed as a number |\n| `prop.json(defaultvalue)` | `propdef<t>` | json.parse from attribute; `reflect: false` |\n| `prop.data<t>(defaultvalue?)` | `propdef<t>` | js only: never reads/writes an attribute; use for objects, arrays, callbacks, or any non serialisable value |\n\n> **choosing the right prop helper:**\n>\n> **`prop.oneof`**: the honest way to type a union valued prop: the restriction is enforced at runtime (`parse` falls back for anything outside the set), not just in a type parameter a raw attribute value could violate. pass an `as const` array of the allowed string or number members.\n> **`prop.json`**: value can be declared in html (`<my el config='{\"x\":1}'>`); attribute string is `json.parse`d.\n> **`prop.data`**: value is always set from javascript (objects, arrays, callbacks, class instances); the attribute is never read. use this for both data and function props.\n\nwhen you need custom parsing or `reflect: false`, use a raw `propdef` object. any `{ default, parse, reflect? }` object is a valid prop definition; `reflect` defaults to `false` for raw objects (the `prop.*` helpers reflect, except `prop.json` and `prop.data`). `define()` reports every invalid definition in one `oreapierror`:\n\n```ts\nprops: {\n items: { default: [], parse: () => [], reflect: false },\n}\n```\n\nuse `prop.data` for props that hold js only values (including callbacks) that cannot be serialised through an html attribute:\n\n```ts\ndefine('data grid', {\n props: {\n getrowkey: prop.data<(row: unknown) => string>(),\n columns: prop.data<datagridcolumn[]>([]),\n onsort: prop.data<(key: string) => void>(),\n },\n setup(props) {\n // set from js: grid.getrowkey = (row) => row.id\n return html`...`;\n },\n});\n```\n\n## template and directives\n\n### `html`\n\ntagged template literal that returns an `htmlresult`. supports text interpolation, ordinary attributes (`attr=`),\nboolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional\n`.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.\n\nan `htmlresult` is opaque and single use: each one owns the dom nodes and bindings for one rendering. rendering the\nsame result twice (mounting it again, interpolating it twice, or returning a cached result from a reactive getter)\nthrows `oreapierror`. call the template function again when you need another copy.\n\n`.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured\nvalues (arrays, objects, callbacks). prototype polluting names (`__proto__`, `constructor`, `prototype`) and\nraw html parsing names (`innerhtml`, `outerhtml`, `srcdoc`) are rejected at compile time: render sanitized\nhtml through the `unsafehtml()` directive instead of a property binding.\n\n`@event.stop`, `.prevent`, `.once`, and `.capture` are shorthand for the matching listener behavior\n(`stoppropagation`/`preventdefault` applied before the handler runs; `once`/`capture` passed as listener\noptions). an unknown modifier throws at compile time.\n\n### `css`\n\ntagged template literal that returns a `cssresult` for use in `styles`.\n\n### directives\n\n| directive | purpose |\n| | |\n| `each(source, key, render, fallback?)` | keyed reactive list; render receives `readable<t>` and `readable<number>`; plain `t[]` is a one time static snapshot |\n| `when(condition, truthy, falsy?)` | conditional rendering |\n| `classmap(record)` | reactive class string from object map |\n| `stylemap(record)` | reactive inline style string from object map |\n| `model(signal, options?)` | two way form control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |\n| `unsafehtml(value)` | html rendering sink; sanitize untrusted values before calling |\n\n`each()` treats number and string keys as distinct. a reconciliation failure (a duplicate key, or a render function that throws) reports `ore:error` and preserves the last valid list: entries created during the failed pass are rolled back, so the previous list stays exactly on screen.\n\n### `model(signal, options?)`\n\ntwo way binding for a form control: `value=${model(signal)}`. it writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and `<select>`; `'input'` otherwise). while the control holds an in progress edit the signal has not received yet, stale writes to the signal are skipped.\n\n```ts\nconst text = signal('');\nconst agree = signal(false);\nconst count = signal(0);\n\nhtml`\n <input value=${model(text)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n`;\n```\n\n`options` overrides the defaults for non native controls: `event` sets the write back event name and `get` reads the current value out of the element (default `el.checked` for checkboxes/radios, `el.value` otherwise). because a native text input's `value` is always a string, pass a `get` like `(el) => number(el.value)` to keep a numeric signal numeric. `model()` can only drive a plain `value`/`checked` attribute binding; using it on a boolean (`?checked=`) or other attribute throws.\n\n### `unsafehtml`\n\n`unsafehtml()` is an explicit html injection sink. it has no global sanitizer: sanitize untrusted\ncontent before passing it to the directive, so the trust boundary remains at the call site.\n\n```ts\nimport { unsafehtml } from '@vielzeug/ore';\n\nconst safearticle = sanitize(usersuppliedarticle);\n\nreturn html`<article>${unsafehtml(safearticle)}</article>`;\n```\n\n## host bindings\n\n`bind(config, options?)` is a plain function imported from `@vielzeug/ore`:\n\n```ts\nbind({\n attr: { role: 'button', 'aria expanded': () => string(open.value) },\n class: { 'is open': open },\n style: { ' height': () => height.value + 'px' },\n on: { click: handleclick },\n});\n```\n\n`bind()` auto registers cleanup with the component scope: no manual `oncleanup` needed. returns a cleanup function for early teardown.\n\n### off host bindings\n\npass `{ target: el }` as a second argument to bind to any element other than the host:\n\n```ts\nbind({ attr: { 'aria expanded': () => string(isopen.value) } }, { target: triggerel });\n```\n\nevent listener options (`once`, `capture`, `passive`) are also accepted in the second argument. cleanup is auto registered with the component scope when called during setup.\n\n### reactive aria attributes\n\nuse explicit `aria *` keys in `bind({ attr }, { target })`:\n\n```ts\nconst stoparia = bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => isopen.value,\n 'aria haspopup': 'listbox',\n },\n },\n { target: triggerel },\n);\n```\n\nstatic values are applied once. getters and signals create reactive effects. calling `stoparia()` stops updates. values of `null`, `undefined`, or `false` remove the attribute.\n\n## slots\n\n `slots.has(name?)`: `readable<boolean>`: whether the named (or default) slot has assigned content\n `slots.elements(name?)`: `readable<element[]>`: the assigned elements for the slot\n\nslot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.\n\npresence is measured through the `<slot>` elements the component has rendered: content assigned to a slot that isn't rendered reports `false`. always render the `<slot>` and use `has()` to hide or style its wrapper; ``when(slots.has('x'), () => html`<slot name=\"x\">`)`` never shows the slot.\n\n## context api\n\n `createcontext<t>(description)`: create a unique typed injection key; the description is diagnostic only\n `provide(key, value)`: provide a value to descendants\n `inject(key)`: resolve from nearest ancestor; returns `undefined` if not found\n `inject(key, fallback)`: resolve with a fallback value\n `injectstrict(key)`: resolve or throw if absent\n\n`provide()` and `inject()` must be called synchronously during `setup()`. calling them outside a setup context throws\n`'lifecycle hooks must be called during component setup'`. context resolution walks the ancestor chain including shadow\ndom boundaries. `inject()` resolves and caches its result once per consumer: provide a `readable` (signal/computed)\nrather than a raw value if descendants need to observe later changes; re calling `provide()` with a new raw value\nafterward is not seen by consumers that already resolved it (a dev mode warning fires when a key is provided twice on\nthe same element). `provide()` registers cleanup automatically: context keys are removed from the registry when the\nproviding component disconnects, so reconnecting the same element runs `setup()` fresh without spurious \"overwriting\"\nwarnings or stale keys leaking to descendants.\n\n## utilities\n\n `ref<t>()`: create a `signal<t | null>` element reference. set to the element via `ref=` in templates.\n `createid(prefix = 'id')`: generate a collision resistant id with a semantic prefix, a per runtime tag, and a monotonic counter (for example, `'field a3k21'`).\n\n## form associated api\n\nimport from `@vielzeug/ore`.\n\n### `usefield(options)`\n\nwire a form associated element to `elementinternals`. requires `formassociated: true` on the component definition. the `disabled` state tracking via `internals.states` (customstateset) is skipped with a dev warning if the api is unavailable in the current environment.\n\n```ts\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t> = {\n disabled?: readable<boolean>;\n /**\n * when true, a null/undefined value is submitted as '' instead of null,\n * keeping the field's key present in formdata even when the value is absent.\n * only applies to the default toformvalue; ignored if toformvalue is provided.\n * @default false\n */\n emptystringfornull?: boolean;\n /** called when the ancestor <form> resets (see onformreset): restore local field state here. */\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n /**\n * recomputed reactively and passed straight to internals.setvalidity().\n * null (or omitted) = always valid. flags and message travel together because\n * the platform's setvalidity() contract couples them (flags without a\n * non empty message throw); a single { flags, message } | null input makes a\n * desynced pair unrepresentable.\n */\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity(): boolean;\n readonly internals: elementinternals;\n reportvalidity(): boolean;\n /** set (non empty message) or clear (empty string) a custom validity error. */\n setcustomvalidity(message: string): void;\n};\n```\n\npass a single `validity` signal to make `required` style constraints participate in native constraint validation\nthrough `checkvalidity()` and `reportvalidity()`. the `{ flags, message }` pair is the one validity input: the old\nsplit `validity` + `validationmessage` options are gone, since they could drift apart into a state the platform\nrejects.\n\n```ts\nconst isblank = (v: string) => v.trim() === '';\n\nusefield({\n validity: computed(() =>\n required.value && isblank(value.value)\n ? { flags: { valuemissing: true }, message: 'this field is required.' }\n : null,\n ),\n value,\n});\n```\n\n## testing apis\n\nimport from `@vielzeug/ore/testing`.\n\n| api | purpose |\n| | |\n| `mount(setup, options?)` | mount a component and return a test fixture |\n| `cleanup()` | remove all mounted elements and reset test state |\n| `install(aftereach)` | register auto cleanup after each test |\n| `flush(options?)` | drain reactive updates and animation frames |\n| `renderhook(setup, options?)` | run a composable in a generated host component; overload accepts `propdefs` first for typed props |\n| `oretimeouterror` | error thrown when `flush()` cannot settle tracked ore work |\n\n> **test isolation:** `cleanup()` removes mounted elements and resets ore's cross test caches and counters. call it in `aftereach`, or use `install(aftereach)`.\n\nimport `within`, named dispatchers such as `fireclick`, and waits such as `waituntil` or `waitforevent` from\n`@vielzeug/assay`.\n\n> **form associated component testing:** jsdom implements none of the `elementinternals` form association api.\n> `@vielzeug/assay` exports `installforminternalspolyfill()` for this: it polyfills\n> `setformvalue`/`setvalidity`/`checkvalidity`/`reportvalidity`/`validationmessage`/`validity`/`states`, mixes\n> `checkvalidity`/`reportvalidity`/`validity`/`validationmessage` onto the host element itself (real browsers do\n> this for any `formassociated: true` element), makes `formdata` collect a form associated element's set value, and\n> makes `<form>.reset()` invoke `formresetcallback()`. every patch is a guarded no op when its target already\n> exists, and the function returns an `uninstall()` that restores every patched global. call it directly from a\n> test setup (alongside `install(aftereach)`) only when the suite tests form associated components: the patches\n> are global, so suites without them shouldn't carry them. a downstream package (e.g. a component library built\n> on `ore`) should rely on it instead of hand rolling its own copy.\n\n#### `fixture` interface\n\n```ts\ninterface fixture<t extends htmlelement = htmlelement> {\n [symbol.dispose](): void; // delegates to dispose(): enables `using` declarations\n element: t;\n readonly disposed: boolean; // true after dispose() has been called\n readonly shadow: shadowroot | null;\n get<e extends element>(selector: string): e;\n query<e extends element>(selector: string): e | null;\n queryall<e extends element>(selector: string): e[];\n getbytext<e extends element>(text: string, selector?: string): e;\n querybytext<e extends element>(text: string, selector?: string): e | null;\n queryallbytext<e extends element>(text: string, selector?: string): e[];\n getbytestid<e extends element>(testid: string): e;\n querybytestid<e extends element>(testid: string): e | null;\n queryallbytestid<e extends element>(testid: string): e[];\n attr(name: string, value: string | number | boolean): promise<void>;\n attrs(record: record<string, string | number | boolean>): promise<void>;\n flush(options?: flushoptions): promise<void>;\n act(fn: () => unknown): promise<void>;\n dispose(): void; // removes the component from the dom: idempotent\n}\n```\n\n#### `renderhook`\n\nuseful for testing composable lifecycle hooks (`onmounted`, `watcheffect`, `inject`, etc.) without a template. the setup runs inside a real, generated host component (exposed as `element`), so every hook behaves exactly as it does in `define()`. pass `{ formassociated: true }` for composables that call `usefield()` or `onformreset()`. like `mount().dispose()`, `dispose()` removes the host and its cleanups run one microtask later:\n\n```ts\n// without props\nconst { result, flush, dispose } = await renderhook(() => {\n const count = signal(0);\n onmounted(() => {\n count.value = 1;\n });\n return count;\n});\nexpect(result.value).tobe(1);\n\n// with typed props (prop defs overload)\nconst { result } = await renderhook({ label: prop.string('hello'), count: prop.number(0) }, (props) => props.label);\nexpect(result.value).tobe('hello');\n```\n\n## ripple primitives\n\nore does **not** re export reactive primitives. import them directly from `@vielzeug/ripple`:\n\n```ts\nimport { batch, computed, signal, watch } from '@vielzeug/ripple';\n```\n\nsee the [ripple documentation](/ripple/) for the full api.\n\n## lifecycle events\n\n| event | when |\n| | |\n| `ore:error` | when a lifecycle callback fails: bubbles, composed; detail is `orelifecycleerror` |\n\n## types\n\n```ts\ntype propdef<t> = {\n readonly default: t;\n readonly parse: (value: string | null) => t;\n reflect?: boolean;\n};\n\ntype propsdef<t extends record<string, unknown>> = {\n [k in keyof t] ?: propdef<t[k]>;\n};\n\ntype propinputdefs = record<string, propdef<unknown>>;\n\n/**\n * infer reactive props type from a propinputdefs map.\n * each entry becomes readable<t> keyed by prop name.\n */\ntype inferprops<d extends propinputdefs> = {\n readonly [k in keyof d] ?: readable<inferpropvalue<d[k]>>;\n};\n\n// runtime hooks: all plain functions imported from '@vielzeug/ore', not fields on an object.\ntype onmountedcallback = () => cleanup | undefined;\ntype onformresetcallback = () => void;\n\ndeclare function onmounted(fn: onmountedcallback): void; // dom ready callback; runs after each connection's render\ndeclare function oncleanup(fn: cleanup): void; // register teardown; called on disconnect\ndeclare function onelement<t extends htmlelement>(\n ref: readable<t | null>,\n callback: (el: t) => cleanup | undefined,\n): () => void;\ndeclare function onevent<k extends keyof htmlelementeventmap>(\n target: eventtarget | null | undefined,\n event: k,\n listener: (e: htmlelementeventmap[k]) => void,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onevent(\n target: eventtarget | null | undefined,\n event: string,\n listener: eventlistener,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onformreset(fn: onformresetcallback): void; // runs on every ancestor <form> reset; formassociated only\ndeclare function watcheffect(fn: () => cleanup | undefined): () => void; // component owned reactive effect; disposed on disconnect, throws outside setup\ndeclare function bind(config: hostbindconfig, options?: bindoptions): () => void; // bindings for host or any target element\ndeclare function provide<t>(key: injectionkey<t>, value: t): void; // register a context value on the host element\ndeclare function inject<t>(key: injectionkey<t>): t | undefined;\ndeclare function inject<t>(key: injectionkey<t>, fallback: t): t;\ndeclare function gethost(): htmlelement; // the current component's host element\ndeclare function useemit<emits extends record<string, unknown> = record<string, never>>(): emitfn<emits>;\ndeclare function useslots<slotnames extends string = string>(): componentslots<slotnames>;\n\ntype componentdefinition<props extends record<string, unknown> = record<never, never>> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom\n styles?: (string | cssstylesheet | cssresult)[];\n};\n\ntype maybereactive<t> = t | readable<t> | (() => t); // plain value, signal, or getter: accepted by when(), each(), classmap(), and bind()\n\ntype hostbindingvalue = maybereactive<string | number | boolean | null | undefined>;\n\ntype attributebindings = record<string, hostbindingvalue>;\n\ntype hostbindconfig = {\n attr?: attributebindings;\n class?: (() => record<string, boolean>) | record<string, readable<boolean> | (() => boolean) | boolean>;\n on?: record<string, ((event: event) => void) | undefined>;\n style?: record<string, hostbindingvalue>;\n};\n\ntype bindoptions = addeventlisteneroptions & {\n target?: element;\n};\n\ntype componentslots<s extends string = string> = {\n elements(name?: s): readable<element[]>;\n has(name?: s): readable<boolean>;\n};\n\ntype ref<t extends element> = signal<t | null>;\n\ntype refcallback<t extends element> = (el: t | null) => void;\n\ntype injectionkey<t> = symbol & { readonly __ore_injection_key?: t };\n\ninterface htmlresult {} // opaque, single use: render it once (return, interpolate, or return from a directive callback)\n\ntype cssresult = {\n content: string;\n tostring(): string;\n};\n\ntype modeloptions<t = unknown> = {\n /** write back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */\n event?: string;\n /** value reader (default: el.checked for checkbox/radio, el.value otherwise). */\n get?: (el: htmlelement) => t;\n};\n\ntype emitfn<t extends record<string, unknown>> = {\n <k extends keyswithoutdetail<t>>(event: k): boolean;\n <k extends exclude<keyof t, keyswithoutdetail<t>>>(event: k, detail: t[k]): boolean;\n};\n// keyswithoutdetail is an internal helper type, not exported.\n\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t = unknown> = {\n disabled?: readable<boolean>;\n emptystringfornull?: boolean;\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity: () => boolean;\n readonly internals: elementinternals;\n reportvalidity: () => boolean;\n setcustomvalidity: (message: string) => void;\n};\n\n/** phase in which a oreerror occurred. */\ntype oreerrorphase = 'each reconcile' | 'form reset' | 'mounted' | 'setup';\n```\n\n## errors\n\n`oreerror` is the base class for every ore error class: `err instanceof oreerror` catches all of them.\n\n **`oreapierror`**: thrown when the `ore` api itself is misused: calling `define()` with a duplicate tag, calling a lifecycle hook (`inject`, `onmounted`, `oncleanup`, `onevent`, …) outside of `setup()`, or passing an invalid prop definition to `define()`.\n **`oreinternalerror`**: thrown when an ore invariant fails, indicating a package bug rather than invalid application code.\n **`orelifecycleerror`**: reported in the `ore:error` event when component `setup()`, a mounted callback, a form reset callback, or `each()` reconciliation fails. extends `oreerror` with:\n `component: string`: the element's local name\n `phase: oreerrorphase`: `'setup'` | `'mounted'` | `'form reset'` | `'each reconcile'`\n `cause: error`: the original error thrown by `setup()`\n **`oretimeouterror`**: thrown by `flush()` (from `@vielzeug/ore/testing`) when pending ore work does not settle before its timeout.\n\nlifecycle failures dispatch a bubbling, composed `ore:error` event whose `detail` is the `orelifecycleerror`. setup\nfailures still rethrow their original error; mounted and form reset callback failures are reported through the same\nevent so their remaining callbacks can continue.\n",
963
+ "usage": " \ntitle: 'ore: usage guide'\ndescription: practical ore usage patterns for components, props, templates, slots, context, forms, sentinel integration, and tests.\n \n\n[[toc]]\n\n## basic usage\n\n`define(tag, definition)` creates and registers a custom element. call it from the module or browser bootstrap responsible for registration.\n\nyour `setup()` function receives typed prop signals and returns an `htmlresult` directly. its state belongs to the\ncurrent connection: disconnect disposes it, and reconnecting the same element runs setup again.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('status chip', {\n setup() {\n const online = signal(true);\n\n return html`\n <button @click=${() => (online.value = !online.value)}>${() => (online.value ? 'online' : 'offline')}</button>\n `;\n },\n});\n```\n\neverything besides `props`: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, gethost, html, bind, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my widget', {\n setup(_props) {\n const el = gethost(); // the host htmlelement\n const emit = useemit<{ close: undefined }>(); // typed event emitter\n const slots = useslots<'header'>(); // reactive slot observation\n\n bind({ attr: { role: 'group' } }); // host binding helper (attr, class, style, on)\n\n return html`<slot></slot>`;\n },\n});\n```\n\n## signals and effects\n\nore does not re export ripple primitives: import them directly from `@vielzeug/ripple`.\n\n```ts\nimport { batch, computed, effect, signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst doubled = computed(() => count.value * 2);\n\neffect(() => {\n console.log('doubled =', doubled.value);\n});\n\nwatch(count, (next, prev) => {\n console.log('count changed', prev, ' >', next);\n});\n\nbatch(() => {\n count.value = 1;\n count.value = 2;\n});\n```\n\n## onmounted and lifecycle\n\nuse `onmounted()` for dom dependent initialization that must run after the template is mounted. use `onelement(ref, cb)` for work tied to a specific dom node. `onevent()` attaches a listener that is automatically removed on disconnect.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, onelement, onevent, onmounted, ref, useslots } from '@vielzeug/ore';\n\ndefine('deferred init', {\n setup(_props) {\n const tabindex = signal(0);\n const inputref = ref<htmlinputelement>();\n const slots = useslots<'items'>();\n\n onmounted(() => {\n const items = slots.elements('items').value;\n console.log('found', items.length, 'items');\n });\n\n onelement(inputref, (input) => {\n input.focus();\n });\n\n onevent(window, 'keydown', (e: keyboardevent) => {\n if (e.key === 'escape') tabindex.value = 0;\n });\n\n return html`<div><slot name=\"items\"></slot><input ref=${inputref} /></div>`;\n },\n});\n```\n\n## prop definitions\n\nuse `prop.*` helpers for common cases, or raw `propdef` objects for custom parsing or `reflect: false`.\n\n```ts\nimport { define, html, prop } from '@vielzeug/ore';\n\ndefine('x button', {\n props: {\n label: prop.string('button'),\n disabled: prop.bool(false),\n variant: prop.oneof(['primary', 'secondary'] as const, 'primary'),\n count: prop.number(0),\n },\n setup(props) {\n return html`\n <button ?disabled=${props.disabled} data variant=${props.variant}>${props.label} (${props.count})</button>\n `;\n },\n});\n```\n\n## template bindings\n\n`html` supports text, attributes, booleans, properties, events, refs, and nested templates. event bindings accept\n`.stop`, `.prevent`, `.once`, and `.capture`: the first two apply before the handler runs, while the latter two use\nnative listener options. unknown modifiers throw while ore compiles the template.\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { define, html, model, ref } from '@vielzeug/ore';\n\ndefine('profile name', {\n setup() {\n const name = signal('alice');\n const inputref = ref<htmlinputelement>();\n\n return html`\n <label title=${computed(() => 'current: ' + name.value)}>name</label>\n <input\n ref=${inputref}\n value=${model(name)}\n aria label=${() => 'current name ' + name.value} />\n <p>hello ${name}</p>\n `;\n },\n});\n```\n\n## directives\n\nore exports `each`, `classmap`, `stylemap`, `when`, `live`, `model`, and `unsafehtml` from `@vielzeug/ore`.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { classmap, define, each, html, stylemap, when } from '@vielzeug/ore';\n\ndefine('task list', {\n setup() {\n const tasks = signal([{ id: 1, text: 'write tests' }]);\n const active = signal(true);\n\n return html`\n <ul\n class=\"${classmap({ ready: () => tasks.value.length > 0 })}\"\n style=${stylemap({ opacity: () => (active.value ? 1 : 0.5) })}>\n ${when(\n () => active.value,\n () => html`<li>active</li>`,\n () => html`<li>paused</li>`,\n )}\n ${each(\n tasks,\n (task) => task.id,\n (task) => html`<li>${() => task.value.text}</li>`,\n )}\n </ul>\n `;\n },\n});\n```\n\n### each() api\n\n`each(source, key, render, fallback?)` takes positional arguments:\n\n **source**: signal, getter, or plain array\n **key**: function returning a unique string or number per item; number and string keys remain distinct\n **render**: receives reactive `item` and `index` signals\n **fallback**: optional, rendered when the list is empty\n\n```ts\neach(\n items,\n (item) => item.id,\n (item, index) => html`<li>#${index}: ${() => item.value.label}</li>`,\n () => html`<li>no items</li>`,\n);\n```\n\neach reactive reconciliation is transactional. ore creates missing entries before committing updates or removing stale\nentries; if a render callback throws, entries created during that pass are rolled back and the last successful list\nremains on screen. ore reports the failure through `ore:error` with phase `each reconcile`.\n\nreused items keep their dom nodes in place: when the surviving items stay in the same relative order (prepend, append,\ninterleaved inserts, or replacing list contents), `each()` never moves a reused node, so css transitions, animations,\nfocus, and nested component state survive the update untouched. only genuine reorders move nodes, and a moved item\ntravels with everything its inner directives rendered. new items are built detached and inserted exactly once at their\nfinal position, so each item's custom elements connect a single time per render.\n\n## model: two way form bindings\n\nuse `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and\nwrites user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`\notherwise).\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, model } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n const agree = signal(false);\n\n return html`\n <input value=${model(query)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n `;\n },\n});\n```\n\na native text input's `value` is always a string, so pass a `get` reader to keep a numeric signal numeric, and an\n`event` name for custom controls that emit their own change event:\n\n```ts\nconst count = signal(0);\n\nhtml`\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n <my picker value=${model(pick, { event: 'pick change', get: (el) => (el as mypicker).selection })} />\n`;\n```\n\n`model()` also guards in progress edits: while the control holds a value the signal has not received yet, a stale\napp state write to the signal is skipped instead of clobbering what the user is typing.\n\n## host bindings\n\n`bind()` wires reactive attrs, classes, styles, and events to the host element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html } from '@vielzeug/ore';\n\ndefine('x toggle', {\n setup(_props) {\n const open = signal(false);\n\n bind({\n attr: { 'aria expanded': () => string(open.value), role: 'button', tabindex: 0 },\n class: { 'is open': open },\n on: { click: () => (open.value = !open.value) },\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nthe `bind` config supports `attr`, `class`, `style`, and `on` sections.\n\n## aria bindings\n\nuse explicit `aria *` keys in `bind({ attr: config }, { target })` to reactively sync aria attributes to any element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onmounted } from '@vielzeug/ore';\n\ndefine('x disclosure', {\n setup(_props) {\n const open = signal(false);\n const panelid = 'disclosure panel';\n\n bind({\n attr: { role: 'button', tabindex: 0 },\n on: { click: () => (open.value = !open.value) },\n });\n\n onmounted(() => {\n const trigger = document.queryselector('#trigger') as htmlelement;\n if (trigger) {\n // bind() registers cleanup automatically when called inside setup\n bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => string(open.value),\n 'aria haspopup': 'region',\n },\n },\n { target: trigger },\n );\n }\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nstatic values are applied once. getter functions create reactive effects. setting a value to `null`, `undefined`, or `false` removes the attribute.\n\n`bind()` always returns a cleanup function. use it to stop syncing early when a trigger element can be swapped out:\n\n```ts\nonmounted(() => {\n const trigger = document.queryselector('#trigger') as htmlelement;\n const stoparia = bind({ attr: { 'aria expanded': () => string(open.value) } }, { target: trigger });\n\n // stop syncing when the trigger is replaced\n oncleanup(stoparia);\n});\n```\n\n### binding a non host element with `bind()`\n\npass `{ target: el }` as a second argument to bind attributes, classes, styles, or events to any element:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onmounted, ref } from '@vielzeug/ore';\n\ndefine('button wrapper', {\n setup(_props) {\n const visible = signal(false);\n const btnref = ref<htmlbuttonelement>();\n\n onmounted(() => {\n const btn = btnref.value;\n if (!btn) return;\n\n bind(\n {\n attr: { 'aria pressed': () => string(visible.value) },\n on: { click: () => (visible.value = !visible.value) },\n },\n { target: btn },\n );\n });\n\n return html`<button ref=${btnref}>toggle</button>`;\n },\n});\n```\n\n## slots and emits\n\n```ts\nimport { define, html, useemit, useslots } from '@vielzeug/ore';\n\ndefine('card with footer', {\n setup(_props) {\n const slots = useslots<'header' | 'footer'>();\n const emit = useemit<{ action: undefined }>();\n\n return html`\n <div class=\"card\">\n <slot name=\"header\"></slot>\n <slot></slot>\n <footer ?hidden=${() => !slots.has('footer').value}><slot name=\"footer\"></slot></footer>\n </div>\n <button @click=${() => emit('action')}>go</button>\n `;\n },\n});\n```\n\npass a `slotnames` type parameter to `useslots<slotnames>()` to get typed `slots.has()` and `slots.elements()` calls.\n\nkeep the `<slot>` rendered and toggle its wrapper with `slots.has()`: presence is read from rendered slots, so a `<slot>` inside `when(slots.has(...))` would never appear.\n\n## context provide/inject\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { createcontext, define, html, injectstrict, provide } from '@vielzeug/ore';\n\nconst count_ctx = createcontext<returntype<typeof signal<number>>>('count');\n\ndefine('count provider', {\n setup(_props) {\n const count = signal(0);\n provide(count_ctx, count);\n\n return html`<button @click=${() => count.value++}><slot></slot></button>`;\n },\n});\n\ndefine('count consumer', {\n setup() {\n const count = injectstrict(count_ctx);\n\n return html`<p>count: ${count}</p>`;\n },\n});\n```\n\n`provide()` registers cleanup automatically: context keys are removed from the registry when the providing component disconnects. on reconnect, `setup()` runs fresh and `provide()` re registers without spurious \"overwriting\" warnings. provide a `readable` (signal/computed) rather than a raw value if descendants need to observe later changes: `inject()` resolves and caches the value once per consumer connection.\n\n## form associated elements\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, prop } from '@vielzeug/ore';\nimport { usefield } from '@vielzeug/ore';\n\ndefine('rating input', {\n formassociated: true,\n setup() {\n const value = signal(0);\n const field = usefield({ value });\n\n return html`\n <button @click=${() => (value.value = 1)}>1</button>\n <button @click=${() => (value.value = 2)}>2</button>\n <button @click=${() => (value.value = 3)}>3</button>\n <button @click=${() => field.reportvalidity()}>validate</button>\n <p>current: ${value}</p>\n `;\n },\n});\n```\n\n## sentinel observers\n\nuse `@vielzeug/sentinel` for subscribable browser and dom observations. create element dependent sentinels inside `onmounted()` and dispose them with the component.\n\n```ts\nimport { define, html, oncleanup, onmounted, ref, watcheffect } from '@vielzeug/ore';\nimport { fromsubscribable } from '@vielzeug/ripple';\nimport { createelementsize, sentinelunavailableerror } from '@vielzeug/sentinel';\n\ndefine('x observed', {\n setup(_props) {\n const boxref = ref<htmldivelement>();\n\n onmounted(() => {\n const element = boxref.value;\n if (!element) return;\n\n try {\n const size = createelementsize(element);\n const sizestate = fromsubscribable(size, { signal: size.disposalsignal });\n\n watcheffect(() => {\n console.log(sizestate.value?.width);\n });\n\n oncleanup(() => size.dispose());\n } catch (error) {\n if (!(error instanceof sentinelunavailableerror)) throw error;\n }\n });\n\n return html`<div ref=${boxref}>observe me</div>`;\n },\n});\n```\n\n## testing utilities\n\nimport from `@vielzeug/ore/testing`.\n\n```ts\nimport { aftereach, describe, expect, it } from 'vitest';\nimport { signal } from '@vielzeug/ripple';\nimport { fireclick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { cleanup, mount } from '@vielzeug/ore/testing';\n\ndescribe('my counter', () => {\n aftereach(cleanup);\n\n it('increments on click', async () => {\n let count!: returntype<typeof signal<number>>;\n const { query, act } = await mount(() => {\n count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n });\n\n expect(query('button')?.textcontent).tobe('0');\n\n await act(() => fireclick(query('button')!));\n\n expect(query('button')?.textcontent).tobe('1');\n });\n});\n```\n\n## framework integration\n\nore components are standard custom elements and work natively in any framework.\n\n::: code group\n\n```tsx [react]\n// react 19+ supports custom elements natively.\nimport './x toggle'; // wherever define('x toggle', { ... }) is called\n\nfunction app() {\n return <x toggle aria label=\"open menu\" />;\n}\n```\n\n```ts [vue 3]\n<script setup lang=\"ts\">\nimport './x toggle'; // wherever define('x toggle', { ... }) is called\nimport { ref } from 'vue';\n\nconst open = ref(false);\n</script>\n\n<template>\n <x toggle :aria label=\"'open menu'\" @click=\"open = !open\" />\n</template>\n```\n\n```svelte [svelte]\n<script>\n import './x toggle'; // wherever define('x toggle', { ... }) is called\n\n function handleclick() {\n console.log('toggled');\n }\n</script>\n\n<x toggle aria label=\"open menu\" on:click={handleclick} />\n```\n\n:::\n\n## working with other vielzeug libraries\n\n### with ripple\n\nimport ripple primitives directly from `@vielzeug/ripple` for standalone reactive state outside components.\n\n```ts\nimport { signal, computed } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\n// shared state created outside any component\nconst theme = signal<'light' | 'dark'>('light');\nconst isdark = computed(() => theme.value === 'dark');\n\ndefine('theme toggle', {\n setup() {\n return html`\n <button @click=${() => (theme.value = isdark.value ? 'light' : 'dark')}>\n ${() =>\n isdark.value ? '<ore icon name=\"sun\" size=\"16\"></ore icon>' : '<ore icon name=\"moon\" size=\"16\"></ore icon>'}\n </button>\n `;\n },\n});\n```\n\n### with forge\n\nuse `@vielzeug/forge` for typed form state. `usefield()` remains intentionally narrow: it connects a form associated\ncustom element to native `elementinternals` without imposing submission, validation, or dirty state policy.\n\n```ts\nimport { createform } from '@vielzeug/forge';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('signup form', {\n setup(_props) {\n const form = createform({ initialvalues: { email: '' } });\n\n return html`\n <form\n @submit=${(event: submitevent) => {\n event.preventdefault();\n void form.submit(async (values) => {\n console.log(values);\n });\n }}>\n <slot></slot>\n </form>\n `;\n },\n});\n```\n\n## best practices\n\n setup returns `html\\`...\\`` directly: not a function wrapping the template.\n use `watcheffect()` for reactive subscriptions tied to component lifetime: it auto registers cleanup on disconnect.\n use `onelement(ref, cb)` instead of `onmounted` when the work is tied to a single dom node.\n bind host attributes and classes via `bind()` rather than mutating the element directly.\n provide context at the nearest ancestor: avoid global context singletons.\n call `oncleanup()` for every resource allocated in `setup()` (websockets, intervals, external subscriptions).\n use `model(signal)` for form inputs: it writes both ways and never clobbers an in progress user edit.\n extract composable helper functions freely: `onmounted`/`oncleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.\n test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic dom events, queries, and waits\n from `@vielzeug/assay`.\n",
964
964
  "examples": " \ntitle: 'ore: examples'\ndescription: practical examples and recipes for ore.\n \n\n## examples\n\n [counter component](./examples/counter component.md)\n [typed props and emits](./examples/typed props and emits.md)\n [observers in onmounted()](./examples/observers in onmount.md)\n [search list with directives](./examples/search list with directives.md)\n [context provider and consumer](./examples/context provider and consumer.md)\n [prop helpers and raw propdef](./examples/propsof builder api.md)\n [form associated rating input](./examples/form associated rating input.md)\n [test example with @vielzeug/ore/testing](./examples/test example at vielzeug ore testing.md)\n"
965
965
  },
966
966
  "examples": [],
@@ -969,7 +969,7 @@
969
969
  "name": "@vielzeug/ore",
970
970
  "related": "ripple refine orbit",
971
971
  "slug": "ore",
972
- "source": "export type { componentdefinition } from './component types';\nexport { createcontext, type injectionkey, inject, injectstrict, provide } from './context';\nexport { define } from './define';\n// near universal template directives: used in most non trivial components (lists,\n// conditionals, and class/style maps. kept in the main entry alongside\n// `html`/`define` rather than a separate sub path: tree shaking already means an unused export\n// costs nothing in a bundled consumer, so splitting these off only adds an extra import line\n// for functionality most components need on day one. `unsafehtml()` and `live()` remain here\n// too: their explicit names make their specialized behavior clear without a second import path.\nexport { classmap } from './directives/classmap';\nexport { each } from './directives/each';\nexport { type livebinding, live } from './directives/live';\nexport { type modeloptions, model } from './directives/model';\nexport { stylemap } from './directives/stylemap';\nexport { unsafehtml } from './directives/unsafe html';\nexport { when } from './directives/when';\nexport { oreapierror, oreerror, type oreerrorphase, oreinternalerror, orelifecycleerror } from './errors';\nexport { type formfieldhandle, type formfieldoptions, type formfieldvalidity, usefield } from './forms/field';\nexport {\n type attributebindings,\n type bindoptions,\n bind,\n type hostbindconfig,\n type hostbindingvalue,\n} from './host bind';\nexport type { inferprops, propdef, propinputdefs, propsdef } from './props';\nexport { prop } from './props';\n// lifecycle hooks: plain functions, called during setup() or a composable it invokes.\nexport {\n gethost,\n type onformresetcallback,\n type onmountedcallback,\n oncleanup,\n onelement,\n onevent,\n onformreset,\n onmounted,\n watcheffect,\n} from './runtime';\nexport { type componentslots, useslots } from './slots';\nexport { html } from './template/instantiator';\nexport { type htmlresult, type ref, type refcallback, ref } from './template/result';\nexport { type cssresult, css } from './utils/css';\nexport type { maybereactive } from './utils/dom';\nexport { type emitfn, useemit } from './utils/emit';\n\nexport { createid } from './utils/id';\n"
972
+ "source": "export type { componentdefinition } from './component types';\nexport { createcontext, type injectionkey, inject, injectstrict, provide } from './context';\nexport { define } from './define';\n// near universal template directives: used in most non trivial components (lists,\n// conditionals, and class/style maps. kept in the main entry alongside\n// `html`/`define` rather than a separate sub path: tree shaking already means an unused export\n// costs nothing in a bundled consumer, so splitting these off only adds an extra import line\n// for functionality most components need on day one. `unsafehtml()` and `model()` remain here\n// too: their explicit names make their specialized behavior clear without a second import path.\nexport { classmap } from './directives/classmap';\nexport { each } from './directives/each';\nexport { type modeloptions, model } from './directives/model';\nexport { stylemap } from './directives/stylemap';\nexport { unsafehtml } from './directives/unsafe html';\nexport { when } from './directives/when';\nexport { oreapierror, oreerror, type oreerrorphase, oreinternalerror, orelifecycleerror } from './errors';\nexport { type formfieldhandle, type formfieldoptions, type formfieldvalidity, usefield } from './forms/field';\nexport {\n type attributebindings,\n type bindoptions,\n bind,\n type hostbindconfig,\n type hostbindingvalue,\n} from './host bind';\nexport type { inferprops, propdef, propinputdefs, propsdef } from './props';\nexport { prop } from './props';\n// lifecycle hooks: plain functions, called during setup() or a composable it invokes.\nexport {\n gethost,\n type onformresetcallback,\n type onmountedcallback,\n oncleanup,\n onelement,\n onevent,\n onformreset,\n onmounted,\n watcheffect,\n} from './runtime';\nexport { type componentslots, useslots } from './slots';\nexport { html } from './template/instantiator';\nexport { type htmlresult, type ref, type refcallback, ref } from './template/result';\nexport { type cssresult, css } from './utils/css';\nexport type { maybereactive } from './utils/dom';\nexport { type emitfn, useemit } from './utils/emit';\n\nexport { createid } from './utils/id';\n"
973
973
  },
974
974
  {
975
975
  "category": "async",
@@ -1072,9 +1072,9 @@
1072
1072
  "category": "state",
1073
1073
  "description": "framework agnostic signals, effects, async resources, scopes, and structural bridges.",
1074
1074
  "docs": {
1075
- "index": " \ntitle: 'ripple: reactive graphs'\ndescription: framework agnostic signals, effects, async resources, scopes, and structural bridges.\npackage: ripple\ncategory: state\nkeywords: [reactive, signals, computed, effects, graph, scope, batch, watch]\nrelated: [ore, clockwork, ledger]\nexports: [createripple, signal, computed, effect, resource]\nenvironments: [browser, node, ssr, deno]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"ripple\" />\n\n## why ripple?\n\nhand rolled reactive state spreads subscription, cleanup, and derived value rules across application code. ripple gives you one graph boundary with explicit disposal and fine grained dependencies while keeping rendering and routing outside the runtime.\n\n```ts\n// before\nlet count = 0;\nconst listeners = new set<() => void>();\n\nfunction setcount(next: number) {\n count = next;\n for (const listener of listeners) listener();\n}\n\n// after\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst doubled = ripple.computed(() => count.value * 2);\nconst stop = ripple.effect(() => console.log(doubled.value));\n\ncount.value = 1;\nstop.dispose();\nripple.dispose();\n```\n\n| feature | ripple | zustand | jotai |\n| | | | |\n| bundle size | <packageinfo package=\"ripple\" type=\"size\" /> | ~3.5 kb | ~7 kb |\n| zero dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| framework agnostic | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | react first |\n| explicit graph lifetime | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| fine grained derived values | <ore icon name=\"check\" size=\"16\"></ore icon> | selectors | atoms |\n\n<div class=\"decision callout\">\n\n**use ripple when** you need framework independent state with explicit graph lifetime and small composable primitives.\n\n**consider a framework store when** component bindings, server cache, or framework specific tooling matter more than portable reactive state.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/ripple\n```\n\n```sh [npm]\nnpm install @vielzeug/ripple\n```\n\n```sh [yarn]\nyarn add @vielzeug/ripple\n```\n\n:::\n\n## quick start\n\ncreate one graph, derive a value, observe it, then dispose when the graph lifetime ends.\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst doubled = ripple.computed(() => count.value * 2);\nconst stop = ripple.effect(() => console.log(doubled.value));\n\nripple.batch(() => {\n count.value = 1;\n count.value = 2;\n});\n\nstop.dispose();\nripple.dispose();\n```\n\n## features\n\n<div class=\"features grid\">\n\n `createripple({ onerror })` creates an isolated graph with one runtime failure callback.\n `signal()` stores writable values with configurable equality.\n `computed()` derives lazy read only values.\n `effect()` reacts to dependency changes with cleanup support.\n `batch()` coalesces synchronous writes and notifications.\n `createscope()` groups owned reactive work.\n `watch()` observes one selected source transition.\n `resource()` owns focused latest request async state.\n `fromsubscribable()` creates a disposable bridge for external `{ getsnapshot, subscribe }` sources.\n `rippleerror`, `ripplecycleerror`, and `rippledisposederror` distinguish package originated failures.\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [ore](/ore/): uses ripple signals and effects for web component reactivity.\n [clockwork](/clockwork/): exposes machine state through reactive ripple values.\n [ledger](/ledger/): adds command based undo and redo beside ripple state.\n\n</div>\n\n<! markdownlint enable >\n",
1076
- "api": " \ntitle: 'ripple: api reference'\ndescription: complete reference for reactive graphs, signals, effects, scopes, and watchers.\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `createripple()` | create isolated graph | sync | disposal is terminal; create a new graph instead of reusing it |\n| `signal()` | create writable value | sync | default graph is process wide |\n| `computed()` | create lazy derived value | sync | keep derivation pure |\n| `effect()` | react to dependency reads | sync | dispose handle or return cleanup |\n| `batch()` | coalesce synchronous writes | sync | does not roll back writes |\n| `createscope()` | group owned reactive work | sync | call `run()` to activate it |\n| `untrack()` | read without tracking | sync | read still happens immediately |\n| `watch()` | observe selected output | sync | use `effect()` for broad reads |\n| `resource()` | load from tracked reactive input | sync factory / async loader | `reload()` returns `void`; completion is observable state |\n| `fromsubscribable()` | bridge external source | sync | returned bridge must be disposed |\n| `isreactive()` | test ripple's marked readable contract | sync | not a security or provenance check |\n| `rippleerror` | base package error | sync | runtime callback failures retain their original value |\n| `ripplecycleerror` | computed cycle or runaway flush | sync | flush failures reach `onerror`, not the write site |\n| `rippledisposederror` | work after disposal | sync | cached reads remain available |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/ripple` | all primitives, types, and errors: signals, computed, effects, scopes, watch, and the isolated graph factory |\n\n## graph creation\n\n### `createripple(options?)`\n\n```ts\nfunction createripple(options?: rippleoptions): ripple;\n```\n\ncreates one isolated reactive graph. factories on the returned object share scheduling, ownership, and error boundaries. `dispose()` is terminal: `ripple.disposed` becomes `true`, existing owned work is disposed, and creating more graph work throws `rippledisposederror`. create a new graph for a new lifetime.\n\n| parameter | type | description |\n| | | |\n| `options.onerror` | `(error, context) => void` | handles computed refresh, effect, cleanup, listener, and flush loop failures. default rethrows asynchronously via `queuemicrotask`; pass a no op to silence. a failure in one node never interrupts sibling propagation. |\n\n`onerror` is the only runtime option. `rippleerrorcontext.kind` is `cleanup`, `computed`,\n`effect`, `flush`, or `listener`; `name` is optional. there is no event stream or error policy option.\n\n**returns:** `ripple`.\n\n**example:**\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst stop = ripple.effect(() => console.log(count.value));\n\nstop.dispose();\nripple.dispose();\n```\n\n \n\n### `isreactive(value)`\n\n```ts\nfunction isreactive<t>(value: t | readable<t>): value is readable<t>;\n```\n\ntests ripple's shared symbol marker and complete readable surface (`value`, `peek()`, and `subscribe()`). recognition works across duplicated ripple module graphs. the marker is intentionally structural and forgeable; do not use this guard for trust or provenance decisions.\n\n**returns:** `true` for marked signals, computeds, resources, and external source bridges with the complete readable contract.\n\n**example:**\n\n```ts\nimport { isreactive, signal } from '@vielzeug/ripple';\n\nconsole.log(isreactive(signal(0)));\n```\n\n## default graph functions\n\nroot helpers (`signal`, `computed`, `effect`, `batch`, `createscope`, `untrack`, `watch`, `resource`, `fromsubscribable`) operate on a process lifetime default graph. the graph itself has no public disposal handle; effects, scopes, resources, and bridges still require owner managed disposal. for isolated, disposable graphs (tests, ssr, embedded features) use `createripple()`.\n\n### `signal(initial, options?)`\n\n```ts\nfunction signal<t>(initial: t, options?: signaloptions<t>): signal<t>;\n```\n\ncreates writable state on the default graph. use `update()` for immutable replacement patterns.\n\n**returns:** `signal<t>`.\n\n**example:**\n\n```ts\nimport { signal } from '@vielzeug/ripple';\n\nconst count = signal(0);\ncount.value += 1;\n\nconst cart = signal({ items: 0 });\ncart.update((state) => ({ ...state, items: state.items + 1 }));\n```\n\n \n\n### `computed(derive, options?)`\n\n```ts\nfunction computed<t>(derive: () => t, options?: computedoptions<t>): readable<t>;\n```\n\ncreates a lazy read only value from reactive reads in `derive`. `peek()` may trigger derivation and throw directly. during dependency propagation, a computed refresh failure is reported to `onerror` with context kind `computed` and does not prevent sibling dependents from updating. a disposed computed returns its last cached value from `peek()` without recomputing; a computed disposed before its first evaluation throws `rippledisposederror` instead of returning a value.\n\n**returns:** `readable<t>`.\n\n**example:**\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\n\nconst count = signal(2);\nconst doubled = computed(() => count.value * 2);\nconsole.log(doubled.value);\n```\n\n \n\n### `effect(callback, options?)`\n\n```ts\nfunction effect(callback: () => cleanup | undefined, options?: effectoptions): effecthandle;\n```\n\nruns immediately and reruns when its tracked reads change. a returned cleanup runs before the next callback or disposal.\n\n| parameter | type | description |\n| | | |\n| `options.name` | `string` | optional label in error context |\n\neffects flush synchronously; `effectoptions` has no scheduler option. use `batch()` to coalesce writes.\n\n**returns:** `effecthandle`.\n\n**example:**\n\n```ts\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst connected = signal(false);\nconst stop = effect(() => {\n if (!connected.value) return;\n\n return () => console.log('disconnect');\n});\n\nstop.dispose();\n```\n\n \n\n### `batch(fn)` and `untrack(fn)`\n\n```ts\nfunction batch<t>(fn: () => t): t;\nfunction untrack<t>(fn: () => t): t;\n```\n\n`batch()` defers effects and listeners until its callback returns. `untrack()` reads current state without adding dependencies to an enclosing effect.\n\n**returns:** the callback result.\n\n**example:**\n\n```ts\nimport { batch, signal, untrack } from '@vielzeug/ripple';\n\nconst first = signal('ada');\nconst last = signal('lovelace');\nconst locale = signal('en us');\n\nbatch(() => {\n first.value = 'grace';\n last.value = 'hopper';\n});\n\nconsole.log(untrack(() => locale.value));\n```\n\n \n\n### `createscope(name?)`\n\n```ts\nfunction createscope(name?: string): scope;\n```\n\ncreates a disposable ownership boundary. work created inside `scope.run()` belongs to that scope. explicit scopes created during an effect run attach to the enclosing scope (not the transient effect run owner) and therefore survive reruns until explicitly or parent disposed. disposed children detach from parent ownership immediately.\n\n**returns:** `scope`.\n\n**example:**\n\n```ts\nimport { createscope, effect, signal } from '@vielzeug/ripple';\n\nconst scope = createscope('panel');\nconst count = signal(0);\n\nscope.run(() => effect(() => console.log(count.value)));\nscope.dispose();\n```\n\n### `resource(source, loader, options?)`\n\n```ts\nfunction resource<source, value>(\n source: () => source,\n loader: (source: source, context: { readonly signal: abortsignal }) => promise<value>,\n options?: resourceoptions,\n): resource<value>;\n```\n\ncreates a disposable readable async state and starts loading immediately. source changes and `reload()` abort stale work before starting the next loader. the last successful value is preserved as `previous`, including when that value is `undefined`.\n\n| parameter | type | description |\n| | | |\n| `source` | `() => source` | tracks reactive input reads |\n| `loader` | `(source, context) => promise<value>` | receives input and a request owned cancellation signal |\n| `options.name` | `string` | optional resource label |\n\n**returns:** `resource<value>`. source and loader failures become error state, not `onerror` reports.\n\n**example:**\n\n```ts\nimport { resource, signal } from '@vielzeug/ripple';\n\nconst userid = signal('42');\nconst user = resource(\n () => userid.value,\n (id, { signal }) => fetch(`/users/${id}`, { signal }).then((response) => response.json()),\n);\nconsole.log(user.value);\nuser.dispose();\n```\n\nthe state is `{ status: 'pending', previous? }`, `{ status: 'success', value }`, or `{ status: 'error', error, previous? }`. reads remain available after disposal; `reload()` and new subscriptions throw `rippledisposederror`.\n\n## watch\n\n### `watch(source, callback, options?)`\n\n```ts\nfunction watch<t>(\n source: readable<t> | (() => t),\n callback: (value: t, previous: t | undefined) => void,\n options?: watchoptions<t>,\n): effecthandle;\n```\n\nobserves selected output changes using the default graph or a `ripple.watch()` method. callback only reactive reads are untracked; without `immediate`, initial evaluation does not count as an invocation. for one shot observation, dispose the returned handle from inside the callback: with `immediate: true`, do the first invocation at the call site instead, because the callback runs before the handle exists.\n\n**returns:** `effecthandle`.\n\n**example:**\n\n```ts\nimport { signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst stop = watch(count, (value, previous) => console.log(previous, value), { immediate: true });\nstop.dispose();\n```\n\n \n\n### `fromsubscribable(source, options?)`\n\n```ts\nfunction fromsubscribable<t>(source: subscribable<t>, options?: fromsubscribableoptions): bridgedreadable<t>;\n```\n\nbridges an external `{ getsnapshot, subscribe }` source into a disposable reactive readable. the bridge subscribes and then rereads the snapshot to avoid missing a change during registration. the root helper uses the default graph; `ripple.fromsubscribable()` binds ownership to an isolated graph. an optional signal disposes the bridge.\n\n**returns:** `bridgedreadable<t>`. disposal invokes the source unsubscribe function. reads remain available afterward, while new subscriptions throw.\n\n**example:**\n\n```ts\nimport { fromsubscribable } from '@vielzeug/ripple';\n\nlet current = 'idle';\nconst listeners = new set<() => void>();\nconst state = fromsubscribable({\n getsnapshot: () => current,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n});\n\ncurrent = 'ready';\nfor (const listener of listeners) listener();\nconsole.log(state.value);\nstate.dispose();\n```\n\n## types\n\n```ts\ntype cleanup = () => void;\ntype equality<t> = (previous: t, next: t) => boolean;\ntype unsubscribe = () => void;\n\ntype signaloptions<t> = { equals?: equality<t>; name?: string };\ntype computedoptions<t> = { equals?: equality<t>; name?: string };\ntype effectoptions = { name?: string };\ntype watchoptions<t> = { equals?: equality<t>; immediate?: boolean; name?: string };\n\ntype rippleerrorcontext = {\n readonly kind: 'cleanup' | 'computed' | 'effect' | 'flush' | 'listener';\n readonly name?: string;\n};\ntype rippleoptions = { onerror?: (error: unknown, context: rippleerrorcontext) => void };\n\ninterface readable<t> {\n readonly name?: string;\n peek(): t;\n /** change only: the listener is not called on subscribe, only after a tracked source changes. */\n subscribe(listener: () => void): unsubscribe;\n readonly value: t;\n}\n\ninterface signal<t> extends readable<t> {\n update(updater: (prev: t) => t): void;\n value: t;\n}\ninterface disposable {\n dispose(): void;\n readonly disposed: boolean;\n readonly disposalsignal: abortsignal;\n [symbol.dispose](): void;\n}\ntype effecthandle = disposable;\ninterface scope extends disposable {\n run<t>(fn: () => t): t;\n}\n\ninterface subscribable<t> {\n getsnapshot(): t;\n subscribe(listener: () => void): unsubscribe;\n}\n\ntype fromsubscribableoptions = { name?: string; signal?: abortsignal };\ntype bridgedreadable<t> = readable<t> & disposable;\n\ntype asyncstate<t> =\n | { readonly previous?: t; readonly status: 'pending' }\n | { readonly status: 'success'; readonly value: t }\n | { readonly error: unknown; readonly previous?: t; readonly status: 'error' };\n\ninterface resource<t> extends readable<asyncstate<t>>, disposable {\n reload(): void;\n}\n\ntype resourceoptions = { name?: string };\n\ninterface ripple extends disposable {\n batch<t>(fn: () => t): t;\n computed<t>(derive: () => t, options?: computedoptions<t>): readable<t>;\n createscope(name?: string): scope;\n effect(callback: () => cleanup | undefined, options?: effectoptions): effecthandle;\n fromsubscribable<t>(source: subscribable<t>, options?: fromsubscribableoptions): bridgedreadable<t>;\n resource<source, value>(\n source: () => source,\n loader: (source: source, context: { readonly signal: abortsignal }) => promise<value>,\n options?: resourceoptions,\n ): resource<value>;\n signal<t>(initial: t, options?: signaloptions<t>): signal<t>;\n untrack<t>(fn: () => t): t;\n watch<t>(\n source: readable<t> | (() => t),\n callback: (value: t, previous: t | undefined) => void,\n options?: watchoptions<t>,\n ): effecthandle;\n}\n```\n\n## errors\n\n| error | trigger | notable properties |\n| | | |\n| `rippleerror` | base ripple error; a new subscription to a disposed external source bridge | use `instanceof rippleerror` to narrow unknown values. |\n| `ripplecycleerror` | a computed reads itself, or a flush exceeds the iteration limit | extends `rippleerror`. a flush loop breach is reported to `onerror` (context kind `flush`) instead of throwing from the write site. |\n| `rippledisposederror` | new graph work, writes, or subscriptions on a disposed runtime; `run()` on a disposed scope; `reload()` or new subscriptions on a disposed resource; reading a never evaluated disposed computed | extends `rippleerror`. cached reads and repeated disposal remain valid. |\n\nthese are the three exported error classes. user callback failures are reported as their original\nvalues through `onerror`; they are not wrapped in `rippleerror`. a direct computed read can throw\nits derivation error to the caller.\n",
1077
- "usage": " \ntitle: 'ripple: usage guide'\ndescription: build reactive state with one explicit graph boundary.\n \n\n[[toc]]\n\n## basic usage\n\nuse top level functions when one application lifetime graph is sufficient. read a signal inside an effect to make that read reactive.\n\n```ts\nimport { computed, effect, signal } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst label = computed(() => `count: ${count.value}`);\nconst stop = effect(() => console.log(label.value));\n\ncount.value = 1;\nstop.dispose();\n```\n\n## isolated graphs\n\nuse `createripple()` for tests, ssr requests, embedded applications, or independently disposable features. never mix reactive values from separate graphs.\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple({\n onerror: (error, context) => console.log(context.kind, error),\n});\n\nconst count = ripple.signal(0);\nconst stop = ripple.effect(() => console.log(count.value));\n\nstop.dispose();\nripple.dispose();\n```\n\n## derived values and batches\n\nuse `computed()` for pure derivation. use `untrack()` when a current read must not become an effect dependency. use `batch()` for related synchronous writes.\n\n```ts\nconst first = ripple.signal('ada');\nconst last = ripple.signal('lovelace');\nconst locale = ripple.signal('en us');\nconst name = ripple.computed(() => `${first.value} ${last.value}`);\n\nripple.effect(() => {\n console.log({ locale: ripple.untrack(() => locale.value), name: name.value });\n});\n\nripple.batch(() => {\n first.value = 'grace';\n last.value = 'hopper';\n});\n```\n\n## scheduling and subscriptions\n\nripple propagates every synchronous write before flushing effects. each flush pass runs effects queued at its\nstart before direct `subscribe()` listeners queued at its start. work queued by either runs in a later pass.\neffects coalesce writes made inside the same synchronous flush: a `batch()` (or any writes during a flush) produces a single effect run.\neach `subscribe()` registration fires once per flush, even when several subscriptions share one callback function.\n\n```ts\nconst count = ripple.signal(0);\nconst log: string[] = [];\n\nripple.effect(() => log.push(`effect: ${count.value}`));\ncount.subscribe(() => log.push(`listener: ${count.value}`));\n\nlog.length = 0; // ignore synchronous creation runs.\nripple.batch(() => {\n count.value = 1;\n count.value = 2;\n});\nconsole.log(log); // ['effect: 2', 'listener: 2']\n```\n\n## ownership with scopes\n\ncreate a scope when a group of effects or derived values shares one lifetime. dispose the scope when its feature ends.\n\n```ts\nconst scope = ripple.createscope('panel');\nconst count = ripple.signal(0);\n\nscope.run(() => {\n ripple.effect(() => console.log(`panel count: ${count.value}`));\n});\n\ncount.value = 1;\nscope.dispose();\n```\n\neffects and computeds created directly during an effect run belong to that run and are disposed before rerun. explicit scopes intentionally attach to the enclosing scope and survive effect reruns; create them outside rerunning effects or retain and dispose each scope yourself.\n\ndisposed owned nodes detach from their parent immediately, so long lived graphs do not retain released effects or scopes.\n\n## watch selected values\n\nuse `watch()` for one selected output. reactive reads made only inside its callback are untracked. for one shot observation, dispose the returned handle from inside the callback; with `immediate: true` the callback runs before the handle exists, so do the first invocation at the call site. use `effect()` when every callback read should be a dependency.\n\n```ts\nconst stopwatch = ripple.watch(\n () => `${first.value} ${last.value}`,\n (value, previous) => console.log({ previous, value }),\n { immediate: true },\n);\n\nstopwatch.dispose();\n```\n\n## error handling\n\nfailures inside effect callbacks, computed derivations, cleanups, and listeners never corrupt the graph: the failing node is reported and siblings keep propagating. the `onerror` option decides what reporting means. by default failures rethrow asynchronously (via `queuemicrotask`), surfacing as unhandled errors; pass a handler to route them to a logger or error boundary instead:\n\n```ts\nconst ripple = createripple({\n onerror: (error, context) => {\n // context.kind: 'cleanup' | 'computed' | 'effect' | 'flush' | 'listener'\n console.error(`${context.kind}:`, error);\n },\n});\n```\n\n`onerror` is the only runtime option. effect options accept only a `name`; effects do not have a\nmicrotask scheduler. use `batch()` to coalesce related writes.\n\na direct computed read can throw its derivation error to the caller. `onerror` handles computed\nrefresh failures during propagation, not every possible synchronous exception. the exported\nhierarchy is `rippleerror`, `ripplecycleerror`, and `rippledisposederror`; callback failures retain\ntheir original values.\n\na runaway effect (one that keeps re triggering itself) is caught by the flush iteration limit and reported with context kind `flush`; the flush is abandoned and the graph stays usable for later writes.\n\n## bridging external sources\n\n`fromsubscribable()` bridges external `{ getsnapshot, subscribe }` sources into a disposable reactive readable. use `ripple.fromsubscribable()` inside isolated graphs; the root helper uses the process lifetime default graph. the bridge rereads after subscription to close registration races, and disposal invokes the external unsubscribe function.\n\n```ts\nimport { fromsubscribable, effect } from '@vielzeug/ripple';\n\nconst routerstate = fromsubscribable({\n getsnapshot: () => router.getsnapshot(),\n subscribe: (cb) => router.subscribe(cb),\n});\n\nconst stop = effect(() => {\n console.log('current route:', routerstate.value);\n});\n\nstop.dispose();\nrouterstate.dispose();\n```\n\n## load async resources\n\n`resource()` starts immediately, tracks its source reads, and aborts the previous loader whenever the source changes or `reload()` is called. it preserves the last successful value (including `undefined`) as `previous` while newer work is pending or fails.\n\n```ts\nconst userid = ripple.signal('42');\nconst user = ripple.resource(\n () => userid.value,\n (id, { signal }) => fetch(`/users/${id}`, { signal }).then((response) => response.json()),\n { name: 'user' },\n);\n\nconst stop = ripple.effect(() => {\n const state = user.value;\n if (state.status === 'success') console.log(state.value);\n if (state.status === 'error') console.error(state.error);\n});\n\nstop.dispose();\nuser.dispose();\n```\n\nsource and loader failures become resource error state rather than `onerror` reports.\n`reload()` returns `void`; observe state to know when loading finishes. disposed resources retain\nreadable state but throw `rippledisposederror` from `reload()` and new subscriptions. use sourcerer\nfor paginated collection state and a dedicated server state cache for shared keyed reads, retries,\nand invalidation.\n\n## object state\n\n`signal()` with `update()` holds one value and supports immutable replacement patterns. return replacement objects from `update()` when object consumers depend on immutable updates.\n\n```ts\nconst cart = ripple.signal({ items: 0, label: 'empty' });\nconst items = ripple.computed(() => cart.value.items);\n\ncart.update((state) => ({ ...state, items: state.items + 1 }));\ncart.value = { items: 3, label: 'ready' };\n\nconsole.log(items.value);\n```\n\n## testing\n\ncreate an isolated graph per test. disposal prevents effects from leaking into later tests.\n\n```ts\nimport { expect, test } from 'vitest';\nimport { createripple } from '@vielzeug/ripple';\n\ntest('derives a doubled count', () => {\n const ripple = createripple();\n const count = ripple.signal(2);\n const doubled = ripple.computed(() => count.value * 2);\n\n expect(doubled.value).tobe(4);\n ripple.dispose();\n});\n```\n\n## framework integration\n\nuse signals and effects with any renderer. dispose component owned effects when the component unmounts.\n\n::: code group\n\n```ts [react]\nimport { useeffect, usestate } from 'react';\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\n\nexport function counter() {\n const [, rerender] = usestate(0);\n\n useeffect(() => {\n const stop = ripple.effect(() => {\n void count.value;\n rerender((revision) => revision + 1);\n });\n\n return () => stop.dispose();\n }, []);\n\n return <button onclick={() => (count.value += 1)}>{count.value}</button>;\n}\n```\n\n```ts [vue 3]\nimport { onunmounted, ref } from 'vue';\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst revision = ref(0);\nconst stop = ripple.effect(() => {\n void count.value;\n revision.value++;\n});\n\nonunmounted(() => stop.dispose());\n```\n\n```ts [svelte]\n<script lang=\"ts\">\n import { ondestroy } from 'svelte';\n import { createripple } from '@vielzeug/ripple';\n\n const ripple = createripple();\n const count = ripple.signal(0);\n let revision = 0;\n const stop = ripple.effect(() => {\n void count.value;\n revision++;\n });\n\n ondestroy(() => stop.dispose());\n</script>\n\n<button on:click={() => (count.value += 1)}>{count.value}</button>\n```\n\n:::\n\n## working with other vielzeug libraries\n\nore uses ripple for component reactivity. clockwork actors expose framework neutral snapshots; bridge actor subscriptions into a ripple signal. ledger adds undo/redo commands around state changes without replacing graph.\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\nimport { definemachine } from '@vielzeug/clockwork';\n\nconst ripple = createripple();\nconst actor = definemachine<record<string, never>, { type: 'start' }>()({\n initial: 'idle',\n states: { active: {}, idle: { on: { start: { target: 'active' } } } },\n}).createactor();\n\nconst snapshot = ripple.signal(actor.snapshot);\nconst stop = actor.subscribe((next) => (snapshot.value = next));\nconst status = ripple.computed(() => snapshot.value.state);\nconsole.log(status.value);\n\nstop();\nactor.dispose();\nripple.dispose();\n```\n\n## gotchas\n\n### `subscribe()` is change only\n\n`readable.subscribe(listener)` never calls the listener on subscribe: it fires only after a tracked source changes. read the current value at the call site when you need an initial state.\n\n### `subscribe()` forces computed evaluation\n\n`readable.subscribe()` calls `peek()` before registering the listener. for signals this is a no op, but for computeds it forces `refresh()`: the derivation runs immediately even if no one reads `.value`. this ensures `equals` comparison works on the first dependency change. avoid subscribing to expensive computeds unless you need their value.\n\n### diamonds recompute each path once per write\n\na computed with dependents refreshes eagerly during propagation, so effects never re run for unchanged derived values. the tradeoff: in a diamond (`a → b, c → d`), one write to `a` recomputes both `b` and `c` and then `d` once per changed path. values a consumer observes are always consistent: a dependent reading a stale intermediate pulls the fresh value on read, so no glitched state is ever visible. prefer keeping diamond depth shallow when a derivation is expensive.\n\n### computed first run failure is recoverable\n\nif a computed's `derive` throws on its first run (e.g., a source is `null`), the computed commits the partial dependencies it tracked before the throw. when a dependency changes and the derivation can succeed, the computed refreshes and notifies its dependents. effects that read a failing computed report the error through `onerror` and re run when the computed recovers.\n\n## best practices\n\n create one graph per ownership boundary.\n keep computed callbacks pure.\n return cleanup from effects.\n dispose test and feature graphs.\n batch related synchronous writes.\n use `watch()` only for selected source transitions; callback only reads are untracked.\n dispose external source bridges when their owner ends.\n route runtime failures with `onerror` and observe async failures through resource state.\n",
1075
+ "index": " \ntitle: 'ripple: reactive graphs'\ndescription: framework agnostic signals, effects, async resources, scopes, and structural bridges.\npackage: ripple\ncategory: state\nkeywords: [reactive, signals, computed, effects, graph, scope, batch, watch]\nrelated: [ore, clockwork, ledger]\nexports: [createripple, signal, computed, effect, resource]\nenvironments: [browser, node, ssr, deno]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"ripple\" />\n\n## why ripple?\n\nhand rolled reactive state spreads subscription, cleanup, and derived value rules across application code. ripple gives you one graph boundary with explicit disposal and fine grained dependencies while keeping rendering and routing outside the runtime.\n\n```ts\n// before\nlet count = 0;\nconst listeners = new set<() => void>();\n\nfunction setcount(next: number) {\n count = next;\n for (const listener of listeners) listener();\n}\n\n// after\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst doubled = ripple.computed(() => count.value * 2);\nconst stop = ripple.effect(() => console.log(doubled.value));\n\ncount.value = 1;\nstop.dispose();\nripple.dispose();\n```\n\n| feature | ripple | zustand | jotai |\n| | | | |\n| bundle size | <packageinfo package=\"ripple\" type=\"size\" /> | ~3.5 kb | ~7 kb |\n| zero dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| framework agnostic | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | react first |\n| explicit graph lifetime | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| fine grained derived values | <ore icon name=\"check\" size=\"16\"></ore icon> | selectors | atoms |\n\n<div class=\"decision callout\">\n\n**use ripple when** you need framework independent state with explicit graph lifetime and small composable primitives.\n\n**consider a framework store when** component bindings, server cache, or framework specific tooling matter more than portable reactive state.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/ripple\n```\n\n```sh [npm]\nnpm install @vielzeug/ripple\n```\n\n```sh [yarn]\nyarn add @vielzeug/ripple\n```\n\n:::\n\n## quick start\n\ncreate one graph, derive a value, observe it, then dispose when the graph lifetime ends.\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst doubled = ripple.computed(() => count.value * 2);\nconst stop = ripple.effect(() => console.log(doubled.value));\n\nripple.batch(() => {\n count.value = 1;\n count.value = 2;\n});\n\nstop.dispose();\nripple.dispose();\n```\n\n## features\n\n<div class=\"features grid\">\n\n `createripple({ onerror })` creates an isolated graph with one runtime failure callback.\n `signal()` stores writable values with configurable equality.\n `computed()` derives lazy, glitch free read only values: at most once per flush, never from a stale source.\n `effect()` reacts to dependency changes with cleanup support.\n `oncleanup()` runs a callback when the active scope or effect run is disposed.\n `batch()` coalesces synchronous writes and notifications.\n `createscope()` groups owned reactive work.\n `watch()` observes one selected source transition.\n `resource()` owns focused latest request async state.\n `fromsubscribable()` creates a disposable bridge for external `{ getsnapshot, subscribe }` sources.\n `rippleerror`, `ripplecycleerror`, and `rippledisposederror` distinguish package originated failures.\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [ore](/ore/): uses ripple signals and effects for web component reactivity.\n [clockwork](/clockwork/): exposes machine state through reactive ripple values.\n [ledger](/ledger/): adds command based undo and redo beside ripple state.\n\n</div>\n\n<! markdownlint enable >\n",
1076
+ "api": " \ntitle: 'ripple: api reference'\ndescription: complete reference for reactive graphs, signals, effects, scopes, and watchers.\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `createripple()` | create isolated graph | sync | disposal is terminal; create a new graph instead of reusing it |\n| `signal()` | create writable value | sync | default graph is process wide |\n| `computed()` | create lazy derived value | sync | keep derivation pure |\n| `effect()` | react to dependency reads | sync | dispose handle or return cleanup |\n| `oncleanup()` | run when the active owner disposes | sync | call it inside a scope or effect |\n| `batch()` | coalesce synchronous writes | sync | does not roll back writes |\n| `createscope()` | group owned reactive work | sync | call `run()` to activate it |\n| `untrack()` | read without tracking | sync | read still happens immediately |\n| `watch()` | observe selected output | sync | use `effect()` for broad reads |\n| `resource()` | load from tracked reactive input | sync factory / async loader | `reload()` returns `void`; completion is observable state |\n| `fromsubscribable()` | bridge external source | sync | returned bridge must be disposed |\n| `isreactive()` | test ripple's marked readable contract | sync | not a security or provenance check |\n| `rippleerror` | base package error | sync | runtime callback failures retain their original value |\n| `ripplecycleerror` | computed cycle or runaway flush | sync | flush failures reach `onerror`, not the write site |\n| `rippledisposederror` | work after disposal | sync | cached reads remain available |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/ripple` | all primitives, types, and errors: signals, computed, effects, scopes, watch, and the isolated graph factory |\n\n## graph creation\n\n### `createripple(options?)`\n\n```ts\nfunction createripple(options?: rippleoptions): ripple;\n```\n\ncreates one isolated reactive graph. factories on the returned object share scheduling, ownership, and error boundaries. `dispose()` is terminal: `ripple.disposed` becomes `true`, existing owned work is disposed, and creating more graph work throws `rippledisposederror`. create a new graph for a new lifetime.\n\n| parameter | type | description |\n| | | |\n| `options.onerror` | `(error, context) => void` | handles effect, cleanup, listener, and flush loop failures, including computed errors those consumers read. default rethrows asynchronously via `queuemicrotask`; pass a no op to silence. a failure in one node never interrupts its siblings. |\n\n`onerror` is the only runtime option. `rippleerrorcontext.kind` is `cleanup`, `effect`, `flush`,\nor `listener`; `name` is optional. there is no event stream or error policy option.\n\n**returns:** `ripple`.\n\n**example:**\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst stop = ripple.effect(() => console.log(count.value));\n\nstop.dispose();\nripple.dispose();\n```\n\n \n\n### `isreactive(value)`\n\n```ts\nfunction isreactive<t>(value: t | readable<t>): value is readable<t>;\n```\n\ntests ripple's shared symbol marker and complete readable surface (`value`, `peek()`, and `subscribe()`). recognition works across duplicated ripple module graphs. the marker is intentionally structural and forgeable; do not use this guard for trust or provenance decisions.\n\n**returns:** `true` for marked signals, computeds, resources, and external source bridges with the complete readable contract.\n\n**example:**\n\n```ts\nimport { isreactive, signal } from '@vielzeug/ripple';\n\nconsole.log(isreactive(signal(0)));\n```\n\n## default graph functions\n\nroot helpers (`signal`, `computed`, `effect`, `oncleanup`, `batch`, `createscope`, `untrack`, `watch`, `resource`, `fromsubscribable`) operate on a process lifetime default graph. the graph itself has no public disposal handle; effects, scopes, resources, and bridges still require owner managed disposal. for isolated, disposable graphs (tests, ssr, embedded features) use `createripple()`.\n\n### `signal(initial, options?)`\n\n```ts\nfunction signal<t>(initial: t, options?: signaloptions<t>): signal<t>;\n```\n\ncreates writable state on the default graph. use `update()` for immutable replacement patterns.\n\n**returns:** `signal<t>`.\n\n**example:**\n\n```ts\nimport { signal } from '@vielzeug/ripple';\n\nconst count = signal(0);\ncount.value += 1;\n\nconst cart = signal({ items: 0 });\ncart.update((state) => ({ ...state, items: state.items + 1 }));\n```\n\n \n\n### `computed(derive, options?)`\n\n```ts\nfunction computed<t>(derive: () => t, options?: computedoptions<t>): readable<t>;\n```\n\ncreates a lazy read only value from reactive reads in `derive`. a write only marks the computed stale; it derives on the next read, at most once per flush, and always from up to date sources. a derivation error is cached and rethrown by every read (`value` or `peek()`) until a source changes; consumers that read it report it through `onerror` in their own context. a disposed computed returns its last cached value from `peek()` without recomputing; a computed disposed before its first evaluation throws `rippledisposederror` instead of returning a value.\n\n**returns:** `readable<t>`.\n\n**example:**\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\n\nconst count = signal(2);\nconst doubled = computed(() => count.value * 2);\nconsole.log(doubled.value);\n```\n\n \n\n### `effect(callback, options?)`\n\n```ts\nfunction effect(callback: () => cleanup | undefined, options?: effectoptions): effecthandle;\n```\n\nruns immediately and reruns when its tracked reads change. an effect that only reads computeds reruns only when one of them derives a different value. a returned cleanup runs before the next callback or disposal.\n\n| parameter | type | description |\n| | | |\n| `options.name` | `string` | optional label in error context |\n\neffects flush synchronously; `effectoptions` has no scheduler option. use `batch()` to coalesce writes.\n\n**returns:** `effecthandle`.\n\n**example:**\n\n```ts\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst connected = signal(false);\nconst stop = effect(() => {\n if (!connected.value) return;\n\n return () => console.log('disconnect');\n});\n\nstop.dispose();\n```\n\n \n\n### `oncleanup(fn)`\n\n```ts\nfunction oncleanup(fn: cleanup): void;\n```\n\nregisters `fn` on the active owner: the current effect run when called inside an effect, otherwise the active scope. the callback runs when that owner is disposed, after the owner's effects and computeds, newest first. for an effect run that means before the next run, and after the cleanup function the effect itself returned. a callback that calls `oncleanup()`, `effect()`, or `computed()` while its owner is being disposed gets that work torn down immediately. a throwing callback is reported through `onerror` and does not skip the others.\n\ncalled with no scope or effect active, it registers on the graph root. the default graph is never disposed, so use `createripple()` or an explicit scope when the callback must run.\n\n**example:**\n\n```ts\nimport { createscope, effect, oncleanup, signal } from '@vielzeug/ripple';\n\nconst scope = createscope('panel');\nconst count = signal(0);\n\nscope.run(() => {\n effect(() => {\n console.log(count.value);\n oncleanup(() => console.log('effect run ended'));\n });\n oncleanup(() => console.log('panel closed'));\n});\n\nscope.dispose();\n```\n\n \n\n### `batch(fn)` and `untrack(fn)`\n\n```ts\nfunction batch<t>(fn: () => t): t;\nfunction untrack<t>(fn: () => t): t;\n```\n\n`batch()` defers effects and listeners until its callback returns. `untrack()` reads current state without adding dependencies to an enclosing effect.\n\n**returns:** the callback result.\n\n**example:**\n\n```ts\nimport { batch, signal, untrack } from '@vielzeug/ripple';\n\nconst first = signal('ada');\nconst last = signal('lovelace');\nconst locale = signal('en us');\n\nbatch(() => {\n first.value = 'grace';\n last.value = 'hopper';\n});\n\nconsole.log(untrack(() => locale.value));\n```\n\n \n\n### `createscope(name?)`\n\n```ts\nfunction createscope(name?: string): scope;\n```\n\ncreates a disposable ownership boundary. work created inside `scope.run()` belongs to that scope. explicit scopes created during an effect run attach to the enclosing scope (not the transient effect run owner) and therefore survive reruns until explicitly or parent disposed. disposed children detach from parent ownership immediately.\n\n**returns:** `scope`.\n\n**example:**\n\n```ts\nimport { createscope, effect, signal } from '@vielzeug/ripple';\n\nconst scope = createscope('panel');\nconst count = signal(0);\n\nscope.run(() => effect(() => console.log(count.value)));\nscope.dispose();\n```\n\n### `resource(source, loader, options?)`\n\n```ts\nfunction resource<source, value>(\n source: () => source,\n loader: (source: source, context: { readonly signal: abortsignal }) => promise<value>,\n options?: resourceoptions,\n): resource<value>;\n```\n\ncreates a disposable readable async state and starts loading immediately. source changes and `reload()` abort stale work before starting the next loader. the last successful value is preserved as `previous`, including when that value is `undefined`.\n\n| parameter | type | description |\n| | | |\n| `source` | `() => source` | tracks reactive input reads |\n| `loader` | `(source, context) => promise<value>` | receives input and a request owned cancellation signal |\n| `options.name` | `string` | optional resource label |\n\n**returns:** `resource<value>`. source and loader failures become error state, not `onerror` reports.\n\n**example:**\n\n```ts\nimport { resource, signal } from '@vielzeug/ripple';\n\nconst userid = signal('42');\nconst user = resource(\n () => userid.value,\n (id, { signal }) => fetch(`/users/${id}`, { signal }).then((response) => response.json()),\n);\nconsole.log(user.value);\nuser.dispose();\n```\n\nthe state is `{ status: 'pending', previous? }`, `{ status: 'success', value }`, or `{ status: 'error', error, previous? }`. reads remain available after disposal; `reload()` and new subscriptions throw `rippledisposederror`.\n\n## watch\n\n### `watch(source, callback, options?)`\n\n```ts\nfunction watch<t>(\n source: readable<t> | (() => t),\n callback: (value: t, previous: t | undefined) => void,\n options?: watchoptions<t>,\n): effecthandle;\n```\n\nobserves selected output changes using the default graph or a `ripple.watch()` method. callback only reactive reads are untracked; without `immediate`, initial evaluation does not count as an invocation. for one shot observation, dispose the returned handle from inside the callback: with `immediate: true`, do the first invocation at the call site instead, because the callback runs before the handle exists.\n\n**returns:** `effecthandle`.\n\n**example:**\n\n```ts\nimport { signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst stop = watch(count, (value, previous) => console.log(previous, value), { immediate: true });\nstop.dispose();\n```\n\n \n\n### `fromsubscribable(source, options?)`\n\n```ts\nfunction fromsubscribable<t>(source: subscribable<t>, options?: fromsubscribableoptions): bridgedreadable<t>;\n```\n\nbridges an external `{ getsnapshot, subscribe }` source into a disposable reactive readable. the bridge subscribes and then rereads the snapshot to avoid missing a change during registration. the root helper uses the default graph; `ripple.fromsubscribable()` binds ownership to an isolated graph. an optional signal disposes the bridge.\n\n**returns:** `bridgedreadable<t>`. disposal invokes the source unsubscribe function. reads remain available afterward, while new subscriptions throw `rippledisposederror`.\n\n**example:**\n\n```ts\nimport { fromsubscribable } from '@vielzeug/ripple';\n\nlet current = 'idle';\nconst listeners = new set<() => void>();\nconst state = fromsubscribable({\n getsnapshot: () => current,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n});\n\ncurrent = 'ready';\nfor (const listener of listeners) listener();\nconsole.log(state.value);\nstate.dispose();\n```\n\n## types\n\n```ts\ntype cleanup = () => void;\ntype equality<t> = (previous: t, next: t) => boolean;\ntype unsubscribe = () => void;\n\ntype signaloptions<t> = { equals?: equality<t>; name?: string };\ntype computedoptions<t> = { equals?: equality<t>; name?: string };\ntype effectoptions = { name?: string };\ntype watchoptions<t> = { equals?: equality<t>; immediate?: boolean; name?: string };\n\ntype rippleerrorcontext = {\n readonly kind: 'cleanup' | 'effect' | 'flush' | 'listener';\n readonly name?: string;\n};\ntype rippleoptions = { onerror?: (error: unknown, context: rippleerrorcontext) => void };\n\ninterface readable<t> {\n readonly name?: string;\n peek(): t;\n /** change only: the listener is not called on subscribe, only after a tracked source changes. */\n subscribe(listener: () => void): unsubscribe;\n readonly value: t;\n}\n\ninterface signal<t> extends readable<t> {\n update(updater: (prev: t) => t): void;\n value: t;\n}\ninterface disposable {\n dispose(): void;\n readonly disposed: boolean;\n readonly disposalsignal: abortsignal;\n [symbol.dispose](): void;\n}\ntype effecthandle = disposable;\ninterface scope extends disposable {\n run<t>(fn: () => t): t;\n}\n\ninterface subscribable<t> {\n getsnapshot(): t;\n subscribe(listener: () => void): unsubscribe;\n}\n\ntype fromsubscribableoptions = { name?: string; signal?: abortsignal };\ntype bridgedreadable<t> = readable<t> & disposable;\n\ntype asyncstate<t> =\n | { readonly previous?: t; readonly status: 'pending' }\n | { readonly status: 'success'; readonly value: t }\n | { readonly error: unknown; readonly previous?: t; readonly status: 'error' };\n\ninterface resource<t> extends readable<asyncstate<t>>, disposable {\n reload(): void;\n}\n\ntype resourceoptions = { name?: string };\n\ninterface ripple extends disposable {\n batch<t>(fn: () => t): t;\n computed<t>(derive: () => t, options?: computedoptions<t>): readable<t>;\n createscope(name?: string): scope;\n effect(callback: () => cleanup | undefined, options?: effectoptions): effecthandle;\n oncleanup(fn: cleanup): void;\n fromsubscribable<t>(source: subscribable<t>, options?: fromsubscribableoptions): bridgedreadable<t>;\n resource<source, value>(\n source: () => source,\n loader: (source: source, context: { readonly signal: abortsignal }) => promise<value>,\n options?: resourceoptions,\n ): resource<value>;\n signal<t>(initial: t, options?: signaloptions<t>): signal<t>;\n untrack<t>(fn: () => t): t;\n watch<t>(\n source: readable<t> | (() => t),\n callback: (value: t, previous: t | undefined) => void,\n options?: watchoptions<t>,\n ): effecthandle;\n}\n```\n\n## errors\n\n| error | trigger | notable properties |\n| | | |\n| `rippleerror` | base class of every ripple error | use `instanceof rippleerror` to narrow unknown values. |\n| `ripplecycleerror` | a computed reads itself, directly or through other computeds, or a flush exceeds the iteration limit | extends `rippleerror`. a flush loop breach is reported to `onerror` (context kind `flush`) instead of throwing from the write site. |\n| `rippledisposederror` | new graph work, writes, or subscriptions on a disposed runtime; `run()` on a disposed scope; `reload()` or new subscriptions on a disposed resource or bridge; reading a never evaluated disposed computed | extends `rippleerror`. cached reads and repeated disposal remain valid. |\n\nthese are the three exported error classes. user callback failures are reported as their original\nvalues through `onerror`; they are not wrapped in `rippleerror`. a direct computed read rethrows\nits cached derivation error to the caller.\n",
1077
+ "usage": " \ntitle: 'ripple: usage guide'\ndescription: build reactive state with one explicit graph boundary.\n \n\n[[toc]]\n\n## basic usage\n\nuse top level functions when one application lifetime graph is sufficient. read a signal inside an effect to make that read reactive.\n\n```ts\nimport { computed, effect, signal } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst label = computed(() => `count: ${count.value}`);\nconst stop = effect(() => console.log(label.value));\n\ncount.value = 1;\nstop.dispose();\n```\n\n## isolated graphs\n\nuse `createripple()` for tests, ssr requests, embedded applications, or independently disposable features. never mix reactive values from separate graphs.\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple({\n onerror: (error, context) => console.log(context.kind, error),\n});\n\nconst count = ripple.signal(0);\nconst stop = ripple.effect(() => console.log(count.value));\n\nstop.dispose();\nripple.dispose();\n```\n\n## derived values and batches\n\nuse `computed()` for pure derivation. use `untrack()` when a current read must not become an effect dependency. use `batch()` for related synchronous writes.\n\n```ts\nconst first = ripple.signal('ada');\nconst last = ripple.signal('lovelace');\nconst locale = ripple.signal('en us');\nconst name = ripple.computed(() => `${first.value} ${last.value}`);\n\nripple.effect(() => {\n console.log({ locale: ripple.untrack(() => locale.value), name: name.value });\n});\n\nripple.batch(() => {\n first.value = 'grace';\n last.value = 'hopper';\n});\n```\n\n## scheduling and subscriptions\n\na synchronous write marks everything downstream stale before any effect runs. each flush pass runs effects queued at its\nstart before direct `subscribe()` listeners queued at its start. work queued by either runs in a later pass.\neffects coalesce writes made inside the same synchronous flush: a `batch()` (or any writes during a flush) produces a single effect run.\neach `subscribe()` registration fires once per flush, even when several subscriptions share one callback function.\n\n```ts\nconst count = ripple.signal(0);\nconst log: string[] = [];\n\nripple.effect(() => log.push(`effect: ${count.value}`));\ncount.subscribe(() => log.push(`listener: ${count.value}`));\n\nlog.length = 0; // ignore synchronous creation runs.\nripple.batch(() => {\n count.value = 1;\n count.value = 2;\n});\nconsole.log(log); // ['effect: 2', 'listener: 2']\n```\n\n## ownership with scopes\n\ncreate a scope when a group of effects or derived values shares one lifetime. dispose the scope when its feature ends.\n\n```ts\nconst scope = ripple.createscope('panel');\nconst count = ripple.signal(0);\n\nscope.run(() => {\n ripple.effect(() => console.log(`panel count: ${count.value}`));\n});\n\ncount.value = 1;\nscope.dispose();\n```\n\neffects and computeds created directly during an effect run belong to that run and are disposed before rerun. `oncleanup(fn)` registers on that same owner: inside an effect it runs before the next run, and inside `scope.run()` it runs when the scope is disposed, after the scope's effects. explicit scopes intentionally attach to the enclosing scope and survive effect reruns; create them outside rerunning effects or retain and dispose each scope yourself. a call with no scope or effect active registers on the graph root.\n\ncleanups run with their disposed owner still active, so an `oncleanup()`, `effect()`, or `computed()` called from inside a cleanup is torn down immediately instead of leaking to the parent.\n\ndisposed owned nodes detach from their parent immediately, so long lived graphs do not retain released effects or scopes.\n\n## watch selected values\n\nuse `watch()` for one selected output. reactive reads made only inside its callback are untracked. for one shot observation, dispose the returned handle from inside the callback; with `immediate: true` the callback runs before the handle exists, so do the first invocation at the call site. use `effect()` when every callback read should be a dependency.\n\n```ts\nconst stopwatch = ripple.watch(\n () => `${first.value} ${last.value}`,\n (value, previous) => console.log({ previous, value }),\n { immediate: true },\n);\n\nstopwatch.dispose();\n```\n\n## error handling\n\nfailures inside effect callbacks, computed derivations, cleanups, and listeners never corrupt the graph: the failing node is reported and siblings keep updating. the `onerror` option decides what reporting means. by default failures rethrow asynchronously (via `queuemicrotask`), surfacing as unhandled errors; pass a handler to route them to a logger or error boundary instead:\n\n```ts\nconst ripple = createripple({\n onerror: (error, context) => {\n // context.kind: 'cleanup' | 'effect' | 'flush' | 'listener'\n console.error(`${context.kind}:`, error);\n },\n});\n```\n\n`onerror` is the only runtime option. effect options accept only a `name`; effects do not have a\nmicrotask scheduler. use `batch()` to coalesce related writes.\n\na computed caches a derivation error like a value: every read rethrows it until a source changes.\nthe failure therefore reaches `onerror` through whatever reads it (context kind `effect` for an\neffect, `listener` for a subscription), and a direct read throws it to the caller. the exported\nhierarchy is `rippleerror`, `ripplecycleerror`, and `rippledisposederror`; callback failures retain\ntheir original values.\n\na runaway effect (one that keeps re triggering itself) is caught by the flush iteration limit and reported with context kind `flush`; the flush is abandoned and the graph stays usable for later writes.\n\n## bridging external sources\n\n`fromsubscribable()` bridges external `{ getsnapshot, subscribe }` sources into a disposable reactive readable. use `ripple.fromsubscribable()` inside isolated graphs; the root helper uses the process lifetime default graph. the bridge rereads after subscription to close registration races, and disposal invokes the external unsubscribe function.\n\n```ts\nimport { fromsubscribable, effect } from '@vielzeug/ripple';\n\nconst routerstate = fromsubscribable({\n getsnapshot: () => router.getsnapshot(),\n subscribe: (cb) => router.subscribe(cb),\n});\n\nconst stop = effect(() => {\n console.log('current route:', routerstate.value);\n});\n\nstop.dispose();\nrouterstate.dispose();\n```\n\n## load async resources\n\n`resource()` starts immediately, tracks its source reads, and aborts the previous loader whenever the source changes or `reload()` is called. it preserves the last successful value (including `undefined`) as `previous` while newer work is pending or fails.\n\n```ts\nconst userid = ripple.signal('42');\nconst user = ripple.resource(\n () => userid.value,\n (id, { signal }) => fetch(`/users/${id}`, { signal }).then((response) => response.json()),\n { name: 'user' },\n);\n\nconst stop = ripple.effect(() => {\n const state = user.value;\n if (state.status === 'success') console.log(state.value);\n if (state.status === 'error') console.error(state.error);\n});\n\nstop.dispose();\nuser.dispose();\n```\n\nsource and loader failures become resource error state rather than `onerror` reports.\n`reload()` returns `void`; observe state to know when loading finishes. disposed resources retain\nreadable state but throw `rippledisposederror` from `reload()` and new subscriptions. use sourcerer\nfor paginated collection state and a dedicated server state cache for shared keyed reads, retries,\nand invalidation.\n\n## object state\n\n`signal()` with `update()` holds one value and supports immutable replacement patterns. return replacement objects from `update()` when object consumers depend on immutable updates.\n\n```ts\nconst cart = ripple.signal({ items: 0, label: 'empty' });\nconst items = ripple.computed(() => cart.value.items);\n\ncart.update((state) => ({ ...state, items: state.items + 1 }));\ncart.value = { items: 3, label: 'ready' };\n\nconsole.log(items.value);\n```\n\n## testing\n\ncreate an isolated graph per test. disposal prevents effects from leaking into later tests.\n\n```ts\nimport { expect, test } from 'vitest';\nimport { createripple } from '@vielzeug/ripple';\n\ntest('derives a doubled count', () => {\n const ripple = createripple();\n const count = ripple.signal(2);\n const doubled = ripple.computed(() => count.value * 2);\n\n expect(doubled.value).tobe(4);\n ripple.dispose();\n});\n```\n\n## framework integration\n\nuse signals and effects with any renderer. dispose component owned effects when the component unmounts.\n\n::: code group\n\n```ts [react]\nimport { useeffect, usestate } from 'react';\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\n\nexport function counter() {\n const [, rerender] = usestate(0);\n\n useeffect(() => {\n const stop = ripple.effect(() => {\n void count.value;\n rerender((revision) => revision + 1);\n });\n\n return () => stop.dispose();\n }, []);\n\n return <button onclick={() => (count.value += 1)}>{count.value}</button>;\n}\n```\n\n```ts [vue 3]\nimport { onunmounted, ref } from 'vue';\nimport { createripple } from '@vielzeug/ripple';\n\nconst ripple = createripple();\nconst count = ripple.signal(0);\nconst revision = ref(0);\nconst stop = ripple.effect(() => {\n void count.value;\n revision.value++;\n});\n\nonunmounted(() => stop.dispose());\n```\n\n```ts [svelte]\n<script lang=\"ts\">\n import { ondestroy } from 'svelte';\n import { createripple } from '@vielzeug/ripple';\n\n const ripple = createripple();\n const count = ripple.signal(0);\n let revision = 0;\n const stop = ripple.effect(() => {\n void count.value;\n revision++;\n });\n\n ondestroy(() => stop.dispose());\n</script>\n\n<button on:click={() => (count.value += 1)}>{count.value}</button>\n```\n\n:::\n\n## working with other vielzeug libraries\n\nore uses ripple for component reactivity. clockwork actors expose framework neutral snapshots; bridge actor subscriptions into a ripple signal. ledger adds undo/redo commands around state changes without replacing graph.\n\n```ts\nimport { createripple } from '@vielzeug/ripple';\nimport { definemachine } from '@vielzeug/clockwork';\n\nconst ripple = createripple();\nconst actor = definemachine<record<string, never>, { type: 'start' }>()({\n initial: 'idle',\n states: { active: {}, idle: { on: { start: { target: 'active' } } } },\n}).createactor();\n\nconst snapshot = ripple.signal(actor.snapshot);\nconst stop = actor.subscribe((next) => (snapshot.value = next));\nconst status = ripple.computed(() => snapshot.value.state);\nconsole.log(status.value);\n\nstop();\nactor.dispose();\nripple.dispose();\n```\n\n## gotchas\n\n### `subscribe()` is change only\n\n`readable.subscribe(listener)` never calls the listener on subscribe: it fires only after a tracked source changes. read the current value at the call site when you need an initial state.\n\n### `subscribe()` evaluates a computed once\n\nsubscribing to a computed derives it immediately so the computed knows its sources, even if no one reads `.value`. a derivation error is cached, not thrown from `subscribe()`. after that, the listener fires only when the derived value actually changes under its `equals`. avoid subscribing to expensive computeds unless you need their value.\n\n### computeds are lazy and glitch free\n\na write only marks downstream computeds stale; nothing re derives until something reads it. when an effect or subscription might be affected, the flush first re derives the computeds it depends on, in the order they were read, and reruns it only if one of them actually changed. in a diamond (`a → b, c → d`), one write to `a` derives `b`, `c`, and `d` once each, and `d` never sees a fresh `b` next to a stale `c`. inside `batch()`, a computed derives at most once however many of its sources were written. a computed no one reads costs nothing after a write.\n\n### computed failures are recoverable\n\nif a computed's `derive` throws (e.g., a source is `null`), the computed keeps the sources it read before the throw and caches the error. when one of those sources changes, the next read derives again; effects that read the failing computed report the error through `onerror` and rerun once it recovers.\n\n## best practices\n\n create one graph per ownership boundary.\n keep computed callbacks pure.\n return cleanup from effects.\n dispose test and feature graphs.\n batch related synchronous writes.\n use `watch()` only for selected source transitions; callback only reads are untracked.\n dispose external source bridges when their owner ends.\n route runtime failures with `onerror` and observe async failures through resource state.\n",
1078
1078
  "examples": " \ntitle: 'ripple: examples'\ndescription: practical ripple recipes.\n \n\n## examples\n\n [reactive counter](./examples/reactive counter.md)\n [batch and untrack](./examples/batch and untrack.md)\n [scope ownership](./examples/scope ownership.md)\n [watch selected value](./examples/watch selected value.md)\n [async resource](./examples/async resource.md)\n [immutable state](./examples/immutable store.md)\n [isolated graph](./examples/isolated runtime.md)\n"
1079
1079
  },
1080
1080
  "examples": [
@@ -1112,7 +1112,7 @@
1112
1112
  "name": "@vielzeug/ripple",
1113
1113
  "related": "ore clockwork ledger",
1114
1114
  "slug": "ripple",
1115
- "source": "export type { asyncstate, resource, resourceoptions } from './_async';\nexport { createripple, type ripple } from './_default';\nexport type { bridgedreadable, fromsubscribableoptions } from './_subscribable';\nexport type { watchoptions } from './_watch';\nexport { ripplecycleerror, rippledisposederror, rippleerror } from './errors';\nexport { isreactive } from './runtime';\nexport type {\n cleanup,\n computedoptions,\n disposable,\n effecthandle,\n effectoptions,\n equality,\n readable,\n rippleerrorcontext,\n rippleoptions,\n scope,\n signal,\n signaloptions,\n subscribable,\n unsubscribe,\n} from './types';\n\nimport { defaultripple } from './_default';\n\nexport const signal = defaultripple.signal;\nexport const computed = defaultripple.computed;\nexport const effect = defaultripple.effect;\nexport const batch = defaultripple.batch;\nexport const createscope = defaultripple.createscope;\nexport const untrack = defaultripple.untrack;\nexport const watch = defaultripple.watch;\nexport const resource = defaultripple.resource;\nexport const fromsubscribable = defaultripple.fromsubscribable;\n"
1115
+ "source": "export type { asyncstate, resource, resourceoptions } from './_async';\nexport { createripple, type ripple } from './_default';\nexport type { bridgedreadable, fromsubscribableoptions } from './_subscribable';\nexport type { watchoptions } from './_watch';\nexport { ripplecycleerror, rippledisposederror, rippleerror } from './errors';\nexport { isreactive } from './runtime';\nexport type {\n cleanup,\n computedoptions,\n disposable,\n effecthandle,\n effectoptions,\n equality,\n readable,\n rippleerrorcontext,\n rippleoptions,\n scope,\n signal,\n signaloptions,\n subscribable,\n unsubscribe,\n} from './types';\n\nimport { defaultripple } from './_default';\n\nexport const signal = defaultripple.signal;\nexport const computed = defaultripple.computed;\nexport const effect = defaultripple.effect;\nexport const oncleanup = defaultripple.oncleanup;\nexport const batch = defaultripple.batch;\nexport const createscope = defaultripple.createscope;\nexport const untrack = defaultripple.untrack;\nexport const watch = defaultripple.watch;\nexport const resource = defaultripple.resource;\nexport const fromsubscribable = defaultripple.fromsubscribable;\n"
1116
1116
  },
1117
1117
  {
1118
1118
  "category": "logging",
@@ -1305,7 +1305,7 @@
1305
1305
  "description": "qr code generation and scanning: pure matrix encoder, svg and canvas renderers, native barcodedetector scanning",
1306
1306
  "docs": {
1307
1307
  "index": " \ntitle: 'sigil: qr code generation and scanning'\ndescription: 'qr code generation and scanning: pure matrix encoder, svg and canvas renderers, native barcodedetector scanning'\npackage: sigil\ncategory: utilities\nkeywords: [qr, qrcode, barcode, encoder, scanner, svg, canvas, barcodedetector, pairing]\nexports: [encodeqr, tosvg, createqrscanner, qrcapacity, detectqr]\nrelated: [mesh, refine]\nenvironments: [browser, node]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"sigil\" />\n\n## why sigil?\n\nqr workflows usually pull in a general purpose barcode library that renders to canvas and guesses at colors, or a from scratch decoder you do not need. sigil is a pure, zero dependency encoder (numeric, alphanumeric, and byte modes; versions 1–40; all four error correction levels; automatic mask selection) with renderers that stay out of the way: an svg string that themes with css, and a canvas painter for print/bitmap flows. scanning is a thin lifecycle wrapper over the platform's native `barcodedetector`, so there is no decoder weight and no polyfill to ship.\n\n```ts\n// before: a qr library per concern, canvas only output, hardcoded colors\nimport qrcode from 'qrcode';\nconst dataurl = await qrcode.todataurl(text, { width: 256, color: { dark: '#000' } });\nimg.src = dataurl; // raster, fixed colors, no theme support\n\n// after: encode once, render anywhere\nimport { encodeqr, tosvg } from '@vielzeug/sigil';\nconst matrix = encodeqr(text); // smallest version that fits, auto mask\nelement.innerhtml = tosvg(matrix); // currentcolor modules: themes with css\n```\n\n| feature | sigil | `qrcode` (node style) | `jsqr` |\n| | | | |\n| bundle size | <packageinfo package=\"sigil\" type=\"size\" /> | ~100 kb+ | decoder only |\n| runtime dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> none | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> none |\n| output | matrix, svg string, canvas | canvas/dataurl/utf 8 | n/a |\n| themeable output | `currentcolor` by default | hardcoded color strings | n/a |\n| scanning | native `barcodedetector` wrapper | <ore icon name=\"x\" size=\"16\"></ore icon> | pure js decoder |\n| ssr safe import | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use sigil when** you need qr output that themes with your ui (svg/`currentcolor`), a minimal encoder with no runtime dependencies, or a scanner that uses the platform decoder instead of shipping one.\n\n**consider `jsqr` style decoding when** you must scan in browsers without `barcodedetector`: sigil reports `sigilunsupportederror` rather than bundling a fallback decoder.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/sigil\n```\n\n```sh [npm]\nnpm install @vielzeug/sigil\n```\n\n```sh [yarn]\nyarn add @vielzeug/sigil\n```\n\n:::\n\n## quick start\n\nencode to an svg string: works in node and the browser:\n\n```ts\nimport { encodeqr, qrcapacity, tosvg } from '@vielzeug/sigil';\n\nconst payload = 'https://vielzeug.dev';\nconst matrix = encodeqr(payload, { errorcorrection: 'm' });\ndocument.queryselector('#qr').innerhtml = tosvg(matrix, { label: 'vielzeug link' });\n```\n\nscan with the camera (browser only: see support notes in the usage guide):\n\n```ts\nimport { createqrscanner } from '@vielzeug/sigil';\n\nconst video = document.queryselector('video');\nconst scanner = createqrscanner({ video });\nscanner.onresult((result) => {\n console.log('scanned:', result.value); // once: true stops after first decode\n});\nawait scanner.start(); // throws sigilunsupportederror / sigilpermissionerror\n```\n\n## features\n\n<div class=\"features grid\">\n\n `encodeqr`: pure matrix encoder: numeric/alphanumeric/byte modes, versions 1–40, ec levels l/m/q/h, automatic or forced mask\n `qrcapacity`: byte capacity per version/mode/level, for pre flight validation\n `tosvg`: compact path merged svg string; `currentcolor` modules, `<title>` + `role=\"img\"` built in\n `drawtocanvas`: bitmap rendering with dpr aware scaling for print and download flows\n `detectqr`: one shot detection on any `imagebitmapsource`\n `createqrscanner`: camera scan loop with `once` mode, status events, `tap()` observability, and strict disposal\n `isqrscansupported`/`qrscansupport`: sync and async feature detection that never assumes\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md): encoding modes, capacity, rendering, scanning, and testing\n [api reference](./api.md): every export, option, type, and error\n [examples](./examples.md): copy paste recipes, including pairing two devices with `meshqrcodec`\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [mesh](../mesh/): backendless p2p sessions; `meshqrcodec` produces compact qr friendly pairing payloads\n [refine](../refine/): `ore qr code` and `ore qr scanner` wrap sigil in ready made, themeable components\n\n</div>\n\n<! markdownlint enable >\n",
1308
- "api": " \ntitle: 'sigil: api reference'\ndescription: 'public api of @vielzeug/sigil: encoder, renderers, scanner, types, and errors.'\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution | common gotcha |\n| | | | |\n| `encodeqr` | encode a payload into a `qrmatrix` | sync | throws `sigilcapacityerror` over capacity |\n| `qrcapacity` | payload limit for a version/level/mode | sync | returns _characters_ for numeric/alphanumeric, _bytes_ for byte mode |\n| `tosvg` | render a matrix as an svg string | sync | escapes `dark`/`light` as raw css: pass values, not markup |\n| `drawtocanvas` | paint a matrix onto a canvas | sync | browser only; resizes the canvas for dpr |\n| `detectqr` | one shot detection on an image source | async | throws `sigilunsupportederror` without `barcodedetector` |\n| `createqrscanner` | camera scan loop | async (start) | must `dispose()`; camera tracks persist otherwise |\n| `isqrscansupported` | sync feature check | sync | constructor exists ≠ `qr_code` supported: prefer `qrscansupport()` |\n| `qrscansupport` | async feature check incl. formats | async | never assume support per browser/version |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/sigil` | complete public sigil api |\n\n## encoding\n\n### `encodeqr(data, options?)`\n\n```ts\nfunction encodeqr(data: string | uint8array, options?: qrencodeoptions): qrmatrix;\n```\n\nencodes `data` into a qr symbol. picks the most compact mode covering the whole input, the smallest fitting version, and the lowest penalty mask.\n\n| parameter | type | default | description |\n| | | | |\n| `data` | `string \\| uint8array` | n/a | payload; `uint8array` is raw binary and always byte mode (no utf 8 round trip) |\n| `options.errorcorrection` | `'l' \\| 'm' \\| 'q' \\| 'h'` | `'m'` | error correction level |\n| `options.version` | `1–40` | auto | pin the version; throws if payload can't fit |\n| `options.minversion` | `1–40` | `1` | smallest acceptable version |\n| `options.mode` | `qrmode` | auto | force a segment mode |\n| `options.mask` | `0–7` | auto | force the mask (test vectors only) |\n\n**returns** a frozen `qrmatrix` with `size`, `version`, `mode`, `errorcorrection`, `mask`, and `get(x, y)`.\n\n**throws** `sigilcapacityerror` (payload exceeds capacity), `sigiloptionerror` (invalid mode/version/mask combination).\n\n```ts\nimport { encodeqr } from '@vielzeug/sigil';\n\nconst matrix = encodeqr('hello world', { errorcorrection: 'q' });\nmatrix.size; // 21 (v1)\nmatrix.get(0, 0); // finder pattern → true\n```\n\n \n\n### `qrcapacity(version, errorcorrection, mode)`\n\n```ts\nfunction qrcapacity(version: number, errorcorrection: qrerrorcorrection, mode: qrmode): number;\n```\n\nreturns the payload limit: characters for `numeric`/`alphanumeric`, bytes for `byte`.\n\n```ts\nqrcapacity(1, 'm', 'byte'); // → 14\nqrcapacity(40, 'l', 'numeric'); // → 7089\n```\n\n## rendering\n\n### `tosvg(matrix, options?)`\n\n```ts\nfunction tosvg(matrix: qrmatrix, options?: qrsvgoptions): string;\n```\n\nreturns a complete `<svg>` string. runs in any environment: no dom required.\n\n| parameter | type | default | description |\n| | | | |\n| `options.dark` | `string` | `'currentcolor'` | dark module color |\n| `options.light` | `string` | `'transparent'` | background color |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.scale` | `number` | `1` | user units per module |\n| `options.optimizepath` | `boolean` | `true` | merge dark runs into one `<path>` |\n| `options.label` | `string` | n/a | `<title>` + `aria label`; enables `role=\"img\"` |\n\n```ts\nconst svg = tosvg(matrix, { label: 'pairing code', dark: 'var( qr dark)' });\n```\n\n \n\n### `drawtocanvas(matrix, canvas, options?)`: browser only\n\n```ts\nfunction drawtocanvas(matrix: qrmatrix, canvas: htmlcanvaselement, options?: qrcanvasoptions): number;\n```\n\npaints the matrix and returns the css pixel edge length. sizes the backing store for `devicepixelratio` so output stays crisp on retina displays.\n\n| parameter | type | default | description |\n| | | | |\n| `options.scale` | `number` | `1` | css px per module |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.dark` / `options.light` | `string` | `'#000'` / `'#fff'` | fill colors |\n\n## scanning (browser only)\n\n### `createqrscanner(options)`\n\n```ts\nfunction createqrscanner(options: qrscanneroptions): qrscanner;\n```\n\ncreates a camera scan loop around the native `barcodedetector`.\n\n| parameter | type | default | description |\n| | | | |\n| `options.video` | `htmlvideoelement` | n/a | element the stream attaches to (needs `autoplay playsinline muted`) |\n| `options.constraints` | `mediatrackconstraints` | `{ facingmode: 'environment' }` | `getusermedia` video constraints |\n| `options.intervalms` | `number` | `200` | minimum ms between detect passes |\n| `options.once` | `boolean` | `true` | stop after the first result |\n| `options.signal` | `abortsignal` | n/a | abort → `stop()` |\n| `options.detector` | `qrdetector` | native | injected detector for tests |\n| `options.mediadevices` | `pick<mediadevices, 'getusermedia'>` | `navigator.mediadevices` | injected media for tests |\n\n**returns** a `qrscanner`:\n\n| member | signature | description |\n| | | |\n| `start()` | `() => promise<void>` | request camera, attach stream, run the detect loop. rejects with `sigilunsupportederror` / `sigilpermissionerror`. `stop()`/`dispose()` while the camera prompt is pending win: the late stream is released and the call resolves |\n| `stop()` | `() => void` | stop the loop and tracks, return to `'idle'`; instance stays usable |\n| `onresult(handler)` | `(handler) => () => void` | decode results; returns unsubscribe |\n| `tap(handler, options?)` | `(handler, { signal? }) => () => void` | observe `sigilevent`s; handler errors are swallowed |\n| `status` | `qrscannerstatus` | `'idle' \\| 'starting' \\| 'scanning' \\| 'disposed'` |\n| `dispose()` / `[symbol.dispose]` | `() => void` | terminal teardown; `disposalsignal` aborts |\n| `disposed` | `boolean` | whether `dispose()` ran |\n\n```ts\nconst scanner = createqrscanner({ video });\nconst off = scanner.onresult(({ value }) => console.log(value));\nawait scanner.start();\n```\n\n \n\n### `detectqr(source, options?)`\n\n```ts\nfunction detectqr(\n source: imagebitmapsource,\n options?: { signal?: abortsignal; detector?: qrdetector },\n): promise<qrscanresult | null>;\n```\n\nsingle pass detection on an image source. returns the first result's `{ value, cornerpoints }`, or `null` when nothing decodes. throws `sigilunsupportederror` when no detector is available.\n\n \n\n### `isqrscansupported()` / `qrscansupport()`\n\n```ts\nfunction isqrscansupported(): boolean;\nfunction qrscansupport(): promise<boolean>;\n```\n\n`isqrscansupported` checks the `barcodedetector` constructor synchronously. `qrscansupport` additionally asks `getsupportedformats()` for `'qr_code'`: use it before showing scan affordances.\n\n## types\n\n```ts\ntype qrerrorcorrection = 'l' | 'm' | 'q' | 'h';\ntype qrmode = 'numeric' | 'alphanumeric' | 'byte';\ntype qrscannerstatus = 'idle' | 'starting' | 'scanning' | 'disposed';\n\ninterface qrmatrix {\n readonly errorcorrection: qrerrorcorrection;\n readonly mask: number;\n readonly mode: qrmode;\n readonly size: number; // 17 + 4 * version\n readonly version: number; // 1–40\n get(x: number, y: number): boolean; // true = dark; false outside bounds\n}\n\ninterface qrscanresult {\n readonly cornerpoints?: readonlyarray<{ readonly x: number; readonly y: number }>;\n readonly value: string;\n}\n\ninterface qrdetector {\n detect(\n source: imagebitmapsource,\n ): promise<readonlyarray<{ rawvalue: string; cornerpoints?: readonlyarray<{ x: number; y: number }> }>>;\n}\n\ntype sigilevent =\n | { readonly type: 'status change'; readonly status: qrscannerstatus }\n | { readonly type: 'detect'; readonly value: string; readonly elapsedms: number }\n | { readonly type: 'frame skipped'; readonly reason: 'not ready' | 'busy' }\n | { readonly type: 'error'; readonly error: sigilerror }\n | { readonly type: 'dispose' };\n```\n\n`qrencodeoptions`, `qrsvgoptions`, `qrcanvasoptions`, `qrscanneroptions`, and `qrscanner` are documented under their factories above.\n\n## errors\n\n| class | trigger | notable members |\n| | | |\n| `sigilerror` | base class for all sigil errors | n/a |\n| `sigilcapacityerror` | payload exceeds the version/mode limit | `bytes`, `maxbytes`, `version` |\n| `sigiloptionerror` | invalid option combination (forced mode can't represent input, bad mask/version) | n/a |\n| `sigilunsupportederror` | `barcodedetector`/`getusermedia`/canvas 2d context missing | n/a |\n| `sigilpermissionerror` | camera `notallowederror` | n/a |\n| `sigildisposederror` | `start()` on a disposed scanner | n/a |\n\nall carry `cause` when wrapping a platform error.\n",
1308
+ "api": " \ntitle: 'sigil: api reference'\ndescription: 'public api of @vielzeug/sigil: encoder, renderers, scanner, types, and errors.'\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution | common gotcha |\n| | | | |\n| `encodeqr` | encode a payload into a `qrmatrix` | sync | throws `sigilcapacityerror` over capacity |\n| `qrcapacity` | payload limit for a version/level/mode | sync | returns _characters_ for numeric/alphanumeric, _bytes_ for byte mode |\n| `tosvg` | render a matrix as an svg string | sync | escapes `dark`/`light` as raw css: pass values, not markup |\n| `drawtocanvas` | paint a matrix onto a canvas | sync | browser only; resizes the canvas for dpr |\n| `detectqr` | one shot detection on an image source | async | throws `sigilunsupportederror` without `barcodedetector` |\n| `createqrscanner` | camera scan loop | async (start) | must `dispose()`; camera tracks persist otherwise |\n| `isqrscansupported` | sync feature check | sync | constructor exists ≠ `qr_code` supported: prefer `qrscansupport()` |\n| `qrscansupport` | async feature check incl. formats | async | never assume support per browser/version |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/sigil` | complete public sigil api |\n\n## encoding\n\n### `encodeqr(data, options?)`\n\n```ts\nfunction encodeqr(data: string | uint8array, options?: qrencodeoptions): qrmatrix;\n```\n\nencodes `data` into a qr symbol. picks the most compact mode covering the whole input, the smallest fitting version, and the lowest penalty mask.\n\n| parameter | type | default | description |\n| | | | |\n| `data` | `string \\| uint8array` | n/a | payload; `uint8array` is raw binary and always byte mode (no utf 8 round trip) |\n| `options.errorcorrection` | `'l' \\| 'm' \\| 'q' \\| 'h'` | `'m'` | error correction level |\n| `options.version` | `1–40` | auto | pin the version; throws if payload can't fit |\n| `options.minversion` | `1–40` | `1` | smallest acceptable version |\n| `options.mode` | `qrmode` | auto | force a segment mode |\n| `options.mask` | `0–7` | auto | force the mask (test vectors only) |\n\n**returns** a frozen `qrmatrix` with `size`, `version`, `mode`, `errorcorrection`, `mask`, and `get(x, y)`.\n\n**throws** `sigilcapacityerror` (payload exceeds capacity), `sigiloptionerror` (invalid mode/version/mask combination).\n\n```ts\nimport { encodeqr } from '@vielzeug/sigil';\n\nconst matrix = encodeqr('hello world', { errorcorrection: 'q' });\nmatrix.size; // 21 (v1)\nmatrix.get(0, 0); // finder pattern → true\n```\n\n \n\n### `qrcapacity(version, errorcorrection, mode)`\n\n```ts\nfunction qrcapacity(version: number, errorcorrection: qrerrorcorrection, mode: qrmode): number;\n```\n\nreturns the payload limit: characters for `numeric`/`alphanumeric`, bytes for `byte`.\n\n```ts\nqrcapacity(1, 'm', 'byte'); // → 14\nqrcapacity(40, 'l', 'numeric'); // → 7089\n```\n\n## rendering\n\n### `tosvg(matrix, options?)`\n\n```ts\nfunction tosvg(matrix: qrmatrix, options?: qrsvgoptions): string;\n```\n\nreturns a complete `<svg>` string. runs in any environment: no dom required.\n\n| parameter | type | default | description |\n| | | | |\n| `options.dark` | `string` | `'currentcolor'` | dark module color (ignored when `gradient` is set) |\n| `options.light` | `string` | `'transparent'` | background color |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.scale` | `number` | `1` | user units per module |\n| `options.optimizepath` | `boolean` | `true` | merge dark runs into one `<path>` |\n| `options.label` | `string` | n/a | `<title>` + `aria label`; enables `role=\"img\"` |\n| `options.dotstyle` | `qrdotstyle` | `'square'` | data module shape; finder zones stay square |\n| `options.gradient` | `qrsvggradientoptions` | n/a | two stop linear gradient replacing module paint |\n| `options.image` | `qrsvgimageoptions` | n/a | centered logo; modules under it are not painted |\n\n```ts\ntype qrdotstyle = 'dots' | 'rounded' | 'square';\n\ntype qrsvggradientoptions = {\n from: string; // first stop\n to: string; // second stop\n angle?: number; // degrees, 0 = top to bottom (default)\n id?: string; // stable <defs> id; auto unique otherwise\n};\n\ntype qrsvgimageoptions = {\n href: string; // logo url (resolved by the consumer, embedded verbatim)\n size?: number; // fraction of the code edge (default 0.22)\n spacing?: number; // clear gap in modules around the logo (default 1)\n background?: string; // optional patch behind the logo\n radius?: number; // corner radius of the background patch\n};\n```\n\nstyling output stays scanner friendly: finder patterns never lose their square shape, and the carve around a logo is a gap, not painted noise. prefer `errorcorrection: 'h'` when overlaying a logo.\n\n```ts\nconst svg = tosvg(matrix, { label: 'pairing code', dark: 'var( qr dark)' });\nconst styled = tosvg(matrix, { dotstyle: 'rounded', gradient: { from: '#0ea5e9', to: '#7c3aed' } });\n```\n\n \n\n### `drawtocanvas(matrix, canvas, options?)`: browser only\n\n```ts\nfunction drawtocanvas(matrix: qrmatrix, canvas: htmlcanvaselement, options?: qrcanvasoptions): number;\n```\n\npaints the matrix and returns the css pixel edge length. sizes the backing store for `devicepixelratio` so output stays crisp on retina displays.\n\n| parameter | type | default | description |\n| | | | |\n| `options.scale` | `number` | `1` | css px per module |\n| `options.margin` | `number` | `4` | quiet zone modules |\n| `options.dark` / `options.light` | `string` | `'#000'` / `'#fff'` | fill colors |\n\n## scanning (browser only)\n\n### `createqrscanner(options)`\n\n```ts\nfunction createqrscanner(options: qrscanneroptions): qrscanner;\n```\n\ncreates a camera scan loop around the native `barcodedetector`.\n\n| parameter | type | default | description |\n| | | | |\n| `options.video` | `htmlvideoelement` | n/a | element the stream attaches to (needs `autoplay playsinline muted`) |\n| `options.constraints` | `mediatrackconstraints` | `{ facingmode: 'environment' }` | `getusermedia` video constraints |\n| `options.intervalms` | `number` | `200` | minimum ms between detect passes |\n| `options.once` | `boolean` | `true` | stop after the first result |\n| `options.signal` | `abortsignal` | n/a | abort → `stop()` |\n| `options.detector` | `qrdetector` | native | injected detector for tests |\n| `options.mediadevices` | `pick<mediadevices, 'getusermedia'>` | `navigator.mediadevices` | injected media for tests |\n\n**returns** a `qrscanner`:\n\n| member | signature | description |\n| | | |\n| `start()` | `() => promise<void>` | request camera, attach stream, run the detect loop. rejects with `sigilunsupportederror` / `sigilpermissionerror`. `stop()`/`dispose()` while the camera prompt is pending win: the late stream is released and the call resolves |\n| `stop()` | `() => void` | stop the loop and tracks, return to `'idle'`; instance stays usable |\n| `onresult(handler)` | `(handler) => () => void` | decode results; returns unsubscribe |\n| `tap(handler, options?)` | `(handler, { signal? }) => () => void` | observe `sigilevent`s; handler errors are swallowed |\n| `status` | `qrscannerstatus` | `'idle' \\| 'starting' \\| 'scanning' \\| 'disposed'` |\n| `dispose()` / `[symbol.dispose]` | `() => void` | terminal teardown; `disposalsignal` aborts |\n| `disposed` | `boolean` | whether `dispose()` ran |\n\n```ts\nconst scanner = createqrscanner({ video });\nconst off = scanner.onresult(({ value }) => console.log(value));\nawait scanner.start();\n```\n\n \n\n### `detectqr(source, options?)`\n\n```ts\nfunction detectqr(\n source: imagebitmapsource,\n options?: { signal?: abortsignal; detector?: qrdetector },\n): promise<qrscanresult | null>;\n```\n\nsingle pass detection on an image source. returns the first result's `{ value, cornerpoints }`, or `null` when nothing decodes. throws `sigilunsupportederror` when no detector is available.\n\n \n\n### `isqrscansupported()` / `qrscansupport()`\n\n```ts\nfunction isqrscansupported(): boolean;\nfunction qrscansupport(): promise<boolean>;\n```\n\n`isqrscansupported` checks the `barcodedetector` constructor synchronously. `qrscansupport` additionally asks `getsupportedformats()` for `'qr_code'`: use it before showing scan affordances.\n\n## types\n\n```ts\ntype qrerrorcorrection = 'l' | 'm' | 'q' | 'h';\ntype qrmode = 'numeric' | 'alphanumeric' | 'byte';\ntype qrscannerstatus = 'idle' | 'starting' | 'scanning' | 'disposed';\n\ninterface qrmatrix {\n readonly errorcorrection: qrerrorcorrection;\n readonly mask: number;\n readonly mode: qrmode;\n readonly size: number; // 17 + 4 * version\n readonly version: number; // 1–40\n get(x: number, y: number): boolean; // true = dark; false outside bounds\n}\n\ninterface qrscanresult {\n readonly cornerpoints?: readonlyarray<{ readonly x: number; readonly y: number }>;\n readonly value: string;\n}\n\ninterface qrdetector {\n detect(\n source: imagebitmapsource,\n ): promise<readonlyarray<{ rawvalue: string; cornerpoints?: readonlyarray<{ x: number; y: number }> }>>;\n}\n\ntype sigilevent =\n | { readonly type: 'status change'; readonly status: qrscannerstatus }\n | { readonly type: 'detect'; readonly value: string; readonly elapsedms: number }\n | { readonly type: 'frame skipped'; readonly reason: 'not ready' | 'busy' }\n | { readonly type: 'error'; readonly error: sigilerror }\n | { readonly type: 'dispose' };\n```\n\n`qrencodeoptions`, `qrsvgoptions`, `qrcanvasoptions`, `qrscanneroptions`, and `qrscanner` are documented under their factories above. `qrdotstyle`, `qrsvggradientoptions`, and `qrsvgimageoptions` are documented under `tosvg`.\n\n## errors\n\n| class | trigger | notable members |\n| | | |\n| `sigilerror` | base class for all sigil errors | n/a |\n| `sigilcapacityerror` | payload exceeds the version/mode limit | `bytes`, `maxbytes`, `version` |\n| `sigiloptionerror` | invalid option combination (forced mode can't represent input, bad mask/version) | n/a |\n| `sigilunsupportederror` | `barcodedetector`/`getusermedia`/canvas 2d context missing | n/a |\n| `sigilpermissionerror` | camera `notallowederror` | n/a |\n| `sigildisposederror` | `start()` on a disposed scanner | n/a |\n\nall carry `cause` when wrapping a platform error.\n",
1309
1309
  "usage": " \ntitle: 'sigil: usage guide'\ndescription: encoding modes, capacity checks, svg/canvas rendering, camera scanning, and testing for @vielzeug/sigil.\n \n\n[[toc]]\n\n## basic usage\n\n`encodeqr` produces a `qrmatrix`: a frozen square of dark/light modules. render it with `tosvg` (string, works anywhere) or `drawtocanvas` (browser).\n\n```ts\nimport { encodeqr, qrcapacity, tosvg } from '@vielzeug/sigil';\n\nconst matrix = encodeqr('https://vielzeug.dev');\n// pick the smallest version automatically, or pin one:\nconst pinned = encodeqr('https://vielzeug.dev', { version: 5, errorcorrection: 'q' });\n\nconst svg = tosvg(matrix); // inline <svg> string: inject or serialize\n```\n\nthe encoder chooses the most compact mode for the whole input and the smallest version that fits. `mask` is chosen by the lowest iso penalty score: override it only for test vectors.\n\n## encoding modes and capacity\n\nthree segment modes cover every payload:\n\n| mode | alphabet | max payload (v40 l) |\n| | | |\n| `numeric` | `0–9` | 7,089 digits |\n| `alphanumeric` | `0–9 a z space $%*+ ./:` | 4,296 chars |\n| `byte` | utf 8 (no eci header) | 2,953 bytes |\n\nmode selection is automatic: `encodeqr('01234567')` uses `numeric`, `'hello world'` uses `alphanumeric`, anything else uses `byte`. force a mode with `mode`, but a forced mode that cannot represent the input throws `sigiloptionerror`.\n\n`uint8array` input is raw binary: it always encodes in byte mode, byte for byte, with no utf 8 round trip: invalid utf 8 (tokens, provisioning payloads) survives intact. forcing a non byte mode with binary input throws `sigiloptionerror`.\n\ncheck capacity before encoding with `qrcapacity(version, errorcorrection, mode)`: it returns the maximum _bytes_ (for `byte` mode) or _characters_ the symbol holds:\n\n```ts\nimport { qrcapacity, sigilcapacityerror } from '@vielzeug/sigil';\n\nqrcapacity(10, 'm', 'byte'); // → 213 (data codewords available at v10 m)\n\ntry {\n encodeqr(hugepayload, { version: 1 });\n} catch (error) {\n if (error instanceof sigilcapacityerror) {\n console.log(`${error.bytes} > ${error.maxbytes} at v${error.version}`);\n }\n}\n```\n\nuse `minversion` to keep a stable symbol size while a payload changes: useful when a layout must not reflow between renders.\n\n## error correction\n\n| level | recovery | trade off |\n| | | |\n| `l` | ~7% | smallest matrix |\n| `m` | ~15% | default: good balance |\n| `q` | ~25% | print, wear |\n| `h` | ~30% | logos/overlays, dense codes |\n\nhigher levels shrink capacity at the same version. for an overlaid logo, prefer `h` _and_ keep the logo inside the quiet zone's margin of safety.\n\n## rendering\n\n### svg: `tosvg`\n\n```ts\nconst svg = tosvg(matrix, {\n dark: 'currentcolor', // default: inherits text color\n light: 'transparent', // default\n margin: 4, // quiet zone in modules (spec minimum is 4)\n scale: 1, // user units per module: prefer scaling via css\n optimizepath: true, // merge adjacent modules into one path (default)\n label: 'pairing code', // <title> + role=\"img\"\n});\n```\n\n`optimizepath` merges each row's dark runs into a single `<path>`: orders of magnitude smaller markup. set `dark`/`light` to css variables to theme the code (`dark: 'var( qr dark)'`).\n\n### canvas: `drawtocanvas` (browser only)\n\n```ts\nconst sizepx = drawtocanvas(matrix, canvas, { scale: 8, margin: 4 });\n// canvas is resized for devicepixelratio; returns the css pixel edge length\n```\n\nuse canvas for print, download (`canvas.toblob`), or compositing. svg is the better default for display.\n\n## scanning (browser only)\n\nscanning wraps the native `barcodedetector`. it is **not** universally available: feature detect, never assume:\n\n| engine | `barcodedetector` | notes |\n| | | |\n| chrome / edge / android webview | yes | `qr_code` format supported |\n| firefox | no (behind flag in some builds) | `isqrscansupported()` → `false` |\n| safari | varies by version | check at runtime; do not rely on version sniffing |\n\n```ts\nimport { createqrscanner, isqrscansupported, qrscansupport } from '@vielzeug/sigil';\n\nisqrscansupported(); // sync: barcodedetector constructor exists\nawait qrscansupport(); // async: also verifies 'qr_code' is a supported format\n\nconst scanner = createqrscanner({\n video, // <video autoplay playsinline muted>\n constraints: { facingmode: 'environment' },\n intervalms: 200, // min ms between detect passes\n once: true, // stop after first result\n});\n\nscanner.onresult((result) => showpairing(result.value));\nscanner.tap((event) => console.debug(event.type)); // status change, detect, frame skipped…\n\nawait scanner.start(); // requests camera, attaches stream, starts the loop\nscanner.stop(); // releases the camera, back to 'idle'; start() resumes\nscanner.dispose(); // terminal: releases everything\n```\n\nstatuses are `'idle' | 'starting' | 'scanning' | 'disposed'`. a `stop()` or `dispose()` that lands while the camera permission prompt is pending wins the race: the late stream is released and `start()` resolves without restarting the loop.\n\n`start()` rejects with `sigilunsupportederror` (no detector/getusermedia) or `sigilpermissionerror` (`notallowederror`). detection failures mid scan surface through `tap` `error` events and stop the scanner.\n\n### one shot detection\n\n`detectqr(source)` runs a single pass over any `imagebitmapsource`: `imagedata`, `blob`, `videoframe`, an `<img>`, or a `<canvas>`:\n\n```ts\nimport { detectqr } from '@vielzeug/sigil';\n\nconst result = await detectqr(imagebitmap); // → { value, cornerpoints } | null\n```\n\n## testing\n\nboth seams are injectable: never touch globals in tests:\n\n```ts\nimport { createqrscanner } from '@vielzeug/sigil';\n\nconst fakescanner = createqrscanner({\n video: document.createelement('video'),\n detector: { detect: async () => [{ rawvalue: 'payload' }] }, // fake barcodedetector\n mediadevices: { getusermedia: async () => fakestream }, // fake camera\n});\n```\n\nfor the web components, `ore qr scanner` exposes a `scannerfactory` js property so tests inject a fake `qrscanner` without stubbing `barcodedetector` or `getusermedia`.\n\n## framework integration\n\nencoding is synchronous and ssr safe: render `tosvg` output as part of server markup:\n\n::: code group\n\n```tsx [react]\nfunction qr({ value }: { value: string }) {\n const svg = usememo(() => tosvg(encodeqr(value)), [value]);\n return <span dangerouslysetinnerhtml={{ __html: svg }} />;\n}\n```\n\n```vue [vue]\n<script setup>\nimport { computed } from 'vue';\nimport { encodeqr, tosvg } from '@vielzeug/sigil';\nconst props = defineprops({ value: string });\nconst svg = computed(() => tosvg(encodeqr(props.value ?? '')));\n</script>\n<template><span v html=\"svg\" /></template>\n```\n\n```html [svelte]\n<script>\n import { encodeqr, tosvg } from '@vielzeug/sigil';\n export let value;\n $: svg = tosvg(encodeqr(value));\n</script>\n<span>{@html svg}</span>\n```\n\n:::\n\nscanning needs lifecycle: start in `onmounted`/`onmount`, always `dispose()` in cleanup.\n\n## working with other vielzeug libraries\n\n **mesh**: `meshqrcodec` compresses webrtc pairing payloads (offer/answer json) to qr friendly strings. the [pair two devices with qr](./examples/pair two devices.md) recipe shows the full flow.\n **refine**: prefer `ore qr code` / `ore qr scanner` over hand rolled wrappers: they compose sigil with themeable markup, a11y labels, and state handling.\n\n## best practices\n\n pre validate payloads with `qrcapacity` before surfacing an encode control.\n keep the quiet zone: `margin` below 4 risks unreadable codes; never overlay content on it.\n prefer `tosvg` + `currentcolor` for display; reserve `drawtocanvas` for print/download.\n feature detect scanning with `qrscansupport()` before showing a scan affordance.\n always `dispose()` scanners: camera tracks outlive route changes otherwise.\n use `once: false` only when the ux genuinely expects repeated decodes.\n treat scanned strings as untrusted input: validate before navigation or pairing.\n pin `minversion` in animated/live payloads so the symbol doesn't resize mid flow.\n",
1310
1310
  "examples": " \ntitle: 'sigil: examples'\ndescription: practical examples and recipes for @vielzeug/sigil.\n \n\n## examples\n\n [themed svg qr code](./examples/themed svg qr code.md)\n [pair two devices with qr](./examples/pair two devices.md)\n"
1311
1311
  },
@@ -1324,7 +1324,7 @@
1324
1324
  "name": "@vielzeug/sigil",
1325
1325
  "related": "mesh refine",
1326
1326
  "slug": "sigil",
1327
- "source": "// public root surface of @vielzeug/sigil. every public export goes through this file.\nexport { drawtocanvas } from './canvas';\nexport { encodeqr, qrcapacity } from './encode';\nexport {\n sigilcapacityerror,\n sigildisposederror,\n sigilerror,\n sigiloptionerror,\n sigilpermissionerror,\n sigilunsupportederror,\n} from './errors';\nexport { createqrscanner, detectqr, isqrscansupported, qrscansupport } from './scan';\nexport { tosvg } from './svg';\nexport type {\n qrcanvasoptions,\n qrdetector,\n qrencodeoptions,\n qrerrorcorrection,\n qrmatrix,\n qrmode,\n qrscanner,\n qrscanneroptions,\n qrscannerstatus,\n qrscanresult,\n qrsvgoptions,\n sigilevent,\n} from './types';\n"
1327
+ "source": "// public root surface of @vielzeug/sigil. every public export goes through this file.\nexport { drawtocanvas } from './canvas';\nexport { encodeqr, qrcapacity } from './encode';\nexport {\n sigilcapacityerror,\n sigildisposederror,\n sigilerror,\n sigiloptionerror,\n sigilpermissionerror,\n sigilunsupportederror,\n} from './errors';\nexport { createqrscanner, detectqr, isqrscansupported, qrscansupport } from './scan';\nexport { tosvg } from './svg';\nexport type {\n qrcanvasoptions,\n qrdetector,\n qrdotstyle,\n qrencodeoptions,\n qrerrorcorrection,\n qrmatrix,\n qrmode,\n qrscanner,\n qrscanneroptions,\n qrscannerstatus,\n qrscanresult,\n qrsvggradientoptions,\n qrsvgimageoptions,\n qrsvgoptions,\n sigilevent,\n} from './types';\n"
1328
1328
  },
1329
1329
  {
1330
1330
  "category": "data",
@@ -1380,10 +1380,10 @@
1380
1380
  "category": "validation",
1381
1381
  "description": "zero dependency schema validation with explicit async checks, standard schema interoperability, and json schema export.",
1382
1382
  "docs": {
1383
- "index": " \ntitle: 'spell: schema validation for typescript'\ndescription: zero dependency schema validation with explicit async checks, standard schema interoperability, and json schema export.\npackage: spell\ncategory: validation\nkeywords: [schema, validation, parsing, standard schema, json schema, locale, typescript, descriptors]\nrelated: [forge, courier, vault]\nexports:\n [\n s,\n createparsecontext,\n joinissuepath,\n spellvalidationerror,\n spelldefinitionerror,\n standardschemav1,\n errorcode,\n './json',\n './predicates',\n ]\nenvironments: [browser, node, ssr, deno]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"spell\" />\n\n## why spell?\n\nspell keeps runtime validation, static inference, and portable definitions in one api. use `s` for schema construction; import json conversion and predicates from dedicated subpaths.\n\nthis example shows the difference between manual branching and a single reusable schema.\n\n```ts\n// before\nfunction parseuserbefore(value: unknown) {\n if (typeof value !== 'object' || value === null) throw new error('expected object');\n\n const candidate = value as record<string, unknown>;\n\n if (typeof candidate.email !== 'string' || !candidate.email.includes('@')) {\n throw new error('expected valid email');\n }\n\n if (typeof candidate.role !== 'string' || !['admin', 'editor', 'viewer'].includes(candidate.role)) {\n throw new error('expected valid role');\n }\n\n return {\n email: candidate.email,\n role: candidate.role,\n };\n}\n\n// after\nimport { s } from '@vielzeug/spell';\n\nconst user = s.object({\n email: s.string().email(),\n role: s.enum(['admin', 'editor', 'viewer'] as const),\n});\n\nconst user = user.parse({ email: 'ada@example.com', role: 'admin' });\n```\n\n| feature | spell | zod | yup |\n| | | | |\n| bundle size | <packageinfo package=\"spell\" type=\"size\" /> | ~62 kb | ~14 kb |\n| type inference | <ore icon name=\"check\" size=\"16\"></ore icon> `infer<t>` | <ore icon name=\"check\" size=\"16\"></ore icon> | partial |\n| coercion api | <ore icon name=\"check\" size=\"16\"></ore icon> `s.coerce.*` | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| async validation | <ore icon name=\"check\" size=\"16\"></ore icon> `.checkasync()` | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| error flattening | <ore icon name=\"check\" size=\"16\"></ore icon> `flatten()` + `flattenfirst()` | <ore icon name=\"check\" size=\"16\"></ore icon> | partial |\n| zero dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use spell when** you want a fluent schema api with strong typescript inference, structured errors, and no third party runtime dependencies.\n\n**consider alternatives when** you are already standardized on another validator ecosystem and migration cost outweighs the api benefits.\n\n</div>\n\n## installation\n\nuse your workspace package manager to add spell.\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/spell\n```\n\n```sh [npm]\nnpm install @vielzeug/spell\n```\n\n```sh [yarn]\nyarn add @vielzeug/spell\n```\n\n:::\n\n## quick start\n\nstart with a schema, then parse unknown input and use the inferred output type everywhere else.\n\n```ts\nimport { s, type infer } from '@vielzeug/spell';\n\nconst user = s\n .object({\n email: s.string().email(),\n name: s.string().min(1),\n role: s.enum(['admin', 'editor', 'viewer'] as const),\n })\n .relaxed(); // allow extra keys: omit for strict mode (default)\n\ntype user = infer<typeof user>;\n\nconst payload: unknown = {\n email: 'ada@example.com',\n name: 'ada',\n role: 'admin',\n team: 'platform',\n};\n\nconst result = user.safeparse(payload);\n\nif (!result.success) throw result.error;\nconst user = result.data;\n```\n\n## features\n\n<div class=\"features grid\">\n\n namespace and tree shakeable schema builders.\n sync and async parsing with `parse()`, `safeparse()`, `parseasync()`, and `safeparseasync()`.\n dependency free standard schema v1 interoperability through `schema['~standard']`.\n explicit `check()` and `checkasync()` rules; sync parsing never skips an async check.\n wrapper modes for `optional`, `nullable`, `nullish`, `default`, `catch`, and `required`.\n frozen declarative definitions through `definition()` and json schema export via `fromdefinition()` from `@vielzeug/spell/json`.\n request local message customization through `createparsecontext()`.\n ordered union parsing produces the same selected branch in sync and async modes.\n structured errors with direct path lookup and flattened views.\n object parsing is hardened against prototype pollution style keys.\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [forge](/forge/): typed form state that uses spell schemas as its validation layer\n [courier](/courier/): http client for validating request and response payloads at service boundaries\n [vault](/vault/): unified storage api that accepts spell schemas to type gate persisted data\n\n</div>\n\n<! markdownlint enable md025 md033 md060 >\n",
1384
- "api": " \ntitle: 'spell: api reference'\ndescription: reference for spell schema builders, parsing, errors, context, and tooling exports.\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `s` | creates schemas | sync or async, depending on checks | `checkasync()` requires async parsing |\n| `createparsecontext()` | creates request local messages | sync | pass the context to each parse call |\n| `joinissuepath()` | flattens issue paths to ui keys | sync | empty or undefined paths join to `''` |\n| `spellvalidationerror` | provides validation issues | sync/async parse failures | use `safeparse()` for expected invalid data |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/spell` | schema builders, errors, types, and parse contexts |\n| `@vielzeug/spell/json` | convert portable definitions to json schema |\n| `@vielzeug/spell/predicates` | standalone format and type predicates |\n\n```ts\nimport { createparsecontext, s, type infer } from '@vielzeug/spell';\nimport { fromdefinition } from '@vielzeug/spell/json';\nimport { isemail } from '@vielzeug/spell/predicates';\n```\n\n## `s`\n\nall builders live under `s`.\n\n| builder | purpose |\n| | |\n| `string`, `number`, `boolean`, `bigint`, `date` | primitive values |\n| `literal`, `enum`, `null`, `undefined`, `unknown`, `never` | exact and universal values |\n| `array`, `tuple`, `set`, `map`, `record`, `object` | collections |\n| `union`, `intersect`, `discriminatedunion`, `lazy` | composition |\n| `coerce.*` | coercing primitive schemas |\n\n```ts\nconst user = s.object({\n email: s.string().email(),\n id: s.string().uuid(),\n role: s.enum(['admin', 'member'] as const),\n});\n\ntype user = infer<typeof user>;\n```\n\nobject schemas reject unknown keys. use `.relaxed()` to retain extras.\n\n## standard schema interoperability\n\nevery schema implements the dependency free standard schema v1 structural protocol through `schema['~standard']`. consumers that accept standard schema validators can use spell schemas directly without an adapter.\n\n```ts\nconst user = s.object({ name: s.string() });\nconst result = await user['~standard'].validate({ name: 'ada' });\n```\n\nsuccessful results contain `value`; failures contain portable `{ message, path }` issues. failed unions remain one stable union issue instead of selecting a branch heuristically.\n\nthe exported `standardschemav1` interface mirrors the full v1 protocol, including `validate(value, options?)` and the `inferinput` and `inferoutput` namespace helpers.\n\n## parsing\n\nevery schema provides:\n\n```ts\nschema.parse(value, context?); // output or spellvalidationerror\nschema.safeparse(value, context?); // parseresult<output>\nschema.parseasync(value, context?); // promise<output>\nschema.safeparseasync(value, context?); // promise<parseresult<output>>\nschema.is(value); // value is output\nschema.assert(value, label?); // assertion\n```\n\n`parse()`, `safeparse()`, `is()`, and `assert()` run synchronous parsing. when a schema, or any schema nested inside it: carries an async check added with `checkasync()`, the synchronous methods throw at runtime with \"cannot evaluate async checks\"; use `parseasync()` or `safeparseasync()` instead. async checks compose at any nesting depth, so `s.object({ tags: s.array(s.string().checkasync(fn)) })` parses correctly through `parseasync()`.\n\nui adapters that accept `anyschema` cannot call `safeparse()` on it: the structural surface type omits it. type adapter parameters against `syncparsable` instead:\n\n```ts\nimport type { syncparsable } from '@vielzeug/spell';\n\nfunction spellvalidator(schema: syncparsable<unknown>) {\n const result = schema.safeparse(value); // types cleanly, no shim or cast\n}\n```\n\nthe shape is structural, so a schema with async checks is assignable to `syncparsable`; calling `safeparse()` on one returns a failed result (\"parse() cannot evaluate async checks\"). when async checks may be present, use `safeparseasync()` instead.\n\n## custom checks\n\n`check()` is synchronous. `checkasync()` is asynchronous. do not return a promise from `check()`.\n\n```ts\nconst signup = s.object({ confirm: s.string(), password: s.string() }).check((value, context) => {\n if (value.password !== value.confirm) {\n context.addissue({ code: 'custom', message: 'passwords must match', path: ['confirm'] });\n }\n});\n\nconst availableemail = s\n .string()\n .email()\n .checkasync(async (value) => {\n return (await emailavailable(value)) || 'email is already registered';\n });\n```\n\n`checkcontext.addissue()` takes `{ code, message, params?, path? }`. paths are relative to current schema.\n\n## modifiers and transforms\n\n```ts\ns.string().optional();\ns.string().nullable();\ns.string().nullish();\ns.string().required();\ns.string().default('guest');\ns.string().catch('guest');\ns.string()\n .trim()\n .transform((value) => value.tolowercase());\ns.string().pipe(s.string().slug());\ns.string().label('user name');\n```\n\n`default()`, `catch()`, preprocessors, transforms, and checks are runtime behavior. they cannot become portable definitions.\n\n## `tolerate()`\n\nwraps an object schema so records saved by older schema versions still parse: the named keys are accepted and stripped instead of failing `invalid_keys`. the parsed output never contains the tolerated keys.\n\n```ts\nconst person = tolerate(s.object({ name: s.string() }), 'address');\n```\n\nthe implementation is a preprocessor on the wrapped schema: non object input reaches the wrapped schema untouched, declared fields keep their validation, and unknown keys outside the tolerated set still fail.\n\n## definitions and json schema\n\n`definition()` is only for schemas containing declarative structure. it returns frozen data and throws `spelldefinitionerror` when runtime behavior is present.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { fromdefinition } from '@vielzeug/spell/json';\n\nconst product = s.object({\n id: s.string().uuid(),\n name: s.string().min(1),\n});\n\nconst definition = product.definition();\nconst jsonschema = fromdefinition(definition);\n```\n\nno implicit schema to json conversion exists. make definition boundary explicit.\n\n## parse contexts\n\n`createparsecontext()` creates immutable request local validation messages.\n\n```ts\nfunction createparsecontext(messages?: deeppartial<messages>): parsecontext;\n```\n\n**returns:** a parse context with built in messages merged with the supplied overrides.\n\n```ts\nimport { createparsecontext, s } from '@vielzeug/spell';\n\nconst context = createparsecontext({\n object: { invalidkeys: () => 'unsupported field' },\n});\n\nconst result = s.object({ email: s.string().email() }).safeparse({ email: 'ada@example.com', extra: true }, context);\n\nif (!result.success) {\n const messages = result.error.messagesat('email');\n console.log(messages);\n}\n```\n\n## types\n\n### inference types\n\n| type | resolves to |\n| | |\n| `infer<tschema>` | parsed output; alias of `inferoutput<tschema>` |\n| `inferinput<tschema>` | input accepted before parsing or transformation |\n| `inferoutput<tschema>` | value returned after parsing and transformation |\n\ncomposite schemas preserve child input types. object input types make fields optional when their field schema accepts `undefined`.\n\n### standard schema\n\n```ts\ninterface standardschemav1<input = unknown, output = input> {\n readonly '~standard': standardschemav1.props<input, output>;\n}\n\nnamespace standardschemav1 {\n interface props<input = unknown, output = input> {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (value: unknown, options?: options) => result<output> | promise<result<output>>;\n readonly types?: types<input, output>;\n }\n\n type result<output> = { readonly value: output; readonly issues?: undefined } | { readonly issues: readonly issue[] };\n interface options {\n readonly libraryoptions?: record<string, unknown>;\n }\n interface issue {\n readonly message: string;\n readonly path?: readonly (propertykey | pathsegment)[];\n }\n interface pathsegment {\n readonly key: propertykey;\n }\n interface types<input = unknown, output = input> {\n readonly input: input;\n readonly output: output;\n }\n type inferinput<schema extends standardschemav1> = nonnullable<schema['~standard']['types']>['input'];\n type inferoutput<schema extends standardschemav1> = nonnullable<schema['~standard']['types']>['output'];\n}\n```\n\n### parse result and issues\n\n```ts\ntype parseresult<t> = { data: t; success: true } | { error: spellvalidationerror; success: false };\n\ntype issue =\n | { code: 'custom'; message: string; params?: record<string, unknown>; path: (string | number)[] }\n | { code: 'invalid_base64'; message: string; params: { format: string }; path: (string | number)[] }\n | { code: 'invalid_date'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_duration'; message: string; params: { format: string }; path: (string | number)[] }\n | { code: 'invalid_enum'; message: string; params: { values: readonly unknown[] }; path: (string | number)[] }\n | { code: 'invalid_finite'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_integer'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_keys'; message: string; params: { keys: string[] }; path: (string | number)[] }\n | { code: 'invalid_length'; message: string; params: { exact: number }; path: (string | number)[] }\n | { code: 'invalid_literal'; message: string; params: { expected: unknown }; path: (string | number)[] }\n | { code: 'invalid_multiple_of'; message: string; params: { step: number | bigint }; path: (string | number)[] }\n | { code: 'invalid_safe'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'invalid_string';\n message: string;\n params: { format?: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };\n path: (string | number)[];\n }\n | { code: 'invalid_type'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_union'; message: string; params: { errors: issue[][] }; path: (string | number)[] }\n | { code: 'invalid_unique'; message: string; params: { unique: true }; path: (string | number)[] }\n | { code: 'invalid_url'; message: string; params: { format: string }; path: (string | number)[] }\n | {\n code: 'invalid_variant';\n message: string;\n params: { discriminator: string; expected: string[] };\n path: (string | number)[];\n }\n | {\n code: 'too_big';\n message: string;\n params: { exclusive?: boolean; max: number | bigint | date };\n path: (string | number)[];\n }\n | {\n code: 'too_small';\n message: string;\n params: { exclusive?: boolean; min: number | bigint | date };\n path: (string | number)[];\n }\n | { code: string & {}; message: string; params?: record<string, unknown>; path: (string | number)[] };\n```\n\n`errorcode` is a const object mapping each issue code to its string literal.\n\n### validation contracts\n\n```ts\ntype parsecontext = { messages: messages };\n\ntype checkcontext = {\n addissue: (issue: {\n code: string;\n message: string;\n params?: record<string, unknown>;\n path?: (string | number)[];\n }) => void;\n};\n\ntype validateresult = boolean | null | undefined | string;\n```\n\n### messages\n\n```ts\ntype messagefn<ctx extends record<string, unknown> = record<string, unknown>> = string | ((ctx: ctx) => string);\n\ntype messages = {\n array: {\n length: (ctx: { exact: number; value: unknown[] }) => string;\n max: (ctx: { max: number; value: unknown[] }) => string;\n min: (ctx: { min: number; value: unknown[] }) => string;\n nonempty: () => string;\n type: () => string;\n unique: () => string;\n };\n bigint: {\n max: (ctx: { max: bigint; value: bigint }) => string;\n min: (ctx: { min: bigint; value: bigint }) => string;\n multipleof: (ctx: { step: bigint; value: bigint }) => string;\n negative: () => string;\n nonnegative: () => string;\n nonpositive: () => string;\n positive: () => string;\n type: () => string;\n };\n boolean: { type: () => string };\n check: { default: () => string };\n date: {\n max: (ctx: { max: date; value: date }) => string;\n min: (ctx: { min: date; value: date }) => string;\n type: () => string;\n };\n enum: { invalid: (ctx: { values: readonly unknown[] }) => string };\n instanceof: { type: (ctx: { classname: string }) => string };\n literal: { expected: (ctx: { expected: unknown }) => string };\n map: {\n max: (ctx: { max: number; value: map<unknown, unknown> }) => string;\n min: (ctx: { min: number; value: map<unknown, unknown> }) => string;\n nonempty: () => string;\n size: (ctx: { exact: number; value: map<unknown, unknown> }) => string;\n type: () => string;\n };\n never: { invalid: () => string };\n number: {\n finite: () => string;\n int: () => string;\n max: (ctx: { max: number; value: number }) => string;\n min: (ctx: { min: number; value: number }) => string;\n multipleof: (ctx: { step: number; value: number }) => string;\n negative: () => string;\n nonnegative: () => string;\n nonpositive: () => string;\n positive: () => string;\n safe: () => string;\n type: () => string;\n };\n object: { invalidkeys: (ctx: { keys: string[] }) => string; type: () => string };\n set: {\n max: (ctx: { max: number; value: set<unknown> }) => string;\n min: (ctx: { min: number; value: set<unknown> }) => string;\n nonempty: () => string;\n size: (ctx: { exact: number; value: set<unknown> }) => string;\n type: () => string;\n };\n string: {\n base64: () => string;\n base64url: () => string;\n cuid: () => string;\n cuid2: () => string;\n date: () => string;\n datetime: () => string;\n duration: () => string;\n email: () => string;\n emoji: () => string;\n endswith: (ctx: { suffix: string; value: string }) => string;\n hex: () => string;\n hexcolor: () => string;\n includes: (ctx: { substr: string; value: string }) => string;\n ip: () => string;\n jwt: () => string;\n length: (ctx: { exact: number; value: string }) => string;\n max: (ctx: { max: number; value: string }) => string;\n min: (ctx: { min: number; value: string }) => string;\n nanoid: () => string;\n nonempty: () => string;\n numeric: () => string;\n regex: (ctx: { value: string }) => string;\n semver: () => string;\n slug: () => string;\n startswith: (ctx: { prefix: string; value: string }) => string;\n time: () => string;\n type: () => string;\n ulid: () => string;\n url: () => string;\n uuid: () => string;\n };\n tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type: () => string };\n union: { invalid: () => string };\n variant: { invaliddiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type: () => string };\n};\n\ntype deeppartial<t> = {\n [k in keyof t]?: t[k] extends record<string, unknown> ? deeppartial<t[k]> : t[k];\n};\n```\n\n### descriptor and json schema\n\n```ts\ntype schemadescriptor = basedescriptor &\n (\n | { kind: 'unknown' | 'never' | 'boolean' | 'bigint' | 'date' | 'lazy' }\n | { classname: string; kind: 'instanceof' }\n | {\n contentencoding?: string;\n format?: string;\n kind: 'string';\n maxlength?: number;\n minlength?: number;\n pattern?: string | null;\n }\n | {\n exclusivemaximum?: number;\n exclusiveminimum?: number;\n kind: 'number';\n maximum?: number;\n minimum?: number;\n multipleof?: number;\n typehint?: 'integer';\n }\n | { kind: 'literal'; value: string | number | boolean | null | undefined }\n | { kind: 'enum'; values: readonly (string | number)[] }\n | { items: schemadescriptor; kind: 'array'; maxitems?: number; minitems?: number }\n | { items: schemadescriptor[]; kind: 'tuple'; rest: schemadescriptor | null }\n | { fields: record<string, schemadescriptor>; kind: 'object'; strict: boolean }\n | { key: schemadescriptor; kind: 'record'; value: schemadescriptor }\n | { items: schemadescriptor; kind: 'set' }\n | { key: schemadescriptor; kind: 'map'; value: schemadescriptor }\n | { branches: schemadescriptor[]; kind: 'union' | 'intersect' }\n | { branches: record<string, schemadescriptor>; discriminator: string; kind: 'variant' }\n | { from: schemadescriptor; kind: 'pipe'; to: schemadescriptor }\n );\n\ntype jsonschema = record<string, unknown>;\n```\n\n### error helpers\n\n```ts\ntype flaterror = { messages: string[]; path: (string | number)[] };\ntype flaterrorfirst = { message: string; path: (string | number)[] };\n\n/** an issue path in either shape: spell native segments or standard schema `{ key }` segments. */\ntype issuepathsegment = propertykey | { readonly key: propertykey };\ntype issuepath = readonly issuepathsegment[];\n\n/** the synchronous parse surface; `anyschema` omits `safeparse`, adapter parameters use this. */\ntype syncparsable<t = unknown> = { safeparse(value: unknown): parseresult<t> };\n\nfunction joinissuepath(path: issuepath | undefined, separator?: string): string;\n```\n\n`joinissuepath()` flattens an issue path into a ui key such as `'permissions.0.slug'`. it accepts spell native `(string | number)[]` paths and standard schema paths with `{ key }` segments, and returns `''` for empty or undefined paths.\n\n## errors\n\n `spellerror`: base class. use `instanceof spellerror` for cross boundary narrowing.\n `spellvalidationerror`: validation failure with `issues`, `messagesat()`, `flatten()`, and `flattenfirst()`.\n `spelldefinitionerror`: schema cannot create portable definition.\n\n```ts\nconst result = s.object({ email: s.string().email() }).safeparse({ email: 'invalid' });\n\nif (!result.success) {\n const { fielderrors, formerrors } = result.error.flatten();\n console.log(fielderrors, formerrors);\n}\n```\n",
1385
- "usage": " \ntitle: 'spell: usage guide'\ndescription: learn how to build schemas, compose wrappers, customize locales, and integrate spell with other vielzeug packages.\n \n\n[[toc]]\n\n## basic usage\n\nstart with `safeparse()` when you want explicit success and failure branches.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst signup = s.object({\n email: s.string().email(),\n password: s.string().min(12),\n referralcode: s.string().optional(),\n});\n\nconst result = signup.safeparse({\n email: 'ada@example.com',\n password: 'horse battery staple',\n});\n\nif (!result.success) {\n console.error(result.error.issues);\n} else {\n console.log(result.data.email);\n}\n```\n\nuse `parse()` when invalid input should throw immediately. use `safeparse()` when invalid input is part of normal control flow.\n\n## building schemas\n\nuse the namespace form when readability matters more than bundle trimming.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst article = s.object({\n id: s.string().uuid(),\n title: s.string().trim().min(1).max(120),\n slug: s.string().slug(),\n tags: s.array(s.string().min(1)).default(() => []),\n meta: s\n .object({\n published: s.boolean(),\n publishedat: s.date().nullable(),\n })\n .relaxed(),\n});\n```\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst todo = s.object({\n done: s.boolean(),\n tags: s.array(s.string().min(1)).default(() => []),\n title: s.string().min(1),\n});\n```\n\nobject schemas reject unknown keys by default. call `.relaxed()` when you need to preserve extra properties.\n\ncall `.defaults()` to get a fully default filled object without providing any input. every required field must have a `.default()` set, or a `spellvalidationerror` is thrown. call `.partialdefaults()` when only some fields have defaults: fields without a default are silently omitted instead of throwing.\n\n```ts\nconst config = s.object({\n host: s.string().default('localhost'),\n port: s.number().default(3000),\n});\n\nconfig.defaults(); // { host: 'localhost', port: 3000 }\n\nconst form = s.object({ name: s.string(), role: s.string().default('viewer') });\nform.partialdefaults(); // { role: 'viewer' }\n```\n\n## wrapper modes, defaults, and fallbacks\n\nchain wrappers to describe missing values and recovery rules without losing schema metadata.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst displayname = s.string().trim().min(2).label('display name').optional().default('guest').nullable();\n\ndisplayname.parse(undefined); // 'guest'\ndisplayname.parse(null); // null\ndisplayname.description; // 'display name'\n```\n\ncall `.required()` to remove `undefined` without removing `null`.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst nullablebutrequired = s.string().optional().nullable().required();\n\nnullablebutrequired.parse('ada');\nnullablebutrequired.parse(null);\n// nullablebutrequired.parse(undefined); // throws\n```\n\nuse `.catch()` when you want a fallback output after validation fails.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst port = s.number().int().min(1).max(65535).catch(3000);\n\nport.parse('not a number'); // 3000\n```\n\n## tolerating removed fields\n\nwhen a persisted record shape evolves, records saved by older versions carry keys the current schema no longer declares. `tolerate` accepts and drops exactly the named keys, so one call documents one removed field: no optional placeholder in the schema and no strip step after parsing.\n\n```ts\nimport { s, tolerate } from '@vielzeug/spell';\n\nconst person = tolerate(s.object({ name: s.string(), email: s.number() }), 'address');\n\nconst parsed = person.parse({\n name: 'john doe',\n address: 'p sherman 42 wallaby way sydney',\n email: 'johndoe@mail.com',\n});\n// { name: 'john doe', email: 'johndoe@mail.com' }: the tolerated key never reaches the output\n```\n\nfields added to later schema versions do not need `tolerate`: give them `default()` and older records repair on parse.\n\n## custom validation\n\nuse `check()` for synchronous domain rules and `checkasync()` for asynchronous rules. sync parsing rejects schemas with asynchronous checks.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\n// boolean shorthand: return false to fail with default message\nconst evennumber = s.number().check((n) => n % 2 === 0);\n\n// string shorthand: return the message as a string\nconst username = s\n .string()\n .min(3)\n .check((v) => !v.startswith('_') || 'cannot start with underscore');\n\n// multiple issues via ctx.addissue()\nconst signup = s.object({ confirm: s.string(), password: s.string() }).check((v, ctx) => {\n if (v.password !== v.confirm) {\n ctx.addissue({ code: 'custom', message: 'passwords must match', path: ['confirm'] });\n }\n});\n```\n\n`checkasync()` marks a schema as asynchronous: synchronous parsing throws at runtime instead of accepting an unchecked value, so async checks require `parseasync()` or `safeparseasync()`. async checks compose at any nesting depth: arrays, objects, unions, intersections, tuples, maps, records, sets, lazy schemas, pipelines, and `s.discriminatedunion(...)` branches all evaluate nested async checks correctly through `parseasync()`.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst takenemails = new set(['ada@example.com']);\n\nconst accountemail = s\n .string()\n .email()\n .checkasync(async (value, ctx) => {\n if (takenemails.has(value)) {\n ctx.addissue({ code: 'custom', message: 'email is already taken', path: [] });\n }\n });\n\n// async checks require parseasync\nawait accountemail.parseasync('grace@example.com');\n```\n\nuse `check()` for predicate only rules too. return `true` on success or message on failure.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst positiveprice = s.number().check((value) => value > 0 || 'must be positive');\npositiveprice.parse(9.99);\n```\n\n## strings, numbers, and safe regex usage\n\nuse schema helpers for common string and number constraints instead of hand written predicates.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst password = s.string().min(12).regex(/[a z]/).regex(/[0 9]/);\nconst price = s.number().nonnegative().multipleof(0.01);\nconst launchwindow = s.date().min(new date('2025 01 01t00:00:00.000z'));\n```\n\nspell strips stateful `/g` and `/y` flags from `regex()` patterns before validation. repeated parses stay deterministic even when the original regular expression is reused.\n\n## coercion and transforms\n\nuse coercion when input arrives as strings, query parameters, or form values.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst query = s.object({\n draft: s.coerce.boolean().default(false),\n limit: s.coerce.number().int().positive().default(20),\n publishedat: s.coerce.date().nullable(),\n search: s.coerce.string().trim().min(1).optional(),\n});\n\nconst parsed = query.parse({\n draft: 'true',\n limit: '50',\n publishedat: '2025 04 01t12:00:00.000z',\n search: ' vielzeug ',\n});\n```\n\nuse `transform()` or `pipe()` after validation when downstream code needs a different output shape.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst trimmedtags = s.array(s.string().trim().min(1)).transform((tags) => tags.map((tag) => tag.tolowercase()));\nconst slug = s.string().trim().min(1).pipe(s.string().slug());\n```\n\n## introspection, round trips, and json schema\n\nuse declarative definitions when schemas need to cross process boundaries or feed tooling.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { fromdefinition } from '@vielzeug/spell/json';\n\nconst product = s\n .object({\n id: s.string().uuid(),\n name: s.string().min(1),\n price: s.number().positive().multipleof(0.01),\n })\n .label('product');\n\nconst definition = product.definition();\nconst jsonschema = fromdefinition(definition);\n\nproduct.parse({ id: '550e8400 e29b 41d4 a716 446655440000', name: 'keyboard', price: 129.99 });\nconsole.log(jsonschema.title);\n```\n\ndefinitions are frozen serializable snapshots of declarative schema structure. use `definition()` and `fromdefinition()` for external tooling. schemas with runtime checks, transforms, defaults, catches, or preprocessors intentionally have no definition.\n\n## messages\n\nspell has no mutable process wide configuration. build one parse context per request, locale, or form, then pass it explicitly.\n\n```ts\nimport { createparsecontext, s } from '@vielzeug/spell';\n\nconst user = s.object({ email: s.string().email() });\nconst german = createparsecontext({\n object: { invalidkeys: () => 'keine unbekannten felder erlaubt' },\n});\n\nuser.safeparse({ email: 'ada@example.com', extra: true }, german);\n```\n\ninternal development warnings always use `console.warn` in development builds. route application diagnostics in application code instead of mutating library wide logger state.\n\n## working with validation errors\n\nuse `spellvalidationerror` helpers when you need ui ready error structures.\n\n```ts\nimport { s, spellvalidationerror } from '@vielzeug/spell';\n\nconst user = s.object({\n email: s.string().email(),\n profile: s.object({\n name: s.string().min(2),\n }),\n});\n\nconst result = user.safeparse({ email: 'nope', profile: { name: '' } });\n\nif (!result.success && result.error instanceof spellvalidationerror) {\n const profileerrors = result.error.messagesat('profile', 'name');\n console.log(profileerrors);\n}\n```\n\nkey inline errors by dot path with `joinissuepath()`, which also unwraps standard schema `{ key }` segments:\n\n```ts\nimport { joinissuepath } from '@vielzeug/spell';\n\nfor (const issue of result.error.issues) {\n console.log(joinissuepath(issue.path), issue.message); // 'profile.name: ...'\n}\n```\n\nunion failures produce one stable `invalid_union` issue. use `s.discriminatedunion()` when a discriminator can identify the intended object branch and provide field specific errors.\n\n## validating synchronously in react\n\nadapters that validate inside a render or `validate` callback need the sync parse surface. `anyschema` does not expose `safeparse`; type the adapter parameter against `syncparsable` instead:\n\n```ts\nimport { type syncparsable } from '@vielzeug/spell';\n\nfunction spellvalidator(schema: syncparsable<unknown>) {\n return (values: unknown) => {\n const result = schema.safeparse(values);\n if (result.success) return undefined;\n\n return result.error.issues.map((issue) => ({\n message: issue.message,\n path: issue.path,\n }));\n };\n}\n\nspellvalidator(s.object({ email: s.string() })); // no shim or cast\n```\n\n## framework integration\n\nspell works anywhere you can call a function before state enters your app.\n\n::: code group\n\n```tsx [react]\nimport { s } from '@vielzeug/spell';\n\nconst searchparams = s\n .object({\n page: s.coerce.number().int().positive().default(1),\n q: s.string().trim().optional(),\n })\n .relaxed();\n\nexport function searchpage({ rawparams }: { rawparams: unknown }) {\n const params = searchparams.parse(rawparams);\n\n return (\n <div>\n {params.q ?? 'all results'}: page {params.page}\n </div>\n );\n}\n```\n\n```ts [vue]\nimport { computed, ref } from 'vue';\nimport { s } from '@vielzeug/spell';\n\nconst settings = s.object({\n locale: s.string().min(2),\n compact: s.coerce.boolean().default(false),\n});\n\nconst raw = ref<unknown>({ locale: 'en', compact: 'true' });\nconst settings = computed(() => settings.parse(raw.value));\n```\n\n:::\n\nuse `safeparse()` at event boundaries and `parse()` inside trusted data flows.\n\n## working with other vielzeug libraries\n\nuse spell as the validation layer and let other packages focus on transport, forms, or storage.\n\n```ts\nimport { createform } from '@vielzeug/forge';\nimport { schemavalidator } from '@vielzeug/forge/schema';\nimport { createcourier } from '@vielzeug/courier';\nimport { s } from '@vielzeug/spell';\n\nconst profile = s.object({\n displayname: s.string().min(2),\n newsletter: s.boolean(),\n});\n\nconst form = createform({\n initialvalues: {\n displayname: '',\n newsletter: false,\n },\n validate: schemavalidator(profile),\n});\n\nconst courier = createcourier({ baseurl: '/api' });\nconst profile = profile.parse(await courier.get('/profile'));\n```\n\nuse spell definitions with `@vielzeug/codex` or other tooling when you need generated docs or external schema consumers.\n\n## best practices\n\n keep schemas close to the boundary where unknown data enters your app.\n use `s` consistently for construction; use explicit `/json` and `/predicates` subpaths for tooling.\n use `.default(() => value)` for mutable defaults such as arrays, objects, `map`, and `set`.\n call `.required()` when you want to remove `undefined` but keep `null` semantics intact.\n use `check()` with a `ctx` argument when you need `ctx.addissue()`; return a message for simple predicate failures.\n use `checkasync()` and `parseasync()` for every asynchronous domain rule.\n build a parse context per request or test; never rely on mutable process wide configuration.\n use `definition()` with `fromdefinition()` from `@vielzeug/spell/json` for external tooling.\n",
1386
- "examples": " \ntitle: 'spell: examples'\ndescription: practical examples and recipes for spell.\n \n\n## examples\n\n [validating api payloads](./examples/api.md)\n [form safe parsing](./examples/forms.md)\n [async business rules](./examples/async.md)\n [schema introspection and round trips](./examples/introspection.md)\n [unions, intersections, and variants](./examples/unions.md)\n"
1383
+ "index": " \ntitle: 'spell: schema validation for typescript'\ndescription: zero dependency schema validation with explicit async checks, standard schema interoperability, and json schema export.\npackage: spell\ncategory: validation\nkeywords: [schema, validation, parsing, standard schema, json schema, locale, typescript, definitions]\nrelated: [forge, courier, vault]\nexports:\n [\n s,\n createparsecontext,\n joinissuepath,\n spellvalidationerror,\n spelldefinitionerror,\n schema,\n standardschemav1,\n errorcode,\n './json',\n './predicates',\n ]\nenvironments: [browser, node, ssr, deno]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"spell\" />\n\n## why spell?\n\nspell keeps runtime validation, static inference, and portable definitions in one api. checks and transforms run in the order you chain them, and every built in constraint appears in the exported definition.\n\nthis example shows the difference between manual branching and a single reusable schema.\n\n```ts\n// before\nfunction parseuserbefore(value: unknown) {\n if (typeof value !== 'object' || value === null) throw new error('expected object');\n\n const candidate = value as record<string, unknown>;\n\n if (typeof candidate.email !== 'string' || !candidate.email.includes('@')) {\n throw new error('expected valid email');\n }\n\n if (typeof candidate.role !== 'string' || !['admin', 'editor', 'viewer'].includes(candidate.role)) {\n throw new error('expected valid role');\n }\n\n return {\n email: candidate.email,\n role: candidate.role,\n };\n}\n\n// after\nimport { s } from '@vielzeug/spell';\n\nconst user = s.object({\n email: s.string().email(),\n role: s.enum(['admin', 'editor', 'viewer'] as const),\n});\n\nconst user = user.parse({ email: 'ada@example.com', role: 'admin' });\n```\n\n| feature | spell | zod | yup |\n| | | | |\n| bundle size | <packageinfo package=\"spell\" type=\"size\" /> | ~62 kb | ~14 kb |\n| type inference | <ore icon name=\"check\" size=\"16\"></ore icon> `infer<t>` | <ore icon name=\"check\" size=\"16\"></ore icon> | partial |\n| coercion api | <ore icon name=\"check\" size=\"16\"></ore icon> `s.coerce.*` | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| async validation | <ore icon name=\"check\" size=\"16\"></ore icon> `.checkasync()` | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| error flattening | <ore icon name=\"check\" size=\"16\"></ore icon> `flatten()` + `flattenfirst()` | <ore icon name=\"check\" size=\"16\"></ore icon> | partial |\n| zero dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use spell when** you want a fluent schema api with strong typescript inference, structured errors, and no third party runtime dependencies.\n\n**consider alternatives when** you are already standardized on another validator ecosystem and migration cost outweighs the api benefits.\n\n</div>\n\n## installation\n\nuse your workspace package manager to add spell.\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/spell\n```\n\n```sh [npm]\nnpm install @vielzeug/spell\n```\n\n```sh [yarn]\nyarn add @vielzeug/spell\n```\n\n:::\n\n## quick start\n\nstart with a schema, then parse unknown input and use the inferred output type everywhere else.\n\n```ts\nimport { s, type infer } from '@vielzeug/spell';\n\nconst user = s\n .object({\n email: s.string().email(),\n name: s.string().min(1),\n role: s.enum(['admin', 'editor', 'viewer'] as const),\n })\n .relaxed(); // allow extra keys: omit for strict mode (default)\n\ntype user = infer<typeof user>;\n\nconst payload: unknown = {\n email: 'ada@example.com',\n name: 'ada',\n role: 'admin',\n team: 'platform',\n};\n\nconst result = user.safeparse(payload);\n\nif (!result.success) throw result.error;\nconst user = result.data;\n```\n\n## features\n\n<div class=\"features grid\">\n\n `s` builders for primitives, collections, objects, unions, and recursive schemas.\n `parse()`, `safeparse()`, `parseasync()`, and `safeparseasync()`; parsing stays synchronous unless a check is async.\n `check()` and `checkasync()` run in chain order with transforms; sync parsing never skips an async check.\n `optional`, `nullable`, `nullish`, `default`, `catch`, and `required` modifiers; defaults are copied per parse.\n `extend()`, `pick()`, `omit()`, `partial()`, and `tolerate()` for object composition and schema evolution.\n `definition()` returns frozen data; `tojsonschema()` from `@vielzeug/spell/json` converts it to json schema.\n `schema['~standard']` implements standard schema v1 without an adapter.\n `createparsecontext()` customizes messages per request, locale, or form.\n `spellvalidationerror` offers `flatten()`, `flattenfirst()`, and `messagesat()` for ui errors.\n object and record parsing is hardened against prototype pollution keys.\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [forge](/forge/): typed form state that uses spell schemas as its validation layer\n [courier](/courier/): http client for validating request and response payloads at service boundaries\n [vault](/vault/): unified storage api that accepts spell schemas to type gate persisted data\n\n</div>\n\n<! markdownlint enable md025 md033 md060 >\n",
1384
+ "api": " \ntitle: 'spell: api reference'\ndescription: reference for spell schema builders, schema methods, parsing, errors, parse contexts, definitions, and json schema export.\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `s` | creates schemas | sync, or async when checks are async | `checkasync()` anywhere in the tree requires `parseasync()` |\n| `schema` | base class of every schema | sync or async | modifiers return copies; schemas are never mutated |\n| `createparsecontext()` | creates request local messages | sync | pass the context to each parse call |\n| `joinissuepath()` | flattens issue paths to ui keys | sync | empty or undefined paths join to `''` |\n| `spellvalidationerror` | carries validation issues | sync/async parse failures | use `safeparse()` for expected invalid data |\n| `spelldefinitionerror` | rejects non portable or invalid definitions | sync | thrown by `definition()` and object derivations, not by parsing |\n| `errorcode` | issue code constants | n/a | narrow `issue` on `code` to read typed `params` |\n| `tojsonschema()` | converts a definition to json schema | sync | imported from `@vielzeug/spell/json` |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/spell` | schema builders, base class, errors, types, and context |\n| `@vielzeug/spell/json` | `tojsonschema()` and the `jsonschema` type |\n| `@vielzeug/spell/predicates` | standalone string format predicates |\n\n```ts\nimport { createparsecontext, s, type infer } from '@vielzeug/spell';\nimport { tojsonschema } from '@vielzeug/spell/json';\nimport { isemail } from '@vielzeug/spell/predicates';\n```\n\n## builders\n\nall builders live under `s`.\n\n| builder | returns | notes |\n| | | |\n| `s.string()` | `stringschema` | |\n| `s.number()` | `numberschema` | rejects `nan` |\n| `s.bigint()` | `bigintschema` | |\n| `s.boolean()` | `booleanschema` | |\n| `s.date()` | `dateschema` | rejects invalid dates with `invalid_date` |\n| `s.literal(value)` | `literalschema<t>` | `string`, `number`, `boolean`, `null`, or `undefined` |\n| `s.enum(values)` | `enumschema<t>` | non empty tuple of strings or numbers |\n| `s.null()`, `s.undefined()` | `literalschema<null \\| undefined>` | |\n| `s.unknown()` | `schema<unknown>` | accepts any value |\n| `s.never()` | `neverschema` | rejects every value |\n| `s.instanceof(cls)` | `instanceofschema<t>` | accepts abstract constructors |\n| `s.array(item)` | `arrayschema<t>` | |\n| `s.tuple(items)` | `tupleschema<t>` | exact length unless `.rest()` is used |\n| `s.set(item)` | `setschema<t>` | |\n| `s.map(key, value)` | `mapschema<k, v>` | |\n| `s.record(key, value)` | `recordschema<k, v>` | drops unsafe keys (`__proto__`, `constructor`, …) |\n| `s.object(shape)` | `objectschema<t>` | strict by default |\n| `s.union(...schemas)` | `unionschema<t>` | at least two schemas; first match wins |\n| `s.intersect(...schemas)` | `intersectschema<t>` | at least two schemas; object outputs are deep merged |\n| `s.discriminatedunion(key, branches)` | `discriminatedunionschema<k, m>` | branches are object schemas keyed by tag |\n| `s.lazy(getter)` | `lazyschema<output, input>` | recursive schemas |\n| `s.coerce.string/number/boolean/bigint/date()` | primitive schema with `unknown` input | coercion runs before the type check |\n\n### `s.coerce`\n\n| builder | converts |\n| | |\n| `s.coerce.string()` | any non nullish value with `string()` |\n| `s.coerce.number()` | numeric strings and booleans with `number()` |\n| `s.coerce.boolean()` | `'true'`/`'1'`/`1` and `'false'`/`'0'`/`0` |\n| `s.coerce.bigint()` | safe integer numbers and integer strings up to 1000 chars |\n| `s.coerce.date()` | strings and epoch milliseconds with `new date()` |\n\nvalues the coercer cannot convert reach the type check unchanged and fail with `invalid_type`.\n\n## schema methods\n\nevery schema extends `schema<output, input>`.\n\n### parsing\n\n```ts\nparse(value: unknown, context?: parsecontext): output;\nsafeparse(value: unknown, context?: parsecontext): parseresult<output>;\nparseasync(value: unknown, context?: parsecontext): promise<output>;\nsafeparseasync(value: unknown, context?: parsecontext): promise<parseresult<output>>;\nis(value: unknown): value is output;\nassert(value: unknown, label?: string): asserts value is output;\n```\n\n**returns:** `parse()` returns the parsed output or throws `spellvalidationerror`. `safeparse()` returns a `parseresult`.\n\n`parse()`, `safeparse()`, `is()`, and `assert()` are synchronous. if the schema or any nested schema has a `checkasync()` step, they throw `spellerror` (\"schema contains async checks; use parseasync() or safeparseasync().\") before running the async check. this is a usage error, not a validation issue, so `catch()` does not intercept it. `assert(value, label)` prefixes root level messages with `label`.\n\n**example:**\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst result = s.string().email().safeparse('ada@example.com');\n\nif (result.success) console.log(result.data);\n```\n\n### checks\n\n```ts\ncheck(fn: (value: output, ctx: checkcontext) => validateresult): this;\ncheckasync(fn: (value: output, ctx: checkcontext) => promise<validateresult>): this;\n```\n\n**returns:** a copy of the schema with the rule appended.\n\na check runs only when the structural type check passed. it returns `true`, `null`, or `undefined` to pass, a string to fail with that message, or `false` to fail with the default message. `ctx.addissue({ code, message, params?, path? })` reports issues at paths relative to the schema. passing an async function to `check()` is a type error.\n\n**example:**\n\n```ts\nconst signup = s.object({ confirm: s.string(), password: s.string() }).check((value, ctx) => {\n if (value.password !== value.confirm)\n ctx.addissue({ code: 'custom', message: 'passwords must match', path: ['confirm'] });\n});\n```\n\n### modifiers\n\n| method | returns | effect |\n| | | |\n| `optional()` | `schema<output \\| undefined, input \\| undefined>` | accepts `undefined` |\n| `nullable()` | `schema<output \\| null, input \\| null>` | accepts `null` |\n| `nullish()` | `schema<output \\| null \\| undefined, …>` | accepts `null` and `undefined` |\n| `required()` | `schema<exclude<output, undefined>, …>` | rejects `undefined` again; clears `optional()` and `default()` |\n| `default(value)` | `this` | returns a fresh copy of `value` for `undefined`; a function is a factory |\n| `catch(fallback)` | `this` | returns a fresh copy of `fallback` when validation fails |\n| `transform(fn)` | `schema<next, input>` | maps the value in chain order; skipped once an earlier step failed |\n| `preprocess(fn)` | `this` | maps raw input before the type check |\n| `pipe(next)` | `pipeschema<this, next>` | parses with this schema, then feeds the output to `next` |\n| `describe(text)` | `this` | sets `description`, which `definition()` includes |\n\n`optional()`, `nullable()`, `nullish()`, `required()`, and `transform()` change the value type, so they return a base `schema`. chain type specific methods such as `.min()` or `.extend()` before them.\n\n### properties and definitions\n\n| member | type | description |\n| | | |\n| `kind` | `schemakind` | schema kind, e.g. `'string'` or `'object'` |\n| `description` | `string \\| undefined` | text set with `describe()` |\n| `isoptional` | `boolean` | `true` with `optional()`, `nullish()`, `default()`, or `catch()` |\n| `isnullable` | `boolean` | `true` with `nullable()` or `nullish()` |\n| `'~standard'` | `standardschemav1.props<input, output>` | standard schema v1 protocol |\n| `definition()` | `schemadescriptor` | frozen declarative descriptor |\n\n`definition()` throws `spelldefinitionerror` when the schema, or a nested schema, has runtime only behavior: `check()`, `checkasync()`, `transform()`, `preprocess()` (including `s.coerce.*`, `trim()`, `lowercase()`, `uppercase()`), `default()`, `catch()`, or `array().unique({ by })`.\n\n### standard schema\n\n`schema['~standard'].validate(value)` returns a result synchronously unless the schema has async checks, in which case it returns a promise. successful results contain `value`; failures contain `{ message, path }` issues. a failed union stays one union issue.\n\n```ts\nconst user = s.object({ name: s.string() });\nconst result = await user['~standard'].validate({ name: 'ada' });\n```\n\n## string schema\n\n```ts\nmin(length: number, message?): this;\nmax(length: number, message?): this;\nlength(exact: number, message?): this;\nnonempty(message?): this;\nstartswith(prefix: string, message?): this;\nendswith(suffix: string, message?): this;\nincludes(substr: string, message?): this;\nregex(pattern: regexp, message?): this;\nurl(options?: { message?: messagefn<{ value: string }>; protocols?: readonly string[] }): this;\nnanoid(length?: number, message?): this;\ntrim(): this;\nlowercase(): this;\nuppercase(): this;\n```\n\nformat methods take an optional `message`: `email`, `url`, `uuid`, `isodate`, `isodatetime`, `time`, `duration`, `ip`, `cuid`, `cuid2`, `ulid`, `nanoid`, `base64`, `base64url`, `hex`, `hexcolor`, `emoji`, `jwt`, `semver`, `slug`, `numeric`.\n\nformat and pattern failures use code `invalid_format` with `params.format` set to the method name, such as `'email'`, `'isodate'`, `'startswith'`, or `'regex'`. `url()` accepts `http` and `https` unless `protocols` is given. `regex()` drops the stateful `g` and `y` flags. `trim()`, `lowercase()`, and `uppercase()` are ordered transforms: constraints chained after them see the normalized value.\n\n## number, bigint, and date schemas\n\n| schema | methods |\n| | |\n| `numberschema` | `min`, `max`, `positive`, `negative`, `nonnegative`, `nonpositive`, `int`, `safe`, `finite`, `multipleof` |\n| `bigintschema` | `min`, `max`, `positive`, `negative`, `nonnegative`, `nonpositive`, `multipleof` |\n| `dateschema` | `min(date)`, `max(date)` |\n\neach method takes an optional trailing `message`. `safe()` requires an integer within `number.min_safe_integer`…`number.max_safe_integer`.\n\n## collection schemas\n\n| schema | methods and members |\n| | |\n| `arrayschema` | `min`, `max`, `length`, `nonempty`, `unique(options?)` |\n| `tupleschema` | `items`, `rest(schema)` |\n| `setschema` | `min`, `max`, `size`, `nonempty` |\n| `mapschema` | `min`, `max`, `size`, `nonempty` |\n| `recordschema` | (none) |\n\n```ts\nunique(options?: { by?: (item: inferoutput<t>) => unknown; message?: messagefn<{ value: unknown[] }> }): this;\n```\n\n`unique()` compares items with `set` semantics, or compares the keys returned by `by`. a `by` selector makes `definition()` throw.\n\n## object schema\n\n```ts\nreadonly shape: t;\nrelaxed(): this;\nstrict(): this;\ntolerate(...keys: string[]): this;\nextend<u extends objectshape>(extra: u): objectschema<omit<t, keyof u> & u>;\npick<k extends keyof t & string>(...keys: k[]): objectschema<pick<t, k>>;\nomit<k extends keyof t & string>(...keys: k[]): objectschema<omit<t, k>>;\npartial(): objectschema<{ [k in keyof t]: optional<t[k]> }>;\npartial<k extends keyof t & string>(...keys: k[]): objectschema<omit<t, k> & { [p in k]: optional<t[p]> }>;\nkeyof(): enumschema<[keyof t & string, ...(keyof t & string)[]]>;\n```\n\n| method | description |\n| | |\n| `strict()` | rejects unknown keys with one `invalid_keys` issue (default) |\n| `relaxed()` | copies unknown keys to the output, skipping unsafe keys |\n| `tolerate()` | accepts and drops the named keys; other unknown keys follow the current mode |\n| `extend()` | adds fields; same named fields are replaced |\n| `pick()` | keeps the named fields |\n| `omit()` | removes the named fields |\n| `partial()` | makes all or the named fields optional |\n| `keyof()` | enum schema of the shape keys |\n\n`extend()`, `pick()`, `omit()`, and `partial()` keep the unknown key mode, tolerated keys, description, and `optional`/`nullable` flags. they throw `spelldefinitionerror` when the object has checks, transforms, preprocessors, a default, or a catch, because those were written for the old shape.\n\nabsent keys whose field returns `undefined` are left out of the output. field defaults are written for absent keys.\n\n## composition schemas\n\n| schema | members | failure |\n| | | |\n| `unionschema` | `schemas` | one `invalid_union` issue; `params.errors` holds each branch's issues |\n| `intersectschema` | `schemas` | issues from every failing branch |\n| `discriminatedunionschema` | `discriminator`, `branches` (`readonlymap`) | `invalid_discriminator` for an unknown tag; branch issues otherwise |\n| `lazyschema` | (none) | issues of the resolved schema |\n| `pipeschema` | `from`, `to` | issues of the first failing stage |\n\n`s.discriminatedunion(key, branches)` adds `key` as a literal of the branch tag when a branch omits it. it throws `spelldefinitionerror` when a branch is not an object schema or declares `key` with a different schema.\n\nintersections of object schemas need `.relaxed()` branches, because each strict branch rejects the other branch's keys.\n\n## parse contexts\n\n```ts\nfunction createparsecontext(messages?: deeppartial<messages>): parsecontext;\n```\n\n**returns:** a frozen parse context with the built in messages merged with the supplied overrides. unsafe override keys such as `__proto__` are ignored with a development warning.\n\n**example:**\n\n```ts\nimport { createparsecontext, s } from '@vielzeug/spell';\n\nconst context = createparsecontext({ object: { invalidkeys: () => 'unsupported field' } });\nconst result = s.object({ email: s.string().email() }).safeparse({ email: 'ada@example.com', extra: true }, context);\n\nif (!result.success) console.log(result.error.issues[0].message); // 'unsupported field'\n```\n\n## json schema\n\n```ts\nimport { tojsonschema, type jsonschema } from '@vielzeug/spell/json';\n\nfunction tojsonschema(definition: schemadescriptor): jsonschema;\n```\n\n**returns:** a json schema 2020 12 object.\n\n| definition | json schema |\n| | |\n| `isodate`, `isodatetime`, `url` | `format: 'date'`, `'date time'`, `'uri'` |\n| `base64`, `base64url` | `contentencoding` |\n| `ip` | `anyof` of `ipv4` and `ipv6` formats |\n| several formats or patterns | `allof` |\n| `bigint` bounds | numeric bounds (may lose precision above `number.max_safe_integer`) |\n| `date`, `instanceof` | `$comment` only |\n| `set`, `map` | array with `uniqueitems`, object with `additionalproperties` |\n| `isnullable` | `anyof` with `{ type: 'null' }` |\n\n**example:**\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { tojsonschema } from '@vielzeug/spell/json';\n\nconst jsonschema = tojsonschema(s.object({ id: s.string().uuid() }).definition());\n```\n\n## predicates\n\n`@vielzeug/spell/predicates` exports the format tests used by `stringschema`. each takes a string and returns `boolean`.\n\n`isbase64`, `isbase64url`, `iscuid`, `iscuid2`, `isduration`, `isemail`, `isemoji`, `ishex`, `ishexcolor`, `isip`, `isisodate`, `isisodatetime`, `isjwt`, `isnanoid(value, length = 21)`, `isnumeric`, `issemver`, `isslug`, `istime`, `isulid`, `isurl(value, protocols = ['http', 'https'])`, `isuuid`.\n\n## types\n\n### inference types\n\n| type | resolves to |\n| | |\n| `infer<tschema>` | parsed output; alias of `inferoutput<tschema>` |\n| `inferinput<tschema>` | input accepted before parsing or transformation |\n| `inferoutput<tschema>` | value returned after parsing and transformation |\n| `anyschema` | `schema<unknown, unknown>`; any schema |\n\nobject input types make a field optional when its schema accepts a missing value (`optional()`, `nullish()`, `default()`, `catch()`). use `anyschema` as a generic constraint, and `schema<t, unknown>` for a parameter that must parse to `t`.\n\n### parse result and issues\n\n```ts\ntype parseresult<t> = { data: t; success: true } | { error: spellvalidationerror; success: false };\n\ntype issue =\n | { code: 'custom'; message: string; params?: record<string, unknown>; path: (string | number)[] }\n | { code: 'invalid_date'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'invalid_discriminator';\n message: string;\n params: { discriminator: string; expected: string[] };\n path: (string | number)[];\n }\n | { code: 'invalid_enum'; message: string; params: { values: readonly unknown[] }; path: (string | number)[] }\n | { code: 'invalid_finite'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'invalid_format';\n message: string;\n params: { format: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };\n path: (string | number)[];\n }\n | { code: 'invalid_integer'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_keys'; message: string; params: { keys: string[] }; path: (string | number)[] }\n | { code: 'invalid_length'; message: string; params: { exact: number }; path: (string | number)[] }\n | { code: 'invalid_literal'; message: string; params: { expected: unknown }; path: (string | number)[] }\n | { code: 'invalid_multiple_of'; message: string; params: { step: number | bigint }; path: (string | number)[] }\n | { code: 'invalid_safe'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_type'; message: string; params?: undefined; path: (string | number)[] }\n | { code: 'invalid_union'; message: string; params: { errors: issue[][] }; path: (string | number)[] }\n | { code: 'invalid_unique'; message: string; params?: undefined; path: (string | number)[] }\n | {\n code: 'too_big';\n message: string;\n params: { exclusive?: boolean; max: number | bigint | date };\n path: (string | number)[];\n }\n | {\n code: 'too_small';\n message: string;\n params: { exclusive?: boolean; min: number | bigint | date };\n path: (string | number)[];\n }\n | { code: string & {}; message: string; params?: record<string, unknown>; path: (string | number)[] };\n```\n\n`errorcode` is a const object mapping each built in code to its string literal.\n\n### validation contracts\n\n```ts\ntype parsecontext = { readonly messages: messages };\n\ntype checkcontext = {\n addissue: (issue: {\n code: string;\n message: string;\n params?: record<string, unknown>;\n path?: (string | number)[];\n }) => void;\n};\n\ntype validateresult = boolean | null | undefined | string;\n\ntype messagefn<ctx extends record<string, unknown> = record<string, unknown>> = string | ((ctx: ctx) => string);\n\ntype deeppartial<t> = { [k in keyof t]?: t[k] extends record<string, unknown> ? deeppartial<t[k]> : t[k] };\n```\n\n### messages\n\n`messages` has one group per schema type. each entry is a function of the constraint context.\n\n```ts\ntype messages = {\n array: { length; max; min; nonempty; type; unique };\n bigint: { max; min; multipleof; negative; nonnegative; nonpositive; positive; type };\n boolean: { type };\n check: { default };\n date: { max; min; type };\n discriminatedunion: { invaliddiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type };\n enum: { invalid: (ctx: { values: readonly unknown[] }) => string };\n instanceof: { type: (ctx: { classname: string }) => string };\n literal: { expected: (ctx: { expected: unknown }) => string };\n map: { max; min; nonempty; size; type };\n never: { invalid };\n number: { finite; int; max; min; multipleof; negative; nonnegative; nonpositive; positive; safe; type };\n object: { invalidkeys: (ctx: { keys: string[] }) => string; type };\n set: { max; min; nonempty; size; type };\n string: {\n base64;\n base64url;\n cuid;\n cuid2;\n duration;\n email;\n emoji;\n endswith;\n hex;\n hexcolor;\n includes;\n ip;\n isodate;\n isodatetime;\n jwt;\n length;\n max;\n min;\n nanoid;\n nonempty;\n numeric;\n regex;\n semver;\n slug;\n startswith;\n time;\n type;\n ulid;\n url;\n uuid;\n };\n tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type };\n union: { invalid };\n};\n```\n\nconstraint messages receive `value` plus the constraint's parameters, e.g. `string.min` receives `{ min, value }` and `string.includes` receives `{ substr, value }`.\n\n### descriptors\n\n```ts\ntype patterndescriptor = { readonly flags: string; readonly source: string };\n\ntype schemadescriptor = { description?: string; isnullable?: true; isoptional?: true } & (\n | { kind: 'unknown' | 'never' | 'boolean' | 'lazy' }\n | {\n kind: 'bigint';\n exclusivemaximum?: bigint;\n exclusiveminimum?: bigint;\n maximum?: bigint;\n minimum?: bigint;\n multipleof?: bigint;\n }\n | {\n kind: 'number';\n exclusivemaximum?: number;\n exclusiveminimum?: number;\n finite?: true;\n integer?: true;\n maximum?: number;\n minimum?: number;\n multipleof?: number;\n }\n | {\n kind: 'string';\n formats?: readonly string[];\n maxlength?: number;\n minlength?: number;\n patterns?: readonly patterndescriptor[];\n }\n | { kind: 'date'; maximum?: string; minimum?: string }\n | { classname: string; kind: 'instanceof' }\n | { kind: 'literal'; value: string | number | boolean | null | undefined }\n | { kind: 'enum'; values: readonly (string | number)[] }\n | { items: schemadescriptor; kind: 'array'; maxitems?: number; minitems?: number; uniqueitems?: true }\n | { items: readonly schemadescriptor[]; kind: 'tuple'; rest: schemadescriptor | null }\n | {\n fields: readonly<record<string, schemadescriptor>>;\n kind: 'object';\n strict: boolean;\n tolerated?: readonly string[];\n }\n | { key: schemadescriptor; kind: 'record'; value: schemadescriptor }\n | { items: schemadescriptor; kind: 'set'; maxsize?: number; minsize?: number }\n | { key: schemadescriptor; kind: 'map'; maxsize?: number; minsize?: number; value: schemadescriptor }\n | { branches: readonly schemadescriptor[]; kind: 'union' | 'intersect' }\n | { branches: readonly<record<string, schemadescriptor>>; discriminator: string; kind: 'discriminatedunion' }\n | { from: schemadescriptor; kind: 'pipe'; to: schemadescriptor }\n);\n\ntype schemakind = schemadescriptor['kind'];\n\ntype jsonschema = record<string, unknown>; // from '@vielzeug/spell/json'\n```\n\ndate bounds are iso strings. `formats` lists format method names in chain order; `patterns` lists `regex()`, `startswith()`, `endswith()`, `includes()`, and `url()` protocol patterns.\n\n### standard schema\n\n```ts\ninterface standardschemav1<input = unknown, output = input> {\n readonly '~standard': standardschemav1.props<input, output>;\n}\n\nnamespace standardschemav1 {\n interface props<input = unknown, output = input> {\n readonly types?: types<input, output> | undefined;\n readonly validate: (value: unknown, options?: options | undefined) => result<output> | promise<result<output>>;\n readonly vendor: string;\n readonly version: 1;\n }\n type result<output> = { readonly issues: readonly issue[] } | { readonly issues?: undefined; readonly value: output };\n interface options {\n readonly libraryoptions?: record<string, unknown> | undefined;\n }\n interface issue {\n readonly message: string;\n readonly path?: readonly (propertykey | pathsegment)[] | undefined;\n }\n interface pathsegment {\n readonly key: propertykey;\n }\n interface types<input = unknown, output = input> {\n readonly input: input;\n readonly output: output;\n }\n type inferinput<schema extends standardschemav1> = nonnullable<schema['~standard']['types']>['input'];\n type inferoutput<schema extends standardschemav1> = nonnullable<schema['~standard']['types']>['output'];\n}\n```\n\n### error helpers\n\n```ts\ntype flaterror = { messages: string[]; path: (string | number)[] };\ntype flaterrorfirst = { message: string; path: (string | number)[] };\n\ntype issuepathsegment = propertykey | { readonly key: propertykey };\ntype issuepath = readonly issuepathsegment[];\n\nfunction joinissuepath(path: issuepath | undefined, separator?: string): string;\n```\n\n`joinissuepath()` flattens a spell or standard schema issue path into a ui key such as `'permissions.0.slug'`.\n\n## errors\n\n| class | thrown when | members |\n| | | |\n| `spellerror` | base class; thrown directly when synchronous parsing meets an async check | `name`, `message` |\n| `spellvalidationerror` | `parse()`, `parseasync()`, or `assert()` receives invalid input | `issues` (frozen), `flatten()`, `flattenfirst()`, `messagesat(...path)` |\n| `spelldefinitionerror` | `definition()` on a non portable schema; invalid object derivation or discriminated branch | `name`, `message` |\n\n`spellvalidationerror.message` lists one `path: message [code]` line per issue; root issues use `value` as the path.\n\n```ts\nconst result = s.object({ email: s.string().email() }).safeparse({ email: 'invalid' });\n\nif (!result.success) {\n const { fielderrors, formerrors } = result.error.flatten();\n console.log(fielderrors, formerrors);\n}\n```\n",
1385
+ "usage": " \ntitle: 'spell: usage guide'\ndescription: build schemas, order checks and transforms, compose objects, customize messages, and integrate spell with other vielzeug packages.\n \n\n[[toc]]\n\n## basic usage\n\nstart with `safeparse()` when you want explicit success and failure branches.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst signup = s.object({\n email: s.string().email(),\n password: s.string().min(12),\n referralcode: s.string().optional(),\n});\n\nconst result = signup.safeparse({\n email: 'ada@example.com',\n password: 'horse battery staple',\n});\n\nif (!result.success) {\n console.error(result.error.issues);\n} else {\n console.log(result.data.email);\n}\n```\n\nuse `parse()` when invalid input should throw. use `safeparse()` when invalid input is part of normal control flow.\n\n## building schemas\n\ncompose schemas from the `s` builders. every method returns a new schema, so you can share and extend base schemas safely.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst article = s.object({\n id: s.string().uuid(),\n meta: s.object({ published: s.boolean(), publishedat: s.date().nullable() }).relaxed(),\n slug: s.string().slug(),\n tags: s.array(s.string().min(1)).default([]),\n title: s.string().trim().min(1).max(120),\n});\n```\n\nobject schemas reject unknown keys by default. call `.relaxed()` to keep extra properties in the output.\n\nfields with a `default()` are filled in when their key is absent, so `parse({})` returns a fully default filled object.\n\n```ts\nconst config = s.object({\n host: s.string().default('localhost'),\n port: s.number().default(3000),\n});\n\nconfig.parse({}); // { host: 'localhost', port: 3000 }\n```\n\n`default()` and `catch()` return a fresh copy of object, array, `map`, `set`, and `date` values on every parse, so callers cannot mutate a shared default.\n\n## ordering checks and transforms\n\nchecks, built in constraints, and transforms run in the order you chain them. a constraint after a transform sees the transformed value.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\n// trim() runs first, so ' ' fails min(1)\nconst title = s.string().trim().min(1);\n\n// the check receives the length, not the string\nconst shortcode = s\n .string()\n .transform((value) => value.length)\n .check((length) => length <= 8 || 'at most 8 characters');\n```\n\ntransforms are skipped once an earlier step reported an issue, so a transform never receives a value that failed validation. use `preprocess()` to change raw input before the type check.\n\n## optional, nullable, and fallback values\n\nuse modifiers to describe missing values and recovery rules.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst displayname = s.string().trim().min(2).describe('display name').optional().default('guest').nullable();\n\ndisplayname.parse(undefined); // 'guest'\ndisplayname.parse(null); // null\ndisplayname.description; // 'display name'\n```\n\n`optional()`, `nullable()`, `nullish()`, `required()`, and `transform()` change the value type and return a base `schema`. chain type specific methods such as `.min()` or `.extend()` before them.\n\ncall `.required()` to make `undefined` invalid again. it clears `optional()` and `default()` and keeps `null` and checks.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst nullablebutrequired = s.string().optional().nullable().required();\n\nnullablebutrequired.parse('ada');\nnullablebutrequired.parse(null);\nnullablebutrequired.safeparse(undefined).success; // false\n```\n\nuse `.catch()` when you want a fallback output after validation fails.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst port = s.number().int().min(1).max(65535).catch(3000);\n\nport.parse('not a number'); // 3000\n```\n\n## composing object schemas\n\nderive new object schemas with `extend()`, `pick()`, `omit()`, and `partial()`. derive the shape first, then add checks, transforms, defaults, or catches to the final schema.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst user = s.object({ email: s.string().email(), id: s.string().uuid(), name: s.string() });\n\nconst admin = user.extend({ role: s.enum(['owner', 'editor']) });\nconst userpatch = user.omit('id').partial();\n\nconst signup = user.pick('email')\n .extend({ confirm: s.string(), password: s.string().min(12) })\n .check((value) => value.password === value.confirm || 'passwords must match');\n```\n\nderiving from an object with checks, transforms, preprocessors, a default, or a catch throws `spelldefinitionerror`. a check written for the old shape could read a field that `omit()` removed, so spell refuses instead of guessing.\n\n## tolerating removed fields\n\nrecords saved by older schema versions can carry keys the current schema no longer declares. `tolerate()` accepts and drops exactly the named keys, and other unknown keys still fail.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst person = s.object({ email: s.string(), name: s.string() }).tolerate('address');\n\nperson.parse({ address: '42 wallaby way', email: 'johndoe@mail.com', name: 'john doe' });\n// { email: 'johndoe@mail.com', name: 'john doe' }\n```\n\nfields added in later schema versions do not need `tolerate()`: give them a `default()` and older records are repaired on parse.\n\n## custom validation\n\nuse `check()` for synchronous domain rules and `checkasync()` for asynchronous rules.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\n// return false to fail with the default message\nconst evennumber = s.number().check((n) => n % 2 === 0);\n\n// return a string to fail with that message\nconst username = s\n .string()\n .min(3)\n .check((v) => !v.startswith('_') || 'cannot start with underscore');\n\n// report issues at specific paths with ctx.addissue()\nconst signup = s.object({ confirm: s.string(), password: s.string() }).check((v, ctx) => {\n if (v.password !== v.confirm) ctx.addissue({ code: 'custom', message: 'passwords must match', path: ['confirm'] });\n});\n```\n\na schema containing `checkasync()` at any depth needs `parseasync()` or `safeparseasync()`. the synchronous methods throw `spellerror` before running the async check, because accepting an unchecked value would be unsafe.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst takenemails = new set(['ada@example.com']);\n\nconst accountemail = s\n .string()\n .email()\n .checkasync(async (value) => !takenemails.has(value) || 'email is already taken');\n\nawait accountemail.parseasync('grace@example.com');\n```\n\n## strings, numbers, and regex safety\n\nuse the built in constraints instead of hand written predicates.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst password = s.string().min(12).regex(/[a z]/).regex(/[0 9]/);\nconst price = s.number().nonnegative().multipleof(0.01);\nconst launchwindow = s.date().min(new date('2025 01 01t00:00:00.000z'));\nconst website = s.string().url({ protocols: ['https'] });\n```\n\nformat failures use the `invalid_format` code with `params.format` set to the method name. `regex()` drops the stateful `g` and `y` flags, so repeated parses agree even when you reuse a global regular expression.\n\n## coercion and pipelines\n\nuse `s.coerce.*` when input arrives as strings, such as query parameters or form values.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst query = s.object({\n draft: s.coerce.boolean().default(false),\n limit: s.coerce.number().int().positive().default(20),\n publishedat: s.coerce.date().nullable(),\n search: s.coerce.string().trim().min(1).optional(),\n});\n\nquery.parse({ draft: 'true', limit: '50', publishedat: '2025 04 01t12:00:00.000z', search: ' vielzeug ' });\n```\n\nuse `transform()` or `pipe()` when downstream code needs a different output.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst lowercasetags = s.array(s.string().trim().min(1)).transform((tags) => tags.map((tag) => tag.tolowercase()));\nconst slug = s.string().trim().pipe(s.string().slug());\n```\n\n## definitions and json schema\n\nuse declarative definitions when schemas feed external tooling.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { tojsonschema } from '@vielzeug/spell/json';\n\nconst product = s\n .object({\n id: s.string().uuid(),\n name: s.string().min(1),\n price: s.number().positive().multipleof(0.01),\n })\n .describe('product');\n\nconst jsonschema = tojsonschema(product.definition());\nconsole.log(jsonschema.description); // 'product'\n```\n\ndefinitions are frozen, serializable data. schemas with checks, transforms, preprocessors (including `s.coerce.*` and `trim()`), defaults, or catches have no definition, and `definition()` throws `spelldefinitionerror`.\n\n## messages\n\nspell has no process wide configuration. build one parse context per request, locale, or form, and pass it explicitly.\n\n```ts\nimport { createparsecontext, s } from '@vielzeug/spell';\n\nconst user = s.object({ email: s.string().email() });\nconst german = createparsecontext({ object: { invalidkeys: () => 'keine unbekannten felder erlaubt' } });\n\nuser.safeparse({ email: 'ada@example.com', extra: true }, german);\n```\n\ndevelopment builds warn through `console.warn` when a message override uses an unsafe key such as `__proto__`.\n\n## working with validation errors\n\nuse `spellvalidationerror` helpers to build ui ready error structures.\n\n```ts\nimport { joinissuepath, s } from '@vielzeug/spell';\n\nconst user = s.object({ email: s.string().email(), profile: s.object({ name: s.string().min(2) }) });\nconst result = user.safeparse({ email: 'nope', profile: { name: '' } });\n\nif (!result.success) {\n console.log(result.error.messagesat('profile', 'name'));\n\n for (const issue of result.error.issues) console.log(joinissuepath(issue.path), issue.message);\n}\n```\n\nunion failures produce one `invalid_union` issue. use `s.discriminatedunion()` when a tag field identifies the intended branch, so errors point at that branch's fields.\n\n## typing schema parameters\n\ntype a function that accepts any schema with `anyschema`, or with `schema<t, unknown>` when it needs the parsed type.\n\n```ts\nimport { type anyschema, type parseresult, type schema, s } from '@vielzeug/spell';\n\nfunction isvalid(schema: anyschema, value: unknown): boolean {\n return schema.safeparse(value).success;\n}\n\nfunction parsewith<t>(schema: schema<t, unknown>, value: unknown): parseresult<t> {\n return schema.safeparse(value);\n}\n\nparsewith(s.object({ email: s.string() }), { email: 'ada@example.com' });\n```\n\n## framework integration\n\nspell works anywhere you can call a function before data enters your app.\n\n::: code group\n\n```tsx [react]\nimport { s } from '@vielzeug/spell';\n\nconst searchparams = s\n .object({\n page: s.coerce.number().int().positive().default(1),\n q: s.string().trim().optional(),\n })\n .relaxed();\n\nexport function searchpage({ rawparams }: { rawparams: unknown }) {\n const params = searchparams.parse(rawparams);\n\n return (\n <div>\n {params.q ?? 'all results'}: page {params.page}\n </div>\n );\n}\n```\n\n```ts [vue]\nimport { computed, ref } from 'vue';\nimport { s } from '@vielzeug/spell';\n\nconst settings = s.object({\n compact: s.coerce.boolean().default(false),\n locale: s.string().min(2),\n});\n\nconst raw = ref<unknown>({ compact: 'true', locale: 'en' });\nconst settings = computed(() => settings.parse(raw.value));\n```\n\n```svelte [svelte]\n<script lang=\"ts\">\n import { s } from '@vielzeug/spell';\n\n const email = s.string().email();\n let value = '';\n $: error = email.safeparse(value).success ? '' : 'enter a valid email';\n</script>\n\n<input bind:value />\n{#if error}<p>{error}</p>{/if}\n```\n\n:::\n\n## working with other vielzeug libraries\n\nspell schemas implement standard schema, so packages that accept standard schema validators use them directly.\n\n```ts\nimport { createcourier } from '@vielzeug/courier';\nimport { createform } from '@vielzeug/forge';\nimport { schemavalidator } from '@vielzeug/forge/schema';\nimport { s } from '@vielzeug/spell';\n\nconst profile = s.object({ displayname: s.string().min(2), newsletter: s.boolean() });\n\nconst form = createform({\n initialvalues: { displayname: '', newsletter: false },\n validate: schemavalidator(profile),\n});\n\nconst courier = createcourier({ baseurl: '/api' });\nconst profile = profile.parse(await courier.get('/profile'));\n```\n\n## best practices\n\n keep schemas close to the boundary where unknown data enters your app.\n chain constraints in the order they should apply; put `trim()` before length checks.\n derive object shapes with `extend()`, `pick()`, `omit()`, or `partial()` before adding checks.\n chain type specific methods before `optional()`, `nullable()`, `transform()`, or `required()`.\n use `check()` with `ctx.addissue()` for multi field rules; return a message for single predicates.\n use `checkasync()` with `parseasync()` for every asynchronous domain rule.\n build a parse context per request, locale, or test instead of relying on global state.\n use `definition()` with `tojsonschema()` for external tooling, and keep runtime only schemas separate.\n",
1386
+ "examples": " \ntitle: 'spell: examples'\ndescription: practical examples and recipes for spell.\n \n\n## examples\n\n [validating api payloads](./examples/api.md)\n [form safe parsing](./examples/forms.md)\n [async business rules](./examples/async.md)\n [schema introspection and round trips](./examples/introspection.md)\n [unions, intersections, and discriminated unions](./examples/unions.md)\n"
1387
1387
  },
1388
1388
  "examples": [
1389
1389
  {
@@ -1408,7 +1408,7 @@
1408
1408
  },
1409
1409
  {
1410
1410
  "id": "descriptor-roundtrip",
1411
- "text": "declarative definition export import { s } from '@vielzeug/spell'\nimport { fromdefinition } from '@vielzeug/spell/json'\n\nconst product = s.object({\n id: s.string().uuid(),\n name: s.string().min(1),\n price: s.number().positive(),\n})\n\nconst definition = product.definition()\nconst jsonschema = fromdefinition(definition)\n\nconsole.log(definition.kind)\nconsole.log(jsonschema)"
1411
+ "text": "declarative definition export import { s } from '@vielzeug/spell';\nimport { tojsonschema } from '@vielzeug/spell/json';\n\nconst product = s.object({\n id: s.string().uuid(),\n name: s.string().min(1).describe('display name'),\n price: s.number().positive(),\n sku: s.string().startswith('sku '),\n});\n\n// definition() returns frozen, declarative data\nconst definition = product.definition();\nconsole.log(definition.kind); // 'object'\nconsole.log(definition.fields.sku); // { kind: 'string', patterns: [{ flags: '', source: '^sku ' }] }\n\n// tojsonschema() maps the definition to json schema 2020 12\nconsole.log(tojsonschema(definition));\n\n// runtime behavior has no declarative form\ntry {\n product.check(() => true).definition();\n} catch (error) {\n console.log(error.name); // 'spelldefinitionerror'\n}\n"
1412
1412
  },
1413
1413
  {
1414
1414
  "id": "discriminated-union",
@@ -1431,16 +1431,16 @@
1431
1431
  "text": "number validation // enforce money like numeric constraints for a checkout amount.\nimport { s } from '@vielzeug/spell'\n\nconst checkouttotal = s.number().nonnegative().multipleof(0.01).max(9999)\n\nfor (const value of [129.99, 4, 19.999, 15000]) {\n const result = checkouttotal.safeparse(value)\n console.log(value, '=>', result.success ? 'accepted' : result.error.issues[0].message)\n}"
1432
1432
  },
1433
1433
  {
1434
- "id": "object-defaults",
1435
- "text": "object defaults import { s } from '@vielzeug/spell';\n\n// schema where all fields have defaults\nconst serverconfig = s.object({\n host: s.string().default('localhost'),\n port: s.number().int().positive().default(3000),\n tls: s.boolean().default(false),\n});\n\n// get a fully filled config without providing any input\nconst config = serverconfig.defaults();\nconsole.log(config);\n// { host: 'localhost', port: 3000, tls: false }\n\n// works with nested schemas too\nconst appconfig = s.object({\n server: serverconfig,\n debug: s.boolean().default(false),\n});\n\n// parse with partial input: missing fields use their defaults\nconst parsed = appconfig.parse({ server: { host: 'prod.example.com', port: 443, tls: true }, debug: true });\nconsole.log(parsed.server.host); // 'prod.example.com'\n\n// schema with required field (no default): throws if .defaults() called\nconst strict = s.object({ name: s.string() });\nconst result = strict.safeparse({});\nconsole.log(result.success); // false: name is required\n"
1434
+ "id": "object-composition",
1435
+ "text": "object composition import { s } from '@vielzeug/spell';\n\nconst user = s.object({\n email: s.string().email(),\n id: s.string().uuid(),\n name: s.string().min(1),\n});\n\n// derive shapes first; extend() overrides fields with the same key\nconst admin = user.extend({ role: s.enum(['owner', 'editor']) });\nconst publicuser = user.omit('email');\nconst userpatch = user.pick('email', 'name').partial();\n\nconsole.log(object.keys(admin.shape)); // ['email', 'id', 'name', 'role']\nconsole.log(publicuser.parse({ id: '550e8400 e29b 41d4 a716 446655440000', name: 'ada' }));\nconsole.log(userpatch.parse({ name: 'grace' })); // { name: 'grace' }\n\n// checks belong to the final shape: add them after deriving\nconst signup = user.pick('email')\n .extend({ confirm: s.string(), password: s.string().min(12) })\n .check((value) => value.password === value.confirm || 'passwords must match');\n\nconsole.log(signup.safeparse({ confirm: 'x', email: 'ada@example.com', password: 'correct horse battery' }).success); // false\n\n// deriving from a schema with checks throws, because the check was written for the old shape\ntry {\n signup.omit('confirm');\n} catch (error) {\n console.log(error.name); // 'spelldefinitionerror'\n}\n"
1436
1436
  },
1437
1437
  {
1438
- "id": "object-merge",
1439
- "text": "object merge & aliases import { s } from '@vielzeug/spell';\n\n// merge() combines two object schemas (right hand fields win on conflict)\nconst base = s.object({\n id: s.string().uuid(),\n createdat: s.date(),\n});\n\nconst withmeta = s.object({\n description: s.string().optional(),\n tags: s.array(s.string()).default(() => []),\n});\n\nconst resource = base.merge(withmeta);\n\nconst result = resource.parse({\n createdat: new date('2025 01 01'),\n id: '550e8400 e29b 41d4 a716 446655440000',\n tags: ['api', 'v2'],\n});\nconsole.log(result.tags); // ['api', 'v2']\nconsole.log(result.id); // '550e8400 ...'\n\n// merge() inherits the right hand schema's strict/relaxed mode\nconst strict = s.object({ a: s.string() });\nconst relaxed = s.object({ b: s.number() }).relaxed();\n\nconst merged = strict.merge(relaxed);\n// extra keys are allowed because relaxed is the right hand schema\nconsole.log(merged.safeparse({ a: 'hi', b: 1, extra: true }).success); // true\n\nconst idorslug = s.union(s.string().uuid(), s.string().slug());\nconsole.log(idorslug.safeparse('550e8400 e29b 41d4 a716 446655440000').success); // true\nconsole.log(idorslug.safeparse('my slug').success); // true\nconsole.log(idorslug.safeparse(42).success); // false\n\nconst nonemptystring = s.intersect(s.string(), s.string().min(1));\nconsole.log(nonemptystring.parse('hello')); // 'hello'\n"
1438
+ "id": "object-defaults",
1439
+ "text": "object defaults import { s } from '@vielzeug/spell';\n\nconst serverconfig = s.object({\n host: s.string().default('localhost'),\n port: s.number().int().positive().default(3000),\n tls: s.boolean().default(false),\n});\n\n// absent keys take their field default\nconsole.log(serverconfig.parse({}));\n// { host: 'localhost', port: 3000, tls: false }\n\n// default() on the object itself covers a missing object\nconst appconfig = s.object({\n debug: s.boolean().default(false),\n server: serverconfig.default({ host: 'localhost', port: 3000, tls: false }),\n});\n\nconsole.log(appconfig.parse({}).server.port); // 3000\n\n// each parse returns a fresh copy of the default value\nconst tags = s.array(s.string()).default([]);\nconst first = tags.parse(undefined);\nfirst.push('mutated');\nconsole.log(tags.parse(undefined)); // []\n\n// fields without a default stay required\nconsole.log(s.object({ name: s.string() }).safeparse({}).success); // false\n"
1440
1440
  },
1441
1441
  {
1442
1442
  "id": "optional-nullable",
1443
- "text": "optional and nullable fields // preserve defaults and validators while tightening undefined away with required().\nimport { s } from '@vielzeug/spell'\n\nconst displayname = s.string().trim().min(2).optional().default('guest').nullable()\nconst requireddisplayname = displayname.required()\n\nconsole.log('default for undefined:', displayname.parse(undefined))\nconsole.log('null stays null:', displayname.parse(null))\n\nconst short = requireddisplayname.safeparse('a')\nconsole.log('short name accepted:', short.success)\n\nconst missing = requireddisplayname.safeparse(undefined)\nconsole.log('undefined accepted after required():', missing.success)\n\nconsole.log('null accepted after required():', requireddisplayname.parse(null))"
1443
+ "text": "optional and nullable fields // required() makes undefined invalid again: it clears optional() and default(), keeping checks and null.\nimport { s } from '@vielzeug/spell'\n\nconst displayname = s.string().trim().min(2).optional().default('guest').nullable()\nconst requireddisplayname = displayname.required()\n\nconsole.log('default for undefined:', displayname.parse(undefined))\nconsole.log('null stays null:', displayname.parse(null))\n\nconst short = requireddisplayname.safeparse('a')\nconsole.log('short name accepted:', short.success)\n\nconst missing = requireddisplayname.safeparse(undefined)\nconsole.log('undefined accepted after required():', missing.success)\n\nconsole.log('null accepted after required():', requireddisplayname.parse(null))"
1444
1444
  },
1445
1445
  {
1446
1446
  "id": "refinements",
@@ -1455,12 +1455,12 @@
1455
1455
  "text": "wrappers & defaults // optional(), nullable(), default(), catch(): missing value semantics\nimport { s } from '@vielzeug/spell'\n\n// optional: accepts undefined, passes through validation otherwise\nconst nickname = s.string().min(2).optional().default('guest')\n\nconsole.log(nickname.parse(undefined)) // 'guest'\nconsole.log(nickname.parse('ada')) // 'ada'\n\n// nullable: accepts null explicitly\nconst bio = s.string().max(200).nullable()\n\nconsole.log(bio.parse(null)) // null\nconsole.log(bio.parse('loves types')) // 'loves types'\n\n// nullish: accepts both null and undefined\nconst avatar = s.string().url().nullish()\n\nconsole.log(avatar.parse(null)) // null\nconsole.log(avatar.parse(undefined)) // undefined\n\n// required(): strips undefined without removing null\nconst nullablebutrequired = s.string().optional().nullable().required()\nconsole.log(nullablebutrequired.parse(null)) // null\nconsole.log(nullablebutrequired.safeparse(undefined).success) // false\n\n// catch(): returns a fallback when validation fails: never throws\nconst port = s.number().int().min(1).max(65535).catch(3000)\nconsole.log(port.parse(8080)) // 8080\nconsole.log(port.parse('not a port')) // 3000"
1456
1456
  }
1457
1457
  ],
1458
- "exports": "s createparsecontext joinissuepath spellvalidationerror spelldefinitionerror standardschemav1 errorcode ./json ./predicates",
1459
- "keywords": "schema validation parsing standard schema json schema locale typescript descriptors",
1458
+ "exports": "s createparsecontext joinissuepath spellvalidationerror spelldefinitionerror schema standardschemav1 errorcode ./json ./predicates",
1459
+ "keywords": "schema validation parsing standard schema json schema locale typescript definitions",
1460
1460
  "name": "@vielzeug/spell",
1461
1461
  "related": "forge courier vault",
1462
1462
  "slug": "spell",
1463
- "source": "export type {\n anyschema,\n checkcontext,\n flaterror,\n flaterrorfirst,\n infer,\n inferinput,\n inferoutput,\n issue,\n issuepath,\n issuepathsegment,\n jsonschema,\n messagefn,\n messages,\n parsecontext,\n parseresult,\n schemadescriptor,\n standardschemav1,\n syncparsable,\n validateresult,\n} from './core';\nexport { errorcode, joinissuepath, schema, spelldefinitionerror, spellerror, spellvalidationerror } from './core';\nexport { createparsecontext, type deeppartial } from './messages';\nexport { s } from './s';\nexport { tolerate } from './tolerate';\n"
1463
+ "source": "export {\n type flaterror,\n type flaterrorfirst,\n joinissuepath,\n spelldefinitionerror,\n spellerror,\n spellvalidationerror,\n} from './errors';\nexport { createparsecontext, type deeppartial, type messages } from './messages';\nexport { s } from './s';\nexport { schema } from './schema';\nexport {\n type anyschema,\n type checkcontext,\n errorcode,\n type infer,\n type inferinput,\n type inferoutput,\n type issue,\n type issuepath,\n type issuepathsegment,\n type messagefn,\n type parsecontext,\n type parseresult,\n type patterndescriptor,\n type schemadescriptor,\n type schemakind,\n type standardschemav1,\n type validateresult,\n} from './types';\n"
1464
1464
  },
1465
1465
  {
1466
1466
  "category": "sync",
@@ -1527,10 +1527,10 @@
1527
1527
  "category": "storage",
1528
1528
  "description": "typed browser storage and opt in driver neutral sqlite with portable keys, ttl, observation, and transactions.",
1529
1529
  "docs": {
1530
- "index": " \ntitle: 'vault: typed storage'\ndescription: typed browser storage and opt in driver neutral sqlite with portable keys, ttl, observation, and transactions.\npackage: vault\ncategory: storage\nkeywords: [storage, indexeddb, localstorage, sessionstorage, sqlite, ttl, browser, node, deno]\nrelated: [courier, forge, ripple]\nexports:\n [table, ttl, validatorcodec, creatememory, createlocalstorage, createsessionstorage, createindexeddb, createsqlite]\nenvironments: [browser, node, deno]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"vault\" />\n\n## why vault?\n\nvault gives browser and sqlite persistence one typed schema while keeping backend guarantees explicit. use `keyvaluevaultstore` for portable crud and observation; choose indexeddb or the opt in sqlite subpath when you need atomic transactions or lazy iteration. durable adapters require codecs so invalid stored data never enters typed code.\n\n```ts\n// before\nlocalstorage.setitem('theme', json.stringify({ value: 'dark' }));\nconst theme = json.parse(localstorage.getitem('theme') ?? '{}').value;\n\n// after\nawait store.put('preferences', { id: 'theme', value: 'dark' });\nconst theme = await store.get('preferences', 'theme');\n```\n\n| feature | vault | raw web storage | dexie |\n| | | | |\n| bundle size | <packageinfo package=\"vault\" type=\"size\" /> | browser built in | extra dependency |\n| runtime dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| typed schema and keys | <ore icon name=\"check\" size=\"16\"></ore icon> | application defined | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| portable key value store api | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"triangle alert\" size=\"16\"></ore icon> | indexeddb only |\n| explicit atomic transactions | indexeddb + sqlite capability | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| required durable codecs | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| driver neutral sqlite | opt in subpath | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use vault when** you need typed browser persistence or application owned sqlite with honest storage capabilities and required durable codecs.\n\n**consider raw web storage when** you only persist one or two unstructured values. **consider dexie when** you need a broader indexeddb ecosystem.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/vault\n```\n\n```sh [npm]\nnpm install @vielzeug/vault\n```\n\n```sh [yarn]\nyarn add @vielzeug/vault\n```\n\n:::\n\n## quick start\n\ndefine a schema, create a key value store with codecs, and dispose it with its owner.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\nconst preferenceschema = s.object({ id: s.string(), theme: s.union('dark', 'light') });\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { preferences: table<{ id: string; theme: 'dark' | 'light' }>('id') },\n codecs: { preferences: preferenceschema },\n});\n\ntry {\n await store.put('preferences', { id: 'theme', theme: 'dark' });\n console.log(await store.get('preferences', 'theme'));\n} finally {\n await store.dispose();\n}\n```\n\n## features\n\n<div class=\"features grid\">\n\n `table()` defines typed records with portable string or number keys.\n spell and other parser schemas work directly as codecs; `validatorcodec()` creates an explicit identity encoding codec.\n `/memory` returns a portable `documentvaultstore` with `batch()` and `iterate()`: codecs optional (in memory, no trust boundary).\n `/local storage` and `/session storage` return `keyvaluevaultstore`: codecs required.\n `observe()` emits current and changed table snapshots.\n `ttl` creates validated expiration durations.\n `/indexeddb` and `/sqlite` return `documentvaultstore` with `batch()` and `iterate()`: codecs required. `/memory` shares the same contract without codecs.\n `/indexeddb` accepts a `migrate` hook for schema upgrades the table schema cannot express.\n `pruneexpired()` removes stale ttl entries on demand.\n bound helpers (`has`, `count`, `update`, `upsert`, `getmany`, `keys`, `deletemany`) are available on every store and transaction context.\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [forge](../forge/index.md) saves and restores form drafts through vault stores.\n [ripple](../ripple/index.md) owns application state that can persist through vault.\n [courier](../courier/index.md) can populate persistent cache data.\n\n</div>\n\n<! markdownlint enable md025 md033 md060 >\n",
1530
+ "index": " \ntitle: 'vault: typed storage'\ndescription: typed browser storage and opt in driver neutral sqlite with portable keys, ttl, observation, and transactions.\npackage: vault\ncategory: storage\nkeywords: [storage, indexeddb, localstorage, sessionstorage, sqlite, ttl, browser, node, deno]\nrelated: [courier, forge, ripple]\nexports:\n [table, ttl, validatorcodec, creatememory, createlocalstorage, createsessionstorage, createindexeddb, createsqlite]\nenvironments: [browser, node, deno]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"vault\" />\n\n## why vault?\n\nvault gives browser and sqlite persistence one typed schema while keeping backend guarantees explicit. use `keyvaluevaultstore` for portable crud and observation; choose indexeddb or the opt in sqlite subpath when you need atomic transactions or lazy iteration. durable adapters require codecs so invalid stored data never enters typed code.\n\n```ts\n// before\nlocalstorage.setitem('theme', json.stringify({ value: 'dark' }));\nconst theme = json.parse(localstorage.getitem('theme') ?? '{}').value;\n\n// after\nawait store.put('preferences', { id: 'theme', value: 'dark' });\nconst theme = await store.get('preferences', 'theme');\n```\n\n| feature | vault | raw web storage | dexie |\n| | | | |\n| bundle size | <packageinfo package=\"vault\" type=\"size\" /> | browser built in | extra dependency |\n| runtime dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| typed schema and keys | <ore icon name=\"check\" size=\"16\"></ore icon> | application defined | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| portable key value store api | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"triangle alert\" size=\"16\"></ore icon> | indexeddb only |\n| explicit atomic transactions | indexeddb + sqlite capability | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| required durable codecs | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| driver neutral sqlite | opt in subpath | <ore icon name=\"x\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use vault when** you need typed browser persistence or application owned sqlite with honest storage capabilities and required durable codecs.\n\n**consider raw web storage when** you only persist one or two unstructured values. **consider dexie when** you need a broader indexeddb ecosystem.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/vault\n```\n\n```sh [npm]\nnpm install @vielzeug/vault\n```\n\n```sh [yarn]\nyarn add @vielzeug/vault\n```\n\n:::\n\n## quick start\n\ndefine a schema, create a key value store with codecs, and dispose it with its owner.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\nconst preferenceschema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { preferences: table<{ id: string; theme: 'dark' | 'light' }>('id') },\n codecs: { preferences: preferenceschema },\n});\n\ntry {\n await store.put('preferences', { id: 'theme', theme: 'dark' });\n console.log(await store.get('preferences', 'theme'));\n} finally {\n await store.dispose();\n}\n```\n\n## features\n\n<div class=\"features grid\">\n\n `table()` defines typed records with portable string or number keys.\n spell and other parser schemas work directly as codecs; `validatorcodec()` creates an explicit identity encoding codec.\n `/memory` returns a portable `documentvaultstore` with `batch()` and `iterate()`: codecs optional (in memory, no trust boundary).\n `/local storage` and `/session storage` return `keyvaluevaultstore`: codecs required.\n `observe()` emits current and changed table snapshots.\n `ttl` creates validated expiration durations.\n `/indexeddb` and `/sqlite` return `documentvaultstore` with `batch()` and `iterate()`: codecs required. `/memory` shares the same contract without codecs.\n `/indexeddb` accepts a `migrate` hook for schema upgrades the table schema cannot express.\n `pruneexpired()` removes stale ttl entries on demand.\n bound helpers (`has`, `count`, `update`, `upsert`, `getmany`, `keys`, `deletemany`) are available on every store and transaction context.\n\n</div>\n\n## documentation\n\n<div class=\"doc links\">\n\n [usage guide](./usage.md)\n [api reference](./api.md)\n [examples](./examples.md)\n [migration guide](./migration.md)\n\n</div>\n\n## see also\n\n<div class=\"see also\">\n\n [forge](../forge/index.md) saves and restores form drafts through vault stores.\n [ripple](../ripple/index.md) owns application state that can persist through vault.\n [courier](../courier/index.md) can populate persistent cache data.\n\n</div>\n\n<! markdownlint enable md025 md033 md060 >\n",
1531
1531
  "api": " \ntitle: 'vault: api reference'\ndescription: reference for vault schemas, adapter entry points, storage capabilities, codecs, sqlite drivers, and errors.\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `creatememory()` | in memory document store | async api | import from `/memory`; codecs optional |\n| `createlocalstorage()` / `createsessionstorage()` | web storage backed key value stores | async api | codecs required; available only where the corresponding web api exists |\n| `createindexeddb()` | browser document store with transactions and cursor iteration | async api | import from `/indexeddb`; codecs required |\n| `createsqlite()` | driver neutral sqlite document store | async api over a synchronous driver | import from `/sqlite`; codecs required |\n| `table()` | typed record schema | sync | the key field must be a string or finite number |\n| `validatorcodec()` | create an identity encoding codec from a parser | sync | spell schemas can also be passed directly |\n| `ttl` | valid expiration durations | sync | durations must be positive |\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/vault` | adapter free schemas, ttl, errors, codecs, derived helpers, and shared types |\n| `@vielzeug/vault/memory` | `creatememory` |\n| `@vielzeug/vault/local storage` | `createlocalstorage` |\n| `@vielzeug/vault/session storage` | `createsessionstorage` |\n| `@vielzeug/vault/indexeddb` | `createindexeddb`, the `migrate` upgrade hook types, and indexeddb only types |\n| `@vielzeug/vault/sqlite` | `createsqlite`, the sqlite driver protocol types, and `transactioncontext` |\n\n## schemas, codecs, and ttl\n\n### `table()`\n\n```ts\nfunction table<t extends object, key extends keyof t & string = keyof t & string>(\n key: key & (t[key] extends vaultkey ? unknown : never),\n options?: { defaultttl?: number; indexes?: readonly (keyof t & string)[] },\n): schemaentry<t, key>;\n```\n\ndefines a typed table and its primary key field.\n\n| parameter | description |\n| | |\n| `key` | a record field whose values are `string` or finite `number` keys |\n| `options.defaultttl` | per table default ttl in milliseconds |\n| `options.indexes` | indexeddb secondary index fields |\n\n**returns:** a `schemaentry` describing the table.\n\n```ts\nimport { table, ttl } from '@vielzeug/vault';\n\nconst users = table<{ id: number; email: string }>('id', {\n indexes: ['email'],\n defaultttl: ttl.days(7),\n});\n```\n\n \n\n### `validatorcodec()`\n\n```ts\nfunction validatorcodec<t>(validator: { parse(value: unknown): t }): recordcodec<t>;\n```\n\nwraps any object with a `parse(value): t` method as an identity encoding `recordcodec`. parser schemas can also be passed directly in `codecs`; a spell schema requires no adapter.\n\n**returns:** a `recordcodec<t>`.\n\n```ts\nimport { s } from '@vielzeug/spell';\n\nconst userschema = s.object({ id: s.number(), name: s.string() });\nconst store = createlocalstorage({\n name: 'app',\n schema: { users: table<{ id: number; name: string }>('id') },\n codecs: { users: userschema },\n});\n```\n\ncustom `recordcodec` values validate writes by round tripping `decode(encode(value))`. indexeddb codecs must preserve declared indexed field names and values in their encoded object.\n\n \n\n### `ttl`\n\n```ts\nconst ttl: {\n days(n: number): number;\n hours(n: number): number;\n minutes(n: number): number;\n ms(n: number): number;\n seconds(n: number): number;\n};\n```\n\ncreates a finite, positive duration in milliseconds for writes and table defaults.\n\n**returns:** `number`.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nconst cachelifetime = ttl.minutes(5);\n```\n\n## factories\n\ndurable factories (localstorage, sessionstorage, indexeddb, sqlite) require `codecs`. memory may omit them.\n\n### `creatememory()`\n\n```ts\nfunction creatememory<s extends anyschema>(options: memorystoreoptions<s>): documentvaultstore<s>;\n```\n\ncreates an in memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws. codecs are optional because memory values never cross a trust boundary.\n\n| parameter | description |\n| | |\n| `schema` | tables created by `table()` |\n| `codecs` | optional per table codecs |\n\n**returns:** `documentvaultstore<s>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { creatememory } from '@vielzeug/vault/memory';\n\nconst store = creatememory({ schema: { users: table<{ id: number; name: string }>('id') } });\n```\n\n \n\n### `createlocalstorage()`\n\n```ts\nfunction createlocalstorage<s extends anyschema>(\n options: durablestoreoptions<s> & {\n name: string;\n },\n): keyvaluevaultstore<s>;\n```\n\ncreates a namespaced `localstorage` store. codecs are required.\n\n| parameter | description |\n| | |\n| `schema` | tables created by `table()` |\n| `codecs` | required per table codecs |\n| `name` | required storage namespace |\n\na write that exceeds the browser quota rejects with `vaultquotaerror`.\n\n**returns:** `keyvaluevaultstore<s>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\nconst store = createlocalstorage({\n name: 'app',\n schema: { settings: table<{ id: string }>('id') },\n codecs: { settings: settingsschema },\n});\n```\n\n \n\n### `createsessionstorage()`\n\n```ts\nfunction createsessionstorage<s extends anyschema>(\n options: durablestoreoptions<s> & {\n name: string;\n },\n): keyvaluevaultstore<s>;\n```\n\ncreates a namespaced `sessionstorage` store. its options and return type match `createlocalstorage()`.\n\n**returns:** `keyvaluevaultstore<s>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createsessionstorage } from '@vielzeug/vault/session storage';\n\nconst store = createsessionstorage({\n name: 'checkout',\n schema: { cart: table<{ id: string }>('id') },\n codecs: { cart: cartschema },\n});\n```\n\n \n\n### `createindexeddb()`\n\n```ts\nfunction createindexeddb<s extends anyschema>(\n options: durablestoreoptions<s> & {\n migrate?: migrationfn;\n name: string;\n version?: number;\n },\n): indexeddbvaultstore<s>;\n```\n\ncreates an indexeddb document store with atomic batches, lazy cursor iteration, and optional schema migrations. codecs are required.\n\n| parameter | description |\n| | |\n| `schema` | tables and indexeddb secondary indexes |\n| `codecs` | required per table codecs |\n| `name` | required database name |\n| `version` | positive schema version; defaults to `1` |\n| `migrate` | synchronous `onupgradeneeded` callback. object stores and schema declared indexes are created automatically; use the hook only for deletes or record transforms |\n\n**returns:** `indexeddbvaultstore<s>`. its `getallbyindex(table, field, value)` method queries a declared indexeddb index without scanning the full table.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\nconst store = createindexeddb({\n name: 'app',\n schema: { users: table<{ id: number; role: string }>('id', { indexes: ['role'] }) },\n codecs: { users: userschema },\n});\n\nconst admins = await store.getallbyindex('users', 'role', 'admin');\n```\n\n \n\n### `createsqlite()`\n\n```ts\nfunction createsqlite<s extends anyschema>(options: sqlitevaultoptions<s>): documentvaultstore<s>;\n```\n\ncreates a namespaced sqlite document store with atomic batches and keyset paginated iteration. codecs are required. it accepts an application provided positional parameter driver and never opens or imports a runtime driver.\n\n| parameter | description |\n| | |\n| `schema` | tables created by `table()` |\n| `codecs` | required per table codecs |\n| `database` | caller provided `sqlitedatabase` connection |\n| `name` | namespace within the connection |\n| `closeondispose` | closes the connection during disposal; defaults to `false` |\n\n**returns:** `documentvaultstore<s>`.\n\n```ts\nimport { databasesync } from 'node:sqlite';\n\nimport { table } from '@vielzeug/vault';\nimport { createsqlite } from '@vielzeug/vault/sqlite';\n\nconst store = createsqlite({\n database: new databasesync(':memory:'),\n name: 'tests',\n schema: { users: table<{ id: number; name: string }>('id') },\n codecs: { users: userschema },\n});\n```\n\nnode `databasesync`, bun `database`, and deno `jsr:@db/sqlite` `database` satisfy the protocol. codec output may be any json compatible value. during a `batch()` callback, calls on every vault store sharing that connection reject; use `tx.*` instead.\n\n## store capabilities\n\n### `keyvaluevaultstore`\n\n```ts\ninterface keyvaluevaultstore<s extends anyschema> {\n clear(table): promise<void>;\n count(table): promise<number>;\n delete(table, key): promise<boolean>;\n deletemany(table, keys): promise<number>;\n get(table, key): promise<record | undefined>;\n getall(table): promise<record[]>;\n getmany(table, keys): promise<(record | undefined)[]>;\n has(table, key): promise<boolean>;\n isempty(table): promise<boolean>;\n keys(table, filter?): promise<vaultkey[]>;\n update(table, key, changes, ttl?): promise<record | undefined>;\n upsert(table, key, update, ttl?): promise<record>;\n observe(table, listener, options?): unsubscribe;\n pruneexpired(): promise<record<string, number>>;\n put<k extends keyof s & string>(table: k, value: recordof<s, k>, ttl?: number): promise<recordof<s, k>>;\n putall(table, values, ttl?): promise<void>;\n readonly disposalsignal: abortsignal;\n dispose(): promise<void>;\n readonly disposed: boolean;\n [symbol.asyncdispose](): promise<void>;\n}\n```\n\nthe portable key value store api is returned by memory and web storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by codec validation. `observe()` emits the current table snapshot by default and then emits after mutations.\n\n \n\n### `documentvaultstore`\n\n```ts\ninterface documentvaultstore<s extends anyschema> extends keyvaluevaultstore<s> {\n batch<k extends keyof s & string, r>(\n tables: readonly k[],\n fn: (tx: transactioncontext<s, k>) => promise<r>,\n ): promise<r>;\n iterate<k extends keyof s & string>(table: k): asynciterable<recordof<s, k>>;\n}\n```\n\n`batch()` runs a scoped atomic callback. `iterate()` lazily yields table records: indexeddb uses a cursor, sqlite uses keyset pagination. both are provided by `createindexeddb()` and `createsqlite()`.\n\n| parameter | description |\n| | |\n| `tables` | tables the transaction may access |\n| `fn` | async callback that uses only the supplied `tx` context |\n\n**returns:** the callback result after commit.\n\n```ts\nawait store.batch(['users'], async (tx) => {\n await tx.put('users', { id: 1, name: 'ada' });\n});\n\nfor await (const user of store.iterate('users')) console.log(user);\n```\n\n## bound helpers\n\nconvenience operations are bound to every store and transaction context. for filtering, ordering, and pagination, compose over `getall()`: it returns a plain array, or use `iterate()` on document stores and `getallbyindex()` on indexeddb for declared equality indexes.\n\n| helper | signature | description |\n| | | |\n| `has()` | `(table, key) => promise<boolean>` | check whether a record exists |\n| `count()` | `(table) => promise<number>` | count live records |\n| `isempty()` | `(table) => promise<boolean>` | check whether a table has no live records |\n| `getmany()` | `(table, keys) => promise<(t \\| undefined)[]>` | fetch multiple records by key |\n| `keys()` | `(table, filter?) => promise<vaultkey[]>` | fetch live primary keys, optionally filtered by record |\n| `deletemany()` | `(table, keys) => promise<number>` | delete multiple records, return count |\n| `update()` | `(table, key, changes, ttl?) => promise<t \\| undefined>` | partially update an existing record |\n| `upsert()` | `(table, key, fn, ttl?) => promise<t>` | read modify write with callback |\n\n```ts\nconst exists = await store.has('users', 1);\nconst total = await store.count('users');\nconst [a, b] = await store.getmany('users', [1, 2]);\nconst updated = await store.update('users', 1, { name: 'alice' });\nconst result = await store.upsert('users', 99, (existing) => ({ id: 99, name: existing?.name ?? 'guest' }));\n\nconst all = await store.getall('users');\nconst active = all\n .filter((user) => user.status === 'active')\n .sort((a, b) => a.name.localecompare(b.name))\n .slice(0, 20);\n```\n\nbound `update()` and `upsert()` are atomic on document stores. their key value store forms are non atomic convenience operations.\n\n## types\n\n```ts\ntype vaultkey = number | string;\ntype unsubscribe = () => void;\ntype observer<t> = (records: t[]) => void;\ntype anyschema = record<\n string,\n {\n defaultttl?: number;\n indexes?: readonly string[];\n key: string;\n }\n>;\ntype schemaentry<t extends object, key extends keyof t & string = keyof t & string> = {\n defaultttl?: number;\n indexes?: readonly (keyof t & string)[];\n key: key;\n};\ntype recordof<s extends anyschema, k extends keyof s> = k extends unknown\n ? s[k] extends schemaentry<infer r, infer _key>\n ? r\n : never\n : never;\ntype keyof<s extends anyschema, k extends keyof s> = k extends unknown\n ? extract<s[k] extends schemaentry<infer r, infer key> ? r[key] : never, vaultkey>\n : never;\n```\n\n```ts\ntype recordcodec<t> = {\n decode(value: unknown): t;\n encode(value: t): unknown;\n};\n\ntype recordparser<t> = { parse(value: unknown): t };\ntype codecinput<t> = recordcodec<t> | recordparser<t>;\n\ntype tablecodecs<s extends anyschema> = {\n [k in keyof s]: codecinput<recordof<s, k>>;\n};\n\ntype memorystoreoptions<s extends anyschema> = {\n schema: s;\n codecs?: tablecodecs<s>;\n};\n\ntype durablestoreoptions<s extends anyschema> = {\n schema: s;\n codecs: tablecodecs<s>;\n};\n```\n\n```ts\ntype migrationcontext = {\n db: idbdatabase;\n newversion: number | null;\n oldversion: number;\n tx: idbtransaction;\n};\n\ntype migrationfn = (ctx: migrationcontext) => void;\n```\n\nimport `migrationcontext` and `migrationfn` from `@vielzeug/vault/indexeddb`.\n\n```ts\ntype sqliteparameter = null | number | string;\n\ninterface sqlitestatement {\n all(...parameters: sqliteparameter[]): readonly record<string, unknown>[];\n finalize?(): void;\n get(...parameters: sqliteparameter[]): record<string, unknown> | null | undefined;\n run(...parameters: sqliteparameter[]): unknown;\n}\n\ninterface sqlitedatabase {\n close?(): void;\n exec(sql: string): void;\n prepare(sql: string): sqlitestatement;\n}\n\ntype sqlitevaultoptions<s extends anyschema> = durablestoreoptions<s> & {\n closeondispose?: boolean;\n database: sqlitedatabase;\n name: string;\n};\n```\n\n```ts\ninterface transactioncontext<s extends anyschema, k extends keyof s & string = keyof s & string> {\n clear<t extends k>(table: t): promise<void>;\n delete<t extends k>(table: t, key: keyof<s, t>): promise<boolean>;\n get<t extends k>(table: t, key: keyof<s, t>): promise<recordof<s, t> | undefined>;\n getall<t extends k>(table: t): promise<recordof<s, t>[]>;\n iterate<t extends k>(table: t): asynciterable<recordof<s, t>>;\n put<t extends k>(table: t, value: recordof<s, t>, ttl?: number): promise<recordof<s, t>>;\n putall<t extends k>(table: t, values: recordof<s, t>[], ttl?: number): promise<void>;\n}\n```\n\n`transactioncontext` has core crud, `iterate()`, and ttl methods, narrowed to the tables declared in `batch()`. import it from `@vielzeug/vault/indexeddb` or `@vielzeug/vault/sqlite`.\n\n## errors\n\n| error | trigger |\n| | |\n| `vaulterror` | any vault originated validation, serialization, storage, or codec error |\n| `vaultdisposederror` | an operation after the store or observer hub is disposed |\n| `vaultscopeerror` | a `batch()` callback accesses a table outside its declared scope |\n| `vaultquotaerror` | a localstorage or sessionstorage write exceeds the browser quota |\n| `vaultmigrationerror` | an indexeddb migration callback throws |\n\nevery listed error extends `vaulterror`.\n",
1532
- "usage": " \ntitle: 'vault: usage guide'\ndescription: persist typed browser or sqlite data, observe table snapshots, and use atomic transactions with required durable codecs.\n \n\n[[toc]]\n\n## basic usage\n\ncreate a key value store with a schema and codecs, then write a typed row.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\ninterface preference {\n id: string;\n theme: 'dark' | 'light';\n}\n\nconst preferenceschema = s.object({ id: s.string(), theme: s.union('dark', 'light') });\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { preferences: table<preference>('id') },\n codecs: { preferences: preferenceschema },\n});\n\nawait store.put('preferences', { id: 'theme', theme: 'dark' });\nconsole.log(await store.get('preferences', 'theme'));\n```\n\n## create a key value store\n\nlocalstorage and sessionstorage return `keyvaluevaultstore`; memory returns a `documentvaultstore` (it adds `batch()` and `iterate()`). they share portable string/number keys, bound helpers, fluent queries, ttl, and `observe()`. memory may omit codecs; web storage requires them. malformed storage envelopes are evicted lazily, while codec validation failures are surfaced without deleting persisted data.\n\nthe root entry is adapter free. import `creatememory` from `@vielzeug/vault/memory`, `createlocalstorage` from `@vielzeug/vault/local storage`, or `createsessionstorage` from `@vielzeug/vault/session storage`. import each adapter from its focused subpath so unused backends stay out of the bundle.\n\nuse a new storage name when upgrading from vault 1. old key and envelope formats are not read by vault 2.\n\n```ts\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { preferences: table<preference>('id') },\n codecs: { preferences: preferenceschema },\n});\n```\n\n## read and change records\n\nuse bound `update()` and `upsert()` methods for read modify write operations; no helper imports are required.\n\n```ts\nconst updated = await store.update('preferences', 'theme', { theme: 'light' });\n\nawait store.upsert('preferences', 'locale', (current) => ({\n id: 'locale',\n theme: current?.theme ?? 'dark',\n}));\n\nconsole.log(updated);\n```\n\n`update()` returns `undefined` for a missing key. `upsert()` always writes the record returned by its callback. document store methods run atomically; key value store methods are non atomic conveniences when multiple writers race.\n\n## iterate and filter records\n\nfilter the plain array returned by `getall()` for in memory selection, sorting, and pagination. use `iterate()` on a `documentvaultstore` for lazy cursor based traversal, and `getallbyindex()` on indexeddb for declared equality indexes.\n\n```ts\n// in memory selection over getall()\nconst themed = (await store.getall('preferences')).filter((preference) => preference.id.startswith('theme'));\n\n// document store: iterate lazily\nfor await (const pref of db.iterate('preferences')) {\n if (pref.id.startswith('theme')) console.log(pref);\n}\n```\n\nfor large tables, prefer `iterate()` on indexeddb or sqlite instead of materializing every record with `getall()`.\n\n## use ttl and pruning\n\nuse `ttl.*` helpers for expiring rows. call `pruneexpired()` to reclaim storage from stale rows that accumulate without reads; tables with removed rows publish fresh observer snapshots.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nawait store.put('preferences', { id: 'temporary', theme: 'dark' }, ttl.hours(1));\n\n// reclaim expired rows on a schedule owned by the application.\nconst pruneinterval = setinterval(() => store.pruneexpired(), ttl.hours(6));\nstore.disposalsignal.addeventlistener('abort', () => clearinterval(pruneinterval));\n```\n\n## observe a table\n\nuse `observe()` for current and future snapshots. notifications are revision ordered, and explicit ttl pruning publishes fresh snapshots for affected tables. tie subscription lifetime to an `abortsignal` when a component or request owns it.\n\n```ts\nconst controller = new abortcontroller();\n\nstore.observe(\n 'preferences',\n (preferences) => {\n console.log(preferences);\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\n```\n\n## use indexeddb for browser transactions\n\nchoose indexeddb when browser storage needs multiple writes to commit together or cursor iteration.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\nconst eventschema = s.object({ id: s.number(), type: s.string() });\nconst db = createindexeddb({\n name: 'app v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n codecs: { events: eventschema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\ntransaction contexts expose the same bound helpers; `tx.update()`, `tx.upsert()`, and `tx.deletemany()` run inside the enclosing transaction. only await `tx.*` operations inside a batch callback. do not retain the transaction context after the callback; later use throws `vaultscopeerror`. do not await timers, fetches, or other external asynchronous work because indexeddb can commit an inactive transaction.\n\n## use sqlite outside the browser\n\nimport sqlite from the opt in subpath so the browser root stays free of runtime drivers. vault never opens a connection or configures its sqlite process behavior for you.\n\n```ts\nimport { databasesync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createsqlite } from '@vielzeug/vault/sqlite';\n\nconst eventschema = s.object({ id: s.number(), type: s.string() });\nconst database = new databasesync('app.db', { timeout: 5_000 });\nconst store = createsqlite({\n database,\n name: 'app v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n codecs: { events: eventschema },\n});\n\nawait store.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nnode's `node:sqlite` api is experimental. bun's `bun:sqlite` `database` satisfies the same positional `exec()` and `prepare()` contract; configure wal from your application when the deployment needs it. deno does not include sqlite, but `jsr:@db/sqlite`'s `database` satisfies the same contract when its ffi, filesystem, and environment permissions are granted.\n\nsqlite stores serialize all access through the injected connection. `batch()` starts `begin immediate` and rolls back callback failures. while its callback runs, calls on any store sharing that connection reject rather than waiting behind the transaction; use `tx.*` instead. the underlying drivers are synchronous, so move large scans and writes to a worker or isolate when event loop latency matters.\n\n## store sqlite values and observe changes\n\nsqlite accepts any json compatible codec output. circular values, `bigint`, class instances, functions, and non finite numbers must be transformed by the codec before writing. number and string primary keys remain distinct.\n\n`observe()` sees mutations written through vault stores sharing the same injected connection after a commit. it cannot detect direct sql changes, writes from another process, or writes through another connection. the connection belongs to the caller by default; use `closeondispose: true` only when the store owns it.\n\n## handle indexeddb schema migrations\n\ndeclare indexeddb indexes in the schema. codecs must preserve each indexed field name and value in their encoded object. use `migrate` only for indexeddb version upgrades and mirror vault's fixed `value.<field>` index path.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb, type migrationfn } from '@vielzeug/vault/indexeddb';\n\nconst userschema = s.object({ id: s.number(), name: s.string() });\nconst schema = { users: table<{ id: number; name: string }>('id', { indexes: ['name'] }) };\nconst migrate: migrationfn = ({ db, oldversion, tx }) => {\n if (oldversion < 2 && db.objectstorenames.contains('users')) {\n tx.objectstore('users').createindex('name', 'value.name');\n }\n};\n\ncreateindexeddb({\n name: 'app v2',\n migrate,\n schema,\n version: 2,\n codecs: { users: userschema },\n});\n```\n\n## framework integration\n\n::: code group\n\n```ts [react]\nimport { useeffect, usestate } from 'react';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function usetable<s extends anyschema, k extends keyof s & string>(store: keyvaluevaultstore<s>, table: k) {\n const [rows, setrows] = usestate<recordof<s, k>[]>([]);\n\n useeffect(() => store.observe(table, setrows), [store, table]);\n return rows;\n}\n```\n\n```ts [vue 3]\nimport { onunmounted, shallowref } from 'vue';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function usetable<s extends anyschema, k extends keyof s & string>(store: keyvaluevaultstore<s>, table: k) {\n const rows = shallowref<recordof<s, k>[]>([]);\n const stop = store.observe(table, (next) => (rows.value = next));\n\n onunmounted(stop);\n return rows;\n}\n```\n\n```ts [svelte]\nimport { readable } from 'svelte/store';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function tablestore<s extends anyschema, k extends keyof s & string>(store: keyvaluevaultstore<s>, table: k) {\n return readable<recordof<s, k>[]>([], (set) => store.observe(table, set));\n}\n```\n\n:::\n\n## working with other vielzeug libraries\n\nkeep ripple signals as application state and persist selected changes through vault writes.\n\n## best practices\n\n define one schema per storage namespace.\n use string or finite number primary keys only.\n provide codecs for every durable adapter; pass spell or another parser schema directly when identity encoding is sufficient.\n use `observe()` for table snapshots.\n use indexeddb or sqlite for atomic work.\n keep external asynchronous work outside `batch()` callbacks.\n use `ttl.*` instead of raw durations.\n keep sqlite scans and writes off latency sensitive event loops.\n dispose stores when their owner ends.\n",
1533
- "examples": " \ntitle: 'vault: examples'\ndescription: practical vault examples for browser storage, sqlite, ttl, transactions, observation, and framework integration.\n \n\n## browser key value store with ttl\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table, ttl } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\ninterface session {\n id: string;\n token: string;\n}\n\nconst sessionschema = s.object({ id: s.string(), token: s.string() });\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { sessions: table<session>('id', { defaultttl: ttl.hours(1) }) },\n codecs: { sessions: sessionschema },\n});\n\nawait store.put('sessions', { id: 'current', token: 'fake token for docs' });\nconsole.log(await store.get('sessions', 'current'));\n```\n\n## indexeddb with transactions and iteration\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\ninterface event {\n id: number;\n type: string;\n createdat: number;\n}\n\nconst eventschema = s.object({ createdat: s.number(), id: s.number(), type: s.string() });\nconst db = createindexeddb({\n name: 'events',\n schema: { events: table<event>('id', { indexes: ['type'] }) },\n codecs: { events: eventschema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened', createdat: date.now() });\n await tx.put('events', { id: 2, type: 'saved', createdat: date.now() });\n});\n\nfor await (const event of db.iterate('events')) {\n console.log(event.type);\n}\n```\n\n## sqlite document store\n\n```ts\nimport { databasesync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createsqlite } from '@vielzeug/vault/sqlite';\n\ninterface job {\n id: string;\n status: 'queued' | 'running' | 'done';\n}\n\nconst jobschema = s.object({ id: s.string(), status: s.union('queued', 'running', 'done') });\nconst database = new databasesync(':memory:');\nconst store = createsqlite({\n database,\n name: 'app',\n schema: { jobs: table<job>('id') },\n codecs: { jobs: jobschema },\n});\n\nawait store.batch(['jobs'], async (tx) => {\n await tx.put('jobs', { id: 'job 1', status: 'queued' });\n await tx.put('jobs', { id: 'job 2', status: 'running' });\n});\n\nfor await (const job of store.iterate('jobs')) {\n console.log(job.id, job.status);\n}\n```\n\n## observe table changes\n\n```ts\nconst stop = store.observe('sessions', (sessions) => {\n console.log(`active sessions: ${sessions.length}`);\n});\n\nstore.disposalsignal.addeventlistener('abort', stop);\n```\n\n## bound helpers\n\n```ts\nconsole.log(await store.has('sessions', 'current'));\nconsole.log(await store.count('sessions'));\nconsole.log(await store.isempty('sessions'));\n\nconst [a, b] = await store.getmany('sessions', ['current', 'old']);\nconsole.log(await store.keys('sessions'));\nconsole.log(await store.deletemany('sessions', ['old', 'expired']));\n\nawait store.update('sessions', 'current', { token: 'fake updated token' });\nawait store.upsert('sessions', 'temp', (existing) => ({\n id: 'temp',\n token: existing?.token ?? 'generated',\n}));\n\nconst current = (await store.getall('sessions')).find((session) => session.id === 'current');\nvoid a, b, current;\n```\n\n## react hook\n\n```tsx\nimport { useeffect, usestate } from 'react';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function usetable<s extends anyschema, k extends keyof s & string>(\n store: keyvaluevaultstore<s>,\n table: k,\n): recordof<s, k>[] {\n const [rows, setrows] = usestate<recordof<s, k>[]>([]);\n\n useeffect(() => store.observe(table, setrows), [store, table]);\n return rows;\n}\n```\n\n## migration example\n\nobject stores and schema declared indexes are created automatically on upgrade. the `migrate` hook covers only what the schema cannot express, such as deleting a removed store or transforming old records.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\nconst userschema = s.object({ email: s.string().email(), id: s.number() });\n\nconst db = createindexeddb({\n name: 'app v2',\n version: 2,\n migrate({ db, oldversion, tx }) {\n // the 'users' store and its 'email' index already exist; drop a retired store.\n if (oldversion < 2 && db.objectstorenames.contains('legacy_sessions')) {\n tx.deleteobjectstore('legacy_sessions');\n }\n },\n schema: { users: table<{ id: number; email: string }>('id', { indexes: ['email'] }) },\n codecs: { users: userschema },\n});\n```\n\n## recipe examples\n\n [crud operations](./examples/crud.md)\n [ttl and pruning](./examples/ttl.md)\n [indexeddb batch transactions](./examples/batch.md)\n [indexeddb lazy iteration](./examples/iterate.md)\n [sqlite transactions and iteration](./examples/sqlite.md)\n [reactive tables with observe()](./examples/reactive.md)\n [validators and error handling](./examples/plugins.md)\n"
1532
+ "usage": " \ntitle: 'vault: usage guide'\ndescription: persist typed browser or sqlite data, observe table snapshots, and use atomic transactions with required durable codecs.\n \n\n[[toc]]\n\n## basic usage\n\ncreate a key value store with a schema and codecs, then write a typed row.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\ninterface preference {\n id: string;\n theme: 'dark' | 'light';\n}\n\nconst preferenceschema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { preferences: table<preference>('id') },\n codecs: { preferences: preferenceschema },\n});\n\nawait store.put('preferences', { id: 'theme', theme: 'dark' });\nconsole.log(await store.get('preferences', 'theme'));\n```\n\n## create a key value store\n\nlocalstorage and sessionstorage return `keyvaluevaultstore`; memory returns a `documentvaultstore` (it adds `batch()` and `iterate()`). they share portable string/number keys, bound helpers, fluent queries, ttl, and `observe()`. memory may omit codecs; web storage requires them. malformed storage envelopes are evicted lazily, while codec validation failures are surfaced without deleting persisted data.\n\nthe root entry is adapter free. import `creatememory` from `@vielzeug/vault/memory`, `createlocalstorage` from `@vielzeug/vault/local storage`, or `createsessionstorage` from `@vielzeug/vault/session storage`. import each adapter from its focused subpath so unused backends stay out of the bundle.\n\nuse a new storage name when upgrading from vault 1. old key and envelope formats are not read by vault 2.\n\n```ts\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { preferences: table<preference>('id') },\n codecs: { preferences: preferenceschema },\n});\n```\n\n## read and change records\n\nuse bound `update()` and `upsert()` methods for read modify write operations; no helper imports are required.\n\n```ts\nconst updated = await store.update('preferences', 'theme', { theme: 'light' });\n\nawait store.upsert('preferences', 'locale', (current) => ({\n id: 'locale',\n theme: current?.theme ?? 'dark',\n}));\n\nconsole.log(updated);\n```\n\n`update()` returns `undefined` for a missing key. `upsert()` always writes the record returned by its callback. document store methods run atomically; key value store methods are non atomic conveniences when multiple writers race.\n\n## iterate and filter records\n\nfilter the plain array returned by `getall()` for in memory selection, sorting, and pagination. use `iterate()` on a `documentvaultstore` for lazy cursor based traversal, and `getallbyindex()` on indexeddb for declared equality indexes.\n\n```ts\n// in memory selection over getall()\nconst themed = (await store.getall('preferences')).filter((preference) => preference.id.startswith('theme'));\n\n// document store: iterate lazily\nfor await (const pref of db.iterate('preferences')) {\n if (pref.id.startswith('theme')) console.log(pref);\n}\n```\n\nfor large tables, prefer `iterate()` on indexeddb or sqlite instead of materializing every record with `getall()`.\n\n## use ttl and pruning\n\nuse `ttl.*` helpers for expiring rows. call `pruneexpired()` to reclaim storage from stale rows that accumulate without reads; tables with removed rows publish fresh observer snapshots.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nawait store.put('preferences', { id: 'temporary', theme: 'dark' }, ttl.hours(1));\n\n// reclaim expired rows on a schedule owned by the application.\nconst pruneinterval = setinterval(() => store.pruneexpired(), ttl.hours(6));\nstore.disposalsignal.addeventlistener('abort', () => clearinterval(pruneinterval));\n```\n\n## observe a table\n\nuse `observe()` for current and future snapshots. notifications are revision ordered, and explicit ttl pruning publishes fresh snapshots for affected tables. tie subscription lifetime to an `abortsignal` when a component or request owns it.\n\n```ts\nconst controller = new abortcontroller();\n\nstore.observe(\n 'preferences',\n (preferences) => {\n console.log(preferences);\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\n```\n\n## use indexeddb for browser transactions\n\nchoose indexeddb when browser storage needs multiple writes to commit together or cursor iteration.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\nconst eventschema = s.object({ id: s.number(), type: s.string() });\nconst db = createindexeddb({\n name: 'app v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n codecs: { events: eventschema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\ntransaction contexts expose the same bound helpers; `tx.update()`, `tx.upsert()`, and `tx.deletemany()` run inside the enclosing transaction. only await `tx.*` operations inside a batch callback. do not retain the transaction context after the callback; later use throws `vaultscopeerror`. do not await timers, fetches, or other external asynchronous work because indexeddb can commit an inactive transaction.\n\n## use sqlite outside the browser\n\nimport sqlite from the opt in subpath so the browser root stays free of runtime drivers. vault never opens a connection or configures its sqlite process behavior for you.\n\n```ts\nimport { databasesync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createsqlite } from '@vielzeug/vault/sqlite';\n\nconst eventschema = s.object({ id: s.number(), type: s.string() });\nconst database = new databasesync('app.db', { timeout: 5_000 });\nconst store = createsqlite({\n database,\n name: 'app v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n codecs: { events: eventschema },\n});\n\nawait store.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nnode's `node:sqlite` api is experimental. bun's `bun:sqlite` `database` satisfies the same positional `exec()` and `prepare()` contract; configure wal from your application when the deployment needs it. deno does not include sqlite, but `jsr:@db/sqlite`'s `database` satisfies the same contract when its ffi, filesystem, and environment permissions are granted.\n\nsqlite stores serialize all access through the injected connection. `batch()` starts `begin immediate` and rolls back callback failures. while its callback runs, calls on any store sharing that connection reject rather than waiting behind the transaction; use `tx.*` instead. the underlying drivers are synchronous, so move large scans and writes to a worker or isolate when event loop latency matters.\n\n## store sqlite values and observe changes\n\nsqlite accepts any json compatible codec output. circular values, `bigint`, class instances, functions, and non finite numbers must be transformed by the codec before writing. number and string primary keys remain distinct.\n\n`observe()` sees mutations written through vault stores sharing the same injected connection after a commit. it cannot detect direct sql changes, writes from another process, or writes through another connection. the connection belongs to the caller by default; use `closeondispose: true` only when the store owns it.\n\n## handle indexeddb schema migrations\n\ndeclare indexeddb indexes in the schema. codecs must preserve each indexed field name and value in their encoded object. use `migrate` only for indexeddb version upgrades and mirror vault's fixed `value.<field>` index path.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb, type migrationfn } from '@vielzeug/vault/indexeddb';\n\nconst userschema = s.object({ id: s.number(), name: s.string() });\nconst schema = { users: table<{ id: number; name: string }>('id', { indexes: ['name'] }) };\nconst migrate: migrationfn = ({ db, oldversion, tx }) => {\n if (oldversion < 2 && db.objectstorenames.contains('users')) {\n tx.objectstore('users').createindex('name', 'value.name');\n }\n};\n\ncreateindexeddb({\n name: 'app v2',\n migrate,\n schema,\n version: 2,\n codecs: { users: userschema },\n});\n```\n\n## framework integration\n\n::: code group\n\n```ts [react]\nimport { useeffect, usestate } from 'react';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function usetable<s extends anyschema, k extends keyof s & string>(store: keyvaluevaultstore<s>, table: k) {\n const [rows, setrows] = usestate<recordof<s, k>[]>([]);\n\n useeffect(() => store.observe(table, setrows), [store, table]);\n return rows;\n}\n```\n\n```ts [vue 3]\nimport { onunmounted, shallowref } from 'vue';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function usetable<s extends anyschema, k extends keyof s & string>(store: keyvaluevaultstore<s>, table: k) {\n const rows = shallowref<recordof<s, k>[]>([]);\n const stop = store.observe(table, (next) => (rows.value = next));\n\n onunmounted(stop);\n return rows;\n}\n```\n\n```ts [svelte]\nimport { readable } from 'svelte/store';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function tablestore<s extends anyschema, k extends keyof s & string>(store: keyvaluevaultstore<s>, table: k) {\n return readable<recordof<s, k>[]>([], (set) => store.observe(table, set));\n}\n```\n\n:::\n\n## working with other vielzeug libraries\n\nkeep ripple signals as application state and persist selected changes through vault writes.\n\n## best practices\n\n define one schema per storage namespace.\n use string or finite number primary keys only.\n provide codecs for every durable adapter; pass spell or another parser schema directly when identity encoding is sufficient.\n use `observe()` for table snapshots.\n use indexeddb or sqlite for atomic work.\n keep external asynchronous work outside `batch()` callbacks.\n use `ttl.*` instead of raw durations.\n keep sqlite scans and writes off latency sensitive event loops.\n dispose stores when their owner ends.\n",
1533
+ "examples": " \ntitle: 'vault: examples'\ndescription: practical vault examples for browser storage, sqlite, ttl, transactions, observation, and framework integration.\n \n\n## browser key value store with ttl\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table, ttl } from '@vielzeug/vault';\nimport { createlocalstorage } from '@vielzeug/vault/local storage';\n\ninterface session {\n id: string;\n token: string;\n}\n\nconst sessionschema = s.object({ id: s.string(), token: s.string() });\nconst store = createlocalstorage({\n name: 'app v2',\n schema: { sessions: table<session>('id', { defaultttl: ttl.hours(1) }) },\n codecs: { sessions: sessionschema },\n});\n\nawait store.put('sessions', { id: 'current', token: 'fake token for docs' });\nconsole.log(await store.get('sessions', 'current'));\n```\n\n## indexeddb with transactions and iteration\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\ninterface event {\n id: number;\n type: string;\n createdat: number;\n}\n\nconst eventschema = s.object({ createdat: s.number(), id: s.number(), type: s.string() });\nconst db = createindexeddb({\n name: 'events',\n schema: { events: table<event>('id', { indexes: ['type'] }) },\n codecs: { events: eventschema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened', createdat: date.now() });\n await tx.put('events', { id: 2, type: 'saved', createdat: date.now() });\n});\n\nfor await (const event of db.iterate('events')) {\n console.log(event.type);\n}\n```\n\n## sqlite document store\n\n```ts\nimport { databasesync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createsqlite } from '@vielzeug/vault/sqlite';\n\ninterface job {\n id: string;\n status: 'queued' | 'running' | 'done';\n}\n\nconst jobschema = s.object({ id: s.string(), status: s.enum(['queued', 'running', 'done']) });\nconst database = new databasesync(':memory:');\nconst store = createsqlite({\n database,\n name: 'app',\n schema: { jobs: table<job>('id') },\n codecs: { jobs: jobschema },\n});\n\nawait store.batch(['jobs'], async (tx) => {\n await tx.put('jobs', { id: 'job 1', status: 'queued' });\n await tx.put('jobs', { id: 'job 2', status: 'running' });\n});\n\nfor await (const job of store.iterate('jobs')) {\n console.log(job.id, job.status);\n}\n```\n\n## observe table changes\n\n```ts\nconst stop = store.observe('sessions', (sessions) => {\n console.log(`active sessions: ${sessions.length}`);\n});\n\nstore.disposalsignal.addeventlistener('abort', stop);\n```\n\n## bound helpers\n\n```ts\nconsole.log(await store.has('sessions', 'current'));\nconsole.log(await store.count('sessions'));\nconsole.log(await store.isempty('sessions'));\n\nconst [a, b] = await store.getmany('sessions', ['current', 'old']);\nconsole.log(await store.keys('sessions'));\nconsole.log(await store.deletemany('sessions', ['old', 'expired']));\n\nawait store.update('sessions', 'current', { token: 'fake updated token' });\nawait store.upsert('sessions', 'temp', (existing) => ({\n id: 'temp',\n token: existing?.token ?? 'generated',\n}));\n\nconst current = (await store.getall('sessions')).find((session) => session.id === 'current');\nvoid a, b, current;\n```\n\n## react hook\n\n```tsx\nimport { useeffect, usestate } from 'react';\n\nimport type { anyschema, keyvaluevaultstore, recordof } from '@vielzeug/vault';\n\nexport function usetable<s extends anyschema, k extends keyof s & string>(\n store: keyvaluevaultstore<s>,\n table: k,\n): recordof<s, k>[] {\n const [rows, setrows] = usestate<recordof<s, k>[]>([]);\n\n useeffect(() => store.observe(table, setrows), [store, table]);\n return rows;\n}\n```\n\n## migration example\n\nobject stores and schema declared indexes are created automatically on upgrade. the `migrate` hook covers only what the schema cannot express, such as deleting a removed store or transforming old records.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createindexeddb } from '@vielzeug/vault/indexeddb';\n\nconst userschema = s.object({ email: s.string().email(), id: s.number() });\n\nconst db = createindexeddb({\n name: 'app v2',\n version: 2,\n migrate({ db, oldversion, tx }) {\n // the 'users' store and its 'email' index already exist; drop a retired store.\n if (oldversion < 2 && db.objectstorenames.contains('legacy_sessions')) {\n tx.deleteobjectstore('legacy_sessions');\n }\n },\n schema: { users: table<{ id: number; email: string }>('id', { indexes: ['email'] }) },\n codecs: { users: userschema },\n});\n```\n\n## recipe examples\n\n [crud operations](./examples/crud.md)\n [ttl and pruning](./examples/ttl.md)\n [indexeddb batch transactions](./examples/batch.md)\n [indexeddb lazy iteration](./examples/iterate.md)\n [sqlite transactions and iteration](./examples/sqlite.md)\n [reactive tables with observe()](./examples/reactive.md)\n [validators and error handling](./examples/plugins.md)\n"
1534
1534
  },
1535
1535
  "examples": [
1536
1536
  {