@vielzeug/codex 26.11.9 → 26.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +47 -46
- package/data/llms-full.txt +604 -562
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/ore.json +3 -5
- package/data/packages/ripple.json +5 -4
- package/data/packages/spell.json +40 -41
- package/data/packages/vault.json +3 -3
- package/data/search.json +23 -23
- package/package.json +2 -2
package/data/llms-full.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug: Full Documentation
|
|
2
2
|
|
|
3
|
-
> Complete documentation for 43 packages. Version: 26.11.
|
|
3
|
+
> Complete documentation for 43 packages. Version: 26.11.9
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -16817,7 +16817,7 @@ define('my-counter', {
|
|
|
16817
16817
|
|
|
16818
16818
|
## API Overview
|
|
16819
16819
|
|
|
16820
|
-
All browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/context/binding functions (`onMounted`, `onCleanup`, `onEvent`, `onElement`, `watchEffect`, `bind`, `provide`, `useEmit`, `useSlots`, `getHost`) resolve the active component through an implicit "current component" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window.
|
|
16820
|
+
All browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/context/binding functions (`onMounted`, `onCleanup`, `onEvent`, `onElement`, `watchEffect`, `bind`, `provide`, `useEmit`, `useSlots`, `getHost`) resolve the active component through an implicit "current component" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window. The one exception is `bind()` with an explicit `options.target`: it also works outside setup (for example from an event handler), where only its returned disposer stops it.
|
|
16821
16821
|
|
|
16822
16822
|
> `watchEffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.
|
|
16823
16823
|
|
|
@@ -16831,7 +16831,6 @@ All browser-runtime symbols below are imported from `@vielzeug/ore`. Lifecycle/c
|
|
|
16831
16831
|
| `createContext()` | Create a unique typed injection key | Sync | Context is scoped to the component tree |
|
|
16832
16832
|
| `each()` | Keyed list rendering with DOM diffing | Sync | Duplicate keys report `ore:error`; plain `T[]` is a one-time static render |
|
|
16833
16833
|
| `when()` | Conditional branch rendering | Sync | Getter-fn computed disposed on cleanup; static bool skips subscription |
|
|
16834
|
-
| `live(signal)` | One-way binding that skips stale writes during input | Sync | Use for controlled inputs alongside a manual `@input` handler |
|
|
16835
16834
|
| `model(signal)` | Two-way form-control binding (value/checked + write-back) | Sync | Plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |
|
|
16836
16835
|
| `onMounted(fn)` | DOM-ready callback | Setup only | Must be called synchronously during `setup()` |
|
|
16837
16836
|
| `onCleanup(fn)` | Register teardown | Setup only | Called on disconnect, one microtask later, unless the element reconnects (a same-turn move) |
|
|
@@ -16860,6 +16859,9 @@ define(tag: string, definition: ComponentDefinition): CustomElementConstructor;
|
|
|
16860
16859
|
|
|
16861
16860
|
Returns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.
|
|
16862
16861
|
|
|
16862
|
+
Omit `Props` to infer prop types from `props`. Pass it explicitly when a public props type already exists: every key it
|
|
16863
|
+
declares must then have a definition in `props`.
|
|
16864
|
+
|
|
16863
16865
|
The `setup()` function receives only typed prop signals:
|
|
16864
16866
|
|
|
16865
16867
|
```ts
|
|
@@ -16883,7 +16885,8 @@ define('my-card', {
|
|
|
16883
16885
|
// emit() returns dispatchEvent's boolean: false if a listener called preventDefault()
|
|
16884
16886
|
const notCancelled = emit('close');
|
|
16885
16887
|
|
|
16886
|
-
|
|
16888
|
+
// Render the unconditionally: has() observes rendered slots, so gating the slot itself on has() never shows it.
|
|
16889
|
+
return html` !slots.has('header').value}>`;
|
|
16887
16890
|
},
|
|
16888
16891
|
});
|
|
16889
16892
|
```
|
|
@@ -16957,7 +16960,7 @@ setup(_props) {
|
|
|
16957
16960
|
> - **`prop.json`**: value can be declared in HTML (``); attribute string is `JSON.parse`d.
|
|
16958
16961
|
> - **`prop.data`**: value is always set from JavaScript (objects, arrays, callbacks, class instances); the attribute is never read. Use this for both data and function props.
|
|
16959
16962
|
|
|
16960
|
-
When you need custom parsing or `reflect: false`, use a raw `PropDef` object
|
|
16963
|
+
When you need custom parsing or `reflect: false`, use a raw `PropDef` object. Any `{ default, parse, reflect? }` object is a valid prop definition; `reflect` defaults to `false` for raw objects (the `prop.*` helpers reflect, except `prop.json` and `prop.data`). `define()` reports every invalid definition in one `OreApiError`:
|
|
16961
16964
|
|
|
16962
16965
|
```ts
|
|
16963
16966
|
props: {
|
|
@@ -16989,6 +16992,10 @@ Tagged template literal that returns an `HTMLResult`. Supports text interpolatio
|
|
|
16989
16992
|
boolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional
|
|
16990
16993
|
`.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.
|
|
16991
16994
|
|
|
16995
|
+
An `HTMLResult` is opaque and single-use: each one owns the DOM nodes and bindings for one rendering. Rendering the
|
|
16996
|
+
same result twice (mounting it again, interpolating it twice, or returning a cached result from a reactive getter)
|
|
16997
|
+
throws `OreApiError`. Call the template function again when you need another copy.
|
|
16998
|
+
|
|
16992
16999
|
`.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured
|
|
16993
17000
|
values (arrays, objects, callbacks). Prototype-polluting names (`__proto__`, `constructor`, `prototype`) and
|
|
16994
17001
|
raw-HTML-parsing names (`innerHTML`, `outerHTML`, `srcdoc`) are rejected at compile time: render sanitized
|
|
@@ -17010,7 +17017,6 @@ Tagged template literal that returns a `CSSResult` for use in `styles`.
|
|
|
17010
17017
|
| `when(condition, truthy, falsy?)` | Conditional rendering |
|
|
17011
17018
|
| `classMap(record)` | Reactive class string from object map |
|
|
17012
17019
|
| `styleMap(record)` | Reactive inline style string from object map |
|
|
17013
|
-
| `live(signal)` | One-way binding that skips stale writes during active user input; use with `@input` handler |
|
|
17014
17020
|
| `model(signal, options?)` | Two-way form-control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |
|
|
17015
17021
|
| `unsafeHtml(value)` | HTML rendering sink; sanitize untrusted values before calling |
|
|
17016
17022
|
|
|
@@ -17018,7 +17024,7 @@ Tagged template literal that returns a `CSSResult` for use in `styles`.
|
|
|
17018
17024
|
|
|
17019
17025
|
### `model(signal, options?)`
|
|
17020
17026
|
|
|
17021
|
-
Two-way binding for a form control: `value=${model(signal)}`. It writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and ``; `'input'` otherwise).
|
|
17027
|
+
Two-way binding for a form control: `value=${model(signal)}`. It writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and ``; `'input'` otherwise). While the control holds an in-progress edit the signal has not received yet, stale writes to the signal are skipped.
|
|
17022
17028
|
|
|
17023
17029
|
```ts
|
|
17024
17030
|
const text = signal('');
|
|
@@ -17098,6 +17104,8 @@ Static values are applied once. Getters and signals create reactive effects. Cal
|
|
|
17098
17104
|
|
|
17099
17105
|
Slot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.
|
|
17100
17106
|
|
|
17107
|
+
Presence is measured through the `` elements the component has rendered: content assigned to a slot that isn't rendered reports `false`. Always render the `` and use `has()` to hide or style its wrapper; ``when(slots.has('x'), () => html``)`` never shows the slot.
|
|
17108
|
+
|
|
17101
17109
|
## Context API
|
|
17102
17110
|
|
|
17103
17111
|
- `createContext(description)`: Create a unique typed injection key; the description is diagnostic only
|
|
@@ -17185,14 +17193,14 @@ useField({
|
|
|
17185
17193
|
|
|
17186
17194
|
Import from `@vielzeug/ore/testing`.
|
|
17187
17195
|
|
|
17188
|
-
| API
|
|
17189
|
-
|
|
|
17190
|
-
| `mount(setup, options?)`
|
|
17191
|
-
| `cleanup()`
|
|
17192
|
-
| `install(afterEach)`
|
|
17193
|
-
| `flush(options?)`
|
|
17194
|
-
| `renderHook(setup)`
|
|
17195
|
-
| `OreTimeoutError`
|
|
17196
|
+
| API | Purpose |
|
|
17197
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
17198
|
+
| `mount(setup, options?)` | Mount a component and return a test fixture |
|
|
17199
|
+
| `cleanup()` | Remove all mounted elements and reset test state |
|
|
17200
|
+
| `install(afterEach)` | Register auto-cleanup after each test |
|
|
17201
|
+
| `flush(options?)` | Drain reactive updates and animation frames |
|
|
17202
|
+
| `renderHook(setup, options?)` | Run a composable in a generated host component; overload accepts `propDefs` first for typed props |
|
|
17203
|
+
| `OreTimeoutError` | Error thrown when `flush()` cannot settle tracked Ore work |
|
|
17196
17204
|
|
|
17197
17205
|
> **Test isolation:** `cleanup()` removes mounted elements and resets Ore's cross-test caches and counters. Call it in `afterEach`, or use `install(afterEach)`.
|
|
17198
17206
|
|
|
@@ -17237,7 +17245,7 @@ interface Fixture {
|
|
|
17237
17245
|
|
|
17238
17246
|
#### `renderHook`
|
|
17239
17247
|
|
|
17240
|
-
Useful for testing composable lifecycle hooks (`onMounted`, `watchEffect`, `inject`, etc.) without a template. `
|
|
17248
|
+
Useful for testing composable lifecycle hooks (`onMounted`, `watchEffect`, `inject`, etc.) without a template. The setup runs inside a real, generated host component (exposed as `element`), so every hook behaves exactly as it does in `define()`. Pass `{ formAssociated: true }` for composables that call `useField()` or `onFormReset()`. Like `mount().dispose()`, `dispose()` removes the host and its cleanups run one microtask later:
|
|
17241
17249
|
|
|
17242
17250
|
```ts
|
|
17243
17251
|
// Without props
|
|
@@ -17281,7 +17289,7 @@ type PropDef = {
|
|
|
17281
17289
|
};
|
|
17282
17290
|
|
|
17283
17291
|
type PropsDef> = {
|
|
17284
|
-
[K in keyof
|
|
17292
|
+
[K in keyof T]-?: PropDef;
|
|
17285
17293
|
};
|
|
17286
17294
|
|
|
17287
17295
|
type PropInputDefs = Record>;
|
|
@@ -17317,7 +17325,7 @@ declare function onEvent(
|
|
|
17317
17325
|
options?: AddEventListenerOptions,
|
|
17318
17326
|
): void;
|
|
17319
17327
|
declare function onFormReset(fn: OnFormResetCallback): void; // Runs on every ancestor reset; formAssociated only
|
|
17320
|
-
declare function watchEffect(fn: () => Cleanup | undefined): () => void; //
|
|
17328
|
+
declare function watchEffect(fn: () => Cleanup | undefined): () => void; // Component-owned reactive effect; disposed on disconnect, throws outside setup
|
|
17321
17329
|
declare function bind(config: HostBindConfig, options?: BindOptions): () => void; // Bindings for host or any target element
|
|
17322
17330
|
declare function provide(key: InjectionKey, value: T): void; // Register a context value on the host element
|
|
17323
17331
|
declare function inject(key: InjectionKey): T | undefined;
|
|
@@ -17362,17 +17370,13 @@ type RefCallback = (el: T | null) => void;
|
|
|
17362
17370
|
|
|
17363
17371
|
type InjectionKey = symbol & { readonly __ore_injection_key?: T };
|
|
17364
17372
|
|
|
17365
|
-
interface HTMLResult {
|
|
17366
|
-
mount(parent: ParentNode, anchor: Node | null, registerCleanup: (fn: () => void) => void): Node[];
|
|
17367
|
-
}
|
|
17373
|
+
interface HTMLResult {} // Opaque, single-use: render it once (return, interpolate, or return from a directive callback)
|
|
17368
17374
|
|
|
17369
17375
|
type CSSResult = {
|
|
17370
17376
|
content: string;
|
|
17371
17377
|
toString(): string;
|
|
17372
17378
|
};
|
|
17373
17379
|
|
|
17374
|
-
type LiveBinding = { readonly source: Readable };
|
|
17375
|
-
|
|
17376
17380
|
type ModelOptions = {
|
|
17377
17381
|
/** Write-back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */
|
|
17378
17382
|
event?: string;
|
|
@@ -17632,7 +17636,7 @@ final position, so each item's custom elements connect a single time per render.
|
|
|
17632
17636
|
|
|
17633
17637
|
Use `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and
|
|
17634
17638
|
writes user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`
|
|
17635
|
-
otherwise).
|
|
17639
|
+
otherwise).
|
|
17636
17640
|
|
|
17637
17641
|
```ts
|
|
17638
17642
|
import { signal } from '@vielzeug/ripple';
|
|
@@ -17663,26 +17667,8 @@ html`
|
|
|
17663
17667
|
`;
|
|
17664
17668
|
```
|
|
17665
17669
|
|
|
17666
|
-
|
|
17667
|
-
|
|
17668
|
-
Use `live(signal)` when a binding must skip a stale app-state write while the user is mid-edit, without writing
|
|
17669
|
-
user input back. `model()` covers the common controlled-input case; `live()` is for one-way bindings that only
|
|
17670
|
-
need the stale-write guard.
|
|
17671
|
-
|
|
17672
|
-
```ts
|
|
17673
|
-
import { signal } from '@vielzeug/ripple';
|
|
17674
|
-
import { define, html, live } from '@vielzeug/ore';
|
|
17675
|
-
|
|
17676
|
-
define('live-search', {
|
|
17677
|
-
setup() {
|
|
17678
|
-
const query = signal('');
|
|
17679
|
-
|
|
17680
|
-
return html`
|
|
17681
|
-
(query.value = (e.target as HTMLInputElement).value)} />
|
|
17682
|
-
`;
|
|
17683
|
-
},
|
|
17684
|
-
});
|
|
17685
|
-
```
|
|
17670
|
+
`model()` also guards in-progress edits: while the control holds a value the signal has not received yet, a stale
|
|
17671
|
+
app-state write to the signal is skipped instead of clobbering what the user is typing.
|
|
17686
17672
|
|
|
17687
17673
|
## host bindings
|
|
17688
17674
|
|
|
@@ -17797,7 +17783,7 @@ define('button-wrapper', {
|
|
|
17797
17783
|
## slots and emits
|
|
17798
17784
|
|
|
17799
17785
|
```ts
|
|
17800
|
-
import { define, html, useEmit, useSlots
|
|
17786
|
+
import { define, html, useEmit, useSlots } from '@vielzeug/ore';
|
|
17801
17787
|
|
|
17802
17788
|
define('card-with-footer', {
|
|
17803
17789
|
setup(_props) {
|
|
@@ -17808,7 +17794,7 @@ define('card-with-footer', {
|
|
|
17808
17794
|
|
|
17809
17795
|
|
|
17810
17796
|
|
|
17811
|
-
|
|
17797
|
+
!slots.has('footer').value}>
|
|
17812
17798
|
|
|
17813
17799
|
emit('action')}>Go
|
|
17814
17800
|
`;
|
|
@@ -17818,6 +17804,8 @@ define('card-with-footer', {
|
|
|
17818
17804
|
|
|
17819
17805
|
Pass a `SlotNames` type parameter to `useSlots()` to get typed `slots.has()` and `slots.elements()` calls.
|
|
17820
17806
|
|
|
17807
|
+
Keep the `` rendered and toggle its wrapper with `slots.has()`: presence is read from rendered slots, so a `` inside `when(slots.has(...))` would never appear.
|
|
17808
|
+
|
|
17821
17809
|
## context provide/inject
|
|
17822
17810
|
|
|
17823
17811
|
```ts
|
|
@@ -18031,7 +18019,7 @@ define('signup-form', {
|
|
|
18031
18019
|
- Bind host attributes and classes via `bind()` rather than mutating the element directly.
|
|
18032
18020
|
- Provide context at the nearest ancestor: avoid global context singletons.
|
|
18033
18021
|
- Call `onCleanup()` for every resource allocated in `setup()` (WebSockets, intervals, external subscriptions).
|
|
18034
|
-
- Use `model(signal)` for
|
|
18022
|
+
- Use `model(signal)` for form inputs: it writes both ways and never clobbers an in-progress user edit.
|
|
18035
18023
|
- Extract composable helper functions freely: `onMounted`/`onCleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.
|
|
18036
18024
|
- Test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic DOM events, queries, and waits
|
|
18037
18025
|
from `@vielzeug/assay`.
|
|
@@ -22670,8 +22658,9 @@ ripple.dispose();
|
|
|
22670
22658
|
|
|
22671
22659
|
- `createRipple({ onError })` creates an isolated graph with one runtime failure callback.
|
|
22672
22660
|
- `signal()` stores writable values with configurable equality.
|
|
22673
|
-
- `computed()` derives lazy read-only values.
|
|
22661
|
+
- `computed()` derives lazy, glitch-free read-only values: at most once per flush, never from a stale source.
|
|
22674
22662
|
- `effect()` reacts to dependency changes with cleanup support.
|
|
22663
|
+
- `onCleanup()` runs a callback when the active scope or effect run is disposed.
|
|
22675
22664
|
- `batch()` coalesces synchronous writes and notifications.
|
|
22676
22665
|
- `createScope()` groups owned reactive work.
|
|
22677
22666
|
- `watch()` observes one selected source transition.
|
|
@@ -22702,6 +22691,7 @@ ripple.dispose();
|
|
|
22702
22691
|
| `signal()` | Create writable value | Sync | Default graph is process-wide |
|
|
22703
22692
|
| `computed()` | Create lazy derived value | Sync | Keep derivation pure |
|
|
22704
22693
|
| `effect()` | React to dependency reads | Sync | Dispose handle or return cleanup |
|
|
22694
|
+
| `onCleanup()` | Run when the active owner disposes | Sync | Call it inside a scope or effect |
|
|
22705
22695
|
| `batch()` | Coalesce synchronous writes | Sync | Does not roll back writes |
|
|
22706
22696
|
| `createScope()` | Group owned reactive work | Sync | Call `run()` to activate it |
|
|
22707
22697
|
| `untrack()` | Read without tracking | Sync | Read still happens immediately |
|
|
@@ -22729,12 +22719,12 @@ function createRipple(options?: RippleOptions): Ripple;
|
|
|
22729
22719
|
|
|
22730
22720
|
Creates one isolated reactive graph. Factories on the returned object share scheduling, ownership, and error boundaries. `dispose()` is terminal: `ripple.disposed` becomes `true`, existing owned work is disposed, and creating more graph work throws `RippleDisposedError`. Create a new graph for a new lifetime.
|
|
22731
22721
|
|
|
22732
|
-
| Parameter | Type | Description
|
|
22733
|
-
| ----------------- | -------------------------- |
|
|
22734
|
-
| `options.onError` | `(error, context) => void` | Handles
|
|
22722
|
+
| Parameter | Type | Description |
|
|
22723
|
+
| ----------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22724
|
+
| `options.onError` | `(error, context) => void` | Handles effect, cleanup, listener, and flush-loop failures, including computed errors those consumers read. Default rethrows asynchronously via `queueMicrotask`; pass a no-op to silence. A failure in one node never interrupts its siblings. |
|
|
22735
22725
|
|
|
22736
|
-
`onError` is the only runtime option. `RippleErrorContext.kind` is `cleanup`, `
|
|
22737
|
-
|
|
22726
|
+
`onError` is the only runtime option. `RippleErrorContext.kind` is `cleanup`, `effect`, `flush`,
|
|
22727
|
+
or `listener`; `name` is optional. There is no event stream or error-policy option.
|
|
22738
22728
|
|
|
22739
22729
|
**Returns:** `Ripple`.
|
|
22740
22730
|
|
|
@@ -22773,7 +22763,7 @@ console.log(isReactive(signal(0)));
|
|
|
22773
22763
|
|
|
22774
22764
|
## Default Graph Functions
|
|
22775
22765
|
|
|
22776
|
-
Root helpers (`signal`, `computed`, `effect`, `batch`, `createScope`, `untrack`, `watch`, `resource`, `fromSubscribable`) operate on a process-lifetime default graph. The graph itself has no public disposal handle; effects, scopes, resources, and bridges still require owner-managed disposal. For isolated, disposable graphs (tests, SSR, embedded features) use `createRipple()`.
|
|
22766
|
+
Root helpers (`signal`, `computed`, `effect`, `onCleanup`, `batch`, `createScope`, `untrack`, `watch`, `resource`, `fromSubscribable`) operate on a process-lifetime default graph. The graph itself has no public disposal handle; effects, scopes, resources, and bridges still require owner-managed disposal. For isolated, disposable graphs (tests, SSR, embedded features) use `createRipple()`.
|
|
22777
22767
|
|
|
22778
22768
|
### `signal(initial, options?)`
|
|
22779
22769
|
|
|
@@ -22805,7 +22795,7 @@ cart.update((state) => ({ ...state, items: state.items + 1 }));
|
|
|
22805
22795
|
function computed(derive: () => T, options?: ComputedOptions): Readable;
|
|
22806
22796
|
```
|
|
22807
22797
|
|
|
22808
|
-
Creates a lazy read-only value from reactive reads in `derive`.
|
|
22798
|
+
Creates a lazy read-only value from reactive reads in `derive`. A write only marks the computed stale; it derives on the next read, at most once per flush, and always from up-to-date sources. A derivation error is cached and rethrown by every read (`value` or `peek()`) until a source changes; consumers that read it report it through `onError` in their own context. A disposed computed returns its last cached value from `peek()` without recomputing; a computed disposed before its first evaluation throws `RippleDisposedError` instead of returning a value.
|
|
22809
22799
|
|
|
22810
22800
|
**Returns:** `Readable`.
|
|
22811
22801
|
|
|
@@ -22827,7 +22817,7 @@ console.log(doubled.value);
|
|
|
22827
22817
|
function effect(callback: () => Cleanup | undefined, options?: EffectOptions): EffectHandle;
|
|
22828
22818
|
```
|
|
22829
22819
|
|
|
22830
|
-
Runs immediately and reruns when its tracked reads change. A returned cleanup runs before the next callback or disposal.
|
|
22820
|
+
Runs immediately and reruns when its tracked reads change. An effect that only reads computeds reruns only when one of them derives a different value. A returned cleanup runs before the next callback or disposal.
|
|
22831
22821
|
|
|
22832
22822
|
| Parameter | Type | Description |
|
|
22833
22823
|
| -------------- | -------- | ------------------------------- |
|
|
@@ -22854,6 +22844,37 @@ stop.dispose();
|
|
|
22854
22844
|
|
|
22855
22845
|
---
|
|
22856
22846
|
|
|
22847
|
+
### `onCleanup(fn)`
|
|
22848
|
+
|
|
22849
|
+
```ts
|
|
22850
|
+
function onCleanup(fn: Cleanup): void;
|
|
22851
|
+
```
|
|
22852
|
+
|
|
22853
|
+
Registers `fn` on the active owner: the current effect run when called inside an effect, otherwise the active scope. The callback runs when that owner is disposed, after the owner's effects and computeds, newest first. For an effect run that means before the next run, and after the cleanup function the effect itself returned. A callback that calls `onCleanup()`, `effect()`, or `computed()` while its owner is being disposed gets that work torn down immediately. A throwing callback is reported through `onError` and does not skip the others.
|
|
22854
|
+
|
|
22855
|
+
Called with no scope or effect active, it registers on the graph root. The default graph is never disposed, so use `createRipple()` or an explicit scope when the callback must run.
|
|
22856
|
+
|
|
22857
|
+
**Example:**
|
|
22858
|
+
|
|
22859
|
+
```ts
|
|
22860
|
+
import { createScope, effect, onCleanup, signal } from '@vielzeug/ripple';
|
|
22861
|
+
|
|
22862
|
+
const scope = createScope('panel');
|
|
22863
|
+
const count = signal(0);
|
|
22864
|
+
|
|
22865
|
+
scope.run(() => {
|
|
22866
|
+
effect(() => {
|
|
22867
|
+
console.log(count.value);
|
|
22868
|
+
onCleanup(() => console.log('effect run ended'));
|
|
22869
|
+
});
|
|
22870
|
+
onCleanup(() => console.log('panel closed'));
|
|
22871
|
+
});
|
|
22872
|
+
|
|
22873
|
+
scope.dispose();
|
|
22874
|
+
```
|
|
22875
|
+
|
|
22876
|
+
---
|
|
22877
|
+
|
|
22857
22878
|
### `batch(fn)` and `untrack(fn)`
|
|
22858
22879
|
|
|
22859
22880
|
```ts
|
|
@@ -22978,7 +22999,7 @@ function fromSubscribable(source: Subscribable, options?: FromSubscribableOption
|
|
|
22978
22999
|
|
|
22979
23000
|
Bridges an external `{ getSnapshot, subscribe }` source into a disposable reactive readable. The bridge subscribes and then rereads the snapshot to avoid missing a change during registration. The root helper uses the default graph; `ripple.fromSubscribable()` binds ownership to an isolated graph. An optional signal disposes the bridge.
|
|
22980
23001
|
|
|
22981
|
-
**Returns:** `BridgedReadable`. Disposal invokes the source unsubscribe function. Reads remain available afterward, while new subscriptions throw
|
|
23002
|
+
**Returns:** `BridgedReadable`. Disposal invokes the source unsubscribe function. Reads remain available afterward, while new subscriptions throw `RippleDisposedError`.
|
|
22982
23003
|
|
|
22983
23004
|
**Example:**
|
|
22984
23005
|
|
|
@@ -23016,7 +23037,7 @@ type EffectOptions = { name?: string };
|
|
|
23016
23037
|
type WatchOptions = { equals?: Equality; immediate?: boolean; name?: string };
|
|
23017
23038
|
|
|
23018
23039
|
type RippleErrorContext = {
|
|
23019
|
-
readonly kind: 'cleanup' | '
|
|
23040
|
+
readonly kind: 'cleanup' | 'effect' | 'flush' | 'listener';
|
|
23020
23041
|
readonly name?: string;
|
|
23021
23042
|
};
|
|
23022
23043
|
type RippleOptions = { onError?: (error: unknown, context: RippleErrorContext) => void };
|
|
@@ -23068,6 +23089,7 @@ interface Ripple extends Disposable {
|
|
|
23068
23089
|
computed(derive: () => T, options?: ComputedOptions): Readable;
|
|
23069
23090
|
createScope(name?: string): Scope;
|
|
23070
23091
|
effect(callback: () => Cleanup | undefined, options?: EffectOptions): EffectHandle;
|
|
23092
|
+
onCleanup(fn: Cleanup): void;
|
|
23071
23093
|
fromSubscribable(source: Subscribable, options?: FromSubscribableOptions): BridgedReadable;
|
|
23072
23094
|
resource(
|
|
23073
23095
|
source: () => Source,
|
|
@@ -23086,15 +23108,15 @@ interface Ripple extends Disposable {
|
|
|
23086
23108
|
|
|
23087
23109
|
## Errors
|
|
23088
23110
|
|
|
23089
|
-
| Error | Trigger
|
|
23090
|
-
| --------------------- |
|
|
23091
|
-
| `RippleError` | Base
|
|
23092
|
-
| `RippleCycleError` | A computed reads itself, or a flush exceeds the iteration limit
|
|
23093
|
-
| `RippleDisposedError` | New graph work, writes, or subscriptions on a disposed runtime; `run()` on a disposed scope; `reload()` or new subscriptions on a disposed resource; reading a never-evaluated disposed computed | Extends `RippleError`. Cached reads and repeated disposal remain valid. |
|
|
23111
|
+
| Error | Trigger | Notable properties |
|
|
23112
|
+
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
23113
|
+
| `RippleError` | Base class of every Ripple error | Use `instanceof RippleError` to narrow unknown values. |
|
|
23114
|
+
| `RippleCycleError` | A computed reads itself, directly or through other computeds, or a flush exceeds the iteration limit | Extends `RippleError`. A flush-loop breach is reported to `onError` (context kind `flush`) instead of throwing from the write site. |
|
|
23115
|
+
| `RippleDisposedError` | New graph work, writes, or subscriptions on a disposed runtime; `run()` on a disposed scope; `reload()` or new subscriptions on a disposed resource or bridge; reading a never-evaluated disposed computed | Extends `RippleError`. Cached reads and repeated disposal remain valid. |
|
|
23094
23116
|
|
|
23095
23117
|
These are the three exported error classes. User callback failures are reported as their original
|
|
23096
|
-
values through `onError`; they are not wrapped in `RippleError`. A direct computed read
|
|
23097
|
-
its derivation error to the caller.
|
|
23118
|
+
values through `onError`; they are not wrapped in `RippleError`. A direct computed read rethrows
|
|
23119
|
+
its cached derivation error to the caller.
|
|
23098
23120
|
|
|
23099
23121
|
### Usage Guide
|
|
23100
23122
|
|
|
@@ -23153,7 +23175,7 @@ ripple.batch(() => {
|
|
|
23153
23175
|
|
|
23154
23176
|
## Scheduling and Subscriptions
|
|
23155
23177
|
|
|
23156
|
-
|
|
23178
|
+
A synchronous write marks everything downstream stale before any effect runs. Each flush pass runs effects queued at its
|
|
23157
23179
|
start before direct `subscribe()` listeners queued at its start. Work queued by either runs in a later pass.
|
|
23158
23180
|
Effects coalesce writes made inside the same synchronous flush: a `batch()` (or any writes during a flush) produces a single effect run.
|
|
23159
23181
|
Each `subscribe()` registration fires once per flush, even when several subscriptions share one callback function.
|
|
@@ -23189,7 +23211,9 @@ count.value = 1;
|
|
|
23189
23211
|
scope.dispose();
|
|
23190
23212
|
```
|
|
23191
23213
|
|
|
23192
|
-
Effects and computeds created directly during an effect run belong to that run and are disposed before rerun. Explicit scopes intentionally attach to the enclosing scope and survive effect reruns; create them outside rerunning effects or retain and dispose each scope yourself.
|
|
23214
|
+
Effects and computeds created directly during an effect run belong to that run and are disposed before rerun. `onCleanup(fn)` registers on that same owner: inside an effect it runs before the next run, and inside `scope.run()` it runs when the scope is disposed, after the scope's effects. Explicit scopes intentionally attach to the enclosing scope and survive effect reruns; create them outside rerunning effects or retain and dispose each scope yourself. A call with no scope or effect active registers on the graph root.
|
|
23215
|
+
|
|
23216
|
+
Cleanups run with their disposed owner still active, so an `onCleanup()`, `effect()`, or `computed()` called from inside a cleanup is torn down immediately instead of leaking to the parent.
|
|
23193
23217
|
|
|
23194
23218
|
Disposed owned nodes detach from their parent immediately, so long-lived graphs do not retain released effects or scopes.
|
|
23195
23219
|
|
|
@@ -23209,12 +23233,12 @@ stopWatch.dispose();
|
|
|
23209
23233
|
|
|
23210
23234
|
## Error Handling
|
|
23211
23235
|
|
|
23212
|
-
Failures inside effect callbacks, computed derivations, cleanups, and listeners never corrupt the graph: the failing node is reported and siblings keep
|
|
23236
|
+
Failures inside effect callbacks, computed derivations, cleanups, and listeners never corrupt the graph: the failing node is reported and siblings keep updating. The `onError` option decides what reporting means. By default failures rethrow asynchronously (via `queueMicrotask`), surfacing as unhandled errors; pass a handler to route them to a logger or error boundary instead:
|
|
23213
23237
|
|
|
23214
23238
|
```ts
|
|
23215
23239
|
const ripple = createRipple({
|
|
23216
23240
|
onError: (error, context) => {
|
|
23217
|
-
// context.kind: 'cleanup' | '
|
|
23241
|
+
// context.kind: 'cleanup' | 'effect' | 'flush' | 'listener'
|
|
23218
23242
|
console.error(`${context.kind}:`, error);
|
|
23219
23243
|
},
|
|
23220
23244
|
});
|
|
@@ -23223,8 +23247,9 @@ const ripple = createRipple({
|
|
|
23223
23247
|
`onError` is the only runtime option. Effect options accept only a `name`; effects do not have a
|
|
23224
23248
|
microtask scheduler. Use `batch()` to coalesce related writes.
|
|
23225
23249
|
|
|
23226
|
-
A
|
|
23227
|
-
|
|
23250
|
+
A computed caches a derivation error like a value: every read rethrows it until a source changes.
|
|
23251
|
+
The failure therefore reaches `onError` through whatever reads it (context kind `effect` for an
|
|
23252
|
+
effect, `listener` for a subscription), and a direct read throws it to the caller. The exported
|
|
23228
23253
|
hierarchy is `RippleError`, `RippleCycleError`, and `RippleDisposedError`; callback failures retain
|
|
23229
23254
|
their original values.
|
|
23230
23255
|
|
|
@@ -23400,17 +23425,17 @@ ripple.dispose();
|
|
|
23400
23425
|
|
|
23401
23426
|
`Readable.subscribe(listener)` never calls the listener on subscribe: it fires only after a tracked source changes. Read the current value at the call site when you need an initial state.
|
|
23402
23427
|
|
|
23403
|
-
### `subscribe()`
|
|
23428
|
+
### `subscribe()` evaluates a computed once
|
|
23404
23429
|
|
|
23405
|
-
|
|
23430
|
+
Subscribing to a computed derives it immediately so the computed knows its sources, even if no one reads `.value`. A derivation error is cached, not thrown from `subscribe()`. After that, the listener fires only when the derived value actually changes under its `equals`. Avoid subscribing to expensive computeds unless you need their value.
|
|
23406
23431
|
|
|
23407
|
-
###
|
|
23432
|
+
### Computeds are lazy and glitch-free
|
|
23408
23433
|
|
|
23409
|
-
A
|
|
23434
|
+
A write only marks downstream computeds stale; nothing re-derives until something reads it. When an effect or subscription might be affected, the flush first re-derives the computeds it depends on, in the order they were read, and reruns it only if one of them actually changed. In a diamond (`a → b, c → d`), one write to `a` derives `b`, `c`, and `d` once each, and `d` never sees a fresh `b` next to a stale `c`. Inside `batch()`, a computed derives at most once however many of its sources were written. A computed no one reads costs nothing after a write.
|
|
23410
23435
|
|
|
23411
|
-
### Computed
|
|
23436
|
+
### Computed failures are recoverable
|
|
23412
23437
|
|
|
23413
|
-
If a computed's `derive` throws
|
|
23438
|
+
If a computed's `derive` throws (e.g., a source is `null`), the computed keeps the sources it read before the throw and caches the error. When one of those sources changes, the next read derives again; effects that read the failing computed report the error through `onError` and rerun once it recovers.
|
|
23414
23439
|
|
|
23415
23440
|
## Best Practices
|
|
23416
23441
|
|
|
@@ -30996,7 +31021,7 @@ Use Scout to compute indexed local matches, Ripple to project state into reactiv
|
|
|
30996
31021
|
|
|
30997
31022
|
## Why Spell?
|
|
30998
31023
|
|
|
30999
|
-
Spell keeps runtime validation, static inference, and portable definitions in one API.
|
|
31024
|
+
Spell 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.
|
|
31000
31025
|
|
|
31001
31026
|
This example shows the difference between manual branching and a single reusable schema.
|
|
31002
31027
|
|
|
@@ -31093,16 +31118,16 @@ const user = result.data;
|
|
|
31093
31118
|
|
|
31094
31119
|
## Features
|
|
31095
31120
|
|
|
31096
|
-
-
|
|
31097
|
-
-
|
|
31098
|
-
-
|
|
31099
|
-
-
|
|
31100
|
-
-
|
|
31101
|
-
-
|
|
31102
|
-
-
|
|
31103
|
-
-
|
|
31104
|
-
-
|
|
31105
|
-
- Object parsing is hardened against prototype-pollution
|
|
31121
|
+
- `s` builders for primitives, collections, objects, unions, and recursive schemas.
|
|
31122
|
+
- `parse()`, `safeParse()`, `parseAsync()`, and `safeParseAsync()`; parsing stays synchronous unless a check is async.
|
|
31123
|
+
- `check()` and `checkAsync()` run in chain order with transforms; sync parsing never skips an async check.
|
|
31124
|
+
- `optional`, `nullable`, `nullish`, `default`, `catch`, and `required` modifiers; defaults are copied per parse.
|
|
31125
|
+
- `extend()`, `pick()`, `omit()`, `partial()`, and `tolerate()` for object composition and schema evolution.
|
|
31126
|
+
- `definition()` returns frozen data; `toJsonSchema()` from `@vielzeug/spell/json` converts it to JSON Schema.
|
|
31127
|
+
- `schema['~standard']` implements Standard Schema v1 without an adapter.
|
|
31128
|
+
- `createParseContext()` customizes messages per request, locale, or form.
|
|
31129
|
+
- `SpellValidationError` offers `flatten()`, `flattenFirst()`, and `messagesAt()` for UI errors.
|
|
31130
|
+
- Object and record parsing is hardened against prototype-pollution keys.
|
|
31106
31131
|
|
|
31107
31132
|
## Documentation
|
|
31108
31133
|
|
|
@@ -31121,184 +31146,307 @@ const user = result.data;
|
|
|
31121
31146
|
|
|
31122
31147
|
## API Overview
|
|
31123
31148
|
|
|
31124
|
-
| Symbol | Purpose
|
|
31125
|
-
| ---------------------- |
|
|
31126
|
-
| `s` | Creates schemas
|
|
31127
|
-
| `
|
|
31128
|
-
| `
|
|
31129
|
-
| `
|
|
31149
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
31150
|
+
| ---------------------- | ------------------------------------------- | ------------------------------------ | --------------------------------------------------------------- |
|
|
31151
|
+
| `s` | Creates schemas | Sync, or async when checks are async | `checkAsync()` anywhere in the tree requires `parseAsync()` |
|
|
31152
|
+
| `Schema` | Base class of every schema | Sync or async | Modifiers return copies; schemas are never mutated |
|
|
31153
|
+
| `createParseContext()` | Creates request-local messages | Sync | Pass the context to each parse call |
|
|
31154
|
+
| `joinIssuePath()` | Flattens issue paths to UI keys | Sync | Empty or undefined paths join to `''` |
|
|
31155
|
+
| `SpellValidationError` | Carries validation issues | Sync/async parse failures | Use `safeParse()` for expected invalid data |
|
|
31156
|
+
| `SpellDefinitionError` | Rejects non-portable or invalid definitions | Sync | Thrown by `definition()` and object derivations, not by parsing |
|
|
31157
|
+
| `ErrorCode` | Issue code constants | n/a | Narrow `Issue` on `code` to read typed `params` |
|
|
31158
|
+
| `toJsonSchema()` | Converts a definition to JSON Schema | Sync | Imported from `@vielzeug/spell/json` |
|
|
31130
31159
|
|
|
31131
31160
|
## Package Entry Point
|
|
31132
31161
|
|
|
31133
|
-
| Import | Purpose
|
|
31134
|
-
| ---------------------------- |
|
|
31135
|
-
| `@vielzeug/spell` | Schema builders, errors, types, and
|
|
31136
|
-
| `@vielzeug/spell/json` |
|
|
31137
|
-
| `@vielzeug/spell/predicates` | Standalone format
|
|
31162
|
+
| Import | Purpose |
|
|
31163
|
+
| ---------------------------- | ------------------------------------------------------- |
|
|
31164
|
+
| `@vielzeug/spell` | Schema builders, base class, errors, types, and context |
|
|
31165
|
+
| `@vielzeug/spell/json` | `toJsonSchema()` and the `JsonSchema` type |
|
|
31166
|
+
| `@vielzeug/spell/predicates` | Standalone string format predicates |
|
|
31138
31167
|
|
|
31139
31168
|
```ts
|
|
31140
31169
|
import { createParseContext, s, type Infer } from '@vielzeug/spell';
|
|
31141
|
-
import {
|
|
31170
|
+
import { toJsonSchema } from '@vielzeug/spell/json';
|
|
31142
31171
|
import { isEmail } from '@vielzeug/spell/predicates';
|
|
31143
31172
|
```
|
|
31144
31173
|
|
|
31145
|
-
##
|
|
31174
|
+
## Builders
|
|
31146
31175
|
|
|
31147
31176
|
All builders live under `s`.
|
|
31148
31177
|
|
|
31149
|
-
| Builder
|
|
31150
|
-
|
|
|
31151
|
-
| `string
|
|
31152
|
-
| `
|
|
31153
|
-
| `
|
|
31154
|
-
| `
|
|
31155
|
-
| `
|
|
31178
|
+
| Builder | Returns | Notes |
|
|
31179
|
+
| ---------------------------------------------- | ------------------------------------- | ----------------------------------------------------- |
|
|
31180
|
+
| `s.string()` | `StringSchema` | |
|
|
31181
|
+
| `s.number()` | `NumberSchema` | Rejects `NaN` |
|
|
31182
|
+
| `s.bigint()` | `BigIntSchema` | |
|
|
31183
|
+
| `s.boolean()` | `BooleanSchema` | |
|
|
31184
|
+
| `s.date()` | `DateSchema` | Rejects invalid dates with `invalid_date` |
|
|
31185
|
+
| `s.literal(value)` | `LiteralSchema` | `string`, `number`, `boolean`, `null`, or `undefined` |
|
|
31186
|
+
| `s.enum(values)` | `EnumSchema` | Non-empty tuple of strings or numbers |
|
|
31187
|
+
| `s.null()`, `s.undefined()` | `LiteralSchema` | |
|
|
31188
|
+
| `s.unknown()` | `Schema` | Accepts any value |
|
|
31189
|
+
| `s.never()` | `NeverSchema` | Rejects every value |
|
|
31190
|
+
| `s.instanceof(cls)` | `InstanceOfSchema` | Accepts abstract constructors |
|
|
31191
|
+
| `s.array(item)` | `ArraySchema` | |
|
|
31192
|
+
| `s.tuple(items)` | `TupleSchema` | Exact length unless `.rest()` is used |
|
|
31193
|
+
| `s.set(item)` | `SetSchema` | |
|
|
31194
|
+
| `s.map(key, value)` | `MapSchema` | |
|
|
31195
|
+
| `s.record(key, value)` | `RecordSchema` | Drops unsafe keys (`__proto__`, `constructor`, …) |
|
|
31196
|
+
| `s.object(shape)` | `ObjectSchema` | Strict by default |
|
|
31197
|
+
| `s.union(...schemas)` | `UnionSchema` | At least two schemas; first match wins |
|
|
31198
|
+
| `s.intersect(...schemas)` | `IntersectSchema` | At least two schemas; object outputs are deep-merged |
|
|
31199
|
+
| `s.discriminatedUnion(key, branches)` | `DiscriminatedUnionSchema` | Branches are object schemas keyed by tag |
|
|
31200
|
+
| `s.lazy(getter)` | `LazySchema` | Recursive schemas |
|
|
31201
|
+
| `s.coerce.string/number/boolean/bigint/date()` | Primitive schema with `unknown` input | Coercion runs before the type check |
|
|
31202
|
+
|
|
31203
|
+
### `s.coerce`
|
|
31204
|
+
|
|
31205
|
+
| Builder | Converts |
|
|
31206
|
+
| -------------------- | --------------------------------------------------------- |
|
|
31207
|
+
| `s.coerce.string()` | Any non-nullish value with `String()` |
|
|
31208
|
+
| `s.coerce.number()` | Numeric strings and booleans with `Number()` |
|
|
31209
|
+
| `s.coerce.boolean()` | `'true'`/`'1'`/`1` and `'false'`/`'0'`/`0` |
|
|
31210
|
+
| `s.coerce.bigint()` | Safe-integer numbers and integer strings up to 1000 chars |
|
|
31211
|
+
| `s.coerce.date()` | Strings and epoch milliseconds with `new Date()` |
|
|
31212
|
+
|
|
31213
|
+
Values the coercer cannot convert reach the type check unchanged and fail with `invalid_type`.
|
|
31214
|
+
|
|
31215
|
+
## Schema Methods
|
|
31216
|
+
|
|
31217
|
+
Every schema extends `Schema`.
|
|
31218
|
+
|
|
31219
|
+
### Parsing
|
|
31220
|
+
|
|
31221
|
+
```ts
|
|
31222
|
+
parse(value: unknown, context?: ParseContext): Output;
|
|
31223
|
+
safeParse(value: unknown, context?: ParseContext): ParseResult;
|
|
31224
|
+
parseAsync(value: unknown, context?: ParseContext): Promise;
|
|
31225
|
+
safeParseAsync(value: unknown, context?: ParseContext): Promise>;
|
|
31226
|
+
is(value: unknown): value is Output;
|
|
31227
|
+
assert(value: unknown, label?: string): asserts value is Output;
|
|
31228
|
+
```
|
|
31229
|
+
|
|
31230
|
+
**Returns:** `parse()` returns the parsed output or throws `SpellValidationError`. `safeParse()` returns a `ParseResult`.
|
|
31231
|
+
|
|
31232
|
+
`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`.
|
|
31233
|
+
|
|
31234
|
+
**Example:**
|
|
31156
31235
|
|
|
31157
31236
|
```ts
|
|
31158
|
-
|
|
31159
|
-
email: s.string().email(),
|
|
31160
|
-
id: s.string().uuid(),
|
|
31161
|
-
role: s.enum(['admin', 'member'] as const),
|
|
31162
|
-
});
|
|
31237
|
+
import { s } from '@vielzeug/spell';
|
|
31163
31238
|
|
|
31164
|
-
|
|
31239
|
+
const result = s.string().email().safeParse('ada@example.com');
|
|
31240
|
+
|
|
31241
|
+
if (result.success) console.log(result.data);
|
|
31165
31242
|
```
|
|
31166
31243
|
|
|
31167
|
-
|
|
31244
|
+
### Checks
|
|
31168
31245
|
|
|
31169
|
-
|
|
31246
|
+
```ts
|
|
31247
|
+
check(fn: (value: Output, ctx: CheckContext) => ValidateResult): this;
|
|
31248
|
+
checkAsync(fn: (value: Output, ctx: CheckContext) => Promise): this;
|
|
31249
|
+
```
|
|
31170
31250
|
|
|
31171
|
-
|
|
31251
|
+
**Returns:** A copy of the schema with the rule appended.
|
|
31252
|
+
|
|
31253
|
+
A 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.
|
|
31254
|
+
|
|
31255
|
+
**Example:**
|
|
31172
31256
|
|
|
31173
31257
|
```ts
|
|
31174
|
-
const
|
|
31175
|
-
|
|
31258
|
+
const Signup = s.object({ confirm: s.string(), password: s.string() }).check((value, ctx) => {
|
|
31259
|
+
if (value.password !== value.confirm)
|
|
31260
|
+
ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
|
|
31261
|
+
});
|
|
31176
31262
|
```
|
|
31177
31263
|
|
|
31178
|
-
|
|
31264
|
+
### Modifiers
|
|
31179
31265
|
|
|
31180
|
-
|
|
31266
|
+
| Method | Returns | Effect |
|
|
31267
|
+
| ----------------- | ------------------------------------------------- | ------------------------------------------------------------------------ |
|
|
31268
|
+
| `optional()` | `Schema` | Accepts `undefined` |
|
|
31269
|
+
| `nullable()` | `Schema` | Accepts `null` |
|
|
31270
|
+
| `nullish()` | `Schema` | Accepts `null` and `undefined` |
|
|
31271
|
+
| `required()` | `Schema, …>` | Rejects `undefined` again; clears `optional()` and `default()` |
|
|
31272
|
+
| `default(value)` | `this` | Returns a fresh copy of `value` for `undefined`; a function is a factory |
|
|
31273
|
+
| `catch(fallback)` | `this` | Returns a fresh copy of `fallback` when validation fails |
|
|
31274
|
+
| `transform(fn)` | `Schema` | Maps the value in chain order; skipped once an earlier step failed |
|
|
31275
|
+
| `preprocess(fn)` | `this` | Maps raw input before the type check |
|
|
31276
|
+
| `pipe(next)` | `PipeSchema` | Parses with this schema, then feeds the output to `next` |
|
|
31277
|
+
| `describe(text)` | `this` | Sets `description`, which `definition()` includes |
|
|
31181
31278
|
|
|
31182
|
-
|
|
31279
|
+
`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.
|
|
31183
31280
|
|
|
31184
|
-
|
|
31281
|
+
### Properties and definitions
|
|
31185
31282
|
|
|
31186
|
-
|
|
31187
|
-
|
|
31188
|
-
|
|
31189
|
-
|
|
31190
|
-
|
|
31191
|
-
|
|
31192
|
-
|
|
31193
|
-
|
|
31283
|
+
| Member | Type | Description |
|
|
31284
|
+
| -------------- | --------------------------------------- | ---------------------------------------------------------------- |
|
|
31285
|
+
| `kind` | `SchemaKind` | Schema kind, e.g. `'string'` or `'object'` |
|
|
31286
|
+
| `description` | `string \| undefined` | Text set with `describe()` |
|
|
31287
|
+
| `isOptional` | `boolean` | `true` with `optional()`, `nullish()`, `default()`, or `catch()` |
|
|
31288
|
+
| `isNullable` | `boolean` | `true` with `nullable()` or `nullish()` |
|
|
31289
|
+
| `'~standard'` | `StandardSchemaV1.Props` | Standard Schema v1 protocol |
|
|
31290
|
+
| `definition()` | `SchemaDescriptor` | Frozen declarative descriptor |
|
|
31194
31291
|
|
|
31195
|
-
`
|
|
31292
|
+
`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 })`.
|
|
31196
31293
|
|
|
31197
|
-
|
|
31294
|
+
### Standard Schema
|
|
31295
|
+
|
|
31296
|
+
`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.
|
|
31198
31297
|
|
|
31199
31298
|
```ts
|
|
31200
|
-
|
|
31299
|
+
const User = s.object({ name: s.string() });
|
|
31300
|
+
const result = await User['~standard'].validate({ name: 'Ada' });
|
|
31301
|
+
```
|
|
31201
31302
|
|
|
31202
|
-
|
|
31203
|
-
|
|
31204
|
-
|
|
31303
|
+
## String Schema
|
|
31304
|
+
|
|
31305
|
+
```ts
|
|
31306
|
+
min(length: number, message?): this;
|
|
31307
|
+
max(length: number, message?): this;
|
|
31308
|
+
length(exact: number, message?): this;
|
|
31309
|
+
nonEmpty(message?): this;
|
|
31310
|
+
startsWith(prefix: string, message?): this;
|
|
31311
|
+
endsWith(suffix: string, message?): this;
|
|
31312
|
+
includes(substr: string, message?): this;
|
|
31313
|
+
regex(pattern: RegExp, message?): this;
|
|
31314
|
+
url(options?: { message?: MessageFn; protocols?: readonly string[] }): this;
|
|
31315
|
+
nanoid(length?: number, message?): this;
|
|
31316
|
+
trim(): this;
|
|
31317
|
+
lowercase(): this;
|
|
31318
|
+
uppercase(): this;
|
|
31205
31319
|
```
|
|
31206
31320
|
|
|
31207
|
-
|
|
31321
|
+
Format 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`.
|
|
31208
31322
|
|
|
31209
|
-
|
|
31323
|
+
Format 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.
|
|
31210
31324
|
|
|
31211
|
-
|
|
31325
|
+
## Number, BigInt, and Date Schemas
|
|
31212
31326
|
|
|
31213
|
-
|
|
31214
|
-
|
|
31215
|
-
|
|
31216
|
-
|
|
31217
|
-
|
|
31218
|
-
});
|
|
31327
|
+
| Schema | Methods |
|
|
31328
|
+
| -------------- | --------------------------------------------------------------------------------------------------------- |
|
|
31329
|
+
| `NumberSchema` | `min`, `max`, `positive`, `negative`, `nonNegative`, `nonPositive`, `int`, `safe`, `finite`, `multipleOf` |
|
|
31330
|
+
| `BigIntSchema` | `min`, `max`, `positive`, `negative`, `nonNegative`, `nonPositive`, `multipleOf` |
|
|
31331
|
+
| `DateSchema` | `min(date)`, `max(date)` |
|
|
31219
31332
|
|
|
31220
|
-
|
|
31221
|
-
.string()
|
|
31222
|
-
.email()
|
|
31223
|
-
.checkAsync(async (value) => {
|
|
31224
|
-
return (await emailAvailable(value)) || 'Email is already registered';
|
|
31225
|
-
});
|
|
31226
|
-
```
|
|
31333
|
+
Each method takes an optional trailing `message`. `safe()` requires an integer within `Number.MIN_SAFE_INTEGER`…`Number.MAX_SAFE_INTEGER`.
|
|
31227
31334
|
|
|
31228
|
-
|
|
31335
|
+
## Collection Schemas
|
|
31229
31336
|
|
|
31230
|
-
|
|
31337
|
+
| Schema | Methods and members |
|
|
31338
|
+
| -------------- | ------------------------------------------------------ |
|
|
31339
|
+
| `ArraySchema` | `min`, `max`, `length`, `nonEmpty`, `unique(options?)` |
|
|
31340
|
+
| `TupleSchema` | `items`, `rest(schema)` |
|
|
31341
|
+
| `SetSchema` | `min`, `max`, `size`, `nonEmpty` |
|
|
31342
|
+
| `MapSchema` | `min`, `max`, `size`, `nonEmpty` |
|
|
31343
|
+
| `RecordSchema` | (none) |
|
|
31231
31344
|
|
|
31232
31345
|
```ts
|
|
31233
|
-
|
|
31234
|
-
s.string().nullable();
|
|
31235
|
-
s.string().nullish();
|
|
31236
|
-
s.string().required();
|
|
31237
|
-
s.string().default('guest');
|
|
31238
|
-
s.string().catch('guest');
|
|
31239
|
-
s.string()
|
|
31240
|
-
.trim()
|
|
31241
|
-
.transform((value) => value.toLowerCase());
|
|
31242
|
-
s.string().pipe(s.string().slug());
|
|
31243
|
-
s.string().label('User name');
|
|
31346
|
+
unique(options?: { by?: (item: InferOutput) => unknown; message?: MessageFn }): this;
|
|
31244
31347
|
```
|
|
31245
31348
|
|
|
31246
|
-
`
|
|
31349
|
+
`unique()` compares items with `Set` semantics, or compares the keys returned by `by`. A `by` selector makes `definition()` throw.
|
|
31247
31350
|
|
|
31248
|
-
##
|
|
31249
|
-
|
|
31250
|
-
Wraps 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.
|
|
31351
|
+
## Object Schema
|
|
31251
31352
|
|
|
31252
31353
|
```ts
|
|
31253
|
-
|
|
31354
|
+
readonly shape: T;
|
|
31355
|
+
relaxed(): this;
|
|
31356
|
+
strict(): this;
|
|
31357
|
+
tolerate(...keys: string[]): this;
|
|
31358
|
+
extend(extra: U): ObjectSchema & U>;
|
|
31359
|
+
pick(...keys: K[]): ObjectSchema>;
|
|
31360
|
+
omit(...keys: K[]): ObjectSchema>;
|
|
31361
|
+
partial(): ObjectSchema }>;
|
|
31362
|
+
partial(...keys: K[]): ObjectSchema & { [P in K]: Optional }>;
|
|
31363
|
+
keyof(): EnumSchema;
|
|
31254
31364
|
```
|
|
31255
31365
|
|
|
31256
|
-
|
|
31366
|
+
| Method | Description |
|
|
31367
|
+
| ------------ | ---------------------------------------------------------------------------- |
|
|
31368
|
+
| `strict()` | Rejects unknown keys with one `invalid_keys` issue (default) |
|
|
31369
|
+
| `relaxed()` | Copies unknown keys to the output, skipping unsafe keys |
|
|
31370
|
+
| `tolerate()` | Accepts and drops the named keys; other unknown keys follow the current mode |
|
|
31371
|
+
| `extend()` | Adds fields; same-named fields are replaced |
|
|
31372
|
+
| `pick()` | Keeps the named fields |
|
|
31373
|
+
| `omit()` | Removes the named fields |
|
|
31374
|
+
| `partial()` | Makes all or the named fields optional |
|
|
31375
|
+
| `keyof()` | Enum schema of the shape keys |
|
|
31257
31376
|
|
|
31258
|
-
|
|
31377
|
+
`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.
|
|
31259
31378
|
|
|
31260
|
-
|
|
31379
|
+
Absent keys whose field returns `undefined` are left out of the output. Field defaults are written for absent keys.
|
|
31261
31380
|
|
|
31262
|
-
|
|
31263
|
-
import { s } from '@vielzeug/spell';
|
|
31264
|
-
import { fromDefinition } from '@vielzeug/spell/json';
|
|
31381
|
+
## Composition Schemas
|
|
31265
31382
|
|
|
31266
|
-
|
|
31267
|
-
|
|
31268
|
-
|
|
31269
|
-
|
|
31383
|
+
| Schema | Members | Failure |
|
|
31384
|
+
| -------------------------- | ------------------------------------------- | --------------------------------------------------------------------- |
|
|
31385
|
+
| `UnionSchema` | `schemas` | One `invalid_union` issue; `params.errors` holds each branch's issues |
|
|
31386
|
+
| `IntersectSchema` | `schemas` | Issues from every failing branch |
|
|
31387
|
+
| `DiscriminatedUnionSchema` | `discriminator`, `branches` (`ReadonlyMap`) | `invalid_discriminator` for an unknown tag; branch issues otherwise |
|
|
31388
|
+
| `LazySchema` | (none) | Issues of the resolved schema |
|
|
31389
|
+
| `PipeSchema` | `from`, `to` | Issues of the first failing stage |
|
|
31270
31390
|
|
|
31271
|
-
|
|
31272
|
-
const jsonSchema = fromDefinition(definition);
|
|
31273
|
-
```
|
|
31391
|
+
`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.
|
|
31274
31392
|
|
|
31275
|
-
|
|
31393
|
+
Intersections of object schemas need `.relaxed()` branches, because each strict branch rejects the other branch's keys.
|
|
31276
31394
|
|
|
31277
31395
|
## Parse Contexts
|
|
31278
31396
|
|
|
31279
|
-
`createParseContext()` creates immutable request-local validation messages.
|
|
31280
|
-
|
|
31281
31397
|
```ts
|
|
31282
31398
|
function createParseContext(messages?: DeepPartial): ParseContext;
|
|
31283
31399
|
```
|
|
31284
31400
|
|
|
31285
|
-
**Returns:** A parse context with built-in messages merged with the supplied overrides.
|
|
31401
|
+
**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.
|
|
31402
|
+
|
|
31403
|
+
**Example:**
|
|
31286
31404
|
|
|
31287
31405
|
```ts
|
|
31288
31406
|
import { createParseContext, s } from '@vielzeug/spell';
|
|
31289
31407
|
|
|
31290
|
-
const context = createParseContext({
|
|
31291
|
-
object: { invalidKeys: () => 'Unsupported field' },
|
|
31292
|
-
});
|
|
31293
|
-
|
|
31408
|
+
const context = createParseContext({ object: { invalidKeys: () => 'Unsupported field' } });
|
|
31294
31409
|
const result = s.object({ email: s.string().email() }).safeParse({ email: 'ada@example.com', extra: true }, context);
|
|
31295
31410
|
|
|
31296
|
-
if (!result.success)
|
|
31297
|
-
|
|
31298
|
-
|
|
31299
|
-
|
|
31411
|
+
if (!result.success) console.log(result.error.issues[0].message); // 'Unsupported field'
|
|
31412
|
+
```
|
|
31413
|
+
|
|
31414
|
+
## JSON Schema
|
|
31415
|
+
|
|
31416
|
+
```ts
|
|
31417
|
+
import { toJsonSchema, type JsonSchema } from '@vielzeug/spell/json';
|
|
31418
|
+
|
|
31419
|
+
function toJsonSchema(definition: SchemaDescriptor): JsonSchema;
|
|
31420
|
+
```
|
|
31421
|
+
|
|
31422
|
+
**Returns:** A JSON Schema 2020-12 object.
|
|
31423
|
+
|
|
31424
|
+
| Definition | JSON Schema |
|
|
31425
|
+
| ------------------------------- | ------------------------------------------------------------------- |
|
|
31426
|
+
| `isoDate`, `isoDateTime`, `url` | `format: 'date'`, `'date-time'`, `'uri'` |
|
|
31427
|
+
| `base64`, `base64url` | `contentEncoding` |
|
|
31428
|
+
| `ip` | `anyOf` of `ipv4` and `ipv6` formats |
|
|
31429
|
+
| Several formats or patterns | `allOf` |
|
|
31430
|
+
| `bigint` bounds | Numeric bounds (may lose precision above `Number.MAX_SAFE_INTEGER`) |
|
|
31431
|
+
| `date`, `instanceof` | `$comment` only |
|
|
31432
|
+
| `set`, `map` | Array with `uniqueItems`, object with `additionalProperties` |
|
|
31433
|
+
| `isNullable` | `anyOf` with `{ type: 'null' }` |
|
|
31434
|
+
|
|
31435
|
+
**Example:**
|
|
31436
|
+
|
|
31437
|
+
```ts
|
|
31438
|
+
import { s } from '@vielzeug/spell';
|
|
31439
|
+
import { toJsonSchema } from '@vielzeug/spell/json';
|
|
31440
|
+
|
|
31441
|
+
const jsonSchema = toJsonSchema(s.object({ id: s.string().uuid() }).definition());
|
|
31300
31442
|
```
|
|
31301
31443
|
|
|
31444
|
+
## Predicates
|
|
31445
|
+
|
|
31446
|
+
`@vielzeug/spell/predicates` exports the format tests used by `StringSchema`. Each takes a string and returns `boolean`.
|
|
31447
|
+
|
|
31448
|
+
`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`.
|
|
31449
|
+
|
|
31302
31450
|
## Types
|
|
31303
31451
|
|
|
31304
31452
|
### Inference types
|
|
@@ -31308,43 +31456,9 @@ if (!result.success) {
|
|
|
31308
31456
|
| `Infer` | Parsed output; alias of `InferOutput` |
|
|
31309
31457
|
| `InferInput` | Input accepted before parsing or transformation |
|
|
31310
31458
|
| `InferOutput` | Value returned after parsing and transformation |
|
|
31459
|
+
| `AnySchema` | `Schema`; any schema |
|
|
31311
31460
|
|
|
31312
|
-
|
|
31313
|
-
|
|
31314
|
-
### Standard Schema
|
|
31315
|
-
|
|
31316
|
-
```ts
|
|
31317
|
-
interface StandardSchemaV1 {
|
|
31318
|
-
readonly '~standard': StandardSchemaV1.Props;
|
|
31319
|
-
}
|
|
31320
|
-
|
|
31321
|
-
namespace StandardSchemaV1 {
|
|
31322
|
-
interface Props {
|
|
31323
|
-
readonly version: 1;
|
|
31324
|
-
readonly vendor: string;
|
|
31325
|
-
readonly validate: (value: unknown, options?: Options) => Result | Promise>;
|
|
31326
|
-
readonly types?: Types;
|
|
31327
|
-
}
|
|
31328
|
-
|
|
31329
|
-
type Result = { readonly value: Output; readonly issues?: undefined } | { readonly issues: readonly Issue[] };
|
|
31330
|
-
interface Options {
|
|
31331
|
-
readonly libraryOptions?: Record;
|
|
31332
|
-
}
|
|
31333
|
-
interface Issue {
|
|
31334
|
-
readonly message: string;
|
|
31335
|
-
readonly path?: readonly (PropertyKey | PathSegment)[];
|
|
31336
|
-
}
|
|
31337
|
-
interface PathSegment {
|
|
31338
|
-
readonly key: PropertyKey;
|
|
31339
|
-
}
|
|
31340
|
-
interface Types {
|
|
31341
|
-
readonly input: Input;
|
|
31342
|
-
readonly output: Output;
|
|
31343
|
-
}
|
|
31344
|
-
type InferInput = NonNullable['input'];
|
|
31345
|
-
type InferOutput = NonNullable['output'];
|
|
31346
|
-
}
|
|
31347
|
-
```
|
|
31461
|
+
Object 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` for a parameter that must parse to `T`.
|
|
31348
31462
|
|
|
31349
31463
|
### Parse result and issues
|
|
31350
31464
|
|
|
@@ -31353,33 +31467,30 @@ type ParseResult = { data: T; success: true } | { error: SpellValidationError; s
|
|
|
31353
31467
|
|
|
31354
31468
|
type Issue =
|
|
31355
31469
|
| { code: 'custom'; message: string; params?: Record; path: (string | number)[] }
|
|
31356
|
-
| { code: 'invalid_base64'; message: string; params: { format: string }; path: (string | number)[] }
|
|
31357
31470
|
| { code: 'invalid_date'; message: string; params?: undefined; path: (string | number)[] }
|
|
31358
|
-
| {
|
|
31471
|
+
| {
|
|
31472
|
+
code: 'invalid_discriminator';
|
|
31473
|
+
message: string;
|
|
31474
|
+
params: { discriminator: string; expected: string[] };
|
|
31475
|
+
path: (string | number)[];
|
|
31476
|
+
}
|
|
31359
31477
|
| { code: 'invalid_enum'; message: string; params: { values: readonly unknown[] }; path: (string | number)[] }
|
|
31360
31478
|
| { code: 'invalid_finite'; message: string; params?: undefined; path: (string | number)[] }
|
|
31479
|
+
| {
|
|
31480
|
+
code: 'invalid_format';
|
|
31481
|
+
message: string;
|
|
31482
|
+
params: { format: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };
|
|
31483
|
+
path: (string | number)[];
|
|
31484
|
+
}
|
|
31361
31485
|
| { code: 'invalid_integer'; message: string; params?: undefined; path: (string | number)[] }
|
|
31362
31486
|
| { code: 'invalid_keys'; message: string; params: { keys: string[] }; path: (string | number)[] }
|
|
31363
31487
|
| { code: 'invalid_length'; message: string; params: { exact: number }; path: (string | number)[] }
|
|
31364
31488
|
| { code: 'invalid_literal'; message: string; params: { expected: unknown }; path: (string | number)[] }
|
|
31365
31489
|
| { code: 'invalid_multiple_of'; message: string; params: { step: number | bigint }; path: (string | number)[] }
|
|
31366
31490
|
| { code: 'invalid_safe'; message: string; params?: undefined; path: (string | number)[] }
|
|
31367
|
-
| {
|
|
31368
|
-
code: 'invalid_string';
|
|
31369
|
-
message: string;
|
|
31370
|
-
params: { format?: string; includes?: string; pattern?: string; prefix?: string; suffix?: string };
|
|
31371
|
-
path: (string | number)[];
|
|
31372
|
-
}
|
|
31373
31491
|
| { code: 'invalid_type'; message: string; params?: undefined; path: (string | number)[] }
|
|
31374
31492
|
| { code: 'invalid_union'; message: string; params: { errors: Issue[][] }; path: (string | number)[] }
|
|
31375
|
-
| { code: 'invalid_unique'; message: string; params
|
|
31376
|
-
| { code: 'invalid_url'; message: string; params: { format: string }; path: (string | number)[] }
|
|
31377
|
-
| {
|
|
31378
|
-
code: 'invalid_variant';
|
|
31379
|
-
message: string;
|
|
31380
|
-
params: { discriminator: string; expected: string[] };
|
|
31381
|
-
path: (string | number)[];
|
|
31382
|
-
}
|
|
31493
|
+
| { code: 'invalid_unique'; message: string; params?: undefined; path: (string | number)[] }
|
|
31383
31494
|
| {
|
|
31384
31495
|
code: 'too_big';
|
|
31385
31496
|
message: string;
|
|
@@ -31395,12 +31506,12 @@ type Issue =
|
|
|
31395
31506
|
| { code: string & {}; message: string; params?: Record; path: (string | number)[] };
|
|
31396
31507
|
```
|
|
31397
31508
|
|
|
31398
|
-
`ErrorCode` is a const object mapping each
|
|
31509
|
+
`ErrorCode` is a const object mapping each built-in code to its string literal.
|
|
31399
31510
|
|
|
31400
31511
|
### Validation contracts
|
|
31401
31512
|
|
|
31402
31513
|
```ts
|
|
31403
|
-
type ParseContext = { messages: Messages };
|
|
31514
|
+
type ParseContext = { readonly messages: Messages };
|
|
31404
31515
|
|
|
31405
31516
|
type CheckContext = {
|
|
31406
31517
|
addIssue: (issue: {
|
|
@@ -31412,151 +31523,162 @@ type CheckContext = {
|
|
|
31412
31523
|
};
|
|
31413
31524
|
|
|
31414
31525
|
type ValidateResult = boolean | null | undefined | string;
|
|
31526
|
+
|
|
31527
|
+
type MessageFn = Record> = string | ((ctx: Ctx) => string);
|
|
31528
|
+
|
|
31529
|
+
type DeepPartial = { [K in keyof T]?: T[K] extends Record ? DeepPartial : T[K] };
|
|
31415
31530
|
```
|
|
31416
31531
|
|
|
31417
31532
|
### Messages
|
|
31418
31533
|
|
|
31419
|
-
|
|
31420
|
-
type MessageFn = Record> = string | ((ctx: Ctx) => string);
|
|
31534
|
+
`Messages` has one group per schema type. Each entry is a function of the constraint context.
|
|
31421
31535
|
|
|
31536
|
+
```ts
|
|
31422
31537
|
type Messages = {
|
|
31423
|
-
array: {
|
|
31424
|
-
|
|
31425
|
-
|
|
31426
|
-
|
|
31427
|
-
|
|
31428
|
-
|
|
31429
|
-
unique: () => string;
|
|
31430
|
-
};
|
|
31431
|
-
bigint: {
|
|
31432
|
-
max: (ctx: { max: bigint; value: bigint }) => string;
|
|
31433
|
-
min: (ctx: { min: bigint; value: bigint }) => string;
|
|
31434
|
-
multipleOf: (ctx: { step: bigint; value: bigint }) => string;
|
|
31435
|
-
negative: () => string;
|
|
31436
|
-
nonNegative: () => string;
|
|
31437
|
-
nonPositive: () => string;
|
|
31438
|
-
positive: () => string;
|
|
31439
|
-
type: () => string;
|
|
31440
|
-
};
|
|
31441
|
-
boolean: { type: () => string };
|
|
31442
|
-
check: { default: () => string };
|
|
31443
|
-
date: {
|
|
31444
|
-
max: (ctx: { max: Date; value: Date }) => string;
|
|
31445
|
-
min: (ctx: { min: Date; value: Date }) => string;
|
|
31446
|
-
type: () => string;
|
|
31447
|
-
};
|
|
31538
|
+
array: { length; max; min; nonEmpty; type; unique };
|
|
31539
|
+
bigint: { max; min; multipleOf; negative; nonNegative; nonPositive; positive; type };
|
|
31540
|
+
boolean: { type };
|
|
31541
|
+
check: { default };
|
|
31542
|
+
date: { max; min; type };
|
|
31543
|
+
discriminatedUnion: { invalidDiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type };
|
|
31448
31544
|
enum: { invalid: (ctx: { values: readonly unknown[] }) => string };
|
|
31449
31545
|
instanceof: { type: (ctx: { className: string }) => string };
|
|
31450
31546
|
literal: { expected: (ctx: { expected: unknown }) => string };
|
|
31451
|
-
map: {
|
|
31452
|
-
|
|
31453
|
-
|
|
31454
|
-
|
|
31455
|
-
|
|
31456
|
-
type: () => string;
|
|
31457
|
-
};
|
|
31458
|
-
never: { invalid: () => string };
|
|
31459
|
-
number: {
|
|
31460
|
-
finite: () => string;
|
|
31461
|
-
int: () => string;
|
|
31462
|
-
max: (ctx: { max: number; value: number }) => string;
|
|
31463
|
-
min: (ctx: { min: number; value: number }) => string;
|
|
31464
|
-
multipleOf: (ctx: { step: number; value: number }) => string;
|
|
31465
|
-
negative: () => string;
|
|
31466
|
-
nonNegative: () => string;
|
|
31467
|
-
nonPositive: () => string;
|
|
31468
|
-
positive: () => string;
|
|
31469
|
-
safe: () => string;
|
|
31470
|
-
type: () => string;
|
|
31471
|
-
};
|
|
31472
|
-
object: { invalidKeys: (ctx: { keys: string[] }) => string; type: () => string };
|
|
31473
|
-
set: {
|
|
31474
|
-
max: (ctx: { max: number; value: Set }) => string;
|
|
31475
|
-
min: (ctx: { min: number; value: Set }) => string;
|
|
31476
|
-
nonEmpty: () => string;
|
|
31477
|
-
size: (ctx: { exact: number; value: Set }) => string;
|
|
31478
|
-
type: () => string;
|
|
31479
|
-
};
|
|
31547
|
+
map: { max; min; nonEmpty; size; type };
|
|
31548
|
+
never: { invalid };
|
|
31549
|
+
number: { finite; int; max; min; multipleOf; negative; nonNegative; nonPositive; positive; safe; type };
|
|
31550
|
+
object: { invalidKeys: (ctx: { keys: string[] }) => string; type };
|
|
31551
|
+
set: { max; min; nonEmpty; size; type };
|
|
31480
31552
|
string: {
|
|
31481
|
-
base64
|
|
31482
|
-
base64url
|
|
31483
|
-
cuid
|
|
31484
|
-
cuid2
|
|
31485
|
-
|
|
31486
|
-
|
|
31487
|
-
|
|
31488
|
-
|
|
31489
|
-
|
|
31490
|
-
|
|
31491
|
-
|
|
31492
|
-
|
|
31493
|
-
|
|
31494
|
-
|
|
31495
|
-
jwt
|
|
31496
|
-
length
|
|
31497
|
-
max
|
|
31498
|
-
min
|
|
31499
|
-
nanoid
|
|
31500
|
-
nonEmpty
|
|
31501
|
-
numeric
|
|
31502
|
-
regex
|
|
31503
|
-
semver
|
|
31504
|
-
slug
|
|
31505
|
-
startsWith
|
|
31506
|
-
time
|
|
31507
|
-
type
|
|
31508
|
-
ulid
|
|
31509
|
-
url
|
|
31510
|
-
uuid
|
|
31553
|
+
base64;
|
|
31554
|
+
base64url;
|
|
31555
|
+
cuid;
|
|
31556
|
+
cuid2;
|
|
31557
|
+
duration;
|
|
31558
|
+
email;
|
|
31559
|
+
emoji;
|
|
31560
|
+
endsWith;
|
|
31561
|
+
hex;
|
|
31562
|
+
hexColor;
|
|
31563
|
+
includes;
|
|
31564
|
+
ip;
|
|
31565
|
+
isoDate;
|
|
31566
|
+
isoDateTime;
|
|
31567
|
+
jwt;
|
|
31568
|
+
length;
|
|
31569
|
+
max;
|
|
31570
|
+
min;
|
|
31571
|
+
nanoid;
|
|
31572
|
+
nonEmpty;
|
|
31573
|
+
numeric;
|
|
31574
|
+
regex;
|
|
31575
|
+
semver;
|
|
31576
|
+
slug;
|
|
31577
|
+
startsWith;
|
|
31578
|
+
time;
|
|
31579
|
+
type;
|
|
31580
|
+
ulid;
|
|
31581
|
+
url;
|
|
31582
|
+
uuid;
|
|
31511
31583
|
};
|
|
31512
|
-
tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type
|
|
31513
|
-
union: { invalid
|
|
31514
|
-
variant: { invalidDiscriminator: (ctx: { discriminator: string; expected: string[] }) => string; type: () => string };
|
|
31584
|
+
tuple: { length: (ctx: { exact: number }) => string; min: (ctx: { min: number }) => string; type };
|
|
31585
|
+
union: { invalid };
|
|
31515
31586
|
};
|
|
31587
|
+
```
|
|
31516
31588
|
|
|
31517
|
-
|
|
31518
|
-
|
|
31519
|
-
|
|
31589
|
+
Constraint messages receive `value` plus the constraint's parameters, e.g. `string.min` receives `{ min, value }` and `string.includes` receives `{ substr, value }`.
|
|
31590
|
+
|
|
31591
|
+
### Descriptors
|
|
31592
|
+
|
|
31593
|
+
```ts
|
|
31594
|
+
type PatternDescriptor = { readonly flags: string; readonly source: string };
|
|
31595
|
+
|
|
31596
|
+
type SchemaDescriptor = { description?: string; isNullable?: true; isOptional?: true } & (
|
|
31597
|
+
| { kind: 'unknown' | 'never' | 'boolean' | 'lazy' }
|
|
31598
|
+
| {
|
|
31599
|
+
kind: 'bigint';
|
|
31600
|
+
exclusiveMaximum?: bigint;
|
|
31601
|
+
exclusiveMinimum?: bigint;
|
|
31602
|
+
maximum?: bigint;
|
|
31603
|
+
minimum?: bigint;
|
|
31604
|
+
multipleOf?: bigint;
|
|
31605
|
+
}
|
|
31606
|
+
| {
|
|
31607
|
+
kind: 'number';
|
|
31608
|
+
exclusiveMaximum?: number;
|
|
31609
|
+
exclusiveMinimum?: number;
|
|
31610
|
+
finite?: true;
|
|
31611
|
+
integer?: true;
|
|
31612
|
+
maximum?: number;
|
|
31613
|
+
minimum?: number;
|
|
31614
|
+
multipleOf?: number;
|
|
31615
|
+
}
|
|
31616
|
+
| {
|
|
31617
|
+
kind: 'string';
|
|
31618
|
+
formats?: readonly string[];
|
|
31619
|
+
maxLength?: number;
|
|
31620
|
+
minLength?: number;
|
|
31621
|
+
patterns?: readonly PatternDescriptor[];
|
|
31622
|
+
}
|
|
31623
|
+
| { kind: 'date'; maximum?: string; minimum?: string }
|
|
31624
|
+
| { className: string; kind: 'instanceof' }
|
|
31625
|
+
| { kind: 'literal'; value: string | number | boolean | null | undefined }
|
|
31626
|
+
| { kind: 'enum'; values: readonly (string | number)[] }
|
|
31627
|
+
| { items: SchemaDescriptor; kind: 'array'; maxItems?: number; minItems?: number; uniqueItems?: true }
|
|
31628
|
+
| { items: readonly SchemaDescriptor[]; kind: 'tuple'; rest: SchemaDescriptor | null }
|
|
31629
|
+
| {
|
|
31630
|
+
fields: Readonly>;
|
|
31631
|
+
kind: 'object';
|
|
31632
|
+
strict: boolean;
|
|
31633
|
+
tolerated?: readonly string[];
|
|
31634
|
+
}
|
|
31635
|
+
| { key: SchemaDescriptor; kind: 'record'; value: SchemaDescriptor }
|
|
31636
|
+
| { items: SchemaDescriptor; kind: 'set'; maxSize?: number; minSize?: number }
|
|
31637
|
+
| { key: SchemaDescriptor; kind: 'map'; maxSize?: number; minSize?: number; value: SchemaDescriptor }
|
|
31638
|
+
| { branches: readonly SchemaDescriptor[]; kind: 'union' | 'intersect' }
|
|
31639
|
+
| { branches: Readonly>; discriminator: string; kind: 'discriminatedUnion' }
|
|
31640
|
+
| { from: SchemaDescriptor; kind: 'pipe'; to: SchemaDescriptor }
|
|
31641
|
+
);
|
|
31642
|
+
|
|
31643
|
+
type SchemaKind = SchemaDescriptor['kind'];
|
|
31644
|
+
|
|
31645
|
+
type JsonSchema = Record; // from '@vielzeug/spell/json'
|
|
31520
31646
|
```
|
|
31521
31647
|
|
|
31522
|
-
|
|
31648
|
+
Date bounds are ISO strings. `formats` lists format method names in chain order; `patterns` lists `regex()`, `startsWith()`, `endsWith()`, `includes()`, and `url()` protocol patterns.
|
|
31649
|
+
|
|
31650
|
+
### Standard Schema
|
|
31523
31651
|
|
|
31524
31652
|
```ts
|
|
31525
|
-
|
|
31526
|
-
|
|
31527
|
-
|
|
31528
|
-
| { className: string; kind: 'instanceof' }
|
|
31529
|
-
| {
|
|
31530
|
-
contentEncoding?: string;
|
|
31531
|
-
format?: string;
|
|
31532
|
-
kind: 'string';
|
|
31533
|
-
maxLength?: number;
|
|
31534
|
-
minLength?: number;
|
|
31535
|
-
pattern?: string | null;
|
|
31536
|
-
}
|
|
31537
|
-
| {
|
|
31538
|
-
exclusiveMaximum?: number;
|
|
31539
|
-
exclusiveMinimum?: number;
|
|
31540
|
-
kind: 'number';
|
|
31541
|
-
maximum?: number;
|
|
31542
|
-
minimum?: number;
|
|
31543
|
-
multipleOf?: number;
|
|
31544
|
-
typeHint?: 'integer';
|
|
31545
|
-
}
|
|
31546
|
-
| { kind: 'literal'; value: string | number | boolean | null | undefined }
|
|
31547
|
-
| { kind: 'enum'; values: readonly (string | number)[] }
|
|
31548
|
-
| { items: SchemaDescriptor; kind: 'array'; maxItems?: number; minItems?: number }
|
|
31549
|
-
| { items: SchemaDescriptor[]; kind: 'tuple'; rest: SchemaDescriptor | null }
|
|
31550
|
-
| { fields: Record; kind: 'object'; strict: boolean }
|
|
31551
|
-
| { key: SchemaDescriptor; kind: 'record'; value: SchemaDescriptor }
|
|
31552
|
-
| { items: SchemaDescriptor; kind: 'set' }
|
|
31553
|
-
| { key: SchemaDescriptor; kind: 'map'; value: SchemaDescriptor }
|
|
31554
|
-
| { branches: SchemaDescriptor[]; kind: 'union' | 'intersect' }
|
|
31555
|
-
| { branches: Record; discriminator: string; kind: 'variant' }
|
|
31556
|
-
| { from: SchemaDescriptor; kind: 'pipe'; to: SchemaDescriptor }
|
|
31557
|
-
);
|
|
31653
|
+
interface StandardSchemaV1 {
|
|
31654
|
+
readonly '~standard': StandardSchemaV1.Props;
|
|
31655
|
+
}
|
|
31558
31656
|
|
|
31559
|
-
|
|
31657
|
+
namespace StandardSchemaV1 {
|
|
31658
|
+
interface Props {
|
|
31659
|
+
readonly types?: Types | undefined;
|
|
31660
|
+
readonly validate: (value: unknown, options?: Options | undefined) => Result | Promise>;
|
|
31661
|
+
readonly vendor: string;
|
|
31662
|
+
readonly version: 1;
|
|
31663
|
+
}
|
|
31664
|
+
type Result = { readonly issues: readonly Issue[] } | { readonly issues?: undefined; readonly value: Output };
|
|
31665
|
+
interface Options {
|
|
31666
|
+
readonly libraryOptions?: Record | undefined;
|
|
31667
|
+
}
|
|
31668
|
+
interface Issue {
|
|
31669
|
+
readonly message: string;
|
|
31670
|
+
readonly path?: readonly (PropertyKey | PathSegment)[] | undefined;
|
|
31671
|
+
}
|
|
31672
|
+
interface PathSegment {
|
|
31673
|
+
readonly key: PropertyKey;
|
|
31674
|
+
}
|
|
31675
|
+
interface Types {
|
|
31676
|
+
readonly input: Input;
|
|
31677
|
+
readonly output: Output;
|
|
31678
|
+
}
|
|
31679
|
+
type InferInput = NonNullable['input'];
|
|
31680
|
+
type InferOutput = NonNullable['output'];
|
|
31681
|
+
}
|
|
31560
31682
|
```
|
|
31561
31683
|
|
|
31562
31684
|
### Error helpers
|
|
@@ -31565,23 +31687,23 @@ type JsonSchema = Record;
|
|
|
31565
31687
|
type FlatError = { messages: string[]; path: (string | number)[] };
|
|
31566
31688
|
type FlatErrorFirst = { message: string; path: (string | number)[] };
|
|
31567
31689
|
|
|
31568
|
-
/** An issue path in either shape: spell-native segments or Standard Schema `{ key }` segments. */
|
|
31569
31690
|
type IssuePathSegment = PropertyKey | { readonly key: PropertyKey };
|
|
31570
31691
|
type IssuePath = readonly IssuePathSegment[];
|
|
31571
31692
|
|
|
31572
|
-
/** The synchronous parse surface; `AnySchema` omits `safeParse`, adapter parameters use this. */
|
|
31573
|
-
type SyncParsable = { safeParse(value: unknown): ParseResult };
|
|
31574
|
-
|
|
31575
31693
|
function joinIssuePath(path: IssuePath | undefined, separator?: string): string;
|
|
31576
31694
|
```
|
|
31577
31695
|
|
|
31578
|
-
`joinIssuePath()` flattens
|
|
31696
|
+
`joinIssuePath()` flattens a Spell or Standard Schema issue path into a UI key such as `'permissions.0.slug'`.
|
|
31579
31697
|
|
|
31580
31698
|
## Errors
|
|
31581
31699
|
|
|
31582
|
-
|
|
31583
|
-
|
|
31584
|
-
|
|
31700
|
+
| Class | Thrown when | Members |
|
|
31701
|
+
| ---------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
|
|
31702
|
+
| `SpellError` | Base class; thrown directly when synchronous parsing meets an async check | `name`, `message` |
|
|
31703
|
+
| `SpellValidationError` | `parse()`, `parseAsync()`, or `assert()` receives invalid input | `issues` (frozen), `flatten()`, `flattenFirst()`, `messagesAt(...path)` |
|
|
31704
|
+
| `SpellDefinitionError` | `definition()` on a non-portable schema; invalid object derivation or discriminated branch | `name`, `message` |
|
|
31705
|
+
|
|
31706
|
+
`SpellValidationError.message` lists one `path: message [code]` line per issue; root issues use `value` as the path.
|
|
31585
31707
|
|
|
31586
31708
|
```ts
|
|
31587
31709
|
const result = s.object({ email: s.string().email() }).safeParse({ email: 'invalid' });
|
|
@@ -31619,42 +31741,27 @@ if (!result.success) {
|
|
|
31619
31741
|
}
|
|
31620
31742
|
```
|
|
31621
31743
|
|
|
31622
|
-
Use `parse()` when invalid input should throw
|
|
31744
|
+
Use `parse()` when invalid input should throw. Use `safeParse()` when invalid input is part of normal control flow.
|
|
31623
31745
|
|
|
31624
31746
|
## Building Schemas
|
|
31625
31747
|
|
|
31626
|
-
|
|
31748
|
+
Compose schemas from the `s` builders. Every method returns a new schema, so you can share and extend base schemas safely.
|
|
31627
31749
|
|
|
31628
31750
|
```ts
|
|
31629
31751
|
import { s } from '@vielzeug/spell';
|
|
31630
31752
|
|
|
31631
31753
|
const Article = s.object({
|
|
31632
31754
|
id: s.string().uuid(),
|
|
31633
|
-
|
|
31755
|
+
meta: s.object({ published: s.boolean(), publishedAt: s.date().nullable() }).relaxed(),
|
|
31634
31756
|
slug: s.string().slug(),
|
|
31635
|
-
tags: s.array(s.string().min(1)).default(
|
|
31636
|
-
|
|
31637
|
-
.object({
|
|
31638
|
-
published: s.boolean(),
|
|
31639
|
-
publishedAt: s.date().nullable(),
|
|
31640
|
-
})
|
|
31641
|
-
.relaxed(),
|
|
31642
|
-
});
|
|
31643
|
-
```
|
|
31644
|
-
|
|
31645
|
-
```ts
|
|
31646
|
-
import { s } from '@vielzeug/spell';
|
|
31647
|
-
|
|
31648
|
-
const Todo = s.object({
|
|
31649
|
-
done: s.boolean(),
|
|
31650
|
-
tags: s.array(s.string().min(1)).default(() => []),
|
|
31651
|
-
title: s.string().min(1),
|
|
31757
|
+
tags: s.array(s.string().min(1)).default([]),
|
|
31758
|
+
title: s.string().trim().min(1).max(120),
|
|
31652
31759
|
});
|
|
31653
31760
|
```
|
|
31654
31761
|
|
|
31655
|
-
Object schemas reject unknown keys by default. Call `.relaxed()`
|
|
31762
|
+
Object schemas reject unknown keys by default. Call `.relaxed()` to keep extra properties in the output.
|
|
31656
31763
|
|
|
31657
|
-
|
|
31764
|
+
Fields with a `default()` are filled in when their key is absent, so `parse({})` returns a fully default-filled object.
|
|
31658
31765
|
|
|
31659
31766
|
```ts
|
|
31660
31767
|
const Config = s.object({
|
|
@@ -31662,92 +31769,68 @@ const Config = s.object({
|
|
|
31662
31769
|
port: s.number().default(3000),
|
|
31663
31770
|
});
|
|
31664
31771
|
|
|
31665
|
-
Config.
|
|
31666
|
-
|
|
31667
|
-
const Form = s.object({ name: s.string(), role: s.string().default('viewer') });
|
|
31668
|
-
Form.partialDefaults(); // { role: 'viewer' }
|
|
31772
|
+
Config.parse({}); // { host: 'localhost', port: 3000 }
|
|
31669
31773
|
```
|
|
31670
31774
|
|
|
31671
|
-
|
|
31672
|
-
|
|
31673
|
-
Chain wrappers to describe missing values and recovery rules without losing schema metadata.
|
|
31775
|
+
`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.
|
|
31674
31776
|
|
|
31675
|
-
|
|
31676
|
-
import { s } from '@vielzeug/spell';
|
|
31777
|
+
## Ordering Checks and Transforms
|
|
31677
31778
|
|
|
31678
|
-
|
|
31679
|
-
|
|
31680
|
-
DisplayName.parse(undefined); // 'Guest'
|
|
31681
|
-
DisplayName.parse(null); // null
|
|
31682
|
-
DisplayName.description; // 'Display name'
|
|
31683
|
-
```
|
|
31684
|
-
|
|
31685
|
-
Call `.required()` to remove `undefined` without removing `null`.
|
|
31779
|
+
Checks, built-in constraints, and transforms run in the order you chain them. A constraint after a transform sees the transformed value.
|
|
31686
31780
|
|
|
31687
31781
|
```ts
|
|
31688
31782
|
import { s } from '@vielzeug/spell';
|
|
31689
31783
|
|
|
31690
|
-
|
|
31784
|
+
// trim() runs first, so ' ' fails min(1)
|
|
31785
|
+
const Title = s.string().trim().min(1);
|
|
31691
31786
|
|
|
31692
|
-
|
|
31693
|
-
|
|
31694
|
-
|
|
31787
|
+
// The check receives the length, not the string
|
|
31788
|
+
const ShortCode = s
|
|
31789
|
+
.string()
|
|
31790
|
+
.transform((value) => value.length)
|
|
31791
|
+
.check((length) => length value.password === value.confirm || 'Passwords must match');
|
|
31695
31792
|
```
|
|
31696
31793
|
|
|
31697
|
-
|
|
31698
|
-
|
|
31699
|
-
```ts
|
|
31700
|
-
import { s } from '@vielzeug/spell';
|
|
31701
|
-
|
|
31702
|
-
const Port = s.number().int().min(1).max(65535).catch(3000);
|
|
31703
|
-
|
|
31704
|
-
Port.parse('not-a-number'); // 3000
|
|
31705
|
-
```
|
|
31794
|
+
Deriving 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.
|
|
31706
31795
|
|
|
31707
31796
|
## Tolerating Removed Fields
|
|
31708
31797
|
|
|
31709
|
-
|
|
31798
|
+
Records 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.
|
|
31710
31799
|
|
|
31711
31800
|
```ts
|
|
31712
|
-
import { s
|
|
31801
|
+
import { s } from '@vielzeug/spell';
|
|
31713
31802
|
|
|
31714
|
-
const Person =
|
|
31803
|
+
const Person = s.object({ email: s.string(), name: s.string() }).tolerate('address');
|
|
31715
31804
|
|
|
31716
|
-
|
|
31717
|
-
|
|
31718
|
-
address: 'p sherman 42 wallaby way sydney',
|
|
31719
|
-
email: 'johndoe@mail.com',
|
|
31720
|
-
});
|
|
31721
|
-
// { name: 'John Doe', email: 'johndoe@mail.com' }: the tolerated key never reaches the output
|
|
31805
|
+
Person.parse({ address: '42 Wallaby Way', email: 'johndoe@mail.com', name: 'John Doe' });
|
|
31806
|
+
// { email: 'johndoe@mail.com', name: 'John Doe' }
|
|
31722
31807
|
```
|
|
31723
31808
|
|
|
31724
|
-
Fields added
|
|
31809
|
+
Fields added in later schema versions do not need `tolerate()`: give them a `default()` and older records are repaired on parse.
|
|
31725
31810
|
|
|
31726
31811
|
## Custom Validation
|
|
31727
31812
|
|
|
31728
|
-
Use `check()` for synchronous domain rules and `checkAsync()` for asynchronous rules.
|
|
31813
|
+
Use `check()` for synchronous domain rules and `checkAsync()` for asynchronous rules.
|
|
31729
31814
|
|
|
31730
31815
|
```ts
|
|
31731
31816
|
import { s } from '@vielzeug/spell';
|
|
31732
31817
|
|
|
31733
|
-
//
|
|
31818
|
+
// Return false to fail with the default message
|
|
31734
31819
|
const EvenNumber = s.number().check((n) => n % 2 === 0);
|
|
31735
31820
|
|
|
31736
|
-
//
|
|
31821
|
+
// Return a string to fail with that message
|
|
31737
31822
|
const Username = s
|
|
31738
31823
|
.string()
|
|
31739
31824
|
.min(3)
|
|
31740
31825
|
.check((v) => !v.startsWith('_') || 'Cannot start with underscore');
|
|
31741
31826
|
|
|
31742
|
-
//
|
|
31827
|
+
// Report issues at specific paths with ctx.addIssue()
|
|
31743
31828
|
const Signup = s.object({ confirm: s.string(), password: s.string() }).check((v, ctx) => {
|
|
31744
|
-
if (v.password !== v.confirm) {
|
|
31745
|
-
ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
|
|
31746
|
-
}
|
|
31829
|
+
if (v.password !== v.confirm) ctx.addIssue({ code: 'custom', message: 'Passwords must match', path: ['confirm'] });
|
|
31747
31830
|
});
|
|
31748
31831
|
```
|
|
31749
31832
|
|
|
31750
|
-
`checkAsync()`
|
|
31833
|
+
A 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.
|
|
31751
31834
|
|
|
31752
31835
|
```ts
|
|
31753
31836
|
import { s } from '@vielzeug/spell';
|
|
@@ -31757,28 +31840,14 @@ const takenEmails = new Set(['ada@example.com']);
|
|
|
31757
31840
|
const AccountEmail = s
|
|
31758
31841
|
.string()
|
|
31759
31842
|
.email()
|
|
31760
|
-
.checkAsync(async (value
|
|
31761
|
-
if (takenEmails.has(value)) {
|
|
31762
|
-
ctx.addIssue({ code: 'custom', message: 'Email is already taken', path: [] });
|
|
31763
|
-
}
|
|
31764
|
-
});
|
|
31843
|
+
.checkAsync(async (value) => !takenEmails.has(value) || 'Email is already taken');
|
|
31765
31844
|
|
|
31766
|
-
// Async checks require parseAsync
|
|
31767
31845
|
await AccountEmail.parseAsync('grace@example.com');
|
|
31768
31846
|
```
|
|
31769
31847
|
|
|
31770
|
-
|
|
31771
|
-
|
|
31772
|
-
```ts
|
|
31773
|
-
import { s } from '@vielzeug/spell';
|
|
31774
|
-
|
|
31775
|
-
const PositivePrice = s.number().check((value) => value > 0 || 'Must be positive');
|
|
31776
|
-
PositivePrice.parse(9.99);
|
|
31777
|
-
```
|
|
31778
|
-
|
|
31779
|
-
## Strings, Numbers, and Safe Regex Usage
|
|
31848
|
+
## Strings, Numbers, and Regex Safety
|
|
31780
31849
|
|
|
31781
|
-
Use
|
|
31850
|
+
Use the built-in constraints instead of hand-written predicates.
|
|
31782
31851
|
|
|
31783
31852
|
```ts
|
|
31784
31853
|
import { s } from '@vielzeug/spell';
|
|
@@ -31786,13 +31855,14 @@ import { s } from '@vielzeug/spell';
|
|
|
31786
31855
|
const Password = s.string().min(12).regex(/[A-Z]/).regex(/[0-9]/);
|
|
31787
31856
|
const Price = s.number().nonNegative().multipleOf(0.01);
|
|
31788
31857
|
const LaunchWindow = s.date().min(new Date('2025-01-01T00:00:00.000Z'));
|
|
31858
|
+
const Website = s.string().url({ protocols: ['https'] });
|
|
31789
31859
|
```
|
|
31790
31860
|
|
|
31791
|
-
|
|
31861
|
+
Format 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.
|
|
31792
31862
|
|
|
31793
|
-
## Coercion and
|
|
31863
|
+
## Coercion and Pipelines
|
|
31794
31864
|
|
|
31795
|
-
Use
|
|
31865
|
+
Use `s.coerce.*` when input arrives as strings, such as query parameters or form values.
|
|
31796
31866
|
|
|
31797
31867
|
```ts
|
|
31798
31868
|
import { s } from '@vielzeug/spell';
|
|
@@ -31804,30 +31874,25 @@ const Query = s.object({
|
|
|
31804
31874
|
search: s.coerce.string().trim().min(1).optional(),
|
|
31805
31875
|
});
|
|
31806
31876
|
|
|
31807
|
-
|
|
31808
|
-
draft: 'true',
|
|
31809
|
-
limit: '50',
|
|
31810
|
-
publishedAt: '2025-04-01T12:00:00.000Z',
|
|
31811
|
-
search: ' vielzeug ',
|
|
31812
|
-
});
|
|
31877
|
+
Query.parse({ draft: 'true', limit: '50', publishedAt: '2025-04-01T12:00:00.000Z', search: ' vielzeug ' });
|
|
31813
31878
|
```
|
|
31814
31879
|
|
|
31815
|
-
Use `transform()` or `pipe()`
|
|
31880
|
+
Use `transform()` or `pipe()` when downstream code needs a different output.
|
|
31816
31881
|
|
|
31817
31882
|
```ts
|
|
31818
31883
|
import { s } from '@vielzeug/spell';
|
|
31819
31884
|
|
|
31820
|
-
const
|
|
31821
|
-
const Slug = s.string().trim().
|
|
31885
|
+
const LowercaseTags = s.array(s.string().trim().min(1)).transform((tags) => tags.map((tag) => tag.toLowerCase()));
|
|
31886
|
+
const Slug = s.string().trim().pipe(s.string().slug());
|
|
31822
31887
|
```
|
|
31823
31888
|
|
|
31824
|
-
##
|
|
31889
|
+
## Definitions and JSON Schema
|
|
31825
31890
|
|
|
31826
|
-
Use declarative definitions when schemas
|
|
31891
|
+
Use declarative definitions when schemas feed external tooling.
|
|
31827
31892
|
|
|
31828
31893
|
```ts
|
|
31829
31894
|
import { s } from '@vielzeug/spell';
|
|
31830
|
-
import {
|
|
31895
|
+
import { toJsonSchema } from '@vielzeug/spell/json';
|
|
31831
31896
|
|
|
31832
31897
|
const Product = s
|
|
31833
31898
|
.object({
|
|
@@ -31835,93 +31900,69 @@ const Product = s
|
|
|
31835
31900
|
name: s.string().min(1),
|
|
31836
31901
|
price: s.number().positive().multipleOf(0.01),
|
|
31837
31902
|
})
|
|
31838
|
-
.
|
|
31903
|
+
.describe('Product');
|
|
31839
31904
|
|
|
31840
|
-
const
|
|
31841
|
-
|
|
31842
|
-
|
|
31843
|
-
Product.parse({ id: '550e8400-e29b-41d4-a716-446655440000', name: 'Keyboard', price: 129.99 });
|
|
31844
|
-
console.log(jsonSchema.title);
|
|
31905
|
+
const jsonSchema = toJsonSchema(Product.definition());
|
|
31906
|
+
console.log(jsonSchema.description); // 'Product'
|
|
31845
31907
|
```
|
|
31846
31908
|
|
|
31847
|
-
Definitions are frozen serializable
|
|
31909
|
+
Definitions are frozen, serializable data. Schemas with checks, transforms, preprocessors (including `s.coerce.*` and `trim()`), defaults, or catches have no definition, and `definition()` throws `SpellDefinitionError`.
|
|
31848
31910
|
|
|
31849
31911
|
## Messages
|
|
31850
31912
|
|
|
31851
|
-
Spell has no
|
|
31913
|
+
Spell has no process-wide configuration. Build one parse context per request, locale, or form, and pass it explicitly.
|
|
31852
31914
|
|
|
31853
31915
|
```ts
|
|
31854
31916
|
import { createParseContext, s } from '@vielzeug/spell';
|
|
31855
31917
|
|
|
31856
31918
|
const User = s.object({ email: s.string().email() });
|
|
31857
|
-
const german = createParseContext({
|
|
31858
|
-
object: { invalidKeys: () => 'Keine unbekannten Felder erlaubt' },
|
|
31859
|
-
});
|
|
31919
|
+
const german = createParseContext({ object: { invalidKeys: () => 'Keine unbekannten Felder erlaubt' } });
|
|
31860
31920
|
|
|
31861
31921
|
User.safeParse({ email: 'ada@example.com', extra: true }, german);
|
|
31862
31922
|
```
|
|
31863
31923
|
|
|
31864
|
-
|
|
31924
|
+
Development builds warn through `console.warn` when a message override uses an unsafe key such as `__proto__`.
|
|
31865
31925
|
|
|
31866
31926
|
## Working with Validation Errors
|
|
31867
31927
|
|
|
31868
|
-
Use `SpellValidationError` helpers
|
|
31928
|
+
Use `SpellValidationError` helpers to build UI-ready error structures.
|
|
31869
31929
|
|
|
31870
31930
|
```ts
|
|
31871
|
-
import {
|
|
31872
|
-
|
|
31873
|
-
const User = s.object({
|
|
31874
|
-
email: s.string().email(),
|
|
31875
|
-
profile: s.object({
|
|
31876
|
-
name: s.string().min(2),
|
|
31877
|
-
}),
|
|
31878
|
-
});
|
|
31931
|
+
import { joinIssuePath, s } from '@vielzeug/spell';
|
|
31879
31932
|
|
|
31933
|
+
const User = s.object({ email: s.string().email(), profile: s.object({ name: s.string().min(2) }) });
|
|
31880
31934
|
const result = User.safeParse({ email: 'nope', profile: { name: '' } });
|
|
31881
31935
|
|
|
31882
|
-
if (!result.success
|
|
31883
|
-
|
|
31884
|
-
console.log(profileErrors);
|
|
31885
|
-
}
|
|
31886
|
-
```
|
|
31887
|
-
|
|
31888
|
-
Key inline errors by dot-path with `joinIssuePath()`, which also unwraps Standard Schema `{ key }` segments:
|
|
31889
|
-
|
|
31890
|
-
```ts
|
|
31891
|
-
import { joinIssuePath } from '@vielzeug/spell';
|
|
31936
|
+
if (!result.success) {
|
|
31937
|
+
console.log(result.error.messagesAt('profile', 'name'));
|
|
31892
31938
|
|
|
31893
|
-
for (const issue of result.error.issues)
|
|
31894
|
-
console.log(joinIssuePath(issue.path), issue.message); // 'profile.name: ...'
|
|
31939
|
+
for (const issue of result.error.issues) console.log(joinIssuePath(issue.path), issue.message);
|
|
31895
31940
|
}
|
|
31896
31941
|
```
|
|
31897
31942
|
|
|
31898
|
-
Union failures produce one
|
|
31943
|
+
Union 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.
|
|
31899
31944
|
|
|
31900
|
-
##
|
|
31945
|
+
## Typing Schema Parameters
|
|
31901
31946
|
|
|
31902
|
-
|
|
31947
|
+
Type a function that accepts any schema with `AnySchema`, or with `Schema` when it needs the parsed type.
|
|
31903
31948
|
|
|
31904
31949
|
```ts
|
|
31905
|
-
import { type
|
|
31950
|
+
import { type AnySchema, type ParseResult, type Schema, s } from '@vielzeug/spell';
|
|
31906
31951
|
|
|
31907
|
-
function
|
|
31908
|
-
return (
|
|
31909
|
-
|
|
31910
|
-
if (result.success) return undefined;
|
|
31952
|
+
function isValid(schema: AnySchema, value: unknown): boolean {
|
|
31953
|
+
return schema.safeParse(value).success;
|
|
31954
|
+
}
|
|
31911
31955
|
|
|
31912
|
-
|
|
31913
|
-
|
|
31914
|
-
path: issue.path,
|
|
31915
|
-
}));
|
|
31916
|
-
};
|
|
31956
|
+
function parseWith(schema: Schema, value: unknown): ParseResult {
|
|
31957
|
+
return schema.safeParse(value);
|
|
31917
31958
|
}
|
|
31918
31959
|
|
|
31919
|
-
|
|
31960
|
+
parseWith(s.object({ email: s.string() }), { email: 'ada@example.com' });
|
|
31920
31961
|
```
|
|
31921
31962
|
|
|
31922
31963
|
## Framework Integration
|
|
31923
31964
|
|
|
31924
|
-
Spell works anywhere you can call a function before
|
|
31965
|
+
Spell works anywhere you can call a function before data enters your app.
|
|
31925
31966
|
|
|
31926
31967
|
```tsx [React]
|
|
31927
31968
|
import { s } from '@vielzeug/spell';
|
|
@@ -31949,36 +31990,39 @@ import { computed, ref } from 'vue';
|
|
|
31949
31990
|
import { s } from '@vielzeug/spell';
|
|
31950
31991
|
|
|
31951
31992
|
const Settings = s.object({
|
|
31952
|
-
locale: s.string().min(2),
|
|
31953
31993
|
compact: s.coerce.boolean().default(false),
|
|
31994
|
+
locale: s.string().min(2),
|
|
31954
31995
|
});
|
|
31955
31996
|
|
|
31956
|
-
const raw = ref({
|
|
31997
|
+
const raw = ref({ compact: 'true', locale: 'en' });
|
|
31957
31998
|
const settings = computed(() => Settings.parse(raw.value));
|
|
31958
31999
|
```
|
|
31959
32000
|
|
|
31960
|
-
|
|
32001
|
+
```svelte [Svelte]
|
|
32002
|
+
|
|
32003
|
+
import { s } from '@vielzeug/spell';
|
|
32004
|
+
|
|
32005
|
+
const Email = s.string().email();
|
|
32006
|
+
let value = '';
|
|
32007
|
+
$: error = Email.safeParse(value).success ? '' : 'Enter a valid email';
|
|
32008
|
+
|
|
32009
|
+
{#if error}{error}{/if}
|
|
32010
|
+
```
|
|
31961
32011
|
|
|
31962
32012
|
## Working with Other Vielzeug Libraries
|
|
31963
32013
|
|
|
31964
|
-
|
|
32014
|
+
Spell schemas implement Standard Schema, so packages that accept Standard Schema validators use them directly.
|
|
31965
32015
|
|
|
31966
32016
|
```ts
|
|
32017
|
+
import { createCourier } from '@vielzeug/courier';
|
|
31967
32018
|
import { createForm } from '@vielzeug/forge';
|
|
31968
32019
|
import { schemaValidator } from '@vielzeug/forge/schema';
|
|
31969
|
-
import { createCourier } from '@vielzeug/courier';
|
|
31970
32020
|
import { s } from '@vielzeug/spell';
|
|
31971
32021
|
|
|
31972
|
-
const Profile = s.object({
|
|
31973
|
-
displayName: s.string().min(2),
|
|
31974
|
-
newsletter: s.boolean(),
|
|
31975
|
-
});
|
|
32022
|
+
const Profile = s.object({ displayName: s.string().min(2), newsletter: s.boolean() });
|
|
31976
32023
|
|
|
31977
32024
|
const form = createForm({
|
|
31978
|
-
initialValues: {
|
|
31979
|
-
displayName: '',
|
|
31980
|
-
newsletter: false,
|
|
31981
|
-
},
|
|
32025
|
+
initialValues: { displayName: '', newsletter: false },
|
|
31982
32026
|
validate: schemaValidator(Profile),
|
|
31983
32027
|
});
|
|
31984
32028
|
|
|
@@ -31986,18 +32030,16 @@ const courier = createCourier({ baseUrl: '/api' });
|
|
|
31986
32030
|
const profile = Profile.parse(await courier.get('/profile'));
|
|
31987
32031
|
```
|
|
31988
32032
|
|
|
31989
|
-
Use Spell definitions with `@vielzeug/codex` or other tooling when you need generated docs or external schema consumers.
|
|
31990
|
-
|
|
31991
32033
|
## Best Practices
|
|
31992
32034
|
|
|
31993
32035
|
- Keep schemas close to the boundary where unknown data enters your app.
|
|
31994
|
-
-
|
|
31995
|
-
-
|
|
31996
|
-
-
|
|
31997
|
-
- Use `check()` with
|
|
31998
|
-
- Use `checkAsync()`
|
|
31999
|
-
- Build a parse context per request or test
|
|
32000
|
-
- Use `definition()` with `
|
|
32036
|
+
- Chain constraints in the order they should apply; put `trim()` before length checks.
|
|
32037
|
+
- Derive object shapes with `extend()`, `pick()`, `omit()`, or `partial()` before adding checks.
|
|
32038
|
+
- Chain type-specific methods before `optional()`, `nullable()`, `transform()`, or `required()`.
|
|
32039
|
+
- Use `check()` with `ctx.addIssue()` for multi-field rules; return a message for single predicates.
|
|
32040
|
+
- Use `checkAsync()` with `parseAsync()` for every asynchronous domain rule.
|
|
32041
|
+
- Build a parse context per request, locale, or test instead of relying on global state.
|
|
32042
|
+
- Use `definition()` with `toJsonSchema()` for external tooling, and keep runtime-only schemas separate.
|
|
32001
32043
|
|
|
32002
32044
|
### Examples
|
|
32003
32045
|
|
|
@@ -32007,7 +32049,7 @@ Use Spell definitions with `@vielzeug/codex` or other tooling when you need gene
|
|
|
32007
32049
|
- [Form-Safe Parsing](./examples/forms.md)
|
|
32008
32050
|
- [Async Business Rules](./examples/async.md)
|
|
32009
32051
|
- [Schema Introspection and Round-Trips](./examples/introspection.md)
|
|
32010
|
-
- [Unions, Intersections, and
|
|
32052
|
+
- [Unions, Intersections, and Discriminated Unions](./examples/unions.md)
|
|
32011
32053
|
|
|
32012
32054
|
### REPL Examples
|
|
32013
32055
|
|
|
@@ -32022,8 +32064,8 @@ Use Spell definitions with `@vielzeug/codex` or other tooling when you need gene
|
|
|
32022
32064
|
- Request-local messages (id: `messages-override`)
|
|
32023
32065
|
- Variant Responses (id: `nested-objects`)
|
|
32024
32066
|
- Number Validation (id: `number-validation`)
|
|
32067
|
+
- Object Composition (id: `object-composition`)
|
|
32025
32068
|
- Object Defaults (id: `object-defaults`)
|
|
32026
|
-
- Object Merge & Aliases (id: `object-merge`)
|
|
32027
32069
|
- Optional and Nullable Fields (id: `optional-nullable`)
|
|
32028
32070
|
- Custom Validation (id: `refinements`)
|
|
32029
32071
|
- String Validation (id: `string-validation`)
|
|
@@ -33838,7 +33880,7 @@ import { s } from '@vielzeug/spell';
|
|
|
33838
33880
|
import { table } from '@vielzeug/vault';
|
|
33839
33881
|
import { createLocalStorage } from '@vielzeug/vault/local-storage';
|
|
33840
33882
|
|
|
33841
|
-
const PreferenceSchema = s.object({ id: s.string(), theme: s.
|
|
33883
|
+
const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });
|
|
33842
33884
|
const store = createLocalStorage({
|
|
33843
33885
|
name: 'app-v2',
|
|
33844
33886
|
schema: { preferences: table('id') },
|
|
@@ -34363,7 +34405,7 @@ interface Preference {
|
|
|
34363
34405
|
theme: 'dark' | 'light';
|
|
34364
34406
|
}
|
|
34365
34407
|
|
|
34366
|
-
const PreferenceSchema = s.object({ id: s.string(), theme: s.
|
|
34408
|
+
const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });
|
|
34367
34409
|
const store = createLocalStorage({
|
|
34368
34410
|
name: 'app-v2',
|
|
34369
34411
|
schema: { preferences: table('id') },
|
|
@@ -34646,7 +34688,7 @@ interface Job {
|
|
|
34646
34688
|
status: 'queued' | 'running' | 'done';
|
|
34647
34689
|
}
|
|
34648
34690
|
|
|
34649
|
-
const JobSchema = s.object({ id: s.string(), status: s.
|
|
34691
|
+
const JobSchema = s.object({ id: s.string(), status: s.enum(['queued', 'running', 'done']) });
|
|
34650
34692
|
const database = new DatabaseSync(':memory:');
|
|
34651
34693
|
const store = createSQLite({
|
|
34652
34694
|
database,
|