@vielzeug/codex 26.11.9 → 26.11.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  {
2
- "apiSource": "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",
2
+ "apiSource": "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",
3
3
  "docs": {
4
- "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",
5
- "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",
6
- "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",
7
- "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"
4
+ "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",
5
+ "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",
6
+ "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",
7
+ "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"
8
8
  },
9
9
  "examples": [
10
10
  {
@@ -34,7 +34,7 @@
34
34
  },
35
35
  {
36
36
  "id": "descriptor-roundtrip",
37
- "code": "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)",
37
+ "code": "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",
38
38
  "name": "Declarative Definition Export"
39
39
  },
40
40
  {
@@ -63,18 +63,18 @@
63
63
  "name": "Number Validation"
64
64
  },
65
65
  {
66
- "id": "object-defaults",
67
- "code": "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",
68
- "name": "Object Defaults"
66
+ "id": "object-composition",
67
+ "code": "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",
68
+ "name": "Object Composition"
69
69
  },
70
70
  {
71
- "id": "object-merge",
72
- "code": "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",
73
- "name": "Object Merge & Aliases"
71
+ "id": "object-defaults",
72
+ "code": "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",
73
+ "name": "Object Defaults"
74
74
  },
75
75
  {
76
76
  "id": "optional-nullable",
77
- "code": "// 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))",
77
+ "code": "// 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))",
78
78
  "name": "Optional and Nullable Fields"
79
79
  },
80
80
  {
@@ -94,34 +94,33 @@
94
94
  }
95
95
  ],
96
96
  "typeSignatures": {
97
- "AnySchema": "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';",
98
- "CheckContext": "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';",
99
- "FlatError": "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';",
100
- "FlatErrorFirst": "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';",
101
- "Infer": "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';",
102
- "InferInput": "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';",
103
- "InferOutput": "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';",
104
- "Issue": "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';",
105
- "IssuePath": "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';",
106
- "IssuePathSegment": "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';",
107
- "JsonSchema": "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';",
108
- "MessageFn": "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';",
109
- "Messages": "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';",
110
- "ParseContext": "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';",
111
- "ParseResult": "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';",
112
- "SchemaDescriptor": "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';",
113
- "StandardSchemaV1": "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';",
114
- "SyncParsable": "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';",
115
- "ValidateResult": "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';",
116
- "ErrorCode": "export { ErrorCode, joinIssuePath, Schema, SpellDefinitionError, SpellError, SpellValidationError } from './core';",
117
- "joinIssuePath": "export { ErrorCode, joinIssuePath, Schema, SpellDefinitionError, SpellError, SpellValidationError } from './core';",
118
- "Schema": "export { ErrorCode, joinIssuePath, Schema, SpellDefinitionError, SpellError, SpellValidationError } from './core';",
119
- "SpellDefinitionError": "export { ErrorCode, joinIssuePath, Schema, SpellDefinitionError, SpellError, SpellValidationError } from './core';",
120
- "SpellError": "export { ErrorCode, joinIssuePath, Schema, SpellDefinitionError, SpellError, SpellValidationError } from './core';",
121
- "SpellValidationError": "export { ErrorCode, joinIssuePath, Schema, SpellDefinitionError, SpellError, SpellValidationError } from './core';",
122
- "createParseContext": "export { createParseContext, type DeepPartial } from './messages';",
123
- "DeepPartial": "export { createParseContext, type DeepPartial } from './messages';",
97
+ "FlatError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
98
+ "FlatErrorFirst": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
99
+ "joinIssuePath": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
100
+ "SpellDefinitionError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
101
+ "SpellError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
102
+ "SpellValidationError": "export {\n type FlatError,\n type FlatErrorFirst,\n joinIssuePath,\n SpellDefinitionError,\n SpellError,\n SpellValidationError,\n} from './errors';",
103
+ "createParseContext": "export { createParseContext, type DeepPartial, type Messages } from './messages';",
104
+ "DeepPartial": "export { createParseContext, type DeepPartial, type Messages } from './messages';",
105
+ "Messages": "export { createParseContext, type DeepPartial, type Messages } from './messages';",
124
106
  "s": "export { s } from './s';",
125
- "tolerate": "export { tolerate } from './tolerate';"
107
+ "Schema": "export { Schema } from './schema';",
108
+ "AnySchema": "export {\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';",
109
+ "CheckContext": "export {\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';",
110
+ "ErrorCode": "export {\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';",
111
+ "Infer": "export {\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';",
112
+ "InferInput": "export {\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';",
113
+ "InferOutput": "export {\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';",
114
+ "Issue": "export {\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';",
115
+ "IssuePath": "export {\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';",
116
+ "IssuePathSegment": "export {\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';",
117
+ "MessageFn": "export {\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';",
118
+ "ParseContext": "export {\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';",
119
+ "ParseResult": "export {\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';",
120
+ "PatternDescriptor": "export {\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';",
121
+ "SchemaDescriptor": "export {\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';",
122
+ "SchemaKind": "export {\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';",
123
+ "StandardSchemaV1": "export {\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';",
124
+ "ValidateResult": "export {\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';"
126
125
  }
127
126
  }
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "apiSource": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';\nexport { ttl } from './ttl';\nexport type {\n AnySchema,\n CodecInput,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n RecordCodec,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableCodecs,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';\nexport { table, validatorCodec } from './types';\n",
3
3
  "docs": {
4
- "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",
4
+ "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",
5
5
  "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",
6
- "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",
7
- "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"
6
+ "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",
7
+ "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"
8
8
  },
9
9
  "examples": [
10
10
  {