@vielzeug/codex 26.11.8 → 26.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  {
2
- "apiSource": "// Public root surface of @vielzeug/sigil. Every public export goes through this file.\nexport { drawToCanvas } from './canvas';\nexport { encodeQr, qrCapacity } from './encode';\nexport {\n SigilCapacityError,\n SigilDisposedError,\n SigilError,\n SigilOptionError,\n SigilPermissionError,\n SigilUnsupportedError,\n} from './errors';\nexport { createQrScanner, detectQr, isQrScanSupported, qrScanSupport } from './scan';\nexport { toSvg } from './svg';\nexport type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';\n",
2
+ "apiSource": "// Public root surface of @vielzeug/sigil. Every public export goes through this file.\nexport { drawToCanvas } from './canvas';\nexport { encodeQr, qrCapacity } from './encode';\nexport {\n SigilCapacityError,\n SigilDisposedError,\n SigilError,\n SigilOptionError,\n SigilPermissionError,\n SigilUnsupportedError,\n} from './errors';\nexport { createQrScanner, detectQr, isQrScanSupported, qrScanSupport } from './scan';\nexport { toSvg } from './svg';\nexport type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';\n",
3
3
  "docs": {
4
4
  "index": "---\ntitle: 'Sigil: QR code generation and scanning'\ndescription: 'QR code generation and scanning: pure matrix encoder, SVG and canvas renderers, native BarcodeDetector scanning'\npackage: sigil\ncategory: utilities\nkeywords: [qr, qrcode, barcode, encoder, scanner, svg, canvas, barcodedetector, pairing]\nexports: [encodeQr, toSvg, createQrScanner, qrCapacity, detectQr]\nrelated: [mesh, refine]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"sigil\" />\n\n## Why Sigil?\n\nQR workflows usually pull in a general-purpose barcode library that renders to canvas and guesses at colors, or a from-scratch decoder you do not need. Sigil is a pure, zero-dependency encoder (numeric, alphanumeric, and byte modes; versions 1–40; all four error-correction levels; automatic mask selection) with renderers that stay out of the way: an SVG string that themes with CSS, and a canvas painter for print/bitmap flows. Scanning is a thin lifecycle wrapper over the platform's native `BarcodeDetector`, so there is no decoder weight and no polyfill to ship.\n\n```ts\n// Before: a QR library per concern, canvas-only output, hardcoded colors\nimport QRCode from 'qrcode';\nconst dataUrl = await QRCode.toDataURL(text, { width: 256, color: { dark: '#000' } });\nimg.src = dataUrl; // raster, fixed colors, no theme support\n\n// After: encode once, render anywhere\nimport { encodeQr, toSvg } from '@vielzeug/sigil';\nconst matrix = encodeQr(text); // smallest version that fits, auto mask\nelement.innerHTML = toSvg(matrix); // currentColor modules: themes with CSS\n```\n\n| Feature | Sigil | `qrcode` (node-style) | `jsqr` |\n| -------------------- | ------------------------------------------------- | ---------------------------------------- | ------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"sigil\" type=\"size\" /> | ~100 kB+ | decoder only |\n| Runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> none | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> none |\n| Output | Matrix, SVG string, canvas | Canvas/DataURL/UTF-8 | N/A |\n| Themeable output | `currentColor` by default | Hardcoded color strings | N/A |\n| Scanning | Native `BarcodeDetector` wrapper | <ore-icon name=\"x\" size=\"16\"></ore-icon> | Pure-JS decoder |\n| SSR-safe import | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Sigil when** you need QR output that themes with your UI (SVG/`currentColor`), a minimal encoder with no runtime dependencies, or a scanner that uses the platform decoder instead of shipping one.\n\n**Consider `jsqr`-style decoding when** you must scan in browsers without `BarcodeDetector`: sigil reports `SigilUnsupportedError` rather than bundling a fallback decoder.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/sigil\n```\n\n```sh [npm]\nnpm install @vielzeug/sigil\n```\n\n```sh [yarn]\nyarn add @vielzeug/sigil\n```\n\n:::\n\n## Quick Start\n\nEncode to an SVG string: works in Node and the browser:\n\n```ts\nimport { encodeQr, qrCapacity, toSvg } from '@vielzeug/sigil';\n\nconst payload = 'https://vielzeug.dev';\nconst matrix = encodeQr(payload, { errorCorrection: 'M' });\ndocument.querySelector('#qr').innerHTML = toSvg(matrix, { label: 'Vielzeug link' });\n```\n\nScan with the camera (browser only: see support notes in the usage guide):\n\n```ts\nimport { createQrScanner } from '@vielzeug/sigil';\n\nconst video = document.querySelector('video');\nconst scanner = createQrScanner({ video });\nscanner.onResult((result) => {\n console.log('scanned:', result.value); // once: true stops after first decode\n});\nawait scanner.start(); // throws SigilUnsupportedError / SigilPermissionError\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `encodeQr`: pure matrix encoder: numeric/alphanumeric/byte modes, versions 1–40, EC levels L/M/Q/H, automatic or forced mask\n- `qrCapacity`: byte capacity per version/mode/level, for pre-flight validation\n- `toSvg`: compact path-merged SVG string; `currentColor` modules, `<title>` + `role=\"img\"` built in\n- `drawToCanvas`: bitmap rendering with DPR-aware scaling for print and download flows\n- `detectQr`: one-shot detection on any `ImageBitmapSource`\n- `createQrScanner`: camera scan loop with `once` mode, status events, `tap()` observability, and strict disposal\n- `isQrScanSupported`/`qrScanSupport`: sync and async feature detection that never assumes\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md): encoding modes, capacity, rendering, scanning, and testing\n- [API Reference](./api.md): every export, option, type, and error\n- [Examples](./examples.md): copy-paste recipes, including pairing two devices with `meshQrCodec`\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Mesh](../mesh/): backendless P2P sessions; `meshQrCodec` produces compact QR-friendly pairing payloads\n- [Refine](../refine/): `ore-qr-code` and `ore-qr-scanner` wrap sigil in ready-made, themeable components\n\n</div>\n\n<!-- markdownlint-enable -->\n",
5
- "api": "---\ntitle: 'Sigil: API Reference'\ndescription: 'Public API of @vielzeug/sigil: encoder, renderers, scanner, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ------------------- | -------------------------------------- | ------------- | -------------------------------------------------------------------- |\n| `encodeQr` | Encode a payload into a `QrMatrix` | Sync | Throws `SigilCapacityError` over capacity |\n| `qrCapacity` | Payload limit for a version/level/mode | Sync | Returns _characters_ for numeric/alphanumeric, _bytes_ for byte mode |\n| `toSvg` | Render a matrix as an SVG string | Sync | Escapes `dark`/`light` as raw CSS: pass values, not markup |\n| `drawToCanvas` | Paint a matrix onto a canvas | Sync | Browser only; resizes the canvas for DPR |\n| `detectQr` | One-shot detection on an image source | Async | Throws `SigilUnsupportedError` without `BarcodeDetector` |\n| `createQrScanner` | Camera scan loop | Async (start) | Must `dispose()`; camera tracks persist otherwise |\n| `isQrScanSupported` | Sync feature check | Sync | Constructor exists ≠ `qr_code` supported: prefer `qrScanSupport()` |\n| `qrScanSupport` | Async feature check incl. formats | Async | Never assume support per browser/version |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ------------------------- |\n| `@vielzeug/sigil` | Complete public Sigil API |\n\n## Encoding\n\n### `encodeQr(data, options?)`\n\n```ts\nfunction encodeQr(data: string | Uint8Array, options?: QrEncodeOptions): QrMatrix;\n```\n\nEncodes `data` into a QR symbol. Picks the most compact mode covering the whole input, the smallest fitting version, and the lowest-penalty mask.\n\n| Parameter | Type | Default | Description |\n| ------------------------- | -------------------------- | ------- | ------------------------------------------------------------------------------ |\n| `data` | `string \\| Uint8Array` | N/A | Payload; `Uint8Array` is raw binary and always byte mode (no UTF-8 round-trip) |\n| `options.errorCorrection` | `'L' \\| 'M' \\| 'Q' \\| 'H'` | `'M'` | Error-correction level |\n| `options.version` | `1–40` | auto | Pin the version; throws if payload can't fit |\n| `options.minVersion` | `1–40` | `1` | Smallest acceptable version |\n| `options.mode` | `QrMode` | auto | Force a segment mode |\n| `options.mask` | `0–7` | auto | Force the mask (test vectors only) |\n\n**Returns** a frozen `QrMatrix` with `size`, `version`, `mode`, `errorCorrection`, `mask`, and `get(x, y)`.\n\n**Throws** `SigilCapacityError` (payload exceeds capacity), `SigilOptionError` (invalid mode/version/mask combination).\n\n```ts\nimport { encodeQr } from '@vielzeug/sigil';\n\nconst matrix = encodeQr('HELLO WORLD', { errorCorrection: 'Q' });\nmatrix.size; // 21 (v1)\nmatrix.get(0, 0); // finder pattern → true\n```\n\n---\n\n### `qrCapacity(version, errorCorrection, mode)`\n\n```ts\nfunction qrCapacity(version: number, errorCorrection: QrErrorCorrection, mode: QrMode): number;\n```\n\nReturns the payload limit: characters for `numeric`/`alphanumeric`, bytes for `byte`.\n\n```ts\nqrCapacity(1, 'M', 'byte'); // → 14\nqrCapacity(40, 'L', 'numeric'); // → 7089\n```\n\n## Rendering\n\n### `toSvg(matrix, options?)`\n\n```ts\nfunction toSvg(matrix: QrMatrix, options?: QrSvgOptions): string;\n```\n\nReturns a complete `<svg>` string. Runs in any environment: no DOM required.\n\n| Parameter | Type | Default | Description |\n| ---------------------- | --------- | ---------------- | ---------------------------------------------- |\n| `options.dark` | `string` | `'currentColor'` | Dark module color |\n| `options.light` | `string` | `'transparent'` | Background color |\n| `options.margin` | `number` | `4` | Quiet-zone modules |\n| `options.scale` | `number` | `1` | User units per module |\n| `options.optimizePath` | `boolean` | `true` | Merge dark runs into one `<path>` |\n| `options.label` | `string` | N/A | `<title>` + `aria-label`; enables `role=\"img\"` |\n\n```ts\nconst svg = toSvg(matrix, { label: 'Pairing code', dark: 'var(--qr-dark)' });\n```\n\n---\n\n### `drawToCanvas(matrix, canvas, options?)`: browser only\n\n```ts\nfunction drawToCanvas(matrix: QrMatrix, canvas: HTMLCanvasElement, options?: QrCanvasOptions): number;\n```\n\nPaints the matrix and returns the CSS-pixel edge length. Sizes the backing store for `devicePixelRatio` so output stays crisp on retina displays.\n\n| Parameter | Type | Default | Description |\n| -------------------------------- | -------- | ------------------- | ------------------ |\n| `options.scale` | `number` | `1` | CSS px per module |\n| `options.margin` | `number` | `4` | Quiet-zone modules |\n| `options.dark` / `options.light` | `string` | `'#000'` / `'#fff'` | Fill colors |\n\n## Scanning (browser only)\n\n### `createQrScanner(options)`\n\n```ts\nfunction createQrScanner(options: QrScannerOptions): QrScanner;\n```\n\nCreates a camera scan loop around the native `BarcodeDetector`.\n\n| Parameter | Type | Default | Description |\n| ---------------------- | ------------------------------------ | ------------------------------- | ------------------------------------------------------------------- |\n| `options.video` | `HTMLVideoElement` | N/A | Element the stream attaches to (needs `autoplay playsinline muted`) |\n| `options.constraints` | `MediaTrackConstraints` | `{ facingMode: 'environment' }` | `getUserMedia` video constraints |\n| `options.intervalMs` | `number` | `200` | Minimum ms between detect passes |\n| `options.once` | `boolean` | `true` | Stop after the first result |\n| `options.signal` | `AbortSignal` | N/A | Abort → `stop()` |\n| `options.detector` | `QrDetector` | native | Injected detector for tests |\n| `options.mediaDevices` | `Pick<MediaDevices, 'getUserMedia'>` | `navigator.mediaDevices` | Injected media for tests |\n\n**Returns** a `QrScanner`:\n\n| Member | Signature | Description |\n| -------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `start()` | `() => Promise<void>` | Request camera, attach stream, run the detect loop. Rejects with `SigilUnsupportedError` / `SigilPermissionError`. `stop()`/`dispose()` while the camera prompt is pending win: the late stream is released and the call resolves |\n| `stop()` | `() => void` | Stop the loop and tracks, return to `'idle'`; instance stays usable |\n| `onResult(handler)` | `(handler) => () => void` | Decode results; returns unsubscribe |\n| `tap(handler, options?)` | `(handler, { signal? }) => () => void` | Observe `SigilEvent`s; handler errors are swallowed |\n| `status` | `QrScannerStatus` | `'idle' \\| 'starting' \\| 'scanning' \\| 'disposed'` |\n| `dispose()` / `[Symbol.dispose]` | `() => void` | Terminal teardown; `disposalSignal` aborts |\n| `disposed` | `boolean` | Whether `dispose()` ran |\n\n```ts\nconst scanner = createQrScanner({ video });\nconst off = scanner.onResult(({ value }) => console.log(value));\nawait scanner.start();\n```\n\n---\n\n### `detectQr(source, options?)`\n\n```ts\nfunction detectQr(\n source: ImageBitmapSource,\n options?: { signal?: AbortSignal; detector?: QrDetector },\n): Promise<QrScanResult | null>;\n```\n\nSingle-pass detection on an image source. Returns the first result's `{ value, cornerPoints }`, or `null` when nothing decodes. Throws `SigilUnsupportedError` when no detector is available.\n\n---\n\n### `isQrScanSupported()` / `qrScanSupport()`\n\n```ts\nfunction isQrScanSupported(): boolean;\nfunction qrScanSupport(): Promise<boolean>;\n```\n\n`isQrScanSupported` checks the `BarcodeDetector` constructor synchronously. `qrScanSupport` additionally asks `getSupportedFormats()` for `'qr_code'`: use it before showing scan affordances.\n\n## Types\n\n```ts\ntype QrErrorCorrection = 'L' | 'M' | 'Q' | 'H';\ntype QrMode = 'numeric' | 'alphanumeric' | 'byte';\ntype QrScannerStatus = 'idle' | 'starting' | 'scanning' | 'disposed';\n\ninterface QrMatrix {\n readonly errorCorrection: QrErrorCorrection;\n readonly mask: number;\n readonly mode: QrMode;\n readonly size: number; // 17 + 4 * version\n readonly version: number; // 1–40\n get(x: number, y: number): boolean; // true = dark; false outside bounds\n}\n\ninterface QrScanResult {\n readonly cornerPoints?: ReadonlyArray<{ readonly x: number; readonly y: number }>;\n readonly value: string;\n}\n\ninterface QrDetector {\n detect(\n source: ImageBitmapSource,\n ): Promise<ReadonlyArray<{ rawValue: string; cornerPoints?: ReadonlyArray<{ x: number; y: number }> }>>;\n}\n\ntype SigilEvent =\n | { readonly type: 'status-change'; readonly status: QrScannerStatus }\n | { readonly type: 'detect'; readonly value: string; readonly elapsedMs: number }\n | { readonly type: 'frame-skipped'; readonly reason: 'not-ready' | 'busy' }\n | { readonly type: 'error'; readonly error: SigilError }\n | { readonly type: 'dispose' };\n```\n\n`QrEncodeOptions`, `QrSvgOptions`, `QrCanvasOptions`, `QrScannerOptions`, and `QrScanner` are documented under their factories above.\n\n## Errors\n\n| Class | Trigger | Notable members |\n| ----------------------- | -------------------------------------------------------------------------------- | ------------------------------ |\n| `SigilError` | Base class for all sigil errors | N/A |\n| `SigilCapacityError` | Payload exceeds the version/mode limit | `bytes`, `maxBytes`, `version` |\n| `SigilOptionError` | Invalid option combination (forced mode can't represent input, bad mask/version) | N/A |\n| `SigilUnsupportedError` | `BarcodeDetector`/`getUserMedia`/canvas 2D context missing | N/A |\n| `SigilPermissionError` | Camera `NotAllowedError` | N/A |\n| `SigilDisposedError` | `start()` on a disposed scanner | N/A |\n\nAll carry `cause` when wrapping a platform error.\n",
5
+ "api": "---\ntitle: 'Sigil: API Reference'\ndescription: 'Public API of @vielzeug/sigil: encoder, renderers, scanner, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ------------------- | -------------------------------------- | ------------- | -------------------------------------------------------------------- |\n| `encodeQr` | Encode a payload into a `QrMatrix` | Sync | Throws `SigilCapacityError` over capacity |\n| `qrCapacity` | Payload limit for a version/level/mode | Sync | Returns _characters_ for numeric/alphanumeric, _bytes_ for byte mode |\n| `toSvg` | Render a matrix as an SVG string | Sync | Escapes `dark`/`light` as raw CSS: pass values, not markup |\n| `drawToCanvas` | Paint a matrix onto a canvas | Sync | Browser only; resizes the canvas for DPR |\n| `detectQr` | One-shot detection on an image source | Async | Throws `SigilUnsupportedError` without `BarcodeDetector` |\n| `createQrScanner` | Camera scan loop | Async (start) | Must `dispose()`; camera tracks persist otherwise |\n| `isQrScanSupported` | Sync feature check | Sync | Constructor exists ≠ `qr_code` supported: prefer `qrScanSupport()` |\n| `qrScanSupport` | Async feature check incl. formats | Async | Never assume support per browser/version |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ------------------------- |\n| `@vielzeug/sigil` | Complete public Sigil API |\n\n## Encoding\n\n### `encodeQr(data, options?)`\n\n```ts\nfunction encodeQr(data: string | Uint8Array, options?: QrEncodeOptions): QrMatrix;\n```\n\nEncodes `data` into a QR symbol. Picks the most compact mode covering the whole input, the smallest fitting version, and the lowest-penalty mask.\n\n| Parameter | Type | Default | Description |\n| ------------------------- | -------------------------- | ------- | ------------------------------------------------------------------------------ |\n| `data` | `string \\| Uint8Array` | N/A | Payload; `Uint8Array` is raw binary and always byte mode (no UTF-8 round-trip) |\n| `options.errorCorrection` | `'L' \\| 'M' \\| 'Q' \\| 'H'` | `'M'` | Error-correction level |\n| `options.version` | `1–40` | auto | Pin the version; throws if payload can't fit |\n| `options.minVersion` | `1–40` | `1` | Smallest acceptable version |\n| `options.mode` | `QrMode` | auto | Force a segment mode |\n| `options.mask` | `0–7` | auto | Force the mask (test vectors only) |\n\n**Returns** a frozen `QrMatrix` with `size`, `version`, `mode`, `errorCorrection`, `mask`, and `get(x, y)`.\n\n**Throws** `SigilCapacityError` (payload exceeds capacity), `SigilOptionError` (invalid mode/version/mask combination).\n\n```ts\nimport { encodeQr } from '@vielzeug/sigil';\n\nconst matrix = encodeQr('HELLO WORLD', { errorCorrection: 'Q' });\nmatrix.size; // 21 (v1)\nmatrix.get(0, 0); // finder pattern → true\n```\n\n---\n\n### `qrCapacity(version, errorCorrection, mode)`\n\n```ts\nfunction qrCapacity(version: number, errorCorrection: QrErrorCorrection, mode: QrMode): number;\n```\n\nReturns the payload limit: characters for `numeric`/`alphanumeric`, bytes for `byte`.\n\n```ts\nqrCapacity(1, 'M', 'byte'); // → 14\nqrCapacity(40, 'L', 'numeric'); // → 7089\n```\n\n## Rendering\n\n### `toSvg(matrix, options?)`\n\n```ts\nfunction toSvg(matrix: QrMatrix, options?: QrSvgOptions): string;\n```\n\nReturns a complete `<svg>` string. Runs in any environment: no DOM required.\n\n| Parameter | Type | Default | Description |\n| ---------------------- | ---------------------- | ---------------- | -------------------------------------------------- |\n| `options.dark` | `string` | `'currentColor'` | Dark module color (ignored when `gradient` is set) |\n| `options.light` | `string` | `'transparent'` | Background color |\n| `options.margin` | `number` | `4` | Quiet-zone modules |\n| `options.scale` | `number` | `1` | User units per module |\n| `options.optimizePath` | `boolean` | `true` | Merge dark runs into one `<path>` |\n| `options.label` | `string` | N/A | `<title>` + `aria-label`; enables `role=\"img\"` |\n| `options.dotStyle` | `QrDotStyle` | `'square'` | Data-module shape; finder zones stay square |\n| `options.gradient` | `QrSvgGradientOptions` | N/A | Two-stop linear gradient replacing module paint |\n| `options.image` | `QrSvgImageOptions` | N/A | Centered logo; modules under it are not painted |\n\n```ts\ntype QrDotStyle = 'dots' | 'rounded' | 'square';\n\ntype QrSvgGradientOptions = {\n from: string; // first stop\n to: string; // second stop\n angle?: number; // degrees, 0 = top-to-bottom (default)\n id?: string; // stable <defs> id; auto-unique otherwise\n};\n\ntype QrSvgImageOptions = {\n href: string; // logo URL (resolved by the consumer, embedded verbatim)\n size?: number; // fraction of the code edge (default 0.22)\n spacing?: number; // clear gap in modules around the logo (default 1)\n background?: string; // optional patch behind the logo\n radius?: number; // corner radius of the background patch\n};\n```\n\nStyling output stays scanner-friendly: finder patterns never lose their square shape, and the carve around a logo is a gap, not painted noise. Prefer `errorCorrection: 'H'` when overlaying a logo.\n\n```ts\nconst svg = toSvg(matrix, { label: 'Pairing code', dark: 'var(--qr-dark)' });\nconst styled = toSvg(matrix, { dotStyle: 'rounded', gradient: { from: '#0ea5e9', to: '#7c3aed' } });\n```\n\n---\n\n### `drawToCanvas(matrix, canvas, options?)`: browser only\n\n```ts\nfunction drawToCanvas(matrix: QrMatrix, canvas: HTMLCanvasElement, options?: QrCanvasOptions): number;\n```\n\nPaints the matrix and returns the CSS-pixel edge length. Sizes the backing store for `devicePixelRatio` so output stays crisp on retina displays.\n\n| Parameter | Type | Default | Description |\n| -------------------------------- | -------- | ------------------- | ------------------ |\n| `options.scale` | `number` | `1` | CSS px per module |\n| `options.margin` | `number` | `4` | Quiet-zone modules |\n| `options.dark` / `options.light` | `string` | `'#000'` / `'#fff'` | Fill colors |\n\n## Scanning (browser only)\n\n### `createQrScanner(options)`\n\n```ts\nfunction createQrScanner(options: QrScannerOptions): QrScanner;\n```\n\nCreates a camera scan loop around the native `BarcodeDetector`.\n\n| Parameter | Type | Default | Description |\n| ---------------------- | ------------------------------------ | ------------------------------- | ------------------------------------------------------------------- |\n| `options.video` | `HTMLVideoElement` | N/A | Element the stream attaches to (needs `autoplay playsinline muted`) |\n| `options.constraints` | `MediaTrackConstraints` | `{ facingMode: 'environment' }` | `getUserMedia` video constraints |\n| `options.intervalMs` | `number` | `200` | Minimum ms between detect passes |\n| `options.once` | `boolean` | `true` | Stop after the first result |\n| `options.signal` | `AbortSignal` | N/A | Abort → `stop()` |\n| `options.detector` | `QrDetector` | native | Injected detector for tests |\n| `options.mediaDevices` | `Pick<MediaDevices, 'getUserMedia'>` | `navigator.mediaDevices` | Injected media for tests |\n\n**Returns** a `QrScanner`:\n\n| Member | Signature | Description |\n| -------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `start()` | `() => Promise<void>` | Request camera, attach stream, run the detect loop. Rejects with `SigilUnsupportedError` / `SigilPermissionError`. `stop()`/`dispose()` while the camera prompt is pending win: the late stream is released and the call resolves |\n| `stop()` | `() => void` | Stop the loop and tracks, return to `'idle'`; instance stays usable |\n| `onResult(handler)` | `(handler) => () => void` | Decode results; returns unsubscribe |\n| `tap(handler, options?)` | `(handler, { signal? }) => () => void` | Observe `SigilEvent`s; handler errors are swallowed |\n| `status` | `QrScannerStatus` | `'idle' \\| 'starting' \\| 'scanning' \\| 'disposed'` |\n| `dispose()` / `[Symbol.dispose]` | `() => void` | Terminal teardown; `disposalSignal` aborts |\n| `disposed` | `boolean` | Whether `dispose()` ran |\n\n```ts\nconst scanner = createQrScanner({ video });\nconst off = scanner.onResult(({ value }) => console.log(value));\nawait scanner.start();\n```\n\n---\n\n### `detectQr(source, options?)`\n\n```ts\nfunction detectQr(\n source: ImageBitmapSource,\n options?: { signal?: AbortSignal; detector?: QrDetector },\n): Promise<QrScanResult | null>;\n```\n\nSingle-pass detection on an image source. Returns the first result's `{ value, cornerPoints }`, or `null` when nothing decodes. Throws `SigilUnsupportedError` when no detector is available.\n\n---\n\n### `isQrScanSupported()` / `qrScanSupport()`\n\n```ts\nfunction isQrScanSupported(): boolean;\nfunction qrScanSupport(): Promise<boolean>;\n```\n\n`isQrScanSupported` checks the `BarcodeDetector` constructor synchronously. `qrScanSupport` additionally asks `getSupportedFormats()` for `'qr_code'`: use it before showing scan affordances.\n\n## Types\n\n```ts\ntype QrErrorCorrection = 'L' | 'M' | 'Q' | 'H';\ntype QrMode = 'numeric' | 'alphanumeric' | 'byte';\ntype QrScannerStatus = 'idle' | 'starting' | 'scanning' | 'disposed';\n\ninterface QrMatrix {\n readonly errorCorrection: QrErrorCorrection;\n readonly mask: number;\n readonly mode: QrMode;\n readonly size: number; // 17 + 4 * version\n readonly version: number; // 1–40\n get(x: number, y: number): boolean; // true = dark; false outside bounds\n}\n\ninterface QrScanResult {\n readonly cornerPoints?: ReadonlyArray<{ readonly x: number; readonly y: number }>;\n readonly value: string;\n}\n\ninterface QrDetector {\n detect(\n source: ImageBitmapSource,\n ): Promise<ReadonlyArray<{ rawValue: string; cornerPoints?: ReadonlyArray<{ x: number; y: number }> }>>;\n}\n\ntype SigilEvent =\n | { readonly type: 'status-change'; readonly status: QrScannerStatus }\n | { readonly type: 'detect'; readonly value: string; readonly elapsedMs: number }\n | { readonly type: 'frame-skipped'; readonly reason: 'not-ready' | 'busy' }\n | { readonly type: 'error'; readonly error: SigilError }\n | { readonly type: 'dispose' };\n```\n\n`QrEncodeOptions`, `QrSvgOptions`, `QrCanvasOptions`, `QrScannerOptions`, and `QrScanner` are documented under their factories above. `QrDotStyle`, `QrSvgGradientOptions`, and `QrSvgImageOptions` are documented under `toSvg`.\n\n## Errors\n\n| Class | Trigger | Notable members |\n| ----------------------- | -------------------------------------------------------------------------------- | ------------------------------ |\n| `SigilError` | Base class for all sigil errors | N/A |\n| `SigilCapacityError` | Payload exceeds the version/mode limit | `bytes`, `maxBytes`, `version` |\n| `SigilOptionError` | Invalid option combination (forced mode can't represent input, bad mask/version) | N/A |\n| `SigilUnsupportedError` | `BarcodeDetector`/`getUserMedia`/canvas 2D context missing | N/A |\n| `SigilPermissionError` | Camera `NotAllowedError` | N/A |\n| `SigilDisposedError` | `start()` on a disposed scanner | N/A |\n\nAll carry `cause` when wrapping a platform error.\n",
6
6
  "usage": "---\ntitle: 'Sigil: Usage Guide'\ndescription: Encoding modes, capacity checks, SVG/canvas rendering, camera scanning, and testing for @vielzeug/sigil.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`encodeQr` produces a `QrMatrix`: a frozen square of dark/light modules. Render it with `toSvg` (string, works anywhere) or `drawToCanvas` (browser).\n\n```ts\nimport { encodeQr, qrCapacity, toSvg } from '@vielzeug/sigil';\n\nconst matrix = encodeQr('https://vielzeug.dev');\n// Pick the smallest version automatically, or pin one:\nconst pinned = encodeQr('https://vielzeug.dev', { version: 5, errorCorrection: 'Q' });\n\nconst svg = toSvg(matrix); // inline <svg> string: inject or serialize\n```\n\nThe encoder chooses the most compact mode for the whole input and the smallest version that fits. `mask` is chosen by the lowest ISO penalty score: override it only for test vectors.\n\n## Encoding Modes and Capacity\n\nThree segment modes cover every payload:\n\n| Mode | Alphabet | Max payload (v40-L) |\n| -------------- | ------------------------ | ------------------- |\n| `numeric` | `0–9` | 7,089 digits |\n| `alphanumeric` | `0–9 A-Z space $%*+-./:` | 4,296 chars |\n| `byte` | UTF-8 (no ECI header) | 2,953 bytes |\n\nMode selection is automatic: `encodeQr('01234567')` uses `numeric`, `'HELLO WORLD'` uses `alphanumeric`, anything else uses `byte`. Force a mode with `mode`, but a forced mode that cannot represent the input throws `SigilOptionError`.\n\n`Uint8Array` input is raw binary: it always encodes in byte mode, byte-for-byte, with no UTF-8 round-trip: invalid UTF-8 (tokens, provisioning payloads) survives intact. Forcing a non-byte mode with binary input throws `SigilOptionError`.\n\nCheck capacity before encoding with `qrCapacity(version, errorCorrection, mode)`: it returns the maximum _bytes_ (for `byte` mode) or _characters_ the symbol holds:\n\n```ts\nimport { qrCapacity, SigilCapacityError } from '@vielzeug/sigil';\n\nqrCapacity(10, 'M', 'byte'); // → 213 (data codewords available at v10-M)\n\ntry {\n encodeQr(hugePayload, { version: 1 });\n} catch (error) {\n if (error instanceof SigilCapacityError) {\n console.log(`${error.bytes} > ${error.maxBytes} at v${error.version}`);\n }\n}\n```\n\nUse `minVersion` to keep a stable symbol size while a payload changes: useful when a layout must not reflow between renders.\n\n## Error Correction\n\n| Level | Recovery | Trade-off |\n| ----- | -------- | --------------------------- |\n| `L` | ~7% | Smallest matrix |\n| `M` | ~15% | Default: good balance |\n| `Q` | ~25% | Print, wear |\n| `H` | ~30% | Logos/overlays, dense codes |\n\nHigher levels shrink capacity at the same version. For an overlaid logo, prefer `H` _and_ keep the logo inside the quiet zone's margin of safety.\n\n## Rendering\n\n### SVG: `toSvg`\n\n```ts\nconst svg = toSvg(matrix, {\n dark: 'currentColor', // default: inherits text color\n light: 'transparent', // default\n margin: 4, // quiet zone in modules (spec minimum is 4)\n scale: 1, // user units per module: prefer scaling via CSS\n optimizePath: true, // merge adjacent modules into one path (default)\n label: 'Pairing code', // <title> + role=\"img\"\n});\n```\n\n`optimizePath` merges each row's dark runs into a single `<path>`: orders of magnitude smaller markup. Set `dark`/`light` to CSS variables to theme the code (`dark: 'var(--qr-dark)'`).\n\n### Canvas: `drawToCanvas` (browser only)\n\n```ts\nconst sizePx = drawToCanvas(matrix, canvas, { scale: 8, margin: 4 });\n// canvas is resized for devicePixelRatio; returns the CSS-pixel edge length\n```\n\nUse canvas for print, download (`canvas.toBlob`), or compositing. SVG is the better default for display.\n\n## Scanning (browser only)\n\nScanning wraps the native `BarcodeDetector`. It is **not** universally available: feature-detect, never assume:\n\n| Engine | `BarcodeDetector` | Notes |\n| ------------------------------- | ------------------------------- | ------------------------------------------------- |\n| Chrome / Edge / Android WebView | Yes | `qr_code` format supported |\n| Firefox | No (behind flag in some builds) | `isQrScanSupported()` → `false` |\n| Safari | Varies by version | Check at runtime; do not rely on version sniffing |\n\n```ts\nimport { createQrScanner, isQrScanSupported, qrScanSupport } from '@vielzeug/sigil';\n\nisQrScanSupported(); // sync: BarcodeDetector constructor exists\nawait qrScanSupport(); // async: also verifies 'qr_code' is a supported format\n\nconst scanner = createQrScanner({\n video, // <video autoplay playsinline muted>\n constraints: { facingMode: 'environment' },\n intervalMs: 200, // min ms between detect passes\n once: true, // stop after first result\n});\n\nscanner.onResult((result) => showPairing(result.value));\nscanner.tap((event) => console.debug(event.type)); // status-change, detect, frame-skipped…\n\nawait scanner.start(); // requests camera, attaches stream, starts the loop\nscanner.stop(); // releases the camera, back to 'idle'; start() resumes\nscanner.dispose(); // terminal: releases everything\n```\n\nStatuses are `'idle' | 'starting' | 'scanning' | 'disposed'`. A `stop()` or `dispose()` that lands while the camera permission prompt is pending wins the race: the late stream is released and `start()` resolves without restarting the loop.\n\n`start()` rejects with `SigilUnsupportedError` (no detector/getUserMedia) or `SigilPermissionError` (`NotAllowedError`). Detection failures mid-scan surface through `tap` `error` events and stop the scanner.\n\n### One-shot detection\n\n`detectQr(source)` runs a single pass over any `ImageBitmapSource`: `ImageData`, `Blob`, `VideoFrame`, an `<img>`, or a `<canvas>`:\n\n```ts\nimport { detectQr } from '@vielzeug/sigil';\n\nconst result = await detectQr(imageBitmap); // → { value, cornerPoints } | null\n```\n\n## Testing\n\nBoth seams are injectable: never touch globals in tests:\n\n```ts\nimport { createQrScanner } from '@vielzeug/sigil';\n\nconst fakeScanner = createQrScanner({\n video: document.createElement('video'),\n detector: { detect: async () => [{ rawValue: 'payload' }] }, // fake BarcodeDetector\n mediaDevices: { getUserMedia: async () => fakeStream }, // fake camera\n});\n```\n\nFor the web components, `ore-qr-scanner` exposes a `scannerFactory` JS property so tests inject a fake `QrScanner` without stubbing `BarcodeDetector` or `getUserMedia`.\n\n## Framework Integration\n\nEncoding is synchronous and SSR-safe: render `toSvg` output as part of server markup:\n\n::: code-group\n\n```tsx [React]\nfunction Qr({ value }: { value: string }) {\n const svg = useMemo(() => toSvg(encodeQr(value)), [value]);\n return <span dangerouslySetInnerHTML={{ __html: svg }} />;\n}\n```\n\n```vue [Vue]\n<script setup>\nimport { computed } from 'vue';\nimport { encodeQr, toSvg } from '@vielzeug/sigil';\nconst props = defineProps({ value: String });\nconst svg = computed(() => toSvg(encodeQr(props.value ?? '')));\n</script>\n<template><span v-html=\"svg\" /></template>\n```\n\n```html [Svelte]\n<script>\n import { encodeQr, toSvg } from '@vielzeug/sigil';\n export let value;\n $: svg = toSvg(encodeQr(value));\n</script>\n<span>{@html svg}</span>\n```\n\n:::\n\nScanning needs lifecycle: start in `onMounted`/`onMount`, always `dispose()` in cleanup.\n\n## Working with Other Vielzeug Libraries\n\n- **Mesh**: `meshQrCodec` compresses WebRTC pairing payloads (offer/answer JSON) to QR-friendly strings. The [Pair Two Devices with QR](./examples/pair-two-devices.md) recipe shows the full flow.\n- **Refine**: prefer `ore-qr-code` / `ore-qr-scanner` over hand-rolled wrappers: they compose sigil with themeable markup, a11y labels, and state handling.\n\n## Best Practices\n\n- Pre-validate payloads with `qrCapacity` before surfacing an encode control.\n- Keep the quiet zone: `margin` below 4 risks unreadable codes; never overlay content on it.\n- Prefer `toSvg` + `currentColor` for display; reserve `drawToCanvas` for print/download.\n- Feature-detect scanning with `qrScanSupport()` before showing a scan affordance.\n- Always `dispose()` scanners: camera tracks outlive route changes otherwise.\n- Use `once: false` only when the UX genuinely expects repeated decodes.\n- Treat scanned strings as untrusted input: validate before navigation or pairing.\n- Pin `minVersion` in animated/live payloads so the symbol doesn't resize mid-flow.\n",
7
7
  "examples": "---\ntitle: 'Sigil: Examples'\ndescription: Practical examples and recipes for @vielzeug/sigil.\n---\n\n## Examples\n\n- [Themed SVG QR Code](./examples/themed-svg-qr-code.md)\n- [Pair Two Devices with QR](./examples/pair-two-devices.md)\n"
8
8
  },
@@ -33,17 +33,20 @@
33
33
  "isQrScanSupported": "export { createQrScanner, detectQr, isQrScanSupported, qrScanSupport } from './scan';",
34
34
  "qrScanSupport": "export { createQrScanner, detectQr, isQrScanSupported, qrScanSupport } from './scan';",
35
35
  "toSvg": "export { toSvg } from './svg';",
36
- "QrCanvasOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
37
- "QrDetector": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
38
- "QrEncodeOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
39
- "QrErrorCorrection": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
40
- "QrMatrix": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
41
- "QrMode": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
42
- "QrScanner": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
43
- "QrScannerOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
44
- "QrScannerStatus": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
45
- "QrScanResult": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
46
- "QrSvgOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
47
- "SigilEvent": "export type {\n QrCanvasOptions,\n QrDetector,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgOptions,\n SigilEvent,\n} from './types';"
36
+ "QrCanvasOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
37
+ "QrDetector": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
38
+ "QrDotStyle": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
39
+ "QrEncodeOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
40
+ "QrErrorCorrection": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
41
+ "QrMatrix": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
42
+ "QrMode": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
43
+ "QrScanner": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
44
+ "QrScannerOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
45
+ "QrScannerStatus": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
46
+ "QrScanResult": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
47
+ "QrSvgGradientOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
48
+ "QrSvgImageOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
49
+ "QrSvgOptions": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';",
50
+ "SigilEvent": "export type {\n QrCanvasOptions,\n QrDetector,\n QrDotStyle,\n QrEncodeOptions,\n QrErrorCorrection,\n QrMatrix,\n QrMode,\n QrScanner,\n QrScannerOptions,\n QrScannerStatus,\n QrScanResult,\n QrSvgGradientOptions,\n QrSvgImageOptions,\n QrSvgOptions,\n SigilEvent,\n} from './types';"
48
51
  }
49
52
  }
@@ -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
  }