@vielzeug/codex 26.11.12 → 26.11.13
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 +181 -61
- package/data/llms-full.txt +1546 -918
- package/data/llms.txt +4 -1
- package/data/manifest.json +2 -6
- package/data/packages/archive.json +1 -1
- package/data/packages/arsenal.json +4 -2
- package/data/packages/clockwork.json +3 -3
- package/data/packages/codex.json +20 -11
- package/data/packages/coins.json +22 -24
- package/data/packages/courier.json +12 -11
- package/data/packages/flux.json +2 -2
- package/data/packages/forge.json +3 -3
- package/data/packages/herald.json +2 -2
- package/data/packages/lingua.json +37 -42
- package/data/packages/patchwork.json +45 -0
- package/data/packages/postmaster.json +8 -8
- package/data/packages/refine.json +2 -2
- package/data/packages/scribe.json +57 -0
- package/data/packages/sentinel.json +1 -1
- package/data/packages/sourcerer.json +2 -2
- package/data/packages/tabula.json +40 -0
- package/data/packages/tavern.json +20 -18
- package/data/packages/tempo.json +48 -63
- package/data/packages/vault.json +29 -31
- package/data/packages/wayfinder.json +3 -6
- package/data/refine.json +76 -0
- package/dist/catalog.d.ts +13 -1
- package/dist/catalog.js +80 -53
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/errors.js +0 -1
- package/dist/errors.js.map +1 -1
- package/dist/http.d.ts +0 -1
- package/dist/http.js +0 -5
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/port.js +2 -2
- package/dist/port.js.map +1 -1
- package/dist/server.d.ts +5 -3
- package/dist/server.js +10 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +11 -8
- package/dist/snapshot.js +24 -128
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +0 -2
- package/dist/tools/index.js +0 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/refine.d.ts +2 -2
- package/dist/tools/refine.js.map +1 -1
- package/dist/types.d.ts +2 -30
- package/dist/types.js +1 -1
- package/package.json +2 -13
- package/skills/vielzeug/SKILL.md +3 -0
- package/data/search.json +0 -1688
- package/dist/refine-catalog.d.ts +0 -15
- package/dist/refine-catalog.js +0 -27
- package/dist/refine-catalog.js.map +0 -1
- package/dist/refine.d.ts +0 -7
- package/dist/refine.js +0 -9
- package/dist/refine.js.map +0 -1
package/data/llms-full.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug: Full Documentation
|
|
2
2
|
|
|
3
|
-
> Complete documentation for
|
|
3
|
+
> Complete documentation for 46 packages. Version: 26.11.12
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -1573,6 +1573,7 @@ console.log(byRole, health, profile);
|
|
|
1573
1573
|
| `assert` | Assert and narrow a condition | Sync | Available from `/function` |
|
|
1574
1574
|
| `retry` | Retry async work | Async | Rethrows final error |
|
|
1575
1575
|
| `taskPool` | Bound concurrent tasks | Async | Available from `/async` |
|
|
1576
|
+
| `timer` | Re-armable single-slot timeout | Async | Available from `/async` |
|
|
1576
1577
|
| `cache` | In-memory identity-keyed cache | Async | Available from `/cache` |
|
|
1577
1578
|
| `fuzzyFilter` | Filter string or selected object fields | Sync | Object collections require `select` |
|
|
1578
1579
|
| `fuzzyScore` | Rank string or selected object fields | Sync | Object collections require `select` |
|
|
@@ -1697,6 +1698,28 @@ const user = await pool.run((signal) => fetch('/user', { signal }).then((respons
|
|
|
1697
1698
|
pool.dispose();
|
|
1698
1699
|
```
|
|
1699
1700
|
|
|
1701
|
+
### timer
|
|
1702
|
+
|
|
1703
|
+
```ts
|
|
1704
|
+
interface Timer {
|
|
1705
|
+
arm(ms: number): void;
|
|
1706
|
+
cancel(): void;
|
|
1707
|
+
readonly pending: boolean;
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
timer(fn: () => void): Timer
|
|
1711
|
+
```
|
|
1712
|
+
|
|
1713
|
+
A single-slot, re-armable timeout. `arm()` cancels any pending run first, so at most one run is ever scheduled. `pending` is already `false` inside the callback, which may re-arm the timer.
|
|
1714
|
+
|
|
1715
|
+
```ts
|
|
1716
|
+
import { timer } from '@vielzeug/arsenal/async';
|
|
1717
|
+
|
|
1718
|
+
const idleFlush = timer(() => flush());
|
|
1719
|
+
idleFlush.arm(500); // debounced: re-arming restarts the delay
|
|
1720
|
+
idleFlush.cancel();
|
|
1721
|
+
```
|
|
1722
|
+
|
|
1700
1723
|
---
|
|
1701
1724
|
|
|
1702
1725
|
## Cache
|
|
@@ -3484,7 +3507,7 @@ const machine = defineMachine()({
|
|
|
3484
3507
|
invoke: [
|
|
3485
3508
|
{
|
|
3486
3509
|
src: ({ signal }) => fetch('/api/items', { signal }).then((response) => response.json() as Promise),
|
|
3487
|
-
onDone: ({ result }) => ({ items: result, type: 'DONE' }),
|
|
3510
|
+
onDone: ({ result }) => ({ items: result as string[], type: 'DONE' }),
|
|
3488
3511
|
},
|
|
3489
3512
|
],
|
|
3490
3513
|
on: { DONE: { reduce: ({ event }) => ({ items: event.items }), target: 'ready' } },
|
|
@@ -3646,10 +3669,13 @@ Throws `ClockworkDefinitionError` when a definition carries a timer delay outsid
|
|
|
3646
3669
|
### `Actor.subscribe()`
|
|
3647
3670
|
|
|
3648
3671
|
```ts
|
|
3649
|
-
subscribe(
|
|
3672
|
+
subscribe(
|
|
3673
|
+
listener: (snapshot: MachineSnapshot) => void,
|
|
3674
|
+
options?: { readonly signal?: AbortSignal },
|
|
3675
|
+
): () => void;
|
|
3650
3676
|
```
|
|
3651
3677
|
|
|
3652
|
-
Subscribes to future committed actor snapshots. It does not run immediately; read `actor.snapshot` for the initial value. Returns an unsubscribe function. Subscriber failures are reported through `tap()` as `error` events with `phase: 'subscriber'` without stopping remaining subscribers, declared effects, or the actor.
|
|
3678
|
+
Subscribes to future committed actor snapshots. It does not run immediately; read `actor.snapshot` for the initial value. `options.signal` auto-unsubscribes when the signal aborts; an already-aborted signal creates no subscription. Returns an unsubscribe function. Subscriber failures are reported through `tap()` as `error` events with `phase: 'subscriber'` without stopping remaining subscribers, declared effects, or the actor.
|
|
3653
3679
|
|
|
3654
3680
|
**Example:**
|
|
3655
3681
|
|
|
@@ -3757,10 +3783,13 @@ Returns whether the current actor snapshot accepts an event. A guard failure is
|
|
|
3757
3783
|
### `actor.subscribe()`
|
|
3758
3784
|
|
|
3759
3785
|
```ts
|
|
3760
|
-
subscribe(
|
|
3786
|
+
subscribe(
|
|
3787
|
+
listener: (snapshot: MachineSnapshot) => void,
|
|
3788
|
+
options?: { readonly signal?: AbortSignal },
|
|
3789
|
+
): () => void;
|
|
3761
3790
|
```
|
|
3762
3791
|
|
|
3763
|
-
Registers a listener for committed snapshots. The listener does not run immediately.
|
|
3792
|
+
Registers a listener for committed snapshots. The listener does not run immediately. `options.signal` auto-unsubscribes on abort; an already-aborted signal creates no subscription.
|
|
3764
3793
|
|
|
3765
3794
|
**Returns:** An unsubscribe function.
|
|
3766
3795
|
|
|
@@ -3824,7 +3853,7 @@ type MachineConfig,
|
|
|
3824
3853
|
};
|
|
3825
3854
|
```
|
|
3826
3855
|
|
|
3827
|
-
A flat machine definition. State nodes cannot contain child states. The `StateNode`, `Transition`, `After`, `Invoke`, `Effect`, `Guard`, and `Reducer` shapes are inferred inline and exported for reusable helpers. `After.delay` must be finite and between 0 and 2,147,483,647 milliseconds; delayed guards and reducers receive `event: undefined`.
|
|
3856
|
+
A flat machine definition. State nodes cannot contain child states. The `StateNode`, `Transition`, `After`, `Invoke`, `Effect`, `Guard`, and `Reducer` shapes are inferred inline and exported for reusable helpers. `After.delay` must be finite and between 0 and 2,147,483,647 milliseconds; delayed guards and reducers receive `event: undefined`. `Invoke` inside a state node fixes its `Result` to `unknown`, so `onDone` receives `result: unknown`; narrow or cast where the result enters your mapped event.
|
|
3828
3857
|
|
|
3829
3858
|
### `Actor`
|
|
3830
3859
|
|
|
@@ -4021,6 +4050,8 @@ Effects receive `context`, the triggering `event` (or `undefined` for initial en
|
|
|
4021
4050
|
|
|
4022
4051
|
Invokes start on state entry. `src` gets readonly entry context, the triggering event or `undefined`, and an `AbortSignal`. `onDone` or `onError` map settlement to ordinary events. All invokes are cancelled when the actor exits the state or disposes.
|
|
4023
4052
|
|
|
4053
|
+
`onDone` receives `result: unknown`: without a schema system the machine cannot tie one callback's parameter to each `src`'s concrete return type, so narrow or cast explicitly where the result enters your event.
|
|
4054
|
+
|
|
4024
4055
|
```ts
|
|
4025
4056
|
type LoadEvent =
|
|
4026
4057
|
| { type: 'FETCH' }
|
|
@@ -4041,7 +4072,7 @@ const loader = defineMachine()({
|
|
|
4041
4072
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
4042
4073
|
return response.json() as Promise;
|
|
4043
4074
|
},
|
|
4044
|
-
onDone: ({ result }) => ({ items: result, type: 'SUCCESS' }),
|
|
4075
|
+
onDone: ({ result }) => ({ items: result as string[], type: 'SUCCESS' }),
|
|
4045
4076
|
onError: ({ error }) => ({ message: String(error), type: 'FAILURE' }),
|
|
4046
4077
|
},
|
|
4047
4078
|
],
|
|
@@ -4077,7 +4108,7 @@ const notification = defineMachine()({
|
|
|
4077
4108
|
|
|
4078
4109
|
## Snapshot observation and persistence
|
|
4079
4110
|
|
|
4080
|
-
`actor.snapshot` is the current shallow-frozen `MachineSnapshot`; read it directly rather than calling a snapshot method. Use `subscribe()` to integrate a state library or persist future committed snapshots. Fresh actors run their initial entry effects and resources; restored actors start only the restored state's invokes and timers, not its entry effects.
|
|
4111
|
+
`actor.snapshot` is the current shallow-frozen `MachineSnapshot`; read it directly rather than calling a snapshot method. Use `subscribe()` to integrate a state library or persist future committed snapshots; pass `{ signal }` to auto-unsubscribe when an owner's lifetime ends. Fresh actors run their initial entry effects and resources; restored actors start only the restored state's invokes and timers, not its entry effects.
|
|
4081
4112
|
|
|
4082
4113
|
```ts
|
|
4083
4114
|
const stored = sessionStorage.getItem('wizard');
|
|
@@ -4265,8 +4296,8 @@ npx -y @vielzeug/codex
|
|
|
4265
4296
|
|
|
4266
4297
|
- `loadSnapshot` validates chunked snapshot metadata.
|
|
4267
4298
|
- `SnapshotCatalog` loads package content only when requested.
|
|
4268
|
-
- `createMcpServer` registers
|
|
4269
|
-
-
|
|
4299
|
+
- `createMcpServer` registers package tools, plus Refine component tools whenever the snapshot carries them.
|
|
4300
|
+
- The single entry point publishes TypeScript declarations.
|
|
4270
4301
|
- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.
|
|
4271
4302
|
|
|
4272
4303
|
## Documentation
|
|
@@ -4284,30 +4315,41 @@ npx -y @vielzeug/codex
|
|
|
4284
4315
|
|
|
4285
4316
|
## API Overview
|
|
4286
4317
|
|
|
4287
|
-
| Symbol
|
|
4288
|
-
|
|
|
4289
|
-
| `loadSnapshot`
|
|
4290
|
-
| `
|
|
4291
|
-
| `
|
|
4292
|
-
| `
|
|
4293
|
-
| `startHttpHost`
|
|
4318
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
4319
|
+
| ------------------ | ------------------------------------------ | -------------- | ------------------------------------- |
|
|
4320
|
+
| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |
|
|
4321
|
+
| `validateSnapshot` | Full artifact verification (all chunks) | Sync | Generation/CI use, not normal startup |
|
|
4322
|
+
| `SnapshotCatalog` | Query package corpus and Refine components | Sync | Construct from loaded snapshot |
|
|
4323
|
+
| `createMcpServer` | MCP adapter factory | Sync | Requires catalog and version |
|
|
4324
|
+
| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |
|
|
4294
4325
|
|
|
4295
|
-
## Package Entry
|
|
4326
|
+
## Package Entry Point
|
|
4296
4327
|
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
| `@vielzeug/codex/refine` | Refine catalog and MCP server with component tools |
|
|
4328
|
+
`@vielzeug/codex` is the single entry point: catalog (package docs plus bundled Refine component
|
|
4329
|
+
metadata), snapshot loader, errors, the MCP server factory, the loopback HTTP host, and a
|
|
4330
|
+
re-export of `StdioServerTransport`. There is one `Catalog` surface and one server factory.
|
|
4301
4331
|
|
|
4302
4332
|
## Snapshot
|
|
4303
4333
|
|
|
4304
4334
|
### `loadSnapshot`
|
|
4305
4335
|
|
|
4306
4336
|
```ts
|
|
4307
|
-
loadSnapshot(
|
|
4337
|
+
loadSnapshot(directory?: string, options?: { validateContents?: boolean }): LoadedSnapshot;
|
|
4338
|
+
```
|
|
4339
|
+
|
|
4340
|
+
Loads one snapshot directory: `manifest.json` plus `catalog.json` (eager metadata), an optional
|
|
4341
|
+
`refine.json`, and lazily read `packages/.json` content chunks. `directory` defaults to the
|
|
4342
|
+
bundled `data/`. The snapshot layout is fixed by code; the manifest carries `{ schemaVersion, version }`
|
|
4343
|
+
only. `validateContents: true` turns the lazy chunks into an eager cross-checked read.
|
|
4344
|
+
|
|
4345
|
+
### `validateSnapshot`
|
|
4346
|
+
|
|
4347
|
+
```ts
|
|
4348
|
+
validateSnapshot(snapshotRoot?: string): void;
|
|
4308
4349
|
```
|
|
4309
4350
|
|
|
4310
|
-
|
|
4351
|
+
Runs `loadSnapshot` with `validateContents: true`. Used by snapshot generation, integration tests,
|
|
4352
|
+
and artifact verification; normal startup keeps package chunks lazy.
|
|
4311
4353
|
|
|
4312
4354
|
### `SnapshotCatalog`
|
|
4313
4355
|
|
|
@@ -4315,7 +4357,11 @@ Loads catalog/search metadata and Refine metadata. `snapshotRoot` defaults to bu
|
|
|
4315
4357
|
new SnapshotCatalog(snapshot: LoadedSnapshot)
|
|
4316
4358
|
```
|
|
4317
4359
|
|
|
4318
|
-
Provides
|
|
4360
|
+
Provides package lookup, docs/source/example/signature access, deterministic search, and the
|
|
4361
|
+
Refine component lookup (`listComponents()`, `getComponent(tagName)`). Component methods return an
|
|
4362
|
+
empty list (and `NOT_FOUND` per tag) when the snapshot carries no Refine metadata. `search()`
|
|
4363
|
+
reads content chunks through the same lazy cache as the content getters; there is no separate
|
|
4364
|
+
search index.
|
|
4319
4365
|
|
|
4320
4366
|
---
|
|
4321
4367
|
|
|
@@ -4327,27 +4373,10 @@ Provides generic package lookup, docs/source/example/signature access, and deter
|
|
|
4327
4373
|
createMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;
|
|
4328
4374
|
```
|
|
4329
4375
|
|
|
4330
|
-
Registers generic package tools over `Catalog
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
### `createMcpServerWithRefine`
|
|
4335
|
-
|
|
4336
|
-
```ts
|
|
4337
|
-
createMcpServerWithRefine(catalog: RefineCatalog, options: { version: string; debug?: boolean }): Server;
|
|
4338
|
-
```
|
|
4339
|
-
|
|
4340
|
-
Creates a server with the general Vielzeug package catalog tools and the additional `refine-*` component tools.
|
|
4341
|
-
|
|
4342
|
-
### `SnapshotRefineCatalog`
|
|
4343
|
-
|
|
4344
|
-
```ts
|
|
4345
|
-
new SnapshotRefineCatalog(snapshot: LoadedSnapshot)
|
|
4346
|
-
```
|
|
4347
|
-
|
|
4348
|
-
Extends `SnapshotCatalog` with `getComponent()` and `listComponents()`.
|
|
4349
|
-
|
|
4350
|
-
Component declarations and their nested data use readonly TypeScript types.
|
|
4376
|
+
Registers the generic package tools over `Catalog`, plus the `refine-*` component tools when the
|
|
4377
|
+
catalog actually carries Refine metadata; tools that could only answer "unavailable" are never
|
|
4378
|
+
offered. The root also re-exports `StdioServerTransport` for connecting the server without a
|
|
4379
|
+
second package import.
|
|
4351
4380
|
|
|
4352
4381
|
## HTTP
|
|
4353
4382
|
|
|
@@ -4357,34 +4386,23 @@ Component declarations and their nested data use readonly TypeScript types.
|
|
|
4357
4386
|
startHttpHost(options: HttpHostOptions): Promise;
|
|
4358
4387
|
```
|
|
4359
4388
|
|
|
4360
|
-
Starts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or
|
|
4389
|
+
Starts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or
|
|
4390
|
+
`::1`; every request must also pass localhost Host and Origin checks. `createServer` must return a
|
|
4391
|
+
fresh, unconnected server with its request handlers registered.
|
|
4361
4392
|
|
|
4362
4393
|
## Types
|
|
4363
4394
|
|
|
4364
4395
|
```ts
|
|
4365
|
-
interface SnapshotPointer {
|
|
4366
|
-
readonly directory: string;
|
|
4367
|
-
}
|
|
4368
|
-
|
|
4369
4396
|
interface SnapshotManifest {
|
|
4370
|
-
readonly catalog: 'catalog.json';
|
|
4371
|
-
readonly contentDirectory: 'packages';
|
|
4372
|
-
readonly refine: 'refine.json' | null;
|
|
4373
4397
|
readonly schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;
|
|
4374
|
-
readonly search: 'search.json';
|
|
4375
4398
|
readonly version: string;
|
|
4376
4399
|
}
|
|
4377
|
-
```
|
|
4378
|
-
|
|
4379
|
-
Dev snapshots use `SnapshotPointer` (via `current.json`); published snapshots are static directories.
|
|
4380
4400
|
|
|
4381
|
-
```ts
|
|
4382
4401
|
interface LoadedSnapshot {
|
|
4383
4402
|
readonly catalog: CatalogFile;
|
|
4384
4403
|
readonly contentDirectory: string;
|
|
4385
4404
|
readonly manifest: SnapshotManifest;
|
|
4386
4405
|
readonly refineComponents: readonly CemDeclaration[];
|
|
4387
|
-
readonly search: readonly SearchRecord[];
|
|
4388
4406
|
}
|
|
4389
4407
|
```
|
|
4390
4408
|
|
|
@@ -4394,19 +4412,6 @@ interface CatalogFile {
|
|
|
4394
4412
|
readonly version: string;
|
|
4395
4413
|
}
|
|
4396
4414
|
|
|
4397
|
-
interface SearchRecord {
|
|
4398
|
-
readonly category: string;
|
|
4399
|
-
readonly description: string;
|
|
4400
|
-
readonly docs: Readonly>>;
|
|
4401
|
-
readonly examples: readonly { readonly id: string; readonly text: string }[];
|
|
4402
|
-
readonly exports: string;
|
|
4403
|
-
readonly keywords: string;
|
|
4404
|
-
readonly name: string;
|
|
4405
|
-
readonly related: string;
|
|
4406
|
-
readonly slug: string;
|
|
4407
|
-
readonly source: string | null;
|
|
4408
|
-
}
|
|
4409
|
-
|
|
4410
4415
|
interface PackageMeta {
|
|
4411
4416
|
readonly availableDocPages: readonly DocPage[];
|
|
4412
4417
|
readonly category: string;
|
|
@@ -4430,21 +4435,18 @@ interface Example {
|
|
|
4430
4435
|
|
|
4431
4436
|
```ts
|
|
4432
4437
|
interface Catalog {
|
|
4438
|
+
getComponent(tagName: string): CemDeclaration;
|
|
4433
4439
|
getDocs(slug: string, page: DocPage): string;
|
|
4434
4440
|
getExample(slug: string, exampleId: string): Example;
|
|
4435
4441
|
getPackage(slug: string): PackageMeta;
|
|
4436
4442
|
getSource(slug: string): string;
|
|
4437
4443
|
getTypeSignature(slug: string, symbol: string): string;
|
|
4444
|
+
listComponents(): readonly CemDeclaration[];
|
|
4438
4445
|
listExamples(slug: string): readonly Pick[];
|
|
4439
4446
|
listPackages(): readonly PackageMeta[];
|
|
4440
4447
|
search(query: string): readonly SearchHit[];
|
|
4441
4448
|
}
|
|
4442
4449
|
|
|
4443
|
-
interface RefineCatalog extends Catalog {
|
|
4444
|
-
getComponent(tagName: string): CemDeclaration;
|
|
4445
|
-
listComponents(): readonly CemDeclaration[];
|
|
4446
|
-
}
|
|
4447
|
-
|
|
4448
4450
|
interface SearchHit {
|
|
4449
4451
|
readonly matchedExamples?: readonly string[];
|
|
4450
4452
|
readonly matchedIn: readonly ('docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source')[];
|
|
@@ -4458,7 +4460,6 @@ Catalog exposes semantic reads. It does not expose its cached content chunks.
|
|
|
4458
4460
|
|
|
4459
4461
|
```ts
|
|
4460
4462
|
interface HttpHost {
|
|
4461
|
-
readonly disposalSignal: AbortSignal;
|
|
4462
4463
|
dispose(): Promise;
|
|
4463
4464
|
readonly disposed: boolean;
|
|
4464
4465
|
readonly host: string;
|
|
@@ -4478,11 +4479,9 @@ interface HttpHostOptions {
|
|
|
4478
4479
|
const DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;
|
|
4479
4480
|
type DocPage = (typeof DOC_PAGES)[number];
|
|
4480
4481
|
|
|
4481
|
-
const SNAPSHOT_SCHEMA_VERSION =
|
|
4482
|
+
const SNAPSHOT_SCHEMA_VERSION = 2 as const;
|
|
4482
4483
|
```
|
|
4483
4484
|
|
|
4484
|
-
CEM types and `RefineCatalog` are exported from `/refine`.
|
|
4485
|
-
|
|
4486
4485
|
```ts
|
|
4487
4486
|
interface CemDeclaration {
|
|
4488
4487
|
readonly attributes?: readonly CemAttribute[];
|
|
@@ -4536,9 +4535,14 @@ interface CemSlot {
|
|
|
4536
4535
|
}
|
|
4537
4536
|
```
|
|
4538
4537
|
|
|
4538
|
+
Component declarations and their nested data use readonly TypeScript types. The loader pins only
|
|
4539
|
+
the contract its consumers depend on: declarations form an array with valid, unique custom-element
|
|
4540
|
+
`tagName`s.
|
|
4541
|
+
|
|
4539
4542
|
## Errors
|
|
4540
4543
|
|
|
4541
|
-
`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,
|
|
4544
|
+
`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,
|
|
4545
|
+
`NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.
|
|
4542
4546
|
|
|
4543
4547
|
### Usage Guide
|
|
4544
4548
|
|
|
@@ -4561,7 +4565,7 @@ npx -y @vielzeug/codex --port=3100
|
|
|
4561
4565
|
curl http://127.0.0.1:3100/health
|
|
4562
4566
|
```
|
|
4563
4567
|
|
|
4564
|
-
Response includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed`
|
|
4568
|
+
Response includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` when coordinating shutdown.
|
|
4565
4569
|
|
|
4566
4570
|
## Agent Skill
|
|
4567
4571
|
|
|
@@ -4589,7 +4593,7 @@ bun run dev
|
|
|
4589
4593
|
|
|
4590
4594
|
`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.
|
|
4591
4595
|
|
|
4592
|
-
`bun run dev` watches documentation and package inputs,
|
|
4596
|
+
`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.
|
|
4593
4597
|
|
|
4594
4598
|
## Debugging
|
|
4595
4599
|
|
|
@@ -4611,23 +4615,13 @@ const catalog = new SnapshotCatalog(snapshot);
|
|
|
4611
4615
|
await createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());
|
|
4612
4616
|
```
|
|
4613
4617
|
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
```ts
|
|
4617
|
-
import { StdioServerTransport, loadSnapshot } from '@vielzeug/codex';
|
|
4618
|
-
import { createMcpServerWithRefine, SnapshotRefineCatalog } from '@vielzeug/codex/refine';
|
|
4619
|
-
|
|
4620
|
-
const snapshot = loadSnapshot();
|
|
4621
|
-
const catalog = new SnapshotRefineCatalog(snapshot);
|
|
4622
|
-
const server = createMcpServerWithRefine(catalog, { version: snapshot.manifest.version });
|
|
4623
|
-
await server.connect(new StdioServerTransport());
|
|
4624
|
-
```
|
|
4618
|
+
`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.
|
|
4625
4619
|
|
|
4626
4620
|
## Best Practices
|
|
4627
4621
|
|
|
4628
4622
|
- Use `search-packages` for capability discovery before loading broad source.
|
|
4629
4623
|
- Use `get-type-signature` before loading full source.
|
|
4630
|
-
-
|
|
4624
|
+
- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.
|
|
4631
4625
|
- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.
|
|
4632
4626
|
- Return a fresh configured server from `startHttpHost`'s `createServer` factory.
|
|
4633
4627
|
- Keep HTTP local. Use stdio for normal client integration.
|
|
@@ -4822,7 +4816,7 @@ function round(
|
|
|
4822
4816
|
value: Money,
|
|
4823
4817
|
options: { fractionDigits: number; rounding?: RoundingMode },
|
|
4824
4818
|
): Money;
|
|
4825
|
-
function
|
|
4819
|
+
function toDecimalString(value: Money): string;
|
|
4826
4820
|
```
|
|
4827
4821
|
|
|
4828
4822
|
`factor` and `divisor` are plain decimal strings; exponent notation, whitespace, and a leading plus are invalid. Matching currency identity is required for binary operations. `round()` requires integer `fractionDigits` from 0 through the currency's `minorUnit`. Scaling and rounding default to `halfAwayFromZero`.
|
|
@@ -4948,18 +4942,9 @@ Every Coins failure extends `CoinsError` and exposes `code`.
|
|
|
4948
4942
|
class CoinsError extends Error {
|
|
4949
4943
|
readonly code: CoinsErrorCode;
|
|
4950
4944
|
}
|
|
4951
|
-
|
|
4952
|
-
class CurrencyMismatchError extends CoinsError {
|
|
4953
|
-
readonly expected: string;
|
|
4954
|
-
readonly received: string;
|
|
4955
|
-
}
|
|
4956
|
-
|
|
4957
|
-
class InvalidCurrencyError extends CoinsError {
|
|
4958
|
-
readonly value: unknown;
|
|
4959
|
-
}
|
|
4960
4945
|
```
|
|
4961
4946
|
|
|
4962
|
-
|
|
4947
|
+
Every failure is a `CoinsError`; branch on the literal `code` union, not on subclasses, and read `message` (and `cause` when present) for details.
|
|
4963
4948
|
|
|
4964
4949
|
### Usage Guide
|
|
4965
4950
|
|
|
@@ -4968,11 +4953,11 @@ class InvalidCurrencyError extends CoinsError {
|
|
|
4968
4953
|
Construct decimal values with a currency definition. Coins stores minor units internally and never accepts implicit floating-point input.
|
|
4969
4954
|
|
|
4970
4955
|
```ts
|
|
4971
|
-
import { USD, add, money,
|
|
4956
|
+
import { USD, add, money, toDecimalString } from '@vielzeug/coins';
|
|
4972
4957
|
|
|
4973
4958
|
const subtotal = add(money('12.50', USD), money('7.25', USD));
|
|
4974
4959
|
|
|
4975
|
-
console.log(
|
|
4960
|
+
console.log(toDecimalString(subtotal)); // '19.75'
|
|
4976
4961
|
```
|
|
4977
4962
|
|
|
4978
4963
|
Use bigint only when data is already in minor units:
|
|
@@ -5002,7 +4987,7 @@ money('500', rewards);
|
|
|
5002
4987
|
Pass plain decimal strings to scaling operations; exponent notation, signs such as `+1`, whitespace, and numeric inputs are rejected. `multiply()`, `divide()`, `exchange()`, `round()`, and visible formatting default to `halfAwayFromZero`; pass a named mode when accounting policy requires another rule.
|
|
5003
4988
|
|
|
5004
4989
|
```ts
|
|
5005
|
-
import { USD, divide, money, multiply, round,
|
|
4990
|
+
import { USD, divide, money, multiply, round, toDecimalString } from '@vielzeug/coins';
|
|
5006
4991
|
|
|
5007
4992
|
const subtotal = money('19.99', USD);
|
|
5008
4993
|
const taxed = multiply(subtotal, '1.08', { rounding: 'halfEven' });
|
|
@@ -5012,7 +4997,7 @@ const roundedInput = money('19.999', USD, { rounding: 'halfAwayFromZero' });
|
|
|
5012
4997
|
const split = divide(taxed, '3', { rounding: 'floor' });
|
|
5013
4998
|
const displayed = round(taxed, { fractionDigits: 0, rounding: 'halfAwayFromZero' });
|
|
5014
4999
|
|
|
5015
|
-
console.log(
|
|
5000
|
+
console.log(toDecimalString(split), toDecimalString(displayed));
|
|
5016
5001
|
```
|
|
5017
5002
|
|
|
5018
5003
|
## Aggregate and Allocate
|
|
@@ -5020,15 +5005,15 @@ console.log(toDecimal(split), toDecimal(displayed));
|
|
|
5020
5005
|
`sum()` infers currency from non-empty values. Pass a canonical `{ currency }` for possibly empty iterables. `allocate()` preserves every minor unit, distributes remainders by largest fractional share with stable index ties, and applies the same allocation symmetrically to negative values. Counts and dense weight arrays are limited to 100,000 shares.
|
|
5021
5006
|
|
|
5022
5007
|
```ts
|
|
5023
|
-
import { USD, allocate, money, sum,
|
|
5008
|
+
import { USD, allocate, money, sum, toDecimalString } from '@vielzeug/coins';
|
|
5024
5009
|
|
|
5025
5010
|
const total = sum([money('10.00', USD), money('5.00', USD)]);
|
|
5026
5011
|
const zero = sum([], { currency: USD });
|
|
5027
5012
|
const weighted = allocate(money('10.00', USD), ['1', '2', '1']);
|
|
5028
5013
|
const even = allocate(money(5n, USD, { unit: 'minor' }), 2);
|
|
5029
5014
|
|
|
5030
|
-
console.log(
|
|
5031
|
-
console.log(weighted.map(
|
|
5015
|
+
console.log(toDecimalString(total));
|
|
5016
|
+
console.log(weighted.map(toDecimalString));
|
|
5032
5017
|
console.log(even.map((value) => value.amount)); // [3n, 2n]
|
|
5033
5018
|
```
|
|
5034
5019
|
|
|
@@ -5758,7 +5743,7 @@ const user = await courier.get('/users/{id}', {
|
|
|
5758
5743
|
prefetch(path: P, config: PrefetchConfig): Promise;
|
|
5759
5744
|
```
|
|
5760
5745
|
|
|
5761
|
-
Starts the same cached GET used by `get()`. `config.cache` is required; `signal`, per-call `timeout`, and `responseType: 'raw'` are unavailable. Fresh values and pending loads are reused. The promise settles when the attempt finishes. Request failures emit `request-error` through `tap()` and resolve without caching data.
|
|
5746
|
+
Starts the same cached GET used by `get()`. `config.cache` is required; `signal`, per-call `timeout`, and `responseType: 'raw'` are unavailable. Fresh values and pending loads are reused. The promise settles when the attempt finishes. Request failures emit `request-error` through `tap()` and resolve without caching data. Cache, key, and URL configuration errors reject before any request is dispatched.
|
|
5762
5747
|
|
|
5763
5748
|
### `invalidateCache()` and `clearCache()`
|
|
5764
5749
|
|
|
@@ -5873,6 +5858,12 @@ type GetRequestConfig = Omit,
|
|
|
5873
5858
|
body?: never;
|
|
5874
5859
|
};
|
|
5875
5860
|
|
|
5861
|
+
// The verbs (`post`, `put`, `patch`, `delete`) accept `HttpRequestConfig`:
|
|
5862
|
+
// request options without `method` or `cache`, exported for typing wrappers.
|
|
5863
|
+
type HttpRequestConfig = Omit, 'cache' | 'method'> & {
|
|
5864
|
+
cache?: never;
|
|
5865
|
+
};
|
|
5866
|
+
|
|
5876
5867
|
type PrefetchConfig = Omit,
|
|
5877
5868
|
'cache' | 'responseType' | 'signal' | 'timeout'
|
|
5878
5869
|
> & {
|
|
@@ -5885,19 +5876,19 @@ type PrefetchConfig = Omit,
|
|
|
5885
5876
|
|
|
5886
5877
|
## Errors
|
|
5887
5878
|
|
|
5888
|
-
| Error | Trigger
|
|
5889
|
-
| ------------------------------ |
|
|
5890
|
-
| `CourierError` | Base class for all Courier errors
|
|
5891
|
-
| `CourierHttpError` | Non-2xx HTTP response
|
|
5892
|
-
| `CourierNetworkError` | Request failure without response
|
|
5893
|
-
| `CourierTimeoutError` | Timeout signal aborts request
|
|
5894
|
-
| `CourierAbortError` | Caller or client cancellation
|
|
5895
|
-
| `CourierSchemaValidationError` | Response schema fails
|
|
5896
|
-
| `CourierParseError` | Response body cannot parse
|
|
5897
|
-
| `CourierConfigError` |
|
|
5898
|
-
| `CourierDisposedError` | Work starts after disposal
|
|
5879
|
+
| Error | Trigger | Notable properties |
|
|
5880
|
+
| ------------------------------ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
5881
|
+
| `CourierError` | Base class for all Courier errors | Use `instanceof` to narrow |
|
|
5882
|
+
| `CourierHttpError` | Non-2xx HTTP response | `status`, `data`, `headers`, `method`, `url`, `problem`; `CourierHttpError.is(e, status?)` narrows by status |
|
|
5883
|
+
| `CourierNetworkError` | Request failure without response | `method`, `url`, `cause` |
|
|
5884
|
+
| `CourierTimeoutError` | Timeout signal aborts request | `method`, `url`, `cause` |
|
|
5885
|
+
| `CourierAbortError` | Caller or client cancellation | `method`, `url`, `cause` |
|
|
5886
|
+
| `CourierSchemaValidationError` | Response schema fails | `data`, `cause` |
|
|
5887
|
+
| `CourierParseError` | Response body cannot parse | N/A |
|
|
5888
|
+
| `CourierConfigError` | Caller bug in the request (GET/HEAD body, raw + schema, unresolved path param, non-JSON-serializable body) | N/A |
|
|
5889
|
+
| `CourierDisposedError` | Work starts after disposal | N/A |
|
|
5899
5890
|
|
|
5900
|
-
Errors thrown directly by custom middleware are preserved rather than reclassified.
|
|
5891
|
+
Errors thrown directly by custom middleware are preserved rather than reclassified. Every request method (`request`, `get`, `prefetch`, and the verbs) reports failures as a rejected promise; only `createCourier()` throws synchronously, for invalid timeout and cache options.
|
|
5901
5892
|
|
|
5902
5893
|
### Problem details
|
|
5903
5894
|
|
|
@@ -6057,7 +6048,7 @@ await courier.prefetch('/users/{id}', { cache, params: { id: userId } });
|
|
|
6057
6048
|
const user = await courier.get('/users/{id}', { cache, params: { id: userId } });
|
|
6058
6049
|
```
|
|
6059
6050
|
|
|
6060
|
-
`prefetch()` returns a promise that settles when warming finishes. Request failures are not cached or rejected from that promise; the physical request emits `request-error` through `tap()`. Cache, key, and URL configuration errors
|
|
6051
|
+
`prefetch()` returns a promise that settles when warming finishes. Request failures are not cached or rejected from that promise; the physical request emits `request-error` through `tap()`. Cache, key, and URL configuration errors reject before prefetch dispatches a request.
|
|
6061
6052
|
|
|
6062
6053
|
Invalidate a structured prefix after writes. Every matching settled or pending key becomes ineligible for caching, while unrelated entries remain available.
|
|
6063
6054
|
|
|
@@ -6118,7 +6109,7 @@ await courier.get('/health', { timeout: 2_000 });
|
|
|
6118
6109
|
|
|
6119
6110
|
## Error Handling
|
|
6120
6111
|
|
|
6121
|
-
Courier classifies URL, request-construction, fetch, cancellation, HTTP, response-parsing, and schema failures into distinct error classes. Errors thrown directly by custom middleware are preserved.
|
|
6112
|
+
Courier classifies URL, request-construction, fetch, cancellation, HTTP, response-parsing, and schema failures into distinct error classes. Errors thrown directly by custom middleware are preserved. Every request method reports failures as a rejected promise; only `createCourier()` throws synchronously, for invalid timeout and cache options.
|
|
6122
6113
|
|
|
6123
6114
|
```ts
|
|
6124
6115
|
import {
|
|
@@ -8293,10 +8284,9 @@ try {
|
|
|
8293
8284
|
|
|
8294
8285
|
## Package Entry Point
|
|
8295
8286
|
|
|
8296
|
-
| Import
|
|
8297
|
-
|
|
|
8298
|
-
| `@vielzeug/flux`
|
|
8299
|
-
| `@vielzeug/flux/async` | `toAsyncIterable()` only |
|
|
8287
|
+
| Import | Purpose |
|
|
8288
|
+
| ---------------- | --------------------------------------------------------------------------------------------- |
|
|
8289
|
+
| `@vielzeug/flux` | Core streams, operators, consumers, errors, types, `createChannel()`, and `toAsyncIterable()` |
|
|
8300
8290
|
|
|
8301
8291
|
## Core
|
|
8302
8292
|
|
|
@@ -8482,10 +8472,12 @@ mergeMap(project: (value: A) => Stream, options: FlattenOptions): Operator
|
|
|
8482
8472
|
|
|
8483
8473
|
Runs inner streams with bounded concurrency and queue capacity. Exceeding capacity errors output with `FluxCapacityError`.
|
|
8484
8474
|
|
|
8485
|
-
| Option | Type
|
|
8486
|
-
| ------------- |
|
|
8487
|
-
| `concurrency` | `number \|
|
|
8488
|
-
| `capacity` | `number`
|
|
8475
|
+
| Option | Type | Description |
|
|
8476
|
+
| ------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
8477
|
+
| `concurrency` | `number \| 'unbounded'` | Maximum concurrently active inner subscriptions; `'unbounded'` starts every value immediately |
|
|
8478
|
+
| `capacity` | `number` | Positive maximum queued source values (required when `concurrency` is a number; unused when `'unbounded'`) |
|
|
8479
|
+
|
|
8480
|
+
Finite `concurrency` without a `capacity` throws `RangeError` when the operator is created.
|
|
8489
8481
|
|
|
8490
8482
|
---
|
|
8491
8483
|
|
|
@@ -8718,7 +8710,7 @@ interface Stream {
|
|
|
8718
8710
|
type OverflowPolicy = 'drop-newest' | 'drop-oldest' | 'error';
|
|
8719
8711
|
type AsyncIterableOptions = { capacity: number; overflow: OverflowPolicy; signal?: AbortSignal };
|
|
8720
8712
|
type TimerOptions = { delay: number; interval?: number };
|
|
8721
|
-
type FlattenOptions = { concurrency: number; capacity: number };
|
|
8713
|
+
type FlattenOptions = { concurrency: number; capacity: number } | { concurrency: 'unbounded'; capacity?: undefined };
|
|
8722
8714
|
type RetryOptions = { times: number; delay?: number | ((attempt: number) => number) };
|
|
8723
8715
|
type ToArrayOptions = { maxItems: number; signal?: AbortSignal };
|
|
8724
8716
|
type ValueOptions = { signal?: AbortSignal; defaultValue?: T };
|
|
@@ -8804,7 +8796,7 @@ clicks.subscribe({
|
|
|
8804
8796
|
});
|
|
8805
8797
|
```
|
|
8806
8798
|
|
|
8807
|
-
Use `switchMap()` for latest-only work, `mergeMap()` for concurrent work with bounded concurrency and queue capacity, and `concatMap()` for ordered work with bounded queue capacity.
|
|
8799
|
+
Use `switchMap()` for latest-only work, `mergeMap()` for concurrent work with bounded concurrency and queue capacity (`{ concurrency: 'unbounded' }` starts every value immediately), and `concatMap()` for ordered work with bounded queue capacity.
|
|
8808
8800
|
|
|
8809
8801
|
```ts
|
|
8810
8802
|
import { from, pipe, retry, switchMap } from '@vielzeug/flux';
|
|
@@ -8959,7 +8951,7 @@ const events = fromSubscribe((listener) => bus.on('message', listener));
|
|
|
8959
8951
|
- Pass `{ signal }` from component, request, or task owner.
|
|
8960
8952
|
- Provide `error` when subscription can recover locally.
|
|
8961
8953
|
- Use `pipe(source, ...)`; never mutate stream definitions.
|
|
8962
|
-
- Bound `mergeMap()` concurrency and queue capacity.
|
|
8954
|
+
- Bound `mergeMap()` concurrency and queue capacity, or choose `'unbounded'` explicitly.
|
|
8963
8955
|
- Bound `concatMap()` queue capacity.
|
|
8964
8956
|
- Bound `toArray()` with realistic `maxItems`.
|
|
8965
8957
|
- Choose async iterator overflow policy deliberately.
|
|
@@ -9749,7 +9741,7 @@ pnpm add @vielzeug/forge
|
|
|
9749
9741
|
- Explicit `validate()` and `submit()` timing
|
|
9750
9742
|
- `/dom`: optional element binding
|
|
9751
9743
|
- `/schema`: validator-agnostic Standard Schema adapter
|
|
9752
|
-
- `/persist`: explicit
|
|
9744
|
+
- `/persist`: explicit key/value draft persistence
|
|
9753
9745
|
- `/form-data`: browser submission serialization
|
|
9754
9746
|
|
|
9755
9747
|
## Documentation
|
|
@@ -9777,7 +9769,7 @@ pnpm add @vielzeug/forge
|
|
|
9777
9769
|
| `submit()` | Validate and submit one captured snapshot | Async | Concurrent submission rejects |
|
|
9778
9770
|
| `bindField()` | Bind a field to an HTML element | Sync | Caller owns returned cleanup |
|
|
9779
9771
|
| `schemaValidator()` | Adapt Standard Schema validation | Async | Transform output is not applied |
|
|
9780
|
-
| `loadForm()` / `saveForm()` | Explicit
|
|
9772
|
+
| `loadForm()` / `saveForm()` | Explicit key/value draft persistence | Async | Loading will not overwrite newer edits |
|
|
9781
9773
|
| `toFormData()` | Serialize supported values | Sync | Dotted keys and object arrays reject |
|
|
9782
9774
|
|
|
9783
9775
|
## Package Entry Point
|
|
@@ -9944,11 +9936,11 @@ Accepts any Standard Schema-compatible validator. Portable issues are copied int
|
|
|
9944
9936
|
```ts
|
|
9945
9937
|
import { loadForm, saveForm } from '@vielzeug/forge/persist';
|
|
9946
9938
|
|
|
9947
|
-
await saveForm(form, store, '
|
|
9948
|
-
await loadForm(form, store, '
|
|
9939
|
+
await saveForm(form, store, 'profile');
|
|
9940
|
+
await loadForm(form, store, 'profile', { signal });
|
|
9949
9941
|
```
|
|
9950
9942
|
|
|
9951
|
-
The store is structural
|
|
9943
|
+
The store is a structural key/value contract: `get(key)` and `put(key, value)`, sync or async. Saved drafts are the form values themselves; `loadForm` restores only plain objects and reports anything else as missing. The optional signal and form disposal cancel pending work; a load returns `false` when values changed before the draft arrived.
|
|
9952
9944
|
|
|
9953
9945
|
## FormData
|
|
9954
9946
|
|
|
@@ -10079,18 +10071,18 @@ Spell schemas implement Standard Schema directly. Forge uses the schema result o
|
|
|
10079
10071
|
## Persist a draft
|
|
10080
10072
|
|
|
10081
10073
|
```ts
|
|
10082
|
-
import { loadForm, saveForm } from '@vielzeug/forge/persist';
|
|
10074
|
+
import { type FormDraftStore, loadForm, saveForm } from '@vielzeug/forge/persist';
|
|
10083
10075
|
|
|
10084
|
-
const
|
|
10085
|
-
|
|
10086
|
-
|
|
10076
|
+
const store: FormDraftStore = {
|
|
10077
|
+
get: async (key) => JSON.parse((await localStorage.getItem(key)) ?? 'null'),
|
|
10078
|
+
put: async (key, value) => localStorage.setItem(key, JSON.stringify(value)),
|
|
10087
10079
|
};
|
|
10088
10080
|
|
|
10089
|
-
await saveForm(form, store, '
|
|
10090
|
-
await loadForm(form, store, '
|
|
10081
|
+
await saveForm(form, store, 'profile');
|
|
10082
|
+
await loadForm(form, store, 'profile', { signal });
|
|
10091
10083
|
```
|
|
10092
10084
|
|
|
10093
|
-
Persistence remains explicit. The store owns durability and
|
|
10085
|
+
Persistence remains explicit. The store owns durability and serialization format; Forge owns the draft shape, which is the form values themselves. Loading returns `false` rather than overwriting edits made while storage was pending, and it never restores a draft that is not a plain object.
|
|
10094
10086
|
|
|
10095
10087
|
## Serialize FormData
|
|
10096
10088
|
|
|
@@ -10161,7 +10153,7 @@ The owner that creates the form disposes it. Framework subscriptions own only th
|
|
|
10161
10153
|
## Working with Other Vielzeug Libraries
|
|
10162
10154
|
|
|
10163
10155
|
- Pass Spell schemas to `schemaValidator()` through Standard Schema.
|
|
10164
|
-
-
|
|
10156
|
+
- Wrap Vault stores in a small `FormDraftStore` adapter for `loadForm()` and `saveForm()`.
|
|
10165
10157
|
- Bind Ore or native controls with `bindField()` and owner cleanup.
|
|
10166
10158
|
|
|
10167
10159
|
## Best Practices
|
|
@@ -10968,13 +10960,10 @@ type Bus = {
|
|
|
10968
10960
|
listenerCount(event?: EventKey): number;
|
|
10969
10961
|
on>(event: K, listener: Listener, options?: SubscribeOptions): Unsubscribe;
|
|
10970
10962
|
onAny(listener: (event: EventKey, payload: unknown) => void, options?: SubscribeOptions): Unsubscribe;
|
|
10971
|
-
once>(event: K, listener: Listener, options?:
|
|
10972
|
-
tap(handler: (event: HeraldEvent) => void, options?:
|
|
10973
|
-
wait>(event: K, options?:
|
|
10974
|
-
waitAny[]>(
|
|
10975
|
-
events: K,
|
|
10976
|
-
options?: { signal?: AbortSignal },
|
|
10977
|
-
): Promise>;
|
|
10963
|
+
once>(event: K, listener: Listener, options?: SubscribeOptions): Unsubscribe;
|
|
10964
|
+
tap(handler: (event: HeraldEvent) => void, options?: SubscribeOptions): Unsubscribe;
|
|
10965
|
+
wait>(event: K, options?: SubscribeOptions): Promise;
|
|
10966
|
+
waitAny[]>(events: K, options?: SubscribeOptions): Promise>;
|
|
10978
10967
|
wildcardCount(): number;
|
|
10979
10968
|
};
|
|
10980
10969
|
```
|
|
@@ -10993,7 +10982,7 @@ type SubscribeOptions = { signal?: AbortSignal };
|
|
|
10993
10982
|
type Unsubscribe = () => void;
|
|
10994
10983
|
```
|
|
10995
10984
|
|
|
10996
|
-
`on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.
|
|
10985
|
+
`SubscribeOptions` is the single options type for every subscription-shaped method: `on`, `once`, `onAny`, `tap`, `wait`, and `waitAny`. `on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.
|
|
10997
10986
|
|
|
10998
10987
|
### `onAny()`
|
|
10999
10988
|
|
|
@@ -11005,7 +10994,7 @@ Resolves with the next payload for one event. It rejects with the external signa
|
|
|
11005
10994
|
|
|
11006
10995
|
### `waitAny()`
|
|
11007
10996
|
|
|
11008
|
-
Accepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription.
|
|
10997
|
+
Accepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription. An empty list throws a synchronous `TypeError`.
|
|
11009
10998
|
|
|
11010
10999
|
```ts
|
|
11011
11000
|
const result = await bus.waitAny(['count', 'ready']);
|
|
@@ -11159,7 +11148,7 @@ const result = await bus.waitAny(['cart:updated', 'user:logout'], {
|
|
|
11159
11148
|
if (result.event === 'cart:updated') console.log(result.payload.count);
|
|
11160
11149
|
```
|
|
11161
11150
|
|
|
11162
|
-
These methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`.
|
|
11151
|
+
These methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`. `waitAny()` with an empty event list throws a synchronous `TypeError`.
|
|
11163
11152
|
|
|
11164
11153
|
## Handle Listener Failures
|
|
11165
11154
|
|
|
@@ -14063,11 +14052,9 @@ try {
|
|
|
14063
14052
|
- `createTranslator()` compiles one immutable fixed-locale catalog.
|
|
14064
14053
|
- `createI18n()` manages eager catalogs, locale changes, and optional lazy loading.
|
|
14065
14054
|
- `translate()` renders text and plural messages through explicit catalog nodes.
|
|
14066
|
-
- `translateDynamic()` makes runtime-key lookup explicit.
|
|
14067
|
-
- `parts()` returns typed discriminated parts for framework content.
|
|
14068
14055
|
- `load()` deduplicates loading and resolves the active locale plus configured fallbacks.
|
|
14069
|
-
- `getSnapshot()` and `subscribe()` expose
|
|
14070
|
-
- `serialize()`
|
|
14056
|
+
- `getSnapshot()` and `subscribe()` expose a stable locale snapshot for framework stores.
|
|
14057
|
+
- `serialize()` transfers resolved SSR catalogs for client hydration.
|
|
14071
14058
|
- `missing: 'throw' | 'key' | handler` controls failure behaviour.
|
|
14072
14059
|
- `validateCatalog()` remains an isolated subpath tool.
|
|
14073
14060
|
|
|
@@ -14091,7 +14078,7 @@ try {
|
|
|
14091
14078
|
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
14092
14079
|
| ---------------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------- |
|
|
14093
14080
|
| `createTranslator()` | Compile one immutable locale catalog | Sync | No fallback locales |
|
|
14094
|
-
| `createI18n()` | Create mutable locale and catalog store | Sync | Provide catalogs,
|
|
14081
|
+
| `createI18n()` | Create mutable locale and catalog store | Sync | Provide eager catalogs, a loader, or both |
|
|
14095
14082
|
| `createFormatter()` | Create a cached Intl facade from `/format` | Sync | Pass a locale getter for dynamic locale changes |
|
|
14096
14083
|
| `createReactiveI18n()` | Mirror an i18n instance into ripple readables from `/ripple` | Sync | Optional `@vielzeug/ripple` peer; import from subpath |
|
|
14097
14084
|
| `catalogKeys()` | Enumerate message keys as dotted paths | Sync | Takes a catalog (or subtree) only; for an i18n instance pass `state.catalogs[state.locale]` |
|
|
@@ -14135,13 +14122,10 @@ const translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });
|
|
|
14135
14122
|
translator.translate('save');
|
|
14136
14123
|
```
|
|
14137
14124
|
|
|
14138
|
-
| Method
|
|
14139
|
-
|
|
|
14140
|
-
| `translate`
|
|
14141
|
-
| `
|
|
14142
|
-
| `parts` | `(textKey, { values })` or `(pluralKey, { count, ordinal?, values? })` | Typed discriminated parts |
|
|
14143
|
-
| `partsDynamic` | `(key, options)` | Parts for runtime key |
|
|
14144
|
-
| `locale` | `Locale` | Resolved active locale |
|
|
14125
|
+
| Method | Signature | Returns |
|
|
14126
|
+
| ----------- | -------------------------------------------------------------------- | ---------------------- |
|
|
14127
|
+
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |
|
|
14128
|
+
| `locale` | `Locale` | Resolved active locale |
|
|
14145
14129
|
|
|
14146
14130
|
---
|
|
14147
14131
|
|
|
@@ -14151,18 +14135,17 @@ translator.translate('save');
|
|
|
14151
14135
|
function createI18n(options: I18nOptions): I18n;
|
|
14152
14136
|
```
|
|
14153
14137
|
|
|
14154
|
-
Creates catalog store, current locale state, and
|
|
14138
|
+
Creates the catalog store, current locale state, and the active translator.
|
|
14155
14139
|
|
|
14156
|
-
| Parameter | Type | Description
|
|
14157
|
-
| --------------------- | ----------------------------- |
|
|
14158
|
-
| `options.catalogs` | `Catalogs` | Eager locale catalogs
|
|
14159
|
-
| `options.locale` | `Locale` | Initial locale; defaults to
|
|
14160
|
-
| `options.loadCatalog` | `(locale) => Promise \| C` |
|
|
14161
|
-
| `options.fallback` | `Locale \| readonly Locale[]` | Fallback locales loaded with the selected locale
|
|
14162
|
-
| `options.missing` | `MissingStrategy` | Missing-key/value strategy
|
|
14163
|
-
| `options.state` | `TranslationState` | Eager serialized state; mutually exclusive with `catalogs` |
|
|
14140
|
+
| Parameter | Type | Description |
|
|
14141
|
+
| --------------------- | ----------------------------- | ------------------------------------------------ |
|
|
14142
|
+
| `options.catalogs` | `Catalogs` | Eager locale catalogs |
|
|
14143
|
+
| `options.locale` | `Locale` | Initial locale; defaults to `en` |
|
|
14144
|
+
| `options.loadCatalog` | `(locale) => Promise \| C` | Loader for catalogs not supplied eagerly |
|
|
14145
|
+
| `options.fallback` | `Locale \| readonly Locale[]` | Fallback locales loaded with the selected locale |
|
|
14146
|
+
| `options.missing` | `MissingStrategy` | Missing-key/value strategy |
|
|
14164
14147
|
|
|
14165
|
-
Provide `catalogs
|
|
14148
|
+
Provide at least one of `catalogs` or `loadCatalog`; you may combine eager `catalogs` with `loadCatalog` for later locales.
|
|
14166
14149
|
|
|
14167
14150
|
**Returns:** `I18n`, with every `Translator` method plus lifecycle methods.
|
|
14168
14151
|
|
|
@@ -14181,13 +14164,12 @@ i18n.translate('title');
|
|
|
14181
14164
|
| Method or property | Signature | Returns |
|
|
14182
14165
|
| ------------------ | ------------------------------------- | -------------------------------------------------------------- |
|
|
14183
14166
|
| `translate` | Translator method | Rendered string |
|
|
14184
|
-
| `parts` | Translator method | Typed discriminated parts |
|
|
14185
14167
|
| `load` | `({ locale? })` | `Promise` after the locale and configured fallbacks load |
|
|
14186
14168
|
| `setLocale` | `(locale)` | `Promise` after an atomic loaded-locale commit |
|
|
14187
14169
|
| `isLoaded` | `({ locale? })` | `boolean` |
|
|
14188
|
-
| `getSnapshot` | `()` |
|
|
14189
|
-
| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function
|
|
14190
|
-
| `serialize` | `()` | Loader-free `
|
|
14170
|
+
| `getSnapshot` | `()` | Current locale, referentially stable until it changes |
|
|
14171
|
+
| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function; listener receives the new locale |
|
|
14172
|
+
| `serialize` | `()` | Loader-free `SerializedI18n` for SSR transfer |
|
|
14191
14173
|
| `dispose` | `()` | `void` |
|
|
14192
14174
|
| `locale` | `Locale` | Current canonical locale |
|
|
14193
14175
|
| `disposed` | `boolean` | Disposal state |
|
|
@@ -14204,7 +14186,7 @@ i18n.translate('title');
|
|
|
14204
14186
|
function createReactiveI18n(i18n: I18n): ReactiveI18n;
|
|
14205
14187
|
```
|
|
14206
14188
|
|
|
14207
|
-
Bridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency.
|
|
14189
|
+
Bridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate` first reads the reactive `locale` readable, so any binding built on it re-evaluates the instant `setLocale()` resolves.
|
|
14208
14190
|
|
|
14209
14191
|
`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.
|
|
14210
14192
|
|
|
@@ -14224,7 +14206,6 @@ await reactive.i18n.setLocale('fr');
|
|
|
14224
14206
|
| `i18n` | `I18n` | The underlying instance for imperative work (`setLocale`, `load`, disposal) |
|
|
14225
14207
|
| `locale` | `Readable` | Reactive locale: reading it inside a computed/template registers the dependency |
|
|
14226
14208
|
| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |
|
|
14227
|
-
| `translateDynamic` | `(key, options?)` | Same, for runtime-assembled keys |
|
|
14228
14209
|
|
|
14229
14210
|
---
|
|
14230
14211
|
|
|
@@ -14333,10 +14314,6 @@ type CatalogNode = Catalog | PluralMessage | string;
|
|
|
14333
14314
|
type Catalog = { readonly [key: string]: CatalogNode };
|
|
14334
14315
|
type Catalogs = Record;
|
|
14335
14316
|
|
|
14336
|
-
type TextPart = { readonly type: 'text'; readonly value: string };
|
|
14337
|
-
type ValuePart = { readonly type: 'value'; readonly value: V };
|
|
14338
|
-
type Part = TextPart | ValuePart;
|
|
14339
|
-
|
|
14340
14317
|
type MissingInfo = { readonly key: string; readonly locale: Locale; readonly name?: string };
|
|
14341
14318
|
type MissingHandler = (info: MissingInfo) => string;
|
|
14342
14319
|
type MissingStrategy = 'throw' | 'key' | MissingHandler;
|
|
@@ -14348,49 +14325,34 @@ type I18nOptions = {
|
|
|
14348
14325
|
readonly locale?: Locale;
|
|
14349
14326
|
readonly missing?: MissingStrategy;
|
|
14350
14327
|
} & (
|
|
14351
|
-
| { readonly catalogs: Catalogs; readonly loadCatalog?: CatalogLoader
|
|
14352
|
-
| { readonly catalogs?:
|
|
14353
|
-
| { readonly catalogs?: never; readonly loadCatalog: CatalogLoader; readonly state?: never }
|
|
14328
|
+
| { readonly catalogs: Catalogs; readonly loadCatalog?: CatalogLoader }
|
|
14329
|
+
| { readonly catalogs?: Catalogs; readonly loadCatalog: CatalogLoader }
|
|
14354
14330
|
);
|
|
14355
14331
|
|
|
14356
14332
|
type CatalogLoader = (locale: Locale) => Promise | C;
|
|
14357
14333
|
|
|
14358
|
-
type
|
|
14334
|
+
type SerializedI18n = {
|
|
14359
14335
|
readonly catalogs: Catalogs;
|
|
14360
14336
|
readonly locale: Locale;
|
|
14361
|
-
readonly version: 1;
|
|
14362
|
-
};
|
|
14363
|
-
|
|
14364
|
-
type I18nSnapshot = {
|
|
14365
|
-
readonly locale: Locale;
|
|
14366
|
-
readonly revision: number;
|
|
14367
|
-
readonly translator: Translator;
|
|
14368
14337
|
};
|
|
14369
14338
|
|
|
14370
14339
|
type I18n = Translator & {
|
|
14371
14340
|
readonly disposalSignal: AbortSignal;
|
|
14372
14341
|
dispose(): void;
|
|
14373
14342
|
readonly disposed: boolean;
|
|
14374
|
-
getSnapshot():
|
|
14343
|
+
getSnapshot(): Locale;
|
|
14375
14344
|
isLoaded(options?: { locale?: Locale }): boolean;
|
|
14376
14345
|
load(options?: { locale?: Locale }): Promise;
|
|
14377
|
-
serialize():
|
|
14346
|
+
serialize(): SerializedI18n;
|
|
14378
14347
|
setLocale(locale: Locale): Promise;
|
|
14379
|
-
subscribe(listener: (
|
|
14348
|
+
subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;
|
|
14380
14349
|
[Symbol.dispose](): void;
|
|
14381
14350
|
};
|
|
14382
14351
|
|
|
14383
14352
|
type Translator = {
|
|
14384
14353
|
readonly locale: Locale;
|
|
14385
|
-
parts(key: TextKey, options: TranslateOptions & { values: Record }): Array>;
|
|
14386
|
-
parts(key: PluralKey, options: PluralOptions & { values?: Record }): Array>;
|
|
14387
|
-
partsDynamic(
|
|
14388
|
-
key: string,
|
|
14389
|
-
options: (TranslateOptions | PluralOptions) & { values?: Record },
|
|
14390
|
-
): Array>;
|
|
14391
14354
|
translate(key: TextKey, options?: TranslateOptions): string;
|
|
14392
14355
|
translate(key: PluralKey, options: PluralOptions): string;
|
|
14393
|
-
translateDynamic(key: string, options?: TranslateOptions | PluralOptions): string;
|
|
14394
14356
|
};
|
|
14395
14357
|
```
|
|
14396
14358
|
|
|
@@ -14400,35 +14362,21 @@ type TranslateOptions = { values?: Values };
|
|
|
14400
14362
|
type PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };
|
|
14401
14363
|
type SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };
|
|
14402
14364
|
|
|
14403
|
-
type
|
|
14404
|
-
? C extends
|
|
14365
|
+
type CatalogPaths = Depth extends readonly [unknown, ...infer Rest]
|
|
14366
|
+
? C extends Leaf
|
|
14405
14367
|
? Prefix
|
|
14406
|
-
: C extends
|
|
14407
|
-
?
|
|
14408
|
-
|
|
14409
|
-
|
|
14410
|
-
|
|
14368
|
+
: C extends PluralMessage
|
|
14369
|
+
? never
|
|
14370
|
+
: C extends Catalog
|
|
14371
|
+
? {
|
|
14372
|
+
[K in string & keyof C]: CatalogPaths;
|
|
14373
|
+
}[string & keyof C]
|
|
14374
|
+
: never
|
|
14411
14375
|
: never;
|
|
14412
14376
|
|
|
14413
|
-
type
|
|
14414
|
-
|
|
14415
|
-
|
|
14416
|
-
: C extends Catalog
|
|
14417
|
-
? {
|
|
14418
|
-
[K in string & keyof C]: TextKey;
|
|
14419
|
-
}[string & keyof C]
|
|
14420
|
-
: never
|
|
14421
|
-
: never;
|
|
14422
|
-
|
|
14423
|
-
type PluralKey = Depth extends readonly [unknown, ...infer Rest]
|
|
14424
|
-
? C extends PluralMessage
|
|
14425
|
-
? Prefix
|
|
14426
|
-
: C extends Catalog
|
|
14427
|
-
? {
|
|
14428
|
-
[K in string & keyof C]: PluralKey;
|
|
14429
|
-
}[string & keyof C]
|
|
14430
|
-
: never
|
|
14431
|
-
: never;
|
|
14377
|
+
type MessageKey = CatalogPaths;
|
|
14378
|
+
type TextKey = CatalogPaths;
|
|
14379
|
+
type PluralKey = CatalogPaths;
|
|
14432
14380
|
|
|
14433
14381
|
type ValidationIssue = { key: string; locale: Locale; missing: Intl.LDMLPluralRule };
|
|
14434
14382
|
type CatalogComparison = {
|
|
@@ -14445,7 +14393,6 @@ type CatalogComparison = {
|
|
|
14445
14393
|
| `LinguaInvalidCatalogError` | Invalid catalog node or reserved key |
|
|
14446
14394
|
| `LinguaInvalidLocaleError` | Invalid BCP 47 locale tag |
|
|
14447
14395
|
| `LinguaInvalidPluralCountError` | Non-finite plural count |
|
|
14448
|
-
| `LinguaInvalidStateError` | Unsupported serialized state version |
|
|
14449
14396
|
| `LinguaMissingCatalogError` | No `loadCatalog` function or catalog source unavailable |
|
|
14450
14397
|
| `LinguaMissingKeyError` | Missing translation key when `missing: 'throw'` |
|
|
14451
14398
|
| `LinguaMissingValueError` | Missing interpolation value when `missing: 'throw'` |
|
|
@@ -14566,30 +14513,6 @@ const navKeys = catalogKeys(messages.nav);
|
|
|
14566
14513
|
// ['home', 'settings']
|
|
14567
14514
|
```
|
|
14568
14515
|
|
|
14569
|
-
## Render Framework Content
|
|
14570
|
-
|
|
14571
|
-
Use `parts()` when replacements are framework nodes, links, or other values that must not be stringified. `parts()` returns a discriminated union: `{ type: 'text', value: string }` for literal text and `{ type: 'value', value: V }` for interpolated values.
|
|
14572
|
-
|
|
14573
|
-
```ts
|
|
14574
|
-
import { createTranslator } from '@vielzeug/lingua';
|
|
14575
|
-
|
|
14576
|
-
const translator = createTranslator({ error: 'Try {retry} or {support}.' }, { locale: 'en' });
|
|
14577
|
-
|
|
14578
|
-
const retry = { href: '/retry', label: 'retry' };
|
|
14579
|
-
const support = { href: '/support', label: 'support' };
|
|
14580
|
-
|
|
14581
|
-
const result = translator.parts('error', { values: { retry, support } });
|
|
14582
|
-
// [
|
|
14583
|
-
// { type: 'text', value: 'Try ' },
|
|
14584
|
-
// { type: 'value', value: { href: '/retry', label: 'retry' } },
|
|
14585
|
-
// { type: 'text', value: ' or ' },
|
|
14586
|
-
// { type: 'value', value: { href: '/support', label: 'support' } },
|
|
14587
|
-
// { type: 'text', value: '.' },
|
|
14588
|
-
// ]
|
|
14589
|
-
```
|
|
14590
|
-
|
|
14591
|
-
Render returned array with framework fragment or list primitive. Give UI values consumer-owned keys before passing them to `parts()`; Lingua preserves value identity and never clones or mutates them.
|
|
14592
|
-
|
|
14593
14516
|
## Use a Fixed-Locale Translator
|
|
14594
14517
|
|
|
14595
14518
|
Use `createTranslator()` when one catalog and locale stay fixed for the translator's lifetime. It defaults locale to `en`; pass `locale` when plural rules or diagnostics need another locale. Lingua snapshots catalog messages during construction. Do not mutate source catalog objects afterward.
|
|
@@ -14620,16 +14543,16 @@ await i18n.setLocale('fr');
|
|
|
14620
14543
|
console.log(i18n.translate('navigation.settings'));
|
|
14621
14544
|
```
|
|
14622
14545
|
|
|
14623
|
-
Use loader-only configuration when every locale is lazy, and call `load()` before the first translation. Concurrent loads for the same locale share work. A failed or superseded locale selection never changes the
|
|
14546
|
+
Use loader-only configuration when every locale is lazy, and call `load()` before the first translation. Concurrent loads for the same locale share work. A failed or superseded locale selection never changes the active locale.
|
|
14624
14547
|
|
|
14625
|
-
## Subscribe to
|
|
14548
|
+
## Subscribe to Locale Changes
|
|
14626
14549
|
|
|
14627
|
-
Subscribe when UI state must change with locale
|
|
14550
|
+
Subscribe when UI state must change with the locale. Every callback receives the newly committed locale; translate through the instance to read current strings.
|
|
14628
14551
|
|
|
14629
14552
|
```ts
|
|
14630
14553
|
const unsubscribe = i18n.subscribe(
|
|
14631
|
-
(
|
|
14632
|
-
console.log(locale,
|
|
14554
|
+
(locale) => {
|
|
14555
|
+
console.log(locale, i18n.translate('navigation.settings'));
|
|
14633
14556
|
},
|
|
14634
14557
|
{ immediate: true },
|
|
14635
14558
|
);
|
|
@@ -14641,7 +14564,7 @@ Pass `{ signal }` when an `AbortController` owns subscription lifetime.
|
|
|
14641
14564
|
|
|
14642
14565
|
## SSR State
|
|
14643
14566
|
|
|
14644
|
-
Serialize resolved catalogs on the server
|
|
14567
|
+
Serialize resolved catalogs on the server and pass them back to `createI18n` on the client together with the serialized locale. `getSnapshot()` returns the current locale and stays referentially stable until the locale changes, so it works directly as a framework store snapshot.
|
|
14645
14568
|
|
|
14646
14569
|
```ts
|
|
14647
14570
|
import { createI18n } from '@vielzeug/lingua';
|
|
@@ -14652,14 +14575,14 @@ const serverI18n = createI18n({
|
|
|
14652
14575
|
});
|
|
14653
14576
|
|
|
14654
14577
|
const state = serverI18n.serialize();
|
|
14655
|
-
const clientI18n = createI18n({ state });
|
|
14578
|
+
const clientI18n = createI18n({ catalogs: state.catalogs, locale: state.locale });
|
|
14656
14579
|
|
|
14657
14580
|
console.log(clientI18n.translate('title'));
|
|
14658
14581
|
serverI18n.dispose();
|
|
14659
14582
|
clientI18n.dispose();
|
|
14660
14583
|
```
|
|
14661
14584
|
|
|
14662
|
-
|
|
14585
|
+
The serialized payload contains raw loaded catalogs and the active locale. It never contains loader functions. Pass an explicit `locale` only when the client should override the serialized locale.
|
|
14663
14586
|
|
|
14664
14587
|
## Validation
|
|
14665
14588
|
|
|
@@ -14687,33 +14610,31 @@ const result = compareCatalogs({
|
|
|
14687
14610
|
|
|
14688
14611
|
## Framework Integration
|
|
14689
14612
|
|
|
14690
|
-
|
|
14613
|
+
`getSnapshot()` and `subscribe()` match external-store primitives directly: the snapshot is the locale string, referentially stable until the locale changes.
|
|
14691
14614
|
|
|
14692
14615
|
```ts [React]
|
|
14693
14616
|
import { useSyncExternalStore } from 'react';
|
|
14694
14617
|
|
|
14695
14618
|
import type { I18n } from '@vielzeug/lingua';
|
|
14696
14619
|
|
|
14697
|
-
export function
|
|
14698
|
-
|
|
14699
|
-
|
|
14700
|
-
return snapshot.translator;
|
|
14620
|
+
export function useLocale(i18n: I18n) {
|
|
14621
|
+
return useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);
|
|
14701
14622
|
}
|
|
14702
14623
|
```
|
|
14703
14624
|
|
|
14704
14625
|
```ts [Vue 3]
|
|
14705
|
-
import {
|
|
14626
|
+
import { readonly, shallowRef } from 'vue';
|
|
14706
14627
|
|
|
14707
14628
|
import type { I18n } from '@vielzeug/lingua';
|
|
14708
14629
|
|
|
14709
|
-
export function
|
|
14710
|
-
const
|
|
14711
|
-
|
|
14712
|
-
|
|
14630
|
+
export function useLocale(i18n: I18n) {
|
|
14631
|
+
const locale = shallowRef(i18n.getSnapshot());
|
|
14632
|
+
|
|
14633
|
+
i18n.subscribe((next) => {
|
|
14634
|
+
locale.value = next;
|
|
14713
14635
|
});
|
|
14714
14636
|
|
|
14715
|
-
|
|
14716
|
-
return snapshot;
|
|
14637
|
+
return readonly(locale);
|
|
14717
14638
|
}
|
|
14718
14639
|
```
|
|
14719
14640
|
|
|
@@ -14722,21 +14643,21 @@ import { readable } from 'svelte/store';
|
|
|
14722
14643
|
|
|
14723
14644
|
import type { I18n } from '@vielzeug/lingua';
|
|
14724
14645
|
|
|
14725
|
-
export function
|
|
14726
|
-
return readable(i18n.getSnapshot()
|
|
14646
|
+
export function localeStore(i18n: I18n) {
|
|
14647
|
+
return readable(i18n.getSnapshot(), (set) => i18n.subscribe(set));
|
|
14727
14648
|
}
|
|
14728
14649
|
```
|
|
14729
14650
|
|
|
14730
14651
|
## Working with Other Vielzeug Libraries
|
|
14731
14652
|
|
|
14732
|
-
Bridge Lingua's
|
|
14653
|
+
Bridge Lingua's `getSnapshot()`/`subscribe()` pair directly when templates need reactive locale reads.
|
|
14733
14654
|
|
|
14734
14655
|
```ts
|
|
14735
14656
|
import { createRipple } from '@vielzeug/ripple';
|
|
14736
14657
|
|
|
14737
14658
|
const ripple = createRipple();
|
|
14738
14659
|
const i18nState = ripple.fromSubscribable(i18n);
|
|
14739
|
-
export const locale = ripple.computed(() => i18nState.value
|
|
14660
|
+
export const locale = ripple.computed(() => i18nState.value);
|
|
14740
14661
|
|
|
14741
14662
|
export const disposeLocaleBridge = () => ripple.dispose();
|
|
14742
14663
|
```
|
|
@@ -14748,9 +14669,7 @@ Use Courier loaders when locale catalogs come from HTTP rather than bundled modu
|
|
|
14748
14669
|
- Define plural messages with `{ plural: ... }` and no sibling metadata.
|
|
14749
14670
|
- Keep arrays and application metadata outside catalogs.
|
|
14750
14671
|
- Treat source catalog objects as immutable after construction.
|
|
14751
|
-
- Use `translateDynamic()` only for runtime-generated keys.
|
|
14752
14672
|
- Provide eager catalogs for translations required during initial render.
|
|
14753
|
-
- Give UI values keys before passing them to `parts()`.
|
|
14754
14673
|
- Keep loader functions out of SSR payloads.
|
|
14755
14674
|
- Dispose temporary instances after requests, tests, and route lifetimes.
|
|
14756
14675
|
- Use `missing: 'throw'` in development to catch missing keys and values early.
|
|
@@ -14764,7 +14683,7 @@ Use Courier loaders when locale catalogs come from HTTP rather than bundled modu
|
|
|
14764
14683
|
### REPL Examples
|
|
14765
14684
|
|
|
14766
14685
|
- Lazy Locale Catalog (id: `feature-resources`)
|
|
14767
|
-
-
|
|
14686
|
+
- Plural Messages (id: `plurals`)
|
|
14768
14687
|
- Static Translator (id: `static-translator`)
|
|
14769
14688
|
- Reactive Locale Store (id: `store`)
|
|
14770
14689
|
|
|
@@ -18039,6 +17958,286 @@ define('signup-form', {
|
|
|
18039
17958
|
|
|
18040
17959
|
---
|
|
18041
17960
|
|
|
17961
|
+
## @vielzeug/patchwork
|
|
17962
|
+
|
|
17963
|
+
**Category:** utilities
|
|
17964
|
+
|
|
17965
|
+
### Overview
|
|
17966
|
+
|
|
17967
|
+
## Why Patchwork?
|
|
17968
|
+
|
|
17969
|
+
Once two places hold the same document, sending the whole document is the lazy answer that
|
|
17970
|
+
scales worst: bandwidth grows with document size, not with what changed, and blind writes
|
|
17971
|
+
clobber concurrent edits. JSON Patch is the wire format for the honest answer, and Patchwork
|
|
17972
|
+
implements it with the two properties sync code actually needs: `apply` is **immutable with
|
|
17973
|
+
structural sharing** (untouched subtrees keep their object identity, so React and every memo
|
|
17974
|
+
layer work for free), and `diff` is **structural** (objects diff field-by-field, append-only
|
|
17975
|
+
arrays stay one operation).
|
|
17976
|
+
|
|
17977
|
+
```ts
|
|
17978
|
+
import { apply, diff } from '@vielzeug/patchwork';
|
|
17979
|
+
|
|
17980
|
+
const patch = diff(before, after); // [{ op: 'replace', path: '/user/address/zip', value: '1010' }]
|
|
17981
|
+
const next = apply(before, patch); // before untouched; next.user.address is new, next.user.orders === before.user.orders
|
|
17982
|
+
```
|
|
17983
|
+
|
|
17984
|
+
A failed `test` operation is an ordinary answer in protocol code, not an exception:
|
|
17985
|
+
`tryApply` returns `{ ok: false, error: { index, path, reason } }`, so conflict handling is
|
|
17986
|
+
data you can log and reply to. Zero runtime dependencies, spec-exact pointers (`~0`/`~1`
|
|
17987
|
+
escaping, `-` append), and a browser-safe build.
|
|
17988
|
+
|
|
17989
|
+
## Installation
|
|
17990
|
+
|
|
17991
|
+
```sh [pnpm]
|
|
17992
|
+
pnpm add @vielzeug/patchwork
|
|
17993
|
+
```
|
|
17994
|
+
|
|
17995
|
+
```sh [npm]
|
|
17996
|
+
npm install @vielzeug/patchwork
|
|
17997
|
+
```
|
|
17998
|
+
|
|
17999
|
+
```sh [yarn]
|
|
18000
|
+
yarn add @vielzeug/patchwork
|
|
18001
|
+
```
|
|
18002
|
+
|
|
18003
|
+
## Quick Start
|
|
18004
|
+
|
|
18005
|
+
```ts
|
|
18006
|
+
import { apply, diff, tryApply } from '@vielzeug/patchwork';
|
|
18007
|
+
|
|
18008
|
+
const doc = { items: ['a'], title: 'Cart' };
|
|
18009
|
+
const patch = diff(doc, { items: ['a', 'b'], title: 'Wagen' });
|
|
18010
|
+
// [{ op: 'add', path: '/items/-', value: 'b' }, { op: 'replace', path: '/title', value: 'Wagen' }]
|
|
18011
|
+
|
|
18012
|
+
const next = apply(doc, patch); // doc untouched; next.title changed, next.items is a new array (it grew)
|
|
18013
|
+
|
|
18014
|
+
tryApply(doc, [{ op: 'test', path: '/title', value: 'Other' }, ...patch]);
|
|
18015
|
+
// { ok: false, error: { index: 0, reason: 'test', path: '/title', message: … } }
|
|
18016
|
+
```
|
|
18017
|
+
|
|
18018
|
+
## Features
|
|
18019
|
+
|
|
18020
|
+
- **`apply`**: immutable RFC 6902 — all six operations, copy-on-write with structural sharing.
|
|
18021
|
+
- **`tryApply`**: the same engine as data; a failed `test` or bad pointer returns a structured rejection with the failing operation index.
|
|
18022
|
+
- **`diff`**: per-field object patches, suffix-trimmed arrays (appends cost a single `add`), pointer-escaped keys.
|
|
18023
|
+
- **Pointer API**: `parsePointer`/`formatPointer` with `~0`/`~1` escaping and `getIn` for reads.
|
|
18024
|
+
- **Spec-exact edges**: `null` is a value not an absence, `replace` requires an existing target, array `add` inserts, `-` appends.
|
|
18025
|
+
- **Input isolation**: `add`/`copy` values are cloned in, so the caller's objects can never mutate a document afterwards.
|
|
18026
|
+
- **Hard JSON domain**: numbers, strings, booleans, null, arrays, objects — no functions, no prototypes, nothing to inherit.
|
|
18027
|
+
|
|
18028
|
+
## Documentation
|
|
18029
|
+
|
|
18030
|
+
- [Usage Guide](./usage.md)
|
|
18031
|
+
- [API Reference](./api.md)
|
|
18032
|
+
- [Examples](./examples.md)
|
|
18033
|
+
|
|
18034
|
+
## See Also
|
|
18035
|
+
|
|
18036
|
+
- [Tandem](/tandem/): transports patches over the wire in sync protocols.
|
|
18037
|
+
- [Forge](/forge/): tracks the dirty fields whose changes become patches.
|
|
18038
|
+
- [Vault](/vault/): schemas that define what a patchable document may contain.
|
|
18039
|
+
|
|
18040
|
+
### API Reference
|
|
18041
|
+
|
|
18042
|
+
## API Overview
|
|
18043
|
+
|
|
18044
|
+
| Symbol | Purpose | Execution | Common gotcha |
|
|
18045
|
+
| --------------- | ------------------------------------------------------ | --------- | -------------------------------------------------------------- |
|
|
18046
|
+
| `apply` | Immutable RFC 6902 application with structural sharing | Sync | Throws on unresolvable pointer or failed `test` |
|
|
18047
|
+
| `tryApply` | Same engine, rejection as data | Sync | `error.index` is the failing operation, not the document size |
|
|
18048
|
+
| `diff` | Structural patch from `from` to `to` | Sync | Patch values reference `to`; clone if `to` keeps mutating |
|
|
18049
|
+
| `getIn` | Pointer read | Sync | Returns `undefined` both for missing and for non-JSON descents |
|
|
18050
|
+
| `parsePointer` | Pointer → decoded tokens | Sync | Throws `PatchPathError` on pointers not starting with `/` |
|
|
18051
|
+
| `formatPointer` | Tokens → pointer | Sync | `[]` formats to `''` (the whole document) |
|
|
18052
|
+
|
|
18053
|
+
## Package Entry Point
|
|
18054
|
+
|
|
18055
|
+
```ts
|
|
18056
|
+
import { apply, diff, getIn, parsePointer, tryApply } from '@vielzeug/patchwork';
|
|
18057
|
+
```
|
|
18058
|
+
|
|
18059
|
+
## Functions
|
|
18060
|
+
|
|
18061
|
+
### apply
|
|
18062
|
+
|
|
18063
|
+
```ts
|
|
18064
|
+
function apply(doc: T, patch: JsonPatch): T;
|
|
18065
|
+
```
|
|
18066
|
+
|
|
18067
|
+
Applies every operation in order, copy-on-write: untouched subtrees keep their identity, and
|
|
18068
|
+
a fully no-op patch returns `doc` itself. `add` inserts into arrays (index may equal the
|
|
18069
|
+
length), sets/overwrites object members, and supports `-` append; `remove` and `replace`
|
|
18070
|
+
require the target to exist; `move` removes the `from` location then adds at `path`; `copy`
|
|
18071
|
+
adds a `structuredClone`; `test` compares structurally. Values from `add`/`copy` are cloned
|
|
18072
|
+
into the document.
|
|
18073
|
+
|
|
18074
|
+
Throws `PatchPathError` when a pointer does not resolve or an index is out of bounds, and
|
|
18075
|
+
`PatchTestError` when a `test` operation does not match.
|
|
18076
|
+
|
|
18077
|
+
### tryApply
|
|
18078
|
+
|
|
18079
|
+
```ts
|
|
18080
|
+
function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult;
|
|
18081
|
+
```
|
|
18082
|
+
|
|
18083
|
+
Never throws for patch failures: returns `{ ok: true, doc }` or
|
|
18084
|
+
`{ ok: false, error: { index, path, reason: 'path' | 'test', message } }`, where `path` is
|
|
18085
|
+
the failing operation's `path` (or `from` for `move`/`copy`).
|
|
18086
|
+
|
|
18087
|
+
### diff
|
|
18088
|
+
|
|
18089
|
+
```ts
|
|
18090
|
+
function diff(from: JsonValue, to: JsonValue): JsonPatch;
|
|
18091
|
+
```
|
|
18092
|
+
|
|
18093
|
+
Computes a patch that turns `from` into `to`. Objects diff per key; arrays trim their common
|
|
18094
|
+
suffix, recurse positionally over the shared head, and emit tail removals followed by `-`
|
|
18095
|
+
appends; anything else becomes one `replace` at the deepest shared pointer. The result always
|
|
18096
|
+
applies via `apply` (`apply(from, diff(from, to))` deep-equals `to`).
|
|
18097
|
+
|
|
18098
|
+
### getIn / parsePointer / formatPointer
|
|
18099
|
+
|
|
18100
|
+
```ts
|
|
18101
|
+
function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined;
|
|
18102
|
+
function parsePointer(pointer: JsonPointer): string[];
|
|
18103
|
+
function formatPointer(tokens: readonly string[]): JsonPointer;
|
|
18104
|
+
```
|
|
18105
|
+
|
|
18106
|
+
RFC 6901 throughout: `~1` decodes to `/`, `~0` to `~`; the empty pointer is the whole
|
|
18107
|
+
document. `parsePointer('x')` throws — pointers start with `/` or are empty.
|
|
18108
|
+
|
|
18109
|
+
## Types
|
|
18110
|
+
|
|
18111
|
+
| Type | Purpose |
|
|
18112
|
+
| ---------------- | --------------------------------------------------------------- |
|
|
18113
|
+
| `JsonValue` | The JSON domain: null, boolean, number, string, arrays, objects |
|
|
18114
|
+
| `JsonObject` | `{ [key: string]: JsonValue }` |
|
|
18115
|
+
| `JsonPointer` | A string RFC 6901 pointer |
|
|
18116
|
+
| `PatchOperation` | Union of the six RFC 6902 operations |
|
|
18117
|
+
| `JsonPatch` | `readonly PatchOperation[]` |
|
|
18118
|
+
| `ApplyResult` | `{ ok: true, doc } \| { ok: false, error: PatchErrorInfo }` |
|
|
18119
|
+
| `PatchErrorInfo` | `{ index, path, reason: 'path' \| 'test', message }` |
|
|
18120
|
+
|
|
18121
|
+
Individual operation types (`AddOperation`, `RemoveOperation`, `ReplaceOperation`,
|
|
18122
|
+
`MoveOperation`, `CopyOperation`, `TestOperation`) are exported for building typed patch
|
|
18123
|
+
builders.
|
|
18124
|
+
|
|
18125
|
+
## Errors
|
|
18126
|
+
|
|
18127
|
+
| Error | Thrown when |
|
|
18128
|
+
| ---------------- | -------------------------------------------------------------------------------- |
|
|
18129
|
+
| `PatchError` | Base class for every patchwork error |
|
|
18130
|
+
| `PatchPathError` | A pointer does not resolve, an index is out of bounds, or a pointer is malformed |
|
|
18131
|
+
| `PatchTestError` | A `test` operation did not match the document |
|
|
18132
|
+
|
|
18133
|
+
### Usage Guide
|
|
18134
|
+
|
|
18135
|
+
## Basic Usage
|
|
18136
|
+
|
|
18137
|
+
A patch is just an array of operations — build them by hand or compute them with `diff`, then
|
|
18138
|
+
apply them immutably:
|
|
18139
|
+
|
|
18140
|
+
```ts
|
|
18141
|
+
import { apply, diff } from '@vielzeug/patchwork';
|
|
18142
|
+
|
|
18143
|
+
const cart = { items: [{ qty: 1, sku: 'a' }], meta: { rev: 7 }, total: '99' };
|
|
18144
|
+
const edited = { items: [{ qty: 3, sku: 'a' }], meta: { rev: 8 }, total: '99' };
|
|
18145
|
+
|
|
18146
|
+
const patch = diff(cart, edited);
|
|
18147
|
+
// [{ op: 'replace', path: '/items/0/qty', value: 3 }, { op: 'replace', path: '/meta/rev', value: 8 }]
|
|
18148
|
+
|
|
18149
|
+
const next = apply(cart, patch);
|
|
18150
|
+
next !== cart; // a new document
|
|
18151
|
+
next.total === cart.total; // untouched subtrees keep their identity, so memoized
|
|
18152
|
+
next.items !== cart.items; // selectors recompute only over the branches that changed
|
|
18153
|
+
```
|
|
18154
|
+
|
|
18155
|
+
`apply` returns the same reference when a patch is a no-op (`[]`, or a `replace` with an
|
|
18156
|
+
equal value), so `Object.is(before, after)` is a reliable "did anything change" check.
|
|
18157
|
+
|
|
18158
|
+
## Reading and Pointers
|
|
18159
|
+
|
|
18160
|
+
```ts
|
|
18161
|
+
import { formatPointer, getIn, parsePointer } from '@vielzeug/patchwork';
|
|
18162
|
+
|
|
18163
|
+
getIn(cart, '/items/0/sku'); // 'a'
|
|
18164
|
+
getIn(cart, '/items/9'); // undefined — reads never throw
|
|
18165
|
+
parsePointer('/a~1b/c~0d'); // ['a/b', 'c~d']
|
|
18166
|
+
formatPointer(['a/b', 'c~d']); // '/a~1b/c~0d'
|
|
18167
|
+
```
|
|
18168
|
+
|
|
18169
|
+
`null` is a value, not an absence: `getIn({ a: null }, '/a')` is `null`, while
|
|
18170
|
+
`getIn({ a: null }, '/b')` is `undefined`.
|
|
18171
|
+
|
|
18172
|
+
## Conflicts as Data
|
|
18173
|
+
|
|
18174
|
+
In collaborative code a rejected patch is a normal message, not a crash. `apply` throws
|
|
18175
|
+
(`PatchPathError` for unresolvable pointers, `PatchTestError` for failed `test` operations);
|
|
18176
|
+
`tryApply` returns the same outcome as data:
|
|
18177
|
+
|
|
18178
|
+
```ts
|
|
18179
|
+
import { tryApply } from '@vielzeug/patchwork';
|
|
18180
|
+
|
|
18181
|
+
const result = tryApply(doc, [
|
|
18182
|
+
{ op: 'test', path: '/rev', value: 41 }, // client last saw rev 41
|
|
18183
|
+
{ op: 'replace', path: '/title', value: 'New' },
|
|
18184
|
+
]);
|
|
18185
|
+
|
|
18186
|
+
if (!result.ok) {
|
|
18187
|
+
// { index: 0, path: '/rev', reason: 'test', message: … } — reply "conflict, rebase on rev 42"
|
|
18188
|
+
}
|
|
18189
|
+
```
|
|
18190
|
+
|
|
18191
|
+
Guarding a write with a leading `test` is the whole optimistic-concurrency protocol: the
|
|
18192
|
+
server `tryApply`s, and a failed test means someone else moved first.
|
|
18193
|
+
|
|
18194
|
+
## What diff Emits
|
|
18195
|
+
|
|
18196
|
+
- **Objects**: per-key `remove`s, `add`s, and recursive descent — changed fields cost one small operation each, regardless of document size.
|
|
18197
|
+
- **Arrays**: the common suffix is trimmed and the head walked positionally; appends become a single `{ op: 'add', path: '/x/-' }`, tail removals become ordered index removes.
|
|
18198
|
+
- **Different types or root changes**: one `replace` at the shared ancestor — patches stay short and always apply cleanly.
|
|
18199
|
+
|
|
18200
|
+
`diff` optimizes for apply-safety and small steady-state payloads (edit-one-field,
|
|
18201
|
+
append-one-row), which is exactly the traffic of form autosaves, live documents, and audit
|
|
18202
|
+
trails. It is not an attempt at minimal-edit-count: reordering an array yields positional
|
|
18203
|
+
replaces, which are correct, just not clever.
|
|
18204
|
+
|
|
18205
|
+
## The JSON Domain
|
|
18206
|
+
|
|
18207
|
+
Documents are JSON: `null`, booleans, numbers, strings, arrays, and plain objects. `apply`
|
|
18208
|
+
clones every incoming `add`/`copy` value (`structuredClone`), so objects you built the patch
|
|
18209
|
+
from can be mutated freely afterwards without touching the document. `diff` treats the two
|
|
18210
|
+
documents read-only and never clones what it returns — `value`s in the patch point into `to`,
|
|
18211
|
+
so freeze `to` (or clone the patch) if you intend to keep mutating it.
|
|
18212
|
+
|
|
18213
|
+
## Error Handling
|
|
18214
|
+
|
|
18215
|
+
All errors extend `PatchError`. `apply` throws at the first failing operation and leaves
|
|
18216
|
+
nothing behind (it builds the next document copy-on-write, so a throw discards it).
|
|
18217
|
+
`PatchErrorInfo.path` names the pointer the failing operation targeted — for `move`/`copy`
|
|
18218
|
+
that is the `from` location when the source was missing.
|
|
18219
|
+
|
|
18220
|
+
## Best Practices
|
|
18221
|
+
|
|
18222
|
+
- Use `tryApply` at network boundaries and `apply` in pure local code — exceptions are for programmer errors, rejections are for protocol answers.
|
|
18223
|
+
- Prefix state-changing patches with a `{ op: 'test', path: '/rev', … }` operation instead of shipping whole documents; the patch is the lock.
|
|
18224
|
+
- Keep patches in your logs as data (they are JSON): replaying `apply` over an old snapshot reconstructs exactly what was sent.
|
|
18225
|
+
- Do not feed non-JSON values (functions, `undefined`, `Date`) through `apply`; validate documents with [Vault](/vault/) schemas at the edge and the domain stays clean.
|
|
18226
|
+
|
|
18227
|
+
### Examples
|
|
18228
|
+
|
|
18229
|
+
## Examples
|
|
18230
|
+
|
|
18231
|
+
- [Diff and Apply](./examples/diff-and-apply.md)
|
|
18232
|
+
- [Optimistic Sync with test Operations](./examples/optimistic-sync.md)
|
|
18233
|
+
|
|
18234
|
+
### REPL Examples
|
|
18235
|
+
|
|
18236
|
+
- Apply - Immutable patches and guarded test (id: `apply-basic`)
|
|
18237
|
+
- Diff - Structural patches (id: `diff-basic`)
|
|
18238
|
+
|
|
18239
|
+
---
|
|
18240
|
+
|
|
18042
18241
|
## @vielzeug/postmaster
|
|
18043
18242
|
|
|
18044
18243
|
**Category:** Async
|
|
@@ -18057,12 +18256,12 @@ async function createTodo(payload: { id: string; title: string }) {
|
|
|
18057
18256
|
}
|
|
18058
18257
|
|
|
18059
18258
|
// After
|
|
18060
|
-
import { createPostmaster,
|
|
18259
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18061
18260
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18062
18261
|
import { s } from '@vielzeug/spell';
|
|
18063
18262
|
|
|
18064
|
-
const jobs =
|
|
18065
|
-
createTodo: {
|
|
18263
|
+
const jobs = {
|
|
18264
|
+
createTodo: defineJob({
|
|
18066
18265
|
version: 1,
|
|
18067
18266
|
validate: s.object({ id: s.string(), title: s.string() }),
|
|
18068
18267
|
key: (p) => p.id,
|
|
@@ -18074,8 +18273,8 @@ const jobs = defineJobs({
|
|
|
18074
18273
|
signal,
|
|
18075
18274
|
});
|
|
18076
18275
|
},
|
|
18077
|
-
},
|
|
18078
|
-
}
|
|
18276
|
+
}),
|
|
18277
|
+
};
|
|
18079
18278
|
|
|
18080
18279
|
const store = createIndexedDbPostmasterStore({ name: 'my-app-outbox' });
|
|
18081
18280
|
const postmaster = createPostmaster({ jobs, store });
|
|
@@ -18130,11 +18329,11 @@ yarn add @vielzeug/postmaster @vielzeug/vault
|
|
|
18130
18329
|
Define typed jobs, create a durable store, enqueue work, and start the processor. Dispose both the processor and the store when the page lifetime ends.
|
|
18131
18330
|
|
|
18132
18331
|
```ts
|
|
18133
|
-
import { createPostmaster,
|
|
18332
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18134
18333
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18135
18334
|
|
|
18136
|
-
const jobs =
|
|
18137
|
-
createTodo: {
|
|
18335
|
+
const jobs = {
|
|
18336
|
+
createTodo: defineJob({
|
|
18138
18337
|
version: 1,
|
|
18139
18338
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18140
18339
|
key: (p) => p.id,
|
|
@@ -18147,8 +18346,8 @@ const jobs = defineJobs({
|
|
|
18147
18346
|
});
|
|
18148
18347
|
},
|
|
18149
18348
|
retry: { maxAttempts: 5, shouldRetry: () => true },
|
|
18150
|
-
},
|
|
18151
|
-
}
|
|
18349
|
+
}),
|
|
18350
|
+
};
|
|
18152
18351
|
|
|
18153
18352
|
const store = createIndexedDbPostmasterStore({ name: 'my-app-outbox' });
|
|
18154
18353
|
const postmaster = createPostmaster({ jobs, store });
|
|
@@ -18163,7 +18362,7 @@ await store.dispose();
|
|
|
18163
18362
|
|
|
18164
18363
|
## Features
|
|
18165
18364
|
|
|
18166
|
-
- `
|
|
18365
|
+
- `defineJob()`: Types one job definition; the payload type comes from the validator (or an explicit `defineJob`) and flows into `execute`, `key`, and `enqueue`.
|
|
18167
18366
|
- `createPostmaster()`: Processor with leased claims, heartbeat renewal, and crash recovery.
|
|
18168
18367
|
- `enqueue()`: Persist a job and wake the processor, with optional delayed eligibility via `availableAt`.
|
|
18169
18368
|
- `flush()`: Process every available job until the queue is empty.
|
|
@@ -18193,7 +18392,7 @@ await store.dispose();
|
|
|
18193
18392
|
|
|
18194
18393
|
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
18195
18394
|
| ---------------------------------- | -------------------------------------- | -------------- | ---------------------------------------------------------------------- |
|
|
18196
|
-
| `
|
|
18395
|
+
| `defineJob()` | Types one job definition | Sync | Configuration is validated by `createPostmaster()` |
|
|
18197
18396
|
| `createPostmaster()` | Processor with leased claims and retry | Sync | Store is borrowed, not disposed with the processor |
|
|
18198
18397
|
| `createIndexedDbPostmasterStore()` | Durable browser store | Sync | Skips corrupt records and reports each issue through `onCorruptRecord` |
|
|
18199
18398
|
| `createMemoryPostmasterStore()` | Deterministic in-memory store | Sync | Use for tests only |
|
|
@@ -18210,29 +18409,29 @@ await store.dispose();
|
|
|
18210
18409
|
|
|
18211
18410
|
## Factories
|
|
18212
18411
|
|
|
18213
|
-
### `
|
|
18412
|
+
### `defineJob()`
|
|
18214
18413
|
|
|
18215
18414
|
```ts
|
|
18216
|
-
function
|
|
18415
|
+
function defineJob(spec: JobDefinition): JobDefinition;
|
|
18217
18416
|
```
|
|
18218
18417
|
|
|
18219
|
-
|
|
18418
|
+
Types a single job definition. The payload type comes from `validate` when TypeScript can read it without context: a named validator, a `{ parse(value) }` validator object such as a Spell schema, or an inline arrow with an annotated `unknown` parameter (an annotated `execute` payload works the same way). Otherwise pass the type argument (`defineJob({ ... })`) to stay independent of property order; with neither, payloads stay `unknown`. `createPostmaster()` validates every registered definition (versions, `execute`/`key`, retry `maxAttempts`, migration ranges) when it is constructed.
|
|
18220
18419
|
|
|
18221
|
-
| Parameter | Type
|
|
18222
|
-
| --------- |
|
|
18223
|
-
| `
|
|
18420
|
+
| Parameter | Type | Description |
|
|
18421
|
+
| --------- | ------------------ | --------------------------------- |
|
|
18422
|
+
| `spec` | `JobDefinition` | Definition with contextual typing |
|
|
18224
18423
|
|
|
18225
|
-
**Returns:**
|
|
18424
|
+
**Returns:** the same definition, typed for payload inference.
|
|
18226
18425
|
|
|
18227
18426
|
**Example**
|
|
18228
18427
|
|
|
18229
18428
|
```ts
|
|
18230
|
-
import {
|
|
18429
|
+
import { defineJob } from '@vielzeug/postmaster';
|
|
18231
18430
|
|
|
18232
|
-
const jobs =
|
|
18233
|
-
createTodo: {
|
|
18431
|
+
const jobs = {
|
|
18432
|
+
createTodo: defineJob({
|
|
18234
18433
|
version: 1,
|
|
18235
|
-
validate: (v) => v as { id: string; title: string },
|
|
18434
|
+
validate: (v: unknown) => v as { id: string; title: string },
|
|
18236
18435
|
key: (p) => p.id,
|
|
18237
18436
|
execute: async (payload, { key, signal }) => {
|
|
18238
18437
|
await fetch('/api/todos', {
|
|
@@ -18242,8 +18441,8 @@ const jobs = defineJobs({
|
|
|
18242
18441
|
signal,
|
|
18243
18442
|
});
|
|
18244
18443
|
},
|
|
18245
|
-
},
|
|
18246
|
-
}
|
|
18444
|
+
}),
|
|
18445
|
+
};
|
|
18247
18446
|
```
|
|
18248
18447
|
|
|
18249
18448
|
---
|
|
@@ -18258,7 +18457,7 @@ Returns a Postmaster processor that claims, executes, retries, and dead-letters
|
|
|
18258
18457
|
|
|
18259
18458
|
| Parameter | Type | Description |
|
|
18260
18459
|
| ----------------------- | ----------------- | -------------------------------------------------- |
|
|
18261
|
-
| `options.jobs` | `J` |
|
|
18460
|
+
| `options.jobs` | `J` | Map of job name to `defineJob()` definition |
|
|
18262
18461
|
| `options.store` | `PostmasterStore` | Borrowed store; not disposed with the processor |
|
|
18263
18462
|
| `options.leaseDuration` | `number` | Lease duration in ms (default 30000, minimum 1000) |
|
|
18264
18463
|
| `options.clock` | `() => number` | Deterministic clock for tests (default `Date.now`) |
|
|
@@ -18288,7 +18487,7 @@ await store.dispose();
|
|
|
18288
18487
|
function createIndexedDbPostmasterStore(options: IndexedDbPostmasterStoreOptions): PostmasterStore;
|
|
18289
18488
|
```
|
|
18290
18489
|
|
|
18291
|
-
Returns a durable Postmaster store backed by Vault IndexedDB. Uses one internal table
|
|
18490
|
+
Returns a durable Postmaster store backed by Vault IndexedDB. Uses one internal `jobs` table keyed by id; all operations run inside Vault transactions. Persisted records are validated before use; invalid records are skipped so they cannot block valid work.
|
|
18292
18491
|
|
|
18293
18492
|
| Parameter | Type | Description |
|
|
18294
18493
|
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------- |
|
|
@@ -18705,11 +18904,11 @@ Thrown when a job definition is missing, a version is incompatible, or a migrati
|
|
|
18705
18904
|
Define typed jobs, create a durable store, enqueue work, and start the processor. Dispose both handles when the owner ends.
|
|
18706
18905
|
|
|
18707
18906
|
```ts
|
|
18708
|
-
import { createPostmaster,
|
|
18907
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18709
18908
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18710
18909
|
|
|
18711
|
-
const jobs =
|
|
18712
|
-
createTodo: {
|
|
18910
|
+
const jobs = {
|
|
18911
|
+
createTodo: defineJob({
|
|
18713
18912
|
version: 1,
|
|
18714
18913
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18715
18914
|
key: (p) => p.id,
|
|
@@ -18721,8 +18920,8 @@ const jobs = defineJobs({
|
|
|
18721
18920
|
signal,
|
|
18722
18921
|
});
|
|
18723
18922
|
},
|
|
18724
|
-
},
|
|
18725
|
-
}
|
|
18923
|
+
}),
|
|
18924
|
+
};
|
|
18726
18925
|
|
|
18727
18926
|
const store = createIndexedDbPostmasterStore({ name: 'my-app-outbox' });
|
|
18728
18927
|
const postmaster = createPostmaster({ jobs, store });
|
|
@@ -18742,8 +18941,8 @@ The store is borrowed by `createPostmaster()` and is not disposed with the proce
|
|
|
18742
18941
|
Postmaster provides **at-least-once delivery**. A crash after the remote write but before local completion can repeat the job. Every job must derive a stable idempotency key, and handlers must send or otherwise enforce that key.
|
|
18743
18942
|
|
|
18744
18943
|
```ts
|
|
18745
|
-
const jobs =
|
|
18746
|
-
createTodo: {
|
|
18944
|
+
const jobs = {
|
|
18945
|
+
createTodo: defineJob({
|
|
18747
18946
|
version: 1,
|
|
18748
18947
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18749
18948
|
key: (p) => p.id,
|
|
@@ -18755,8 +18954,8 @@ const jobs = defineJobs({
|
|
|
18755
18954
|
signal,
|
|
18756
18955
|
});
|
|
18757
18956
|
},
|
|
18758
|
-
},
|
|
18759
|
-
}
|
|
18957
|
+
}),
|
|
18958
|
+
};
|
|
18760
18959
|
```
|
|
18761
18960
|
|
|
18762
18961
|
Never assume exactly-once execution. Design handlers so a repeated delivery is safe.
|
|
@@ -18767,12 +18966,12 @@ Courier performs immediate HTTP transport. Postmaster coordinates durable delive
|
|
|
18767
18966
|
|
|
18768
18967
|
```ts
|
|
18769
18968
|
import { createCourier, CourierNetworkError } from '@vielzeug/courier';
|
|
18770
|
-
import { createPostmaster,
|
|
18969
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18771
18970
|
|
|
18772
18971
|
const courier = createCourier({ baseUrl: 'https://api.example.com' });
|
|
18773
18972
|
|
|
18774
|
-
const jobs =
|
|
18775
|
-
createTodo: {
|
|
18973
|
+
const jobs = {
|
|
18974
|
+
createTodo: defineJob({
|
|
18776
18975
|
version: 1,
|
|
18777
18976
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18778
18977
|
key: (p) => p.id,
|
|
@@ -18785,8 +18984,8 @@ const jobs = defineJobs({
|
|
|
18785
18984
|
});
|
|
18786
18985
|
},
|
|
18787
18986
|
retry: { maxAttempts: 5, shouldRetry: (error) => error instanceof CourierNetworkError },
|
|
18788
|
-
},
|
|
18789
|
-
}
|
|
18987
|
+
}),
|
|
18988
|
+
};
|
|
18790
18989
|
```
|
|
18791
18990
|
|
|
18792
18991
|
Postmaster does not import Courier. The integration happens in your job definitions.
|
|
@@ -18798,8 +18997,8 @@ Each job declares a `version` and an optional `validate` function. When a stored
|
|
|
18798
18997
|
```ts
|
|
18799
18998
|
import { s } from '@vielzeug/spell';
|
|
18800
18999
|
|
|
18801
|
-
const jobs =
|
|
18802
|
-
createTodo: {
|
|
19000
|
+
const jobs = {
|
|
19001
|
+
createTodo: defineJob({
|
|
18803
19002
|
version: 2,
|
|
18804
19003
|
validate: s.object({ id: s.string(), title: s.string(), priority: s.number().optional() }),
|
|
18805
19004
|
key: (p) => p.id,
|
|
@@ -18814,8 +19013,8 @@ const jobs = defineJobs({
|
|
|
18814
19013
|
signal,
|
|
18815
19014
|
});
|
|
18816
19015
|
},
|
|
18817
|
-
},
|
|
18818
|
-
}
|
|
19016
|
+
}),
|
|
19017
|
+
};
|
|
18819
19018
|
```
|
|
18820
19019
|
|
|
18821
19020
|
Unknown job names, unsupported versions, failed migrations, `undefined` migration output, and invalid migrated payloads move to dead-letter rather than being executed.
|
|
@@ -18838,8 +19037,8 @@ The callback may omit `id` when the persisted value has no usable identifier. Ha
|
|
|
18838
19037
|
Retries are opt-in and explicitly classified. No `retry` block means one attempt followed by dead-letter.
|
|
18839
19038
|
|
|
18840
19039
|
```ts
|
|
18841
|
-
const jobs =
|
|
18842
|
-
syncTodo: {
|
|
19040
|
+
const jobs = {
|
|
19041
|
+
syncTodo: defineJob({
|
|
18843
19042
|
version: 1,
|
|
18844
19043
|
validate: (v: unknown) => v as { id: string },
|
|
18845
19044
|
key: (p) => p.id,
|
|
@@ -18850,8 +19049,8 @@ const jobs = defineJobs({
|
|
|
18850
19049
|
maxAttempts: 5,
|
|
18851
19050
|
shouldRetry: (error) => error instanceof TypeError, // network errors only
|
|
18852
19051
|
},
|
|
18853
|
-
},
|
|
18854
|
-
}
|
|
19052
|
+
}),
|
|
19053
|
+
};
|
|
18855
19054
|
```
|
|
18856
19055
|
|
|
18857
19056
|
- `maxAttempts` means total executions, including the first.
|
|
@@ -18939,19 +19138,19 @@ controller.abort(); // stops tapping
|
|
|
18939
19138
|
Use the in-memory store for deterministic tests.
|
|
18940
19139
|
|
|
18941
19140
|
```ts
|
|
18942
|
-
import { createPostmaster,
|
|
19141
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18943
19142
|
import { createMemoryPostmasterStore } from '@vielzeug/postmaster/testing';
|
|
18944
19143
|
|
|
18945
19144
|
const store = createMemoryPostmasterStore();
|
|
18946
19145
|
const postmaster = createPostmaster({
|
|
18947
|
-
jobs:
|
|
18948
|
-
send: {
|
|
19146
|
+
jobs: {
|
|
19147
|
+
send: defineJob({
|
|
18949
19148
|
version: 1,
|
|
18950
19149
|
validate: (v: unknown) => String(v),
|
|
18951
19150
|
key: (p) => p,
|
|
18952
19151
|
execute: async () => {},
|
|
18953
|
-
},
|
|
18954
|
-
}
|
|
19152
|
+
}),
|
|
19153
|
+
},
|
|
18955
19154
|
store,
|
|
18956
19155
|
});
|
|
18957
19156
|
|
|
@@ -18973,19 +19172,19 @@ Create the Postmaster after the component mounts, start processing, and dispose
|
|
|
18973
19172
|
|
|
18974
19173
|
```tsx [React]
|
|
18975
19174
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18976
|
-
import { createPostmaster,
|
|
19175
|
+
import { createPostmaster, defineJob, type Postmaster } from '@vielzeug/postmaster';
|
|
18977
19176
|
import { useEffect } from 'react';
|
|
18978
19177
|
|
|
18979
|
-
const jobs =
|
|
18980
|
-
sync: {
|
|
19178
|
+
const jobs = {
|
|
19179
|
+
sync: defineJob({
|
|
18981
19180
|
version: 1,
|
|
18982
19181
|
validate: (v: unknown) => v as { id: string },
|
|
18983
19182
|
key: (p) => p.id,
|
|
18984
19183
|
execute: async (payload, { signal }) => {
|
|
18985
19184
|
await fetch(`/api/sync/${payload.id}`, { signal });
|
|
18986
19185
|
},
|
|
18987
|
-
},
|
|
18988
|
-
}
|
|
19186
|
+
}),
|
|
19187
|
+
};
|
|
18989
19188
|
|
|
18990
19189
|
export function OutboxProvider() {
|
|
18991
19190
|
useEffect(() => {
|
|
@@ -19006,19 +19205,19 @@ export function OutboxProvider() {
|
|
|
19006
19205
|
```vue [Vue 3]
|
|
19007
19206
|
|
|
19008
19207
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
19009
|
-
import { createPostmaster,
|
|
19208
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
19010
19209
|
import { onMounted, onUnmounted } from 'vue';
|
|
19011
19210
|
|
|
19012
|
-
const jobs =
|
|
19013
|
-
sync: {
|
|
19211
|
+
const jobs = {
|
|
19212
|
+
sync: defineJob({
|
|
19014
19213
|
version: 1,
|
|
19015
19214
|
validate: (v: unknown) => v as { id: string },
|
|
19016
19215
|
key: (p) => p.id,
|
|
19017
19216
|
execute: async (payload, { signal }) => {
|
|
19018
19217
|
await fetch(`/api/sync/${payload.id}`, { signal });
|
|
19019
19218
|
},
|
|
19020
|
-
},
|
|
19021
|
-
}
|
|
19219
|
+
}),
|
|
19220
|
+
};
|
|
19022
19221
|
|
|
19023
19222
|
let postmaster: ReturnType | undefined;
|
|
19024
19223
|
let store: ReturnType | undefined;
|
|
@@ -19041,19 +19240,19 @@ onUnmounted(() => {
|
|
|
19041
19240
|
```svelte [Svelte]
|
|
19042
19241
|
|
|
19043
19242
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
19044
|
-
import { createPostmaster,
|
|
19243
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
19045
19244
|
import { onMount } from 'svelte';
|
|
19046
19245
|
|
|
19047
|
-
const jobs =
|
|
19048
|
-
sync: {
|
|
19246
|
+
const jobs = {
|
|
19247
|
+
sync: defineJob({
|
|
19049
19248
|
version: 1,
|
|
19050
19249
|
validate: (v: unknown) => v as { id: string },
|
|
19051
19250
|
key: (p) => p.id,
|
|
19052
19251
|
execute: async (payload, { signal }) => {
|
|
19053
19252
|
await fetch(`/api/sync/${payload.id}`, { signal });
|
|
19054
19253
|
},
|
|
19055
|
-
},
|
|
19056
|
-
}
|
|
19254
|
+
}),
|
|
19255
|
+
};
|
|
19057
19256
|
|
|
19058
19257
|
onMount(() => {
|
|
19059
19258
|
const store = createIndexedDbPostmasterStore({ name: 'outbox' });
|
|
@@ -19076,12 +19275,12 @@ Use Courier inside job handlers for HTTP transport. Postmaster coordinates deliv
|
|
|
19076
19275
|
|
|
19077
19276
|
```ts
|
|
19078
19277
|
import { createCourier, CourierNetworkError } from '@vielzeug/courier';
|
|
19079
|
-
import { createPostmaster,
|
|
19278
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
19080
19279
|
|
|
19081
19280
|
const courier = createCourier({ baseUrl: 'https://api.example.com' });
|
|
19082
19281
|
|
|
19083
|
-
const jobs =
|
|
19084
|
-
createTodo: {
|
|
19282
|
+
const jobs = {
|
|
19283
|
+
createTodo: defineJob({
|
|
19085
19284
|
version: 1,
|
|
19086
19285
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
19087
19286
|
key: (p) => p.id,
|
|
@@ -19094,8 +19293,8 @@ const jobs = defineJobs({
|
|
|
19094
19293
|
});
|
|
19095
19294
|
},
|
|
19096
19295
|
retry: { maxAttempts: 5, shouldRetry: (e) => e instanceof CourierNetworkError },
|
|
19097
|
-
},
|
|
19098
|
-
}
|
|
19296
|
+
}),
|
|
19297
|
+
};
|
|
19099
19298
|
```
|
|
19100
19299
|
|
|
19101
19300
|
### Postmaster + Sentinel
|
|
@@ -19146,7 +19345,7 @@ The IndexedDB adapter is built on Vault. Use Vault directly for unrelated storag
|
|
|
19146
19345
|
|
|
19147
19346
|
### REPL Examples
|
|
19148
19347
|
|
|
19149
|
-
-
|
|
19348
|
+
- defineJob - Basic Outbox (id: `define-jobs`)
|
|
19150
19349
|
- delayedEnqueue - Delayed Eligibility (id: `delayed-enqueue`)
|
|
19151
19350
|
|
|
19152
19351
|
---
|
|
@@ -21979,7 +22178,7 @@ Component registration happens through side-effect imports such as `@vielzeug/re
|
|
|
21979
22178
|
|
|
21980
22179
|
Each entry below is a component with its own documentation page and registration subpath. Sub-element tags (`ore-accordion-item`, `ore-card-picker-item`, `ore-tab-item`, `ore-avatar-group`, and the rest) are documented on their parent's page and registered with it.
|
|
21981
22180
|
|
|
21982
|
-
**Content:** `ore-accordion`, `ore-avatar`, `ore-card`, `ore-card-picker`, `ore-carousel`, `ore-chat-message`, `ore-chat-panel`, `ore-code-window`, `ore-copy-command`, `ore-icon`, `ore-keyboard-key`, `ore-list`, `ore-marquee`, `ore-qr-code`, `ore-rank-list`, `ore-speech-player`, `ore-speed-reading`, `ore-stats`, `ore-table`, `ore-text`
|
|
22181
|
+
**Content:** `ore-accordion`, `ore-avatar`, `ore-card`, `ore-card-picker`, `ore-carousel`, `ore-chat-message`, `ore-chat-panel`, `ore-code-window`, `ore-copy-command`, `ore-icon`, `ore-keyboard-key`, `ore-list`, `ore-marquee`, `ore-prose`, `ore-qr-code`, `ore-rank-list`, `ore-speech-player`, `ore-speed-reading`, `ore-stats`, `ore-table`, `ore-text`
|
|
21983
22182
|
|
|
21984
22183
|
**Feedback:** `ore-alert`, `ore-badge`, `ore-chip`, `ore-cookie-banner`, `ore-password-strength`, `ore-progress`, `ore-pull-to-refresh`, `ore-skeleton`, `ore-state`, `ore-toast`, `ore-typing-indicator`
|
|
21985
22184
|
|
|
@@ -22128,7 +22327,7 @@ import type { OreButtonProps } from '@vielzeug/refine/button';
|
|
|
22128
22327
|
|
|
22129
22328
|
| Area | Components |
|
|
22130
22329
|
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22131
|
-
| Content | `accordion`, `avatar`, `card`, `card-picker`, `carousel`, `chat-message`, `chat-panel`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `marquee`, `qr-code`, `rank-list`, `speech-player`, `speed-reading`, `stats`, `table`, `text`
|
|
22330
|
+
| Content | `accordion`, `avatar`, `card`, `card-picker`, `carousel`, `chat-message`, `chat-panel`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `marquee`, `prose`, `qr-code`, `rank-list`, `speech-player`, `speed-reading`, `stats`, `table`, `text` |
|
|
22132
22331
|
| Feedback | `alert`, `badge`, `chip`, `cookie-banner`, `password-strength`, `progress`, `pull-to-refresh`, `skeleton`, `state`, `toast`, `typing-indicator` |
|
|
22133
22332
|
| Inputs | `app-store-button`, `button`, `calendar`, `checkbox`, `color-picker`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `qr-scanner`, `query-bar`, `radio`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |
|
|
22134
22333
|
| Layout | `box`, `dock`, `grid`, `navbar`, `separator`, `sidebar` |
|
|
@@ -26400,6 +26599,328 @@ Call `toFilterPredicate` again whenever the query or corpus changes: the predica
|
|
|
26400
26599
|
|
|
26401
26600
|
---
|
|
26402
26601
|
|
|
26602
|
+
## @vielzeug/scribe
|
|
26603
|
+
|
|
26604
|
+
**Category:** utilities
|
|
26605
|
+
|
|
26606
|
+
### Overview
|
|
26607
|
+
|
|
26608
|
+
## Why Scribe?
|
|
26609
|
+
|
|
26610
|
+
Rendering Markdown someone else wrote is a security decision. The usual stack pairs a parser
|
|
26611
|
+
that happily passes raw HTML through with a sanitizer bolted on afterward — one forgotten
|
|
26612
|
+
`innerHTML` and the bolt is worthless. Scribe makes safety a property of construction instead:
|
|
26613
|
+
raw HTML is **not** part of the language, text reaches the DOM only through
|
|
26614
|
+
`createTextNode`/`createElement`, and no attribute is ever sourced from the document except
|
|
26615
|
+
policy-checked `href`/`src`. There is no sanitizer step to forget because there is no unsafe
|
|
26616
|
+
path to take.
|
|
26617
|
+
|
|
26618
|
+
```ts
|
|
26619
|
+
// Before: parser + sanitizer + escape hatch
|
|
26620
|
+
import { marked } from 'marked';
|
|
26621
|
+
import DOMPurify from 'dompurify';
|
|
26622
|
+
container.innerHTML = DOMPurify.sanitize(marked.parse(userText)); // two libs, one memory
|
|
26623
|
+
|
|
26624
|
+
// After: one fixed-profile pipeline, safe by construction
|
|
26625
|
+
import { parseProse, renderProseDom } from '@vielzeug/scribe';
|
|
26626
|
+
container.replaceChildren(renderProseDom(parseProse(userText))); // zero deps, no innerHTML
|
|
26627
|
+
```
|
|
26628
|
+
|
|
26629
|
+
The profile is a fixed, deterministic GFM-flavored subset — headings, lists, code, tables,
|
|
26630
|
+
emphasis, links, images, autolinks, strikethrough — with deliberate, documented limits: no
|
|
26631
|
+
raw HTML, reference links, setext headings, entities, or plugin system. Chat bubbles, archive
|
|
26632
|
+
publications, and documentation excerpts are exactly the prose this covers.
|
|
26633
|
+
|
|
26634
|
+
## Installation
|
|
26635
|
+
|
|
26636
|
+
```sh [pnpm]
|
|
26637
|
+
pnpm add @vielzeug/scribe
|
|
26638
|
+
```
|
|
26639
|
+
|
|
26640
|
+
```sh [npm]
|
|
26641
|
+
npm install @vielzeug/scribe
|
|
26642
|
+
```
|
|
26643
|
+
|
|
26644
|
+
```sh [yarn]
|
|
26645
|
+
yarn add @vielzeug/scribe
|
|
26646
|
+
```
|
|
26647
|
+
|
|
26648
|
+
## Quick Start
|
|
26649
|
+
|
|
26650
|
+
```ts
|
|
26651
|
+
import { parseProse, proseOutline, renderProseHtml } from '@vielzeug/scribe';
|
|
26652
|
+
|
|
26653
|
+
const doc = parseProse('# Setup\n\nRun **install** first.\n\n## Configure\n\nEdit the config.');
|
|
26654
|
+
|
|
26655
|
+
console.log(renderProseHtml(doc, { headingIds: true }));
|
|
26656
|
+
// Setup
|
|
26657
|
+
// Run install first.
|
|
26658
|
+
// Configure
|
|
26659
|
+
// Edit the config.
|
|
26660
|
+
|
|
26661
|
+
console.log(proseOutline(doc)); // TOC ids match the ids above, exactly
|
|
26662
|
+
```
|
|
26663
|
+
|
|
26664
|
+
## Features
|
|
26665
|
+
|
|
26666
|
+
- **`parseProse`**: frozen, serializable AST from a fixed GFM-flavored profile — no raw HTML, no plugins, deterministic output.
|
|
26667
|
+
- **`renderProseHtml`**: escaped HTML string for SSR, static sites, and tests.
|
|
26668
|
+
- **`renderProseDom`**: `DocumentFragment` built with DOM APIs only — markup-lookalike content renders as visible characters.
|
|
26669
|
+
- **`proseToText`**: plain text for notifications, search indexing, and previews.
|
|
26670
|
+
- **`proseOutline`**: top-level headings with slug ids that match the renderers exactly.
|
|
26671
|
+
- **Policy-checked links**: relative/`http`/`https`/`mailto` pass, `javascript:`/`data:` degrade to label text with a dev warning — never a crash, never an anchor.
|
|
26672
|
+
- **Hard limits**: oversized or pathologically nested input fails fast with `ScribeLimitError` instead of hanging.
|
|
26673
|
+
|
|
26674
|
+
## Documentation
|
|
26675
|
+
|
|
26676
|
+
- [Usage Guide](./usage.md)
|
|
26677
|
+
- [API Reference](./api.md)
|
|
26678
|
+
- [Examples](./examples.md)
|
|
26679
|
+
|
|
26680
|
+
## See Also
|
|
26681
|
+
|
|
26682
|
+
- [Refine](/refine/): `ore-prose` renders Markdown with this pipeline and Refine typography.
|
|
26683
|
+
- [Archive](/archive/): publishes the prose that Scribe renders.
|
|
26684
|
+
- [Spell](/spell/): validation for the structured payloads around the prose.
|
|
26685
|
+
|
|
26686
|
+
### API Reference
|
|
26687
|
+
|
|
26688
|
+
## API Overview
|
|
26689
|
+
|
|
26690
|
+
| Symbol | Purpose | Execution | Common gotcha |
|
|
26691
|
+
| ----------------- | -------------------------------------------- | --------- | ------------------------------------------------------------------- |
|
|
26692
|
+
| `parseProse` | Markdown string → frozen `ProseDoc` AST | Sync | Fixed profile: raw HTML, entities, reference links are literal text |
|
|
26693
|
+
| `renderProseHtml` | AST → escaped HTML string | Sync | No heading `id`s unless `headingIds: true` |
|
|
26694
|
+
| `renderProseDom` | AST → `DocumentFragment` built with DOM APIs | Sync | Needs a DOM; pass the doc, not its blocks |
|
|
26695
|
+
| `proseToText` | AST → plain text | Sync | Links keep labels, images keep alt text |
|
|
26696
|
+
| `proseOutline` | Headings with ids, renderer order | Sync | Nested headings count in the slug sequence, matching the renderer |
|
|
26697
|
+
|
|
26698
|
+
## Package Entry Point
|
|
26699
|
+
|
|
26700
|
+
| Import | Purpose |
|
|
26701
|
+
| ------------------ | -------------------------- |
|
|
26702
|
+
| `@vielzeug/scribe` | Complete public Scribe API |
|
|
26703
|
+
|
|
26704
|
+
## Functions
|
|
26705
|
+
|
|
26706
|
+
### `parseProse(markdown, options?)`
|
|
26707
|
+
|
|
26708
|
+
Parses the fixed GFM-flavored profile (see the Usage Guide) into a frozen `ProseDoc`.
|
|
26709
|
+
Link/image destinations are policy-checked here: relative URLs always pass, `data:` always
|
|
26710
|
+
fails, other schemes require membership in `options.linkProtocols` (default
|
|
26711
|
+
`['http', 'https', 'mailto']`). A rejected destination becomes the label/alt text plus a
|
|
26712
|
+
dev-only warning — parsing never throws for a bad URL.
|
|
26713
|
+
|
|
26714
|
+
```ts
|
|
26715
|
+
const doc = parseProse('Read the [guide](/scribe/).');
|
|
26716
|
+
```
|
|
26717
|
+
|
|
26718
|
+
- **Throws** `ScribeLimitError` beyond 200,000 characters or 32 nesting levels.
|
|
26719
|
+
|
|
26720
|
+
### `renderProseHtml(doc, options?)` → `string`
|
|
26721
|
+
|
|
26722
|
+
Escapes every dynamic value; emits only the fixed tag set. `options.headingIds` adds unique
|
|
26723
|
+
slug ids matching `proseOutline`.
|
|
26724
|
+
|
|
26725
|
+
### `renderProseDom(doc, options?)` → `DocumentFragment`
|
|
26726
|
+
|
|
26727
|
+
DOM construction only (`createTextNode`/`createElement`/`setAttribute`): content can never
|
|
26728
|
+
execute. Requires a browser environment. Same options and id behavior as the string renderer.
|
|
26729
|
+
|
|
26730
|
+
### `proseToText(doc)` → `string`
|
|
26731
|
+
|
|
26732
|
+
Plain text: blocks separated by blank lines, list markers preserved, links reduced to labels.
|
|
26733
|
+
For notifications, search indexing, and previews.
|
|
26734
|
+
|
|
26735
|
+
### `proseOutline(doc, options?)` → `readonly ProseOutlineEntry[]`
|
|
26736
|
+
|
|
26737
|
+
Headings as `{ level, text, id }` in document order — the same traversal and slug sequence the
|
|
26738
|
+
renderers use with `headingIds`, including headings nested in blockquotes and lists.
|
|
26739
|
+
`options.maxLevel` (1–6) filters entries without shifting the slug sequence, so ids keep
|
|
26740
|
+
matching the rendered document.
|
|
26741
|
+
|
|
26742
|
+
## Types
|
|
26743
|
+
|
|
26744
|
+
The AST is public: safe to branch on, cache, and cross worker boundaries (frozen, serializable).
|
|
26745
|
+
|
|
26746
|
+
| Type | Purpose |
|
|
26747
|
+
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
|
|
26748
|
+
| `ProseDoc` | `{ blocks }`: the parsed document |
|
|
26749
|
+
| `ProseBlock` | Union of block nodes (paragraph, heading, list …) |
|
|
26750
|
+
| `ProseInline` | Union of inline nodes (text, link, codeSpan …) |
|
|
26751
|
+
| `ProseParagraph`, `ProseHeading`, `ProseCodeBlock`, `ProseBlockquote`, `ProseList`, `ProseListItem`, `ProseThematicBreak`, `ProseTable`, `ProseTableCell` | Block variants |
|
|
26752
|
+
| `ProseText`, `ProseCodeSpan`, `ProseStrong`, `ProseEmphasis`, `ProseStrikethrough`, `ProseLink`, `ProseImage`, `ProseSoftBreak`, `ProseHardBreak` | Inline variants |
|
|
26753
|
+
| `ProseParseOptions`, `ProseRenderOptions`, `ProseOutlineOptions` | Option bags |
|
|
26754
|
+
| `ProseOutlineEntry`, `ProseHeadingLevel`, `ProseAlignment` | Outline entry, `1–6`, table alignment |
|
|
26755
|
+
|
|
26756
|
+
## Errors
|
|
26757
|
+
|
|
26758
|
+
| Error | Thrown by | Meaning |
|
|
26759
|
+
| ------------------ | -------------- | ----------------------------------------------- |
|
|
26760
|
+
| `ScribeError` | — (base class) | Narrow with `instanceof` for any scribe failure |
|
|
26761
|
+
| `ScribeLimitError` | `parseProse` | Input exceeds the size or nesting limit |
|
|
26762
|
+
|
|
26763
|
+
### Usage Guide
|
|
26764
|
+
|
|
26765
|
+
## Basic Usage
|
|
26766
|
+
|
|
26767
|
+
Parse Markdown into a frozen AST once, then render it as many times as you like into any of
|
|
26768
|
+
four shapes:
|
|
26769
|
+
|
|
26770
|
+
```ts
|
|
26771
|
+
import { parseProse, proseOutline, proseToText, renderProseDom, renderProseHtml } from '@vielzeug/scribe';
|
|
26772
|
+
|
|
26773
|
+
const doc = parseProse('# Hello\n\nShip **today**.');
|
|
26774
|
+
|
|
26775
|
+
renderProseHtml(doc); // string (SSR, VitePress, archive publications)
|
|
26776
|
+
renderProseDom(doc); // DocumentFragment (client replaces, refine ore-prose)
|
|
26777
|
+
proseToText(doc); // plain text (search, notifications, a11y)
|
|
26778
|
+
proseOutline(doc); // [{ level: 1, text: 'Hello', id: 'hello' }]
|
|
26779
|
+
```
|
|
26780
|
+
|
|
26781
|
+
`renderProseDom` builds nodes exclusively with `document.createElement` and
|
|
26782
|
+
`document.createTextNode` — the DOM path cannot inject markup at all. It requires a live
|
|
26783
|
+
`document`; in Node use `renderProseHtml`.
|
|
26784
|
+
|
|
26785
|
+
## The Language Profile
|
|
26786
|
+
|
|
26787
|
+
Scribe implements a fixed CommonMark + GFM subset — the same on every platform and every
|
|
26788
|
+
release:
|
|
26789
|
+
|
|
26790
|
+
| Feature | Notes |
|
|
26791
|
+
| ------------ | ---------------------------------------------------------------------------------------------------------- |
|
|
26792
|
+
| Headings | ATX (`#`–`######`) only; setext underlines render literally |
|
|
26793
|
+
| Emphasis | `*`, `**`, `***`, `_`, `__` with CommonMark flanking rules (`snake_case` is safe); `~~strikethrough~~` |
|
|
26794
|
+
| Code | Fenced (``` / `~~~`, info string preserved as `lang`), indented (4 spaces), backtick spans |
|
|
26795
|
+
| Blocks | Paragraphs, blockquotes, thematic breaks, hard breaks (`two spaces` or `\`) |
|
|
26796
|
+
| Lists | `-`/`+`/`*` bullets and `1.` ordered; strict last-marker nesting; simplified tight/loose rule |
|
|
26797
|
+
| Tables | GFM pipes with alignment row; a table must start on its own line |
|
|
26798
|
+
| Links/images | Inline links with optional titles, images with alt text; autolinks and bare www URLs; GFM autoliteral URLs |
|
|
26799
|
+
| Task lists | `[ ]`/`[x]` items render a **disabled** checkbox (never interactive) |
|
|
26800
|
+
|
|
26801
|
+
Deliberately absent: raw HTML and entities (rendered as inert text), reference link
|
|
26802
|
+
definitions, setext headings, lazy list continuation, definition lists, footnotes, math.
|
|
26803
|
+
|
|
26804
|
+
## HTML and DOM Rendering
|
|
26805
|
+
|
|
26806
|
+
### Headings with ids
|
|
26807
|
+
|
|
26808
|
+
```ts
|
|
26809
|
+
import { parseProse, renderProseHtml } from '@vielzeug/scribe';
|
|
26810
|
+
|
|
26811
|
+
const doc = parseProse('# Guide\n\n# Guide');
|
|
26812
|
+
|
|
26813
|
+
renderProseHtml(doc, { headingIds: true });
|
|
26814
|
+
// GuideGuide
|
|
26815
|
+
```
|
|
26816
|
+
|
|
26817
|
+
`proseOutline` runs the same slugger over the full doc, so its `id` values always match the
|
|
26818
|
+
ids the renderer emits for the same document.
|
|
26819
|
+
|
|
26820
|
+
### DOM vs HTML
|
|
26821
|
+
|
|
26822
|
+
Both renderers produce identical structures. Choose by surface:
|
|
26823
|
+
|
|
26824
|
+
```ts
|
|
26825
|
+
// Node / static site: a string you embed in a page
|
|
26826
|
+
const html = renderProseHtml(parseProse(source), { headingIds: true });
|
|
26827
|
+
|
|
26828
|
+
// Browser: real nodes for replaceChildren — no innerHTML, no sanitizer needed
|
|
26829
|
+
article.replaceChildren(renderProseDom(parseProse(source), { headingIds: true }));
|
|
26830
|
+
```
|
|
26831
|
+
|
|
26832
|
+
## Link Policy
|
|
26833
|
+
|
|
26834
|
+
Every link destination and image src passes a protocol allowlist **after** control-character
|
|
26835
|
+
stripping and numeric entity decoding (so `:javascript:` degrades like the direct form):
|
|
26836
|
+
|
|
26837
|
+
```ts
|
|
26838
|
+
import { parseProse, renderProseHtml } from '@vielzeug/scribe';
|
|
26839
|
+
|
|
26840
|
+
const doc = parseProse('[a](javascript:alert(1)) [b](https://ok.test) [c](/relative)');
|
|
26841
|
+
|
|
26842
|
+
renderProseHtml(doc);
|
|
26843
|
+
// a b c
|
|
26844
|
+
// ↑ rejected link degraded to its label text
|
|
26845
|
+
```
|
|
26846
|
+
|
|
26847
|
+
Default allowlist is `http`, `https`, `mailto`; `data:` can never be allowed
|
|
26848
|
+
(`data:image/svg+xml` carries scripts). Relative and protocol-relative (`//host`)
|
|
26849
|
+
destinations always pass — they carry no scheme. Override with:
|
|
26850
|
+
|
|
26851
|
+
```ts
|
|
26852
|
+
parseProse(source, { linkProtocols: ['https'] });
|
|
26853
|
+
```
|
|
26854
|
+
|
|
26855
|
+
Degradation keeps the link **label** (or image **alt**) as plain text — content is never
|
|
26856
|
+
silently dropped — and a dev-mode warning names the rejected destination.
|
|
26857
|
+
|
|
26858
|
+
## Outline and Plain Text
|
|
26859
|
+
|
|
26860
|
+
```ts
|
|
26861
|
+
import { parseProse, proseOutline, proseToText } from '@vielzeug/scribe';
|
|
26862
|
+
|
|
26863
|
+
const doc = parseProse('# Intro\n\nText\n\n## Setup\n\nMore text.');
|
|
26864
|
+
|
|
26865
|
+
proseOutline(doc); // [{ level: 1, text: 'Intro', id: 'intro' }, …]
|
|
26866
|
+
proseOutline(doc, { maxLevel: 2 }); // shallow TOC for sidebars
|
|
26867
|
+
proseToText(doc); // "Intro\nText\nSetup\nMore text." for search & alerts
|
|
26868
|
+
```
|
|
26869
|
+
|
|
26870
|
+
Outline `id`s are produced by the same slugger the renderer uses with `headingIds`, so TOC
|
|
26871
|
+
anchors resolve against the rendered HTML with no extra bookkeeping. `proseToText` keeps code
|
|
26872
|
+
content and drops formatting, links, and images.
|
|
26873
|
+
|
|
26874
|
+
## Error Handling
|
|
26875
|
+
|
|
26876
|
+
Only two throw paths exist:
|
|
26877
|
+
|
|
26878
|
+
```ts
|
|
26879
|
+
import { parseProse, ScribeError, ScribeLimitError } from '@vielzeug/scribe';
|
|
26880
|
+
|
|
26881
|
+
try {
|
|
26882
|
+
parseProse(megabyteOfMarkdown); // > 200_000 characters
|
|
26883
|
+
} catch (error) {
|
|
26884
|
+
if (error instanceof ScribeLimitError) console.error(error.reason, error.limit);
|
|
26885
|
+
}
|
|
26886
|
+
```
|
|
26887
|
+
|
|
26888
|
+
`ScribeError` is the base class; `ScribeLimitError` covers the input size cap and the
|
|
26889
|
+
nesting-depth cap (32). Anything malformed degrades to literal text instead of throwing —
|
|
26890
|
+
unclosed emphasis, dangling fences, and broken tables all render as readable prose.
|
|
26891
|
+
|
|
26892
|
+
## Refine Integration
|
|
26893
|
+
|
|
26894
|
+
`@vielzeug/refine` ships [``](/refine/components/prose), which wraps this
|
|
26895
|
+
pipeline with Refine theme tokens:
|
|
26896
|
+
|
|
26897
|
+
```html
|
|
26898
|
+
|
|
26899
|
+
```
|
|
26900
|
+
|
|
26901
|
+
It re-emits `ScribeError` as an `error` event and falls back to the source's plain text.
|
|
26902
|
+
|
|
26903
|
+
## Best Practices
|
|
26904
|
+
|
|
26905
|
+
1. **Parse once, render many.** The AST is frozen; keep it and re-render instead of reparsing the same source.
|
|
26906
|
+
2. **`headingIds` on both sides.** When you build a TOC with `proseOutline`, enable `headingIds` in the renderer, or the anchors match nothing.
|
|
26907
|
+
3. **Don't post-process the HTML with `innerHTML`.** If you need different semantics, walk the AST instead — the renderers are the safety boundary; re-parsing your own edits through `innerHTML` reopens the hole they close. `[VERIFY]`
|
|
26908
|
+
4. **Keep hostile input under the caps.** A `ScribeLimitError` is the signal to reject the input at your boundary, not to retry with a bigger limit.
|
|
26909
|
+
|
|
26910
|
+
### Examples
|
|
26911
|
+
|
|
26912
|
+
## Examples
|
|
26913
|
+
|
|
26914
|
+
- [Parse and Render](./examples/parse-and-render.md)
|
|
26915
|
+
- [Safe Rendering for Untrusted Content](./examples/safe-rendering.md)
|
|
26916
|
+
|
|
26917
|
+
### REPL Examples
|
|
26918
|
+
|
|
26919
|
+
- Outline and plain text (id: `outline`)
|
|
26920
|
+
- Safe render of hostile input (id: `safe-render`)
|
|
26921
|
+
|
|
26922
|
+
---
|
|
26923
|
+
|
|
26403
26924
|
## @vielzeug/scroll
|
|
26404
26925
|
|
|
26405
26926
|
**Category:** ui-performance
|
|
@@ -28892,7 +29413,7 @@ intersection.dispose();
|
|
|
28892
29413
|
### `createWakeLock()`
|
|
28893
29414
|
|
|
28894
29415
|
```ts
|
|
28895
|
-
function createWakeLock(options?:
|
|
29416
|
+
function createWakeLock(options?: WindowSentinelOptions): WakeLockSentinel;
|
|
28896
29417
|
```
|
|
28897
29418
|
|
|
28898
29419
|
Returns a Sentinel-backed screen wake lock. `request()` acquires the lock; `release()` frees it. When the tab is hidden the browser auto-releases the lock; the Sentinel re-acquires it automatically on `visibilitychange` if the lock was active. Degrades silently when the Screen Wake Lock API is unavailable.
|
|
@@ -28927,7 +29448,7 @@ wakeLock.dispose();
|
|
|
28927
29448
|
### `createFullscreen()`
|
|
28928
29449
|
|
|
28929
29450
|
```ts
|
|
28930
|
-
function createFullscreen(options?:
|
|
29451
|
+
function createFullscreen(options?: WindowSentinelOptions): FullscreenSentinel;
|
|
28931
29452
|
```
|
|
28932
29453
|
|
|
28933
29454
|
Returns a Sentinel-backed fullscreen view. `request()` enters fullscreen for an element (default: the document element), `exit()` leaves it, and `toggle()` flips it. All degrade silently when the Fullscreen API is missing or the browser refuses (user-activation requirements). Disposing the sentinel exits fullscreen and stops tracking `fullscreenchange`.
|
|
@@ -30242,7 +30763,7 @@ try {
|
|
|
30242
30763
|
|
|
30243
30764
|
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
30244
30765
|
| ----------------------------- | ----------------------------------- | -------------- | ----------------------------------------------------------- |
|
|
30245
|
-
| `createLocalSource()` | Filter and paginate in-memory items | Sync | `params` replacement
|
|
30766
|
+
| `createLocalSource()` | Filter and paginate in-memory items | Sync | `params` replacement compares structurally |
|
|
30246
30767
|
| `createPageSource()` | Load numbered pages | Async | Construction is inert |
|
|
30247
30768
|
| `createCursorSource()` | Load server-issued cursor pages | Async | `after` and `before` cannot coexist initially |
|
|
30248
30769
|
| `createInfiniteSource()` | Append numbered pages | Async | `loadMore()` is a no-op while loading or exhausted |
|
|
@@ -30299,7 +30820,7 @@ source.setParams('Ada');
|
|
|
30299
30820
|
| `previous()` | `void` | Move backward when available |
|
|
30300
30821
|
| `setItems(items)` | `void` | Replace the collection and recompute state |
|
|
30301
30822
|
| `setPageSize(pageSize)` | `void` | Replace page size and reset to page one |
|
|
30302
|
-
| `setParams(params)` | `void` | Replace params and reset to page one
|
|
30823
|
+
| `setParams(params)` | `void` | Replace params structurally and reset to page one |
|
|
30303
30824
|
| `subscribe(listener)` | `() => void` | Register a state listener and return its unsubscribe function |
|
|
30304
30825
|
| `dispose()` | `void` | Stop notifications and reject later mutations |
|
|
30305
30826
|
|
|
@@ -30344,13 +30865,18 @@ await source.reload();
|
|
|
30344
30865
|
| `subscribe(listener)` | `() => void` | Register a state listener and return its unsubscribe function |
|
|
30345
30866
|
| `dispose()` | `void` | Abort work and stop notifications |
|
|
30346
30867
|
|
|
30347
|
-
`apply(update: PageSourceUpdate): Promise` compares params structurally
|
|
30348
|
-
|
|
30349
|
-
|
|
30350
|
-
|
|
30351
|
-
|
|
30352
|
-
preserve the requested value; use `setParams(undefined)` when `undefined` is a valid
|
|
30353
|
-
The update does not include page size; use `setPageSize()` separately.
|
|
30868
|
+
`apply(update: PageSourceUpdate): Promise` compares params structurally after a
|
|
30869
|
+
reference fast path, the same rule every params comparison in the package uses. Changed params use
|
|
30870
|
+
the supplied positive page without clamping, or page one when omitted. Unchanged params with a page
|
|
30871
|
+
use `goTo()` and clamp after the first successful load. An unchanged request does not refetch a
|
|
30872
|
+
committed result or duplicate an active request; it loads an inert source. Omitted or `undefined`
|
|
30873
|
+
params preserve the requested value; use `setParams(undefined)` when `undefined` is a valid
|
|
30874
|
+
replacement. The update does not include page size; use `setPageSize()` separately.
|
|
30875
|
+
|
|
30876
|
+
All async sources share a rollback rule: a failed current request reverts the requested page, size,
|
|
30877
|
+
params, and (for infinite feeds) continuation position to the last committed values, so navigation
|
|
30878
|
+
after a failure retries the same move. Superseded work never rolls anything back. Retry with
|
|
30879
|
+
`reload()`.
|
|
30354
30880
|
|
|
30355
30881
|
---
|
|
30356
30882
|
|
|
@@ -30688,7 +31214,7 @@ console.log(source.state.params);
|
|
|
30688
31214
|
source.dispose();
|
|
30689
31215
|
```
|
|
30690
31216
|
|
|
30691
|
-
A non-optional parameter type requires an initial `params` value.
|
|
31217
|
+
A non-optional parameter type requires an initial `params` value. Every params comparison is structural after a reference fast path, so a freshly built but equal filter object never refetches, from `setParams()` or `apply()`. Idle sources load on the next command; retry a failed request with `reload()`. See [Apply Page and Filter Together](#apply-page-and-filter-together).
|
|
30692
31218
|
|
|
30693
31219
|
While replacement parameters load, `state.params` continues to describe the committed items and `state.pendingParams` contains the requested value. Page-only navigation does not set `pendingParams`.
|
|
30694
31220
|
|
|
@@ -30706,7 +31232,7 @@ await source.last();
|
|
|
30706
31232
|
await source.setPageSize(50);
|
|
30707
31233
|
```
|
|
30708
31234
|
|
|
30709
|
-
After the first successful load, navigation is clamped to the known `pageCount`. Before that load, `goTo()` accepts any positive page because the total is unknown.
|
|
31235
|
+
After the first successful load, navigation is clamped to the known `pageCount`. Before that load, `goTo()` accepts any positive page because the total is unknown. `next()` on an inert source loads page one. A failed navigation command rolls back to the committed page, so retrying `next()` moves to the same next page instead of skipping ahead.
|
|
30710
31236
|
|
|
30711
31237
|
## Apply Page and Filter Together
|
|
30712
31238
|
|
|
@@ -30739,8 +31265,8 @@ try {
|
|
|
30739
31265
|
```
|
|
30740
31266
|
|
|
30741
31267
|
Parameters are compared structurally, so a freshly built object with the same contents does not
|
|
30742
|
-
refetch a committed result or duplicate active work. An inert source still loads
|
|
30743
|
-
request
|
|
31268
|
+
refetch a committed result or duplicate active work. An inert source still loads; retry a failed
|
|
31269
|
+
request with `reload()`. When parameters change,
|
|
30744
31270
|
`page` is validated but never clamped: the page count still describes the previous filter set, so
|
|
30745
31271
|
clamping against it would silently move the reader elsewhere. Omit `page` in that case and the
|
|
30746
31272
|
source returns to page one. When parameters are unchanged, `apply()` routes through `goTo()` and
|
|
@@ -32073,6 +32599,338 @@ const profile = Profile.parse(await courier.get('/profile'));
|
|
|
32073
32599
|
|
|
32074
32600
|
---
|
|
32075
32601
|
|
|
32602
|
+
## @vielzeug/tabula
|
|
32603
|
+
|
|
32604
|
+
**Category:** utilities
|
|
32605
|
+
|
|
32606
|
+
### Overview
|
|
32607
|
+
|
|
32608
|
+
## Why Tabula?
|
|
32609
|
+
|
|
32610
|
+
CSV is the format every spreadsheet, analytics tool, and finance department speaks — and the
|
|
32611
|
+
format most hand-rolled parsers get subtly wrong: an embedded comma in a quoted title, a
|
|
32612
|
+
double-quote escape, a CRLF that silently becomes part of a value. Tabula implements RFC 4180
|
|
32613
|
+
exactly, with one scanner behind every entry point, so paste-box input, uploaded files, and
|
|
32614
|
+
Node streams all parse with identical semantics.
|
|
32615
|
+
|
|
32616
|
+
```ts
|
|
32617
|
+
// Before: a join that dies on the first comma inside a product name
|
|
32618
|
+
const rows = orders.map((o) => [o.id, o.title, o.total].join(',')); // title: "Red, Metallic" → corrupt
|
|
32619
|
+
|
|
32620
|
+
// After: quoting, CRLF, and escaping are the library's problem
|
|
32621
|
+
import { parseRecords, recordsToCsv } from '@vielzeug/tabula';
|
|
32622
|
+
|
|
32623
|
+
const csv = recordsToCsv(orders); // every field quoted only when needed, round-trips exactly
|
|
32624
|
+
```
|
|
32625
|
+
|
|
32626
|
+
Records are plain objects, and `parseTypedRecords` hands them straight to a
|
|
32627
|
+
[Spell](/spell/) standard schema — strings in, typed rows out, with per-line issues aggregated
|
|
32628
|
+
into one error. The streaming reader processes chunks and blobs without ever buffering the
|
|
32629
|
+
whole document.
|
|
32630
|
+
|
|
32631
|
+
## Installation
|
|
32632
|
+
|
|
32633
|
+
```sh [pnpm]
|
|
32634
|
+
pnpm add @vielzeug/tabula
|
|
32635
|
+
```
|
|
32636
|
+
|
|
32637
|
+
```sh [npm]
|
|
32638
|
+
npm install @vielzeug/tabula
|
|
32639
|
+
```
|
|
32640
|
+
|
|
32641
|
+
```sh [yarn]
|
|
32642
|
+
yarn add @vielzeug/tabula
|
|
32643
|
+
```
|
|
32644
|
+
|
|
32645
|
+
## Quick Start
|
|
32646
|
+
|
|
32647
|
+
```ts
|
|
32648
|
+
import { parseRecords, recordsToCsv } from '@vielzeug/tabula';
|
|
32649
|
+
|
|
32650
|
+
const grid = parseRecords('id,total\n7,"1,200.00"\n8,99.50\n');
|
|
32651
|
+
// [{ id: '7', total: '1,200.00' }, { id: '8', total: '99.50' }]
|
|
32652
|
+
|
|
32653
|
+
console.log(recordsToCsv([{ a: 1, b: 'x,y' }]));
|
|
32654
|
+
// a,b
|
|
32655
|
+
// 1,"x,y"
|
|
32656
|
+
```
|
|
32657
|
+
|
|
32658
|
+
## Features
|
|
32659
|
+
|
|
32660
|
+
- **`parseGrid`**: RFC 4180 scanner into a string grid — BOM stripped, CRLF/CR/LF endings, `""` escapes, configurable delimiter.
|
|
32661
|
+
- **`parseRecords`**: first row as keys (or your own `headers`), short rows omit keys instead of inventing `undefined`.
|
|
32662
|
+
- **`detectDelimiter`**: counts `,` `;` and tabs outside quotes on the first line — auto-detect with no content sniffing.
|
|
32663
|
+
- **`toCsv` / `recordsToCsv`**: quotes only when needed, `quoteAll` for spreadsheet paranoia, CRLF by default.
|
|
32664
|
+
- **`createCsvGridStream`**: a `TransformStream` of rows for uploads and Node streams; even delimiter auto-detection buffers at most one line.
|
|
32665
|
+
- **`parseTypedRecords`**: rows through any Spell/standard-schema validator — one `TabulaValidationError` with every row's line number and issues.
|
|
32666
|
+
- **One scanner everywhere**: `CsvScanner` is push-based; sync parse, streams, and typed parsing share the exact same state machine.
|
|
32667
|
+
|
|
32668
|
+
## Documentation
|
|
32669
|
+
|
|
32670
|
+
- [Usage Guide](./usage.md)
|
|
32671
|
+
- [API Reference](./api.md)
|
|
32672
|
+
- [Examples](./examples.md)
|
|
32673
|
+
|
|
32674
|
+
## See Also
|
|
32675
|
+
|
|
32676
|
+
- [Spell](/spell/): the schema engine behind `parseTypedRecords`.
|
|
32677
|
+
- [Archive](/archive/): stores the files these rows came from.
|
|
32678
|
+
- [Tempo](/tempo/): parse and serialize the dates that live in CSV columns.
|
|
32679
|
+
|
|
32680
|
+
### API Reference
|
|
32681
|
+
|
|
32682
|
+
## API Overview
|
|
32683
|
+
|
|
32684
|
+
| Symbol | Purpose | Execution | Common gotcha |
|
|
32685
|
+
| --------------------- | ---------------------------------------------------- | --------- | -------------------------------------------------------------------- |
|
|
32686
|
+
| `parseGrid` | RFC 4180 text → string grid | Sync | Blank lines skipped unless `skipEmptyLines: false` |
|
|
32687
|
+
| `parseRecords` | First row (or `headers`) as keys | Sync | Short rows omit keys; extra cells are dropped |
|
|
32688
|
+
| `detectDelimiter` | Count `,` `;` tab outside quotes on the first line | Sync | Ties resolve to `,`; pin `delimiter` when the source is known |
|
|
32689
|
+
| `toCsv` | Grid → CSV text | Sync | CRLF by default; pass `newline: '\n'` for LF output |
|
|
32690
|
+
| `recordsToCsv` | Records → CSV text with column union | Sync | Without `columns`, order comes from first-seen keys |
|
|
32691
|
+
| `createCsvGridStream` | `TransformStream` for chunked text | Async | The header row is emitted like any other row |
|
|
32692
|
+
| `parseTypedRecords` | Records through a standard schema | Sync | Async schemas throw; failures aggregate into `TabulaValidationError` |
|
|
32693
|
+
| `CsvScanner` | Push-based state machine behind every parser | Sync | Call `finish()` after the last `push()` |
|
|
32694
|
+
|
|
32695
|
+
## Package Entry Point
|
|
32696
|
+
|
|
32697
|
+
```ts
|
|
32698
|
+
import { parseGrid, parseRecords, recordsToCsv, toCsv } from '@vielzeug/tabula';
|
|
32699
|
+
```
|
|
32700
|
+
|
|
32701
|
+
## Functions
|
|
32702
|
+
|
|
32703
|
+
### parseGrid
|
|
32704
|
+
|
|
32705
|
+
```ts
|
|
32706
|
+
function parseGrid(text: string, options?: TabulaParseOptions): string[][];
|
|
32707
|
+
```
|
|
32708
|
+
|
|
32709
|
+
Parses CSV text into rows of cells. A leading BOM is stripped; `\r\n`, `\r`, and `\n` all
|
|
32710
|
+
terminate records; `""` inside quoted fields is an escaped quote; quotes inside unquoted
|
|
32711
|
+
fields are literal (spreadsheet producers emit them constantly). `delimiter` defaults to
|
|
32712
|
+
`detectDelimiter(text)`.
|
|
32713
|
+
|
|
32714
|
+
### parseRecords
|
|
32715
|
+
|
|
32716
|
+
```ts
|
|
32717
|
+
function parseRecords(text: string, options?: TabulaRecordOptions): Record[];
|
|
32718
|
+
```
|
|
32719
|
+
|
|
32720
|
+
Reads the first row as headers unless `headers` is supplied (then the first row is data).
|
|
32721
|
+
Extra cells beyond the header are dropped; missing cells leave the key off the record.
|
|
32722
|
+
Empty `headers` throws `TabulaParseError`.
|
|
32723
|
+
|
|
32724
|
+
### detectDelimiter
|
|
32725
|
+
|
|
32726
|
+
```ts
|
|
32727
|
+
function detectDelimiter(text: string): string;
|
|
32728
|
+
```
|
|
32729
|
+
|
|
32730
|
+
Counts `,`, `;`, and tab outside quoted regions of the first line and returns the most
|
|
32731
|
+
frequent; ties go to `,`.
|
|
32732
|
+
|
|
32733
|
+
### toCsv
|
|
32734
|
+
|
|
32735
|
+
```ts
|
|
32736
|
+
function toCsv(rows: Iterable, options?: TabulaSerializeOptions): string;
|
|
32737
|
+
```
|
|
32738
|
+
|
|
32739
|
+
Serializes a grid. Fields are quoted only when they contain the delimiter, a quote, `\r`,
|
|
32740
|
+
`\n`, or leading/trailing spaces — or when `quoteAll` is set. `null`/`undefined` become empty
|
|
32741
|
+
cells; other values go through `String()`. Lines end with `\r\n` unless `newline` says
|
|
32742
|
+
otherwise.
|
|
32743
|
+
|
|
32744
|
+
### recordsToCsv
|
|
32745
|
+
|
|
32746
|
+
```ts
|
|
32747
|
+
function recordsToCsv(records: Iterable>, options?: TabulaRecordSerializeOptions): string;
|
|
32748
|
+
```
|
|
32749
|
+
|
|
32750
|
+
Writes a header row plus one row per record. Columns are `options.columns` or the first-seen
|
|
32751
|
+
union of record keys. Missing keys serialize as empty cells.
|
|
32752
|
+
|
|
32753
|
+
### createCsvGridStream
|
|
32754
|
+
|
|
32755
|
+
```ts
|
|
32756
|
+
function createCsvGridStream(options?: TabulaParseOptions): TransformStream;
|
|
32757
|
+
```
|
|
32758
|
+
|
|
32759
|
+
Transforms streamed text into completed rows. Until the first newline arrives (needed for
|
|
32760
|
+
delimiter auto-detection unless `delimiter` is pinned) input is buffered; after that rows are
|
|
32761
|
+
emitted as they complete.
|
|
32762
|
+
|
|
32763
|
+
### parseTypedRecords
|
|
32764
|
+
|
|
32765
|
+
```ts
|
|
32766
|
+
function parseTypedRecords(
|
|
32767
|
+
text: string,
|
|
32768
|
+
schema: StandardSchemaV1, T>,
|
|
32769
|
+
options?: TabulaRecordOptions,
|
|
32770
|
+
): T[];
|
|
32771
|
+
```
|
|
32772
|
+
|
|
32773
|
+
Validates every record through `schema['~standard'].validate`. Valid rows accumulate;
|
|
32774
|
+
invalid rows produce a `TabulaRowError` with the row's 1-based physical line number, exactly
|
|
32775
|
+
as a spreadsheet would show it. All rows are attempted, then failures throw as one `TabulaValidationError`.
|
|
32776
|
+
|
|
32777
|
+
### CsvScanner
|
|
32778
|
+
|
|
32779
|
+
```ts
|
|
32780
|
+
class CsvScanner {
|
|
32781
|
+
constructor(delimiter?: string, skipEmptyLines?: boolean);
|
|
32782
|
+
push(text: string, onRow: (row: string[], line: number) => void): void;
|
|
32783
|
+
finish(onRow: (row: string[], line: number) => void): void;
|
|
32784
|
+
}
|
|
32785
|
+
```
|
|
32786
|
+
|
|
32787
|
+
The push-based state machine every parser shares — split a fetch body however you like and
|
|
32788
|
+
semantics stay identical. `push` may be called with any chunk boundary, mid-quote included.
|
|
32789
|
+
Each row arrives with the 1-based physical line it started on (quoted newlines and blank
|
|
32790
|
+
lines included), which is what `TabulaRowError.line` reports.
|
|
32791
|
+
|
|
32792
|
+
## Types
|
|
32793
|
+
|
|
32794
|
+
| Type | Purpose |
|
|
32795
|
+
| ------------------------------ | -------------------------------------------------- |
|
|
32796
|
+
| `TabulaOptions` | `{ delimiter? }` shared by parsers and serializers |
|
|
32797
|
+
| `TabulaParseOptions` | `+ { skipEmptyLines? }` (default `true`) |
|
|
32798
|
+
| `TabulaRecordOptions` | `+ { headers? }` for headerless documents |
|
|
32799
|
+
| `TabulaSerializeOptions` | `{ delimiter?, quoteAll?, newline? }` |
|
|
32800
|
+
| `TabulaRecordSerializeOptions` | `+ { columns? }` for explicit column order |
|
|
32801
|
+
|
|
32802
|
+
## Errors
|
|
32803
|
+
|
|
32804
|
+
| Error | Thrown when |
|
|
32805
|
+
| ----------------------- | ----------------------------------------------------------------------- |
|
|
32806
|
+
| `TabulaError` | Base class for every tabula error |
|
|
32807
|
+
| `TabulaParseError` | A request cannot be honored (e.g. `headers: []`) |
|
|
32808
|
+
| `TabulaRowError` | One row failed schema validation (`line`, `issues`) |
|
|
32809
|
+
| `TabulaValidationError` | Typed parse finished with any invalid rows (`errors: TabulaRowError[]`) |
|
|
32810
|
+
|
|
32811
|
+
### Usage Guide
|
|
32812
|
+
|
|
32813
|
+
## Basic Usage
|
|
32814
|
+
|
|
32815
|
+
Everything is strings in, strings out — CSV has no types, and tabula does not pretend
|
|
32816
|
+
otherwise. Parse to a grid when you need positional access, or to records when the first row
|
|
32817
|
+
is a header:
|
|
32818
|
+
|
|
32819
|
+
```ts
|
|
32820
|
+
import { parseGrid, parseRecords } from '@vielzeug/tabula';
|
|
32821
|
+
|
|
32822
|
+
parseGrid('a,b\n"x,y",z\n');
|
|
32823
|
+
// [['a', 'b'], ['x,y', 'z']]
|
|
32824
|
+
|
|
32825
|
+
parseRecords('id,total\n7,"1,200.00"\n');
|
|
32826
|
+
// [{ id: '7', total: '1,200.00' }]
|
|
32827
|
+
```
|
|
32828
|
+
|
|
32829
|
+
A few parser behaviors worth knowing because every hand-rolled parser gets them wrong:
|
|
32830
|
+
|
|
32831
|
+
- A BOM is stripped, and `\r\n`, `\r`, and `\n` all end a record.
|
|
32832
|
+
- `""` inside a quoted field is an escaped quote; fields are quoted only as needed on output.
|
|
32833
|
+
- A row longer than the header is truncated to the header; a shorter row simply omits keys
|
|
32834
|
+
(no surprise `undefined` values in your records).
|
|
32835
|
+
- Blank lines are skipped by default; pass `skipEmptyLines: false` to keep them as `['']`.
|
|
32836
|
+
|
|
32837
|
+
## Delimiter Detection
|
|
32838
|
+
|
|
32839
|
+
`detectDelimiter` counts `,`, `;`, and tab occurrences outside quotes on the first line and
|
|
32840
|
+
returns the winner (ties go to `,`). Every parse entry point defaults to it, so a paste box
|
|
32841
|
+
and an uploaded `.csv` both just work:
|
|
32842
|
+
|
|
32843
|
+
```ts
|
|
32844
|
+
import { parseGrid } from '@vielzeug/tabula';
|
|
32845
|
+
|
|
32846
|
+
parseGrid('a;b\n1;2\n'); // German Excel export: delimiter is ';'
|
|
32847
|
+
```
|
|
32848
|
+
|
|
32849
|
+
Pin `delimiter` whenever the source is known — it is faster (the parser never counts) and it
|
|
32850
|
+
makes a stray comma in a title harmless.
|
|
32851
|
+
|
|
32852
|
+
## Serializing
|
|
32853
|
+
|
|
32854
|
+
`toCsv` writes a grid; `recordsToCsv` writes records, taking the column order from explicit
|
|
32855
|
+
`columns` or from the first-seen key order. Fields are quoted only when they contain the
|
|
32856
|
+
delimiter, a quote, a newline, or leading/trailing spaces:
|
|
32857
|
+
|
|
32858
|
+
```ts
|
|
32859
|
+
import { recordsToCsv, toCsv } from '@vielzeug/tabula';
|
|
32860
|
+
|
|
32861
|
+
toCsv([['note'], ['said "hi"']]);
|
|
32862
|
+
// note\r\n"said ""hi"""
|
|
32863
|
+
|
|
32864
|
+
recordsToCsv([{ b: 2, a: 1 }], { columns: ['a', 'b'], newline: '\n' });
|
|
32865
|
+
// a,b\n1,2
|
|
32866
|
+
```
|
|
32867
|
+
|
|
32868
|
+
`null` and `undefined` serialize as empty cells; everything else goes through `String()`.
|
|
32869
|
+
Use `quoteAll: true` when the consumer is a spreadsheet import wizard that guesses column
|
|
32870
|
+
types from the first rows.
|
|
32871
|
+
|
|
32872
|
+
## Streaming
|
|
32873
|
+
|
|
32874
|
+
`createCsvGridStream` is a `TransformStream`: pipe a text stream through it
|
|
32875
|
+
and consume rows as they complete. Even when auto-detecting the delimiter it buffers at most
|
|
32876
|
+
one line, so gigabyte exports never touch memory:
|
|
32877
|
+
|
|
32878
|
+
```ts
|
|
32879
|
+
import { createCsvGridStream } from '@vielzeug/tabula';
|
|
32880
|
+
|
|
32881
|
+
const rows = file.stream().pipeThrough(new TextDecoderStream()).pipeThrough(createCsvGridStream());
|
|
32882
|
+
for await (const row of rows) consume(row);
|
|
32883
|
+
```
|
|
32884
|
+
|
|
32885
|
+
The header row is emitted like any other row — decide what to do with it at the consumer.
|
|
32886
|
+
|
|
32887
|
+
## Typed Rows
|
|
32888
|
+
|
|
32889
|
+
`parseTypedRecords` runs every record through a Spell (or any standard-schema) validator and
|
|
32890
|
+
aggregates failures: one `TabulaValidationError` carrying a `TabulaRowError` per bad row with
|
|
32891
|
+
its 1-based line number, so a broken export is reported in full rather than at the first bad
|
|
32892
|
+
cell.
|
|
32893
|
+
|
|
32894
|
+
```ts
|
|
32895
|
+
import { s } from '@vielzeug/spell';
|
|
32896
|
+
import { parseTypedRecords } from '@vielzeug/tabula';
|
|
32897
|
+
|
|
32898
|
+
const orderSchema = s.object({ id: s.string(), qty: s.coerce.number() });
|
|
32899
|
+
const orders = parseTypedRecords(text, orderSchema); // qty arrives as a number
|
|
32900
|
+
```
|
|
32901
|
+
|
|
32902
|
+
Schema validation must be synchronous; an async schema throws a `TypeError` immediately
|
|
32903
|
+
rather than half-parsing the file.
|
|
32904
|
+
|
|
32905
|
+
## Error Handling
|
|
32906
|
+
|
|
32907
|
+
All errors extend `TabulaError`. Parsing is deliberately forgiving of stray quotes
|
|
32908
|
+
(spreadsheet producers emit them constantly), so `TabulaParseError` fires only on requests
|
|
32909
|
+
that cannot be honored, such as `headers: []`. Row-level validation failures arrive as one
|
|
32910
|
+
`TabulaValidationError` whose `errors` lists a `TabulaRowError` per bad line — report those
|
|
32911
|
+
per line, not as one opaque message.
|
|
32912
|
+
|
|
32913
|
+
## Best Practices
|
|
32914
|
+
|
|
32915
|
+
- Pin `delimiter` and `quote` when the producer is known; auto-detect only for paste boxes and unknown uploads.
|
|
32916
|
+
- Feed user imports through `parseTypedRecords` with Spell schemas — CSV hands you strings, and the coercion is where bugs live.
|
|
32917
|
+
- Serialize with `recordsToCsv` and explicit `columns` for exports; key insertion order is accidental API otherwise.
|
|
32918
|
+
- For files larger than a few MB, stream: `createCsvGridStream` keeps memory flat and shares the exact scanner semantics of `parseGrid`.
|
|
32919
|
+
|
|
32920
|
+
### Examples
|
|
32921
|
+
|
|
32922
|
+
## Examples
|
|
32923
|
+
|
|
32924
|
+
- [Parse and Serialize](./examples/parse-and-serialize.md)
|
|
32925
|
+
- [Typed Import Pipeline](./examples/typed-imports.md)
|
|
32926
|
+
|
|
32927
|
+
### REPL Examples
|
|
32928
|
+
|
|
32929
|
+
- Parse - Delimiters, quoting, records (id: `parse-basic`)
|
|
32930
|
+
- Serialize - Safe quoting and detection (id: `serialize-basic`)
|
|
32931
|
+
|
|
32932
|
+
---
|
|
32933
|
+
|
|
32076
32934
|
## @vielzeug/tandem
|
|
32077
32935
|
|
|
32078
32936
|
**Category:** sync
|
|
@@ -32633,12 +33491,11 @@ bus.on('subject:updated', () => {
|
|
|
32633
33491
|
|
|
32634
33492
|
// After: tavern owns the protocol, the validation, the broadcasting.
|
|
32635
33493
|
const host = hostTavern({
|
|
32636
|
-
commands: {
|
|
32637
|
-
|
|
32638
|
-
|
|
32639
|
-
|
|
32640
|
-
|
|
32641
|
-
snapshot: () => store.read('doc-1'),
|
|
33494
|
+
commands: { rename: (args) => store.rename(docId, args[0] as string) },
|
|
33495
|
+
subject: {
|
|
33496
|
+
onChanged: (listener) => store.onUpdated(docId, listener),
|
|
33497
|
+
onRemoved: (listener) => store.onRemoved(docId, listener),
|
|
33498
|
+
snapshot: () => store.read(docId),
|
|
32642
33499
|
},
|
|
32643
33500
|
});
|
|
32644
33501
|
```
|
|
@@ -32675,33 +33532,36 @@ yarn add @vielzeug/tavern
|
|
|
32675
33532
|
```ts
|
|
32676
33533
|
import { hostTavern, joinTavern } from '@vielzeug/tavern';
|
|
32677
33534
|
|
|
32678
|
-
// Host:
|
|
33535
|
+
// Host: wire the command table and snapshot access for the shared subject.
|
|
32679
33536
|
const host = hostTavern({
|
|
32680
33537
|
commands: {
|
|
32681
|
-
|
|
32682
|
-
|
|
33538
|
+
rename: (args) => myStore.rename(docId, args[0] as string),
|
|
33539
|
+
append: (args) => myStore.append(docId, args[0] as string),
|
|
32683
33540
|
},
|
|
32684
|
-
|
|
32685
|
-
|
|
32686
|
-
|
|
32687
|
-
|
|
32688
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33541
|
+
subject: {
|
|
33542
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33543
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33544
|
+
snapshot: () => myStore.read(docId),
|
|
32689
33545
|
},
|
|
32690
33546
|
});
|
|
32691
33547
|
|
|
32692
|
-
// Produce a single-use invitation; deliver it out-of-band (QR, copy/paste).
|
|
32693
|
-
const
|
|
33548
|
+
// Produce a single-use invitation code; deliver it out-of-band (QR, copy/paste).
|
|
33549
|
+
const invitationCode = await host.createInvitationCode();
|
|
32694
33550
|
|
|
32695
|
-
// Guest: consume the invitation, produce an answer for the host.
|
|
32696
|
-
const {
|
|
32697
|
-
|
|
33551
|
+
// Guest: consume the invitation code, produce an answer code for the host.
|
|
33552
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33553
|
+
invitationCode,
|
|
32698
33554
|
mount: (snapshot) => parseAndMount(snapshot),
|
|
32699
33555
|
name: 'Alex',
|
|
32700
33556
|
});
|
|
32701
|
-
await host.
|
|
33557
|
+
await host.acceptAnswerCode(answerCode);
|
|
32702
33558
|
|
|
32703
|
-
//
|
|
32704
|
-
|
|
33559
|
+
// `ready` settles once the first snapshot arrives and mounts: the mirror is live.
|
|
33560
|
+
await ready;
|
|
33561
|
+
|
|
33562
|
+
// The guest's commands run through the host's own table; their effect
|
|
33563
|
+
// arrives with the next snapshot, so a successful command needs no ack.
|
|
33564
|
+
guest.sendCommand('rename', ['Quarterly report']);
|
|
32705
33565
|
|
|
32706
33566
|
// Cleanup: hosting ends for every guest; onEnded fires exactly once on both sides.
|
|
32707
33567
|
host.dispose();
|
|
@@ -32711,9 +33571,9 @@ guest.dispose();
|
|
|
32711
33571
|
## Features
|
|
32712
33572
|
|
|
32713
33573
|
- **`hostTavern`**: host one subject: pairing, protocol validation, command application, coalesced snapshot broadcasts
|
|
32714
|
-
- **`joinTavern`**: join as a guest: consume the invitation, produce the answer, mirror the host's snapshots
|
|
32715
|
-
- **`TavernCommands`**: the host's command table: the same
|
|
32716
|
-
- **`
|
|
33574
|
+
- **`joinTavern`**: join as a guest: consume the invitation code, produce the answer code, mirror the host's snapshots
|
|
33575
|
+
- **`TavernCommands`**: the host's command table as a plain record of handlers: the same functions the host's own UI calls, so remote actions cannot bypass validation
|
|
33576
|
+
- **`ready` promise**: the join lifecycle is awaitable: `ready` resolves with the mounted mirror or rejects with why the session never came up
|
|
32717
33577
|
- **Coalesced snapshots**: bursts of local changes ship one snapshot per microtask, not one per change
|
|
32718
33578
|
- **`onEnded` fires exactly once**: on both handles: channel drops, subject removal, and explicit disposal share a single idempotent cleanup path
|
|
32719
33579
|
- **Typed errors**: `TavernPairingError` covers every unusable pasted code with the mesh failure chained as `cause`
|
|
@@ -32737,14 +33597,14 @@ guest.dispose();
|
|
|
32737
33597
|
| Symbol | Purpose | Execution | Common gotcha |
|
|
32738
33598
|
| --------------------- | ---------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------- |
|
|
32739
33599
|
| `hostTavern()` | Host a subject: pairing, command validation, snapshot broadcast | Sync factory | Disposing ends hosting for every guest |
|
|
32740
|
-
| `joinTavern()` | Join a session: consume invitation, produce answer
|
|
33600
|
+
| `joinTavern()` | Join a session: consume invitation code, produce answer code | Async | The session lives only after the host accepts and the first snapshot mounts |
|
|
32741
33601
|
| `TavernHost` | Host handle: invitation, answer acceptance, kick, notice relay, presence tap | N/A | `dispose()` is idempotent; control-plane methods throw `TavernDisposedError` after |
|
|
32742
33602
|
| `TavernGuest` | Guest handle: command forwarding, rejection tap, disposal | N/A | `dispose()` fires `onEnded` exactly once |
|
|
32743
|
-
| `
|
|
32744
|
-
| `
|
|
32745
|
-
| `
|
|
32746
|
-
| `
|
|
32747
|
-
| `
|
|
33603
|
+
| `TavernJoinResult` | Join outcome: answer code, guest handle, and the `ready` promise | N/A | A `ready` nobody awaits never surfaces as an unhandled rejection |
|
|
33604
|
+
| `TavernHostEvent` | Host observability union for `tap()`: presence, warnings, dispose | N/A | Lifecycle transitions are `onEnded`, not events |
|
|
33605
|
+
| `TavernGuestEvent` | Guest observability union for `tap()`: rejections, warnings, dispose | N/A | The opening transition is `ready`, not an event |
|
|
33606
|
+
| `TavernCommands` | The host's command table: a record of handlers keyed by command name | N/A | A name the record does not hold rejects without applying |
|
|
33607
|
+
| `TavernSubject` | Snapshot reading, change and removal subscriptions | N/A | `snapshot` returning `null` skips the broadcast |
|
|
32748
33608
|
| `TavernError` | Base error for every Tavern failure | N/A | N/A |
|
|
32749
33609
|
| `TavernPairingError` | The consumer pasted the wrong kind of pairing code | N/A | N/A |
|
|
32750
33610
|
| `TavernDisposedError` | A stopped host or ended guest was used again | N/A | N/A |
|
|
@@ -32755,20 +33615,21 @@ guest.dispose();
|
|
|
32755
33615
|
| ------------------ | -------------------------- |
|
|
32756
33616
|
| `@vielzeug/tavern` | Complete public Tavern API |
|
|
32757
33617
|
|
|
33618
|
+
The `MeshPeer` type carried by host events and the `peers` getter is re-exported here, so a single import types everything.
|
|
33619
|
+
|
|
32758
33620
|
## `hostTavern(options)`
|
|
32759
33621
|
|
|
32760
|
-
Creates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol)
|
|
33622
|
+
Creates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol) and checked against `commands`: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with the error's message. Local changes (via `subject.onChanged`) re-broadcast `subject.snapshot()`: coalesced on a microtask; `subject.onRemoved` ends hosting. Presence and transport warnings are reported through `tap()` as `TavernHostEvent`s, and the live peer list is the `peers` getter; hosting ending: from removal or `dispose()`: fires `onEnded` exactly once. `relayNotice` serializes through `serializeNotice` and broadcasts to every guest.
|
|
32761
33623
|
|
|
32762
33624
|
**Returns:** `TavernHost`: the host handle.
|
|
32763
33625
|
|
|
32764
|
-
| Option
|
|
32765
|
-
|
|
|
32766
|
-
| `commands
|
|
32767
|
-
| `
|
|
32768
|
-
| `
|
|
32769
|
-
| `
|
|
32770
|
-
| `
|
|
32771
|
-
| `subjects` | `TavernSubjects` | Snapshot reading, change and removal subscriptions |
|
|
33626
|
+
| Option | Type | Description |
|
|
33627
|
+
| ------------------ | ----------------------------- | ----------------------------------------------------------------------------- |
|
|
33628
|
+
| `commands?` | `TavernCommands` | The command table guest actions run through; omit for a read-only session |
|
|
33629
|
+
| `onEnded?` | `() => void` | Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once |
|
|
33630
|
+
| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |
|
|
33631
|
+
| `serializeNotice?` | `(notice) => unknown \| null` | Serializes a local notice for `relayNotice`; null skips that notice |
|
|
33632
|
+
| `subject` | `TavernSubject` | Snapshot reading, change and removal subscriptions for the hosted subject |
|
|
32772
33633
|
|
|
32773
33634
|
**Example**
|
|
32774
33635
|
|
|
@@ -32777,239 +33638,182 @@ import { hostTavern } from '@vielzeug/tavern';
|
|
|
32777
33638
|
|
|
32778
33639
|
const host = hostTavern({
|
|
32779
33640
|
commands: {
|
|
32780
|
-
|
|
32781
|
-
|
|
33641
|
+
rename: (args) => myStore.rename(docId, args[0] as string),
|
|
33642
|
+
append: (args) => myStore.append(docId, args[0] as string),
|
|
32782
33643
|
},
|
|
32783
|
-
|
|
32784
|
-
|
|
32785
|
-
|
|
32786
|
-
|
|
32787
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33644
|
+
subject: {
|
|
33645
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33646
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33647
|
+
snapshot: () => myStore.read(docId),
|
|
32788
33648
|
},
|
|
32789
33649
|
});
|
|
32790
33650
|
```
|
|
32791
33651
|
|
|
32792
33652
|
### `TavernHost` members
|
|
32793
33653
|
|
|
32794
|
-
| Member |
|
|
32795
|
-
| ------------------------ |
|
|
32796
|
-
| `
|
|
32797
|
-
| `
|
|
32798
|
-
| `disposalSignal` | `AbortSignal`
|
|
32799
|
-
| `dispose()` | `void`
|
|
32800
|
-
| `disposed` | `boolean`
|
|
32801
|
-
| `kick(
|
|
32802
|
-
| `peers` | `readonly MeshPeer[]`
|
|
32803
|
-
| `relayNotice(
|
|
32804
|
-
| `tap(handler,
|
|
32805
|
-
| `[Symbol.dispose]()` | `void`
|
|
32806
|
-
|
|
32807
|
-
---
|
|
33654
|
+
| Member | Type | Behavior |
|
|
33655
|
+
| ------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------- |
|
|
33656
|
+
| `acceptAnswerCode()` | `(code) => Promise` | Consumes a guest's answer code; resolves with the peer once the channel is open |
|
|
33657
|
+
| `createInvitationCode()` | `() => Promise` | Produces a single-use invitation code, QR-compact when the environment allows |
|
|
33658
|
+
| `disposalSignal` | `AbortSignal` | Aborted when hosting ends |
|
|
33659
|
+
| `dispose()` | `() => void` | Stops hosting: closes every channel and detaches all subscriptions; idempotent |
|
|
33660
|
+
| `disposed` | `boolean` | Whether hosting has ended |
|
|
33661
|
+
| `kick()` | `(peerId) => void` | Disconnects one guest; the guest observes it and fires `onEnded` |
|
|
33662
|
+
| `peers` | `readonly MeshPeer[]` | The guests currently connected |
|
|
33663
|
+
| `relayNotice()` | `(notice) => void` | Broadcasts `serializeNotice(notice)` to every guest. Dropped after hosting ended |
|
|
33664
|
+
| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernHostEvent`s; handler errors are swallowed; detaches on abort or end |
|
|
33665
|
+
| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |
|
|
32808
33666
|
|
|
32809
33667
|
## `joinTavern(options)`
|
|
32810
33668
|
|
|
32811
|
-
|
|
33669
|
+
Joins a session as a guest: decodes the invitation code, opens the mesh guest, and returns the answer code to show back. Snapshots mount through `mount` as they arrive; the first non-null mount settles `ready`. The session ends exactly once: from the channel dropping (`TavernError`), an early exit before mounting (`TavernDisposedError`), or disposal.
|
|
32812
33670
|
|
|
32813
|
-
**Returns:** `Promise
|
|
33671
|
+
**Returns:** `Promise>`: the answer code, the guest handle, and the `ready` promise. Rejects with `TavernPairingError` when the invitation code cannot be used.
|
|
32814
33672
|
|
|
32815
|
-
| Option | Type
|
|
32816
|
-
| ---------------- |
|
|
32817
|
-
| `
|
|
32818
|
-
| `mount` | `(snapshot
|
|
32819
|
-
| `name` | `string`
|
|
32820
|
-
| `
|
|
32821
|
-
| `
|
|
32822
|
-
| `
|
|
32823
|
-
| `onJoined?` | `(subject: Mounted) => void` | The mounted value once the first snapshot arrives |
|
|
32824
|
-
| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |
|
|
33673
|
+
| Option | Type | Description |
|
|
33674
|
+
| ---------------- | ------------------------------- | --------------------------------------------------------------------------------------- |
|
|
33675
|
+
| `invitationCode` | `string` | The invitation code the host produced |
|
|
33676
|
+
| `mount` | `(snapshot) => Mounted \| null` | Turns a received snapshot into the mounted mirror; null ignores it. Called per snapshot |
|
|
33677
|
+
| `name` | `string` | The guest's display name on the channel |
|
|
33678
|
+
| `onEnded?` | `(subject: Mounted) => void` | The channel ended after joining; receives the mounted subject for unmounting |
|
|
33679
|
+
| `onNotice?` | `(wire: unknown) => void` | Receives a notice the host relayed: re-emit it in the local UI |
|
|
33680
|
+
| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |
|
|
32825
33681
|
|
|
32826
33682
|
**Example**
|
|
32827
33683
|
|
|
32828
33684
|
```ts
|
|
32829
33685
|
import { joinTavern } from '@vielzeug/tavern';
|
|
32830
33686
|
|
|
32831
|
-
const {
|
|
32832
|
-
|
|
32833
|
-
mount: (snapshot) =>
|
|
33687
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33688
|
+
invitationCode,
|
|
33689
|
+
mount: (snapshot) => mySchema.parse(snapshot),
|
|
32834
33690
|
name: 'Alex',
|
|
32835
|
-
onEnded: (subject) => unmountMirror(subject
|
|
32836
|
-
onJoined: (subject) => mountMirror(subject),
|
|
33691
|
+
onEnded: (subject) => unmountMirror(subject),
|
|
32837
33692
|
});
|
|
32838
|
-
|
|
32839
|
-
|
|
32840
|
-
});
|
|
32841
|
-
|
|
32842
|
-
guest.sendCommand('doc-1', 'rename', ['New name']);
|
|
32843
|
-
guest.dispose();
|
|
33693
|
+
await host.acceptAnswerCode(answerCode);
|
|
33694
|
+
await ready; // the mirror is live
|
|
32844
33695
|
```
|
|
32845
33696
|
|
|
32846
|
-
### `
|
|
33697
|
+
### `TavernJoinResult` members
|
|
32847
33698
|
|
|
32848
|
-
| Member
|
|
32849
|
-
|
|
|
32850
|
-
| `
|
|
32851
|
-
| `
|
|
32852
|
-
| `
|
|
32853
|
-
| `sendCommand(subjectId, name, args)` | `void` | Forwards a command to the host. Throws `TavernDisposedError` if the session has ended |
|
|
32854
|
-
| `tap(handler, options?)` | `() => void` | Observes `TavernGuestEvent`s; returns an unsubscribe function |
|
|
32855
|
-
| `[Symbol.dispose]()` | `void` | Delegates to `dispose()`. Enables `using` declarations |
|
|
33699
|
+
| Member | Type | Behavior |
|
|
33700
|
+
| ------------ | ------------------ | ------------------------------------------------------------------------------------------------ |
|
|
33701
|
+
| `answerCode` | `string` | The answer code to show back to the host, QR-compact when the environment allows |
|
|
33702
|
+
| `guest` | `TavernGuest` | The guest handle |
|
|
33703
|
+
| `ready` | `Promise` | Resolves with the mounted subject on the first mount; rejects with why the session never came up |
|
|
32856
33704
|
|
|
32857
|
-
|
|
33705
|
+
### `TavernGuest` members
|
|
33706
|
+
|
|
33707
|
+
| Member | Type | Behavior |
|
|
33708
|
+
| -------------------- | -------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
33709
|
+
| `disposalSignal` | `AbortSignal` | Aborted when the session ends |
|
|
33710
|
+
| `dispose()` | `() => void` | Leaves the session; `onEnded` fires exactly once |
|
|
33711
|
+
| `disposed` | `boolean` | Whether the session has ended |
|
|
33712
|
+
| `sendCommand()` | `(name, args?) => void` | Forwards a command to the host's table; throws `TavernDisposedError` after the session ended |
|
|
33713
|
+
| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernGuestEvent`s; handler errors are swallowed; detaches on abort or end |
|
|
33714
|
+
| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |
|
|
32858
33715
|
|
|
32859
33716
|
## Types
|
|
32860
33717
|
|
|
33718
|
+
### `TavernCommands`
|
|
33719
|
+
|
|
32861
33720
|
```ts
|
|
32862
|
-
|
|
32863
|
-
|
|
32864
|
-
|
|
32865
|
-
has(name: string): boolean;
|
|
32866
|
-
/** Applies the command; throwing rejects the guest with the error's message. */
|
|
32867
|
-
apply(name: string, args: readonly unknown[]): unknown;
|
|
32868
|
-
}
|
|
33721
|
+
type TavernCommand = (args: readonly unknown[]) => void;
|
|
33722
|
+
type TavernCommands = Record;
|
|
33723
|
+
```
|
|
32869
33724
|
|
|
32870
|
-
|
|
32871
|
-
|
|
32872
|
-
|
|
32873
|
-
|
|
32874
|
-
|
|
32875
|
-
interface
|
|
32876
|
-
/** Reads the snapshot to broadcast; null while the subject is missing. */
|
|
32877
|
-
snapshot(): unknown;
|
|
32878
|
-
/** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */
|
|
33725
|
+
The host's command table, keyed by name: the same functions the host's own UI calls, so guest actions follow exactly the same validation path as local ones. A missing key rejects the guest with `The host has no command named "..."`; a throwing handler rejects with its message. Omit the table entirely for a read-only session.
|
|
33726
|
+
|
|
33727
|
+
### `TavernSubject`
|
|
33728
|
+
|
|
33729
|
+
```ts
|
|
33730
|
+
interface TavernSubject {
|
|
32879
33731
|
onChanged(listener: () => void): () => void;
|
|
32880
|
-
/** Subscribes to the hosted subject's removal: hosting ends when it fires. */
|
|
32881
33732
|
onRemoved(listener: () => void): () => void;
|
|
33733
|
+
snapshot(): unknown;
|
|
32882
33734
|
}
|
|
33735
|
+
```
|
|
32883
33736
|
|
|
32884
|
-
|
|
32885
|
-
* Notice relay between host and guests. Notices cross the wire as opaque
|
|
32886
|
-
* values: each client translates locally.
|
|
32887
|
-
*/
|
|
32888
|
-
interface TavernNotices {
|
|
32889
|
-
/** Serializes a local notice for the wire; null skips this one. */
|
|
32890
|
-
toWire(notice: unknown): unknown | null;
|
|
32891
|
-
/** Re-emits a received wire notice locally. */
|
|
32892
|
-
fromWire(wire: unknown): void;
|
|
32893
|
-
}
|
|
32894
|
-
|
|
32895
|
-
/** Notable host moments reported through `TavernHost.tap`. */
|
|
32896
|
-
type TavernHostEvent =
|
|
32897
|
-
| { readonly peer: MeshPeer; readonly type: 'peer-joined' }
|
|
32898
|
-
| { readonly peer: MeshPeer; readonly reason?: string; readonly type: 'peer-left' }
|
|
32899
|
-
| { readonly error: unknown; readonly message: string; readonly type: 'warning' };
|
|
32900
|
-
|
|
32901
|
-
/** Notable guest moments reported through `TavernGuest.tap`. */
|
|
32902
|
-
type TavernGuestEvent =
|
|
32903
|
-
| { readonly commandId: string; readonly message: string; readonly type: 'rejected' }
|
|
32904
|
-
| { readonly error: unknown; readonly message: string; readonly type: 'warning' };
|
|
32905
|
-
|
|
32906
|
-
/** Options for `hostTavern`. */
|
|
32907
|
-
interface TavernHostOptions {
|
|
32908
|
-
commands: TavernCommands;
|
|
32909
|
-
notices?: TavernNotices;
|
|
32910
|
-
/** Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once. */
|
|
32911
|
-
onEnded?(): void;
|
|
32912
|
-
rtc?: MeshRtcFactory;
|
|
32913
|
-
subjectId: string;
|
|
32914
|
-
subjects: TavernSubjects;
|
|
32915
|
-
}
|
|
32916
|
-
|
|
32917
|
-
/** Options for `joinTavern`. */
|
|
32918
|
-
interface TavernGuestOptions {
|
|
32919
|
-
invitationText: string;
|
|
32920
|
-
/** Mounts a received snapshot; the mounted value, or null to ignore. */
|
|
32921
|
-
mount(snapshot: unknown): Mounted | null;
|
|
32922
|
-
name: string;
|
|
32923
|
-
notices?: TavernNotices;
|
|
32924
|
-
onEnded?(subject: Mounted): void;
|
|
32925
|
-
onFailed?(reason: string): void;
|
|
32926
|
-
onJoined?(subject: Mounted): void;
|
|
32927
|
-
rtc?: MeshRtcFactory;
|
|
32928
|
-
}
|
|
33737
|
+
How the host reads and watches the single subject it shares. `onChanged` is the re-broadcast trigger; `onRemoved` ends hosting; `snapshot()` returns the JSON-serializable state to broadcast, or `null` while the subject is missing (the broadcast skips). A throwing `snapshot` is reported as a `warning` tap event instead of crashing the host.
|
|
32929
33738
|
|
|
32930
|
-
|
|
32931
|
-
interface TavernHost {
|
|
32932
|
-
acceptAnswerText(text: string): Promise;
|
|
32933
|
-
createInvitationText(): Promise;
|
|
32934
|
-
readonly disposalSignal: AbortSignal;
|
|
32935
|
-
dispose(): void;
|
|
32936
|
-
readonly disposed: boolean;
|
|
32937
|
-
kick(peerId: string): void;
|
|
32938
|
-
readonly peers: readonly MeshPeer[];
|
|
32939
|
-
relayNotice(notice: unknown): void;
|
|
32940
|
-
tap(handler: (event: TavernHostEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;
|
|
32941
|
-
[Symbol.dispose](): void;
|
|
32942
|
-
}
|
|
33739
|
+
### `TavernHostEvent`
|
|
32943
33740
|
|
|
32944
|
-
|
|
32945
|
-
|
|
32946
|
-
|
|
32947
|
-
|
|
32948
|
-
|
|
32949
|
-
|
|
32950
|
-
|
|
32951
|
-
|
|
32952
|
-
|
|
32953
|
-
|
|
33741
|
+
| Variant | Fires when |
|
|
33742
|
+
| -------------------------------------- | ---------------------------------------------------------- |
|
|
33743
|
+
| `{ type: 'peer-joined'; peer }` | A guest's channel opened |
|
|
33744
|
+
| `{ type: 'peer-left'; peer; reason? }` | A guest's channel closed |
|
|
33745
|
+
| `{ type: 'warning'; message; error }` | A transport error or a throwing snapshot read was survived |
|
|
33746
|
+
| `{ type: 'dispose' }` | Hosting ended and the tap stream is about to clear |
|
|
33747
|
+
|
|
33748
|
+
### `TavernGuestEvent`
|
|
33749
|
+
|
|
33750
|
+
| Variant | Fires when |
|
|
33751
|
+
| ------------------------------------------ | ------------------------------------------------------ |
|
|
33752
|
+
| `{ type: 'rejected'; commandId; message }` | The host rejected a forwarded command |
|
|
33753
|
+
| `{ type: 'warning'; message; error }` | A transport error was survived |
|
|
33754
|
+
| `{ type: 'dispose' }` | The session ended and the tap stream is about to clear |
|
|
32954
33755
|
|
|
32955
33756
|
## Errors
|
|
32956
33757
|
|
|
32957
|
-
|
|
32958
|
-
|
|
32959
|
-
|
|
32960
|
-
|
|
32961
|
-
|
|
33758
|
+
### `TavernError`
|
|
33759
|
+
|
|
33760
|
+
Base class for every Tavern failure; `instanceof TavernError` narrows the whole hierarchy. Channel failures before the first snapshot reject `ready` with this class.
|
|
33761
|
+
|
|
33762
|
+
### `TavernPairingError`
|
|
32962
33763
|
|
|
32963
|
-
|
|
33764
|
+
The code the consumer pasted could not be used: garbage, the wrong kind, an expired invitation, or an answer the host refuses. The underlying `@vielzeug/mesh` failure is chained as `cause`.
|
|
33765
|
+
|
|
33766
|
+
### `TavernDisposedError`
|
|
33767
|
+
|
|
33768
|
+
A stopped host or ended guest was used again: control-plane calls throw it so leaked handles surface, and it rejects `ready` when the guest leaves before the first snapshot.
|
|
32964
33769
|
|
|
32965
33770
|
### Usage Guide
|
|
32966
33771
|
|
|
32967
33772
|
## Basic Usage
|
|
32968
33773
|
|
|
32969
|
-
Host one subject per session; guests join through the invitation/answer pair.
|
|
33774
|
+
Host one subject per session; guests join through the invitation/answer code pair. A session always carries exactly one subject: the guest handle needs no routing keys, and the host's command table is the single validation path for local and remote actions alike.
|
|
32970
33775
|
|
|
32971
33776
|
```ts
|
|
32972
33777
|
import { hostTavern, joinTavern } from '@vielzeug/tavern';
|
|
32973
33778
|
|
|
32974
33779
|
const host = hostTavern({
|
|
32975
|
-
commands: {
|
|
32976
|
-
|
|
32977
|
-
|
|
32978
|
-
|
|
32979
|
-
|
|
32980
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33780
|
+
commands: { rename: (args) => myStore.rename(docId, args[0] as string) },
|
|
33781
|
+
subject: {
|
|
33782
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33783
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33784
|
+
snapshot: () => myStore.read(docId),
|
|
32981
33785
|
},
|
|
32982
33786
|
});
|
|
32983
|
-
const
|
|
33787
|
+
const invitationCode = await host.createInvitationCode();
|
|
32984
33788
|
|
|
32985
|
-
const {
|
|
32986
|
-
|
|
33789
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33790
|
+
invitationCode,
|
|
32987
33791
|
mount: (snapshot) => parseAndMount(snapshot),
|
|
32988
33792
|
name: 'Alex',
|
|
32989
33793
|
});
|
|
32990
|
-
await host.
|
|
33794
|
+
await host.acceptAnswerCode(answerCode);
|
|
33795
|
+
await ready;
|
|
32991
33796
|
|
|
32992
|
-
guest.sendCommand('
|
|
33797
|
+
guest.sendCommand('rename', ['Quarterly report']);
|
|
32993
33798
|
```
|
|
32994
33799
|
|
|
32995
33800
|
## Host a Subject
|
|
32996
33801
|
|
|
32997
|
-
The host validates every guest command
|
|
33802
|
+
The host validates every guest command against its command table: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with its message. The snapshot re-broadcasts on every local change: coalesced on a microtask, so bursts of changes ship one snapshot, not many. `onEnded` fires exactly once when hosting ends, whether the subject was removed or the host was disposed: reset your session UI there instead of intercepting your own `onRemoved` seam.
|
|
32998
33803
|
|
|
32999
33804
|
```ts
|
|
33000
33805
|
import { hostTavern } from '@vielzeug/tavern';
|
|
33001
33806
|
|
|
33002
33807
|
const host = hostTavern({
|
|
33003
33808
|
commands: {
|
|
33004
|
-
|
|
33005
|
-
|
|
33809
|
+
rename: (args) => myStore.rename(docId, args[0] as string),
|
|
33810
|
+
append: (args) => myStore.append(docId, args[0] as string),
|
|
33006
33811
|
},
|
|
33007
33812
|
onEnded: () => updateSessionUi(), // hosting ended: subject removed or disposed
|
|
33008
|
-
|
|
33009
|
-
|
|
33010
|
-
|
|
33011
|
-
|
|
33012
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33813
|
+
subject: {
|
|
33814
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33815
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33816
|
+
snapshot: () => myStore.read(docId),
|
|
33013
33817
|
},
|
|
33014
33818
|
});
|
|
33015
33819
|
|
|
@@ -33021,9 +33825,9 @@ host.tap((event) => {
|
|
|
33021
33825
|
updatePeerList(host.peers); // always current inside a presence event
|
|
33022
33826
|
});
|
|
33023
33827
|
|
|
33024
|
-
const
|
|
33025
|
-
// Show the invitation (QR or copy/paste); the guest returns an answer code.
|
|
33026
|
-
await host.
|
|
33828
|
+
const invitationCode = await host.createInvitationCode();
|
|
33829
|
+
// Show the invitation code (QR or copy/paste); the guest returns an answer code.
|
|
33830
|
+
await host.acceptAnswerCode(answerCode);
|
|
33027
33831
|
|
|
33028
33832
|
// Kick a peer; the guest observes a disconnect and fires onEnded.
|
|
33029
33833
|
host.kick(peerId);
|
|
@@ -33031,59 +33835,69 @@ host.kick(peerId);
|
|
|
33031
33835
|
host.dispose(); // stop hosting: every guest disconnects
|
|
33032
33836
|
```
|
|
33033
33837
|
|
|
33838
|
+
Omit `commands` for a read-only session: guests mirror the subject, and every command rejects with `The host has no command named "..."`.
|
|
33839
|
+
|
|
33034
33840
|
## Join as a Guest
|
|
33035
33841
|
|
|
33036
|
-
Joining consumes the invitation and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot
|
|
33842
|
+
Joining consumes the invitation code and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot mounts: that transition settles the `ready` promise, so there is no race between the handshake and your code attaching handlers.
|
|
33037
33843
|
|
|
33038
33844
|
```ts
|
|
33039
33845
|
import { joinTavern } from '@vielzeug/tavern';
|
|
33040
33846
|
|
|
33041
|
-
const {
|
|
33042
|
-
|
|
33847
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33848
|
+
invitationCode,
|
|
33043
33849
|
mount: (snapshot) => sanitizeAndMount(snapshot),
|
|
33044
33850
|
name: 'Alex',
|
|
33045
33851
|
onEnded: (subject) => unmountMirror(subject.id),
|
|
33046
|
-
onFailed: (reason) => showError(reason),
|
|
33047
|
-
onJoined: (subject) => mountMirror(subject),
|
|
33048
33852
|
});
|
|
33049
33853
|
guest.tap((event) => {
|
|
33050
33854
|
if (event.type === 'rejected') showToast(event.message); // event.commandId names the command it answers
|
|
33051
33855
|
if (event.type === 'warning') log.warn(event.message, event.error);
|
|
33052
33856
|
});
|
|
33053
33857
|
|
|
33054
|
-
|
|
33858
|
+
try {
|
|
33859
|
+
await ready; // resolves with the mounted mirror once the first snapshot arrives
|
|
33860
|
+
} catch (error) {
|
|
33861
|
+
showError(error.message); // the channel failed, the host closed it, or the guest left early
|
|
33862
|
+
}
|
|
33863
|
+
|
|
33864
|
+
guest.sendCommand('rename', ['New name']);
|
|
33055
33865
|
guest.dispose(); // leave; onEnded fires with the mounted subject exactly once
|
|
33056
33866
|
```
|
|
33057
33867
|
|
|
33058
|
-
The snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. Returning `null` ignores the
|
|
33868
|
+
The snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. It is called for every snapshot the host broadcasts. Returning `null` ignores one; the first non-null return becomes the mounted subject: it settles `ready` and is passed to `onEnded` when the session ends. A `ready` you never await is safe: its rejection is pre-handled and never surfaces as an unhandled rejection.
|
|
33059
33869
|
|
|
33060
33870
|
## Relay Notices
|
|
33061
33871
|
|
|
33062
|
-
|
|
33872
|
+
Notices are ephemeral out-of-band UI signals: a toast fired elsewhere, a comment added. Catalog keys rather than prose cross the wire, so each client translates locally. The host serializes its own notices with `serializeNotice` and relays them with `relayNotice`; guests receive them through `onNotice`.
|
|
33063
33873
|
|
|
33064
33874
|
```ts
|
|
33065
|
-
|
|
33066
|
-
|
|
33067
|
-
|
|
33068
|
-
|
|
33069
|
-
|
|
33070
|
-
|
|
33875
|
+
// Host side: forward local notices through the session.
|
|
33876
|
+
const host = hostTavern({
|
|
33877
|
+
/* ... */
|
|
33878
|
+
serializeNotice: (notice) => (isLocalNotice(notice) ? toWireShape(notice) : null),
|
|
33879
|
+
});
|
|
33880
|
+
host.relayNotice(localNotice); // null from serializeNotice skips this one
|
|
33071
33881
|
|
|
33072
|
-
//
|
|
33073
|
-
|
|
33882
|
+
// Guest side: re-emit received notices in the local UI.
|
|
33883
|
+
const { guest } = await joinTavern({
|
|
33884
|
+
/* ... */
|
|
33885
|
+
onNotice: (wire) => bus.emit('notify', wire),
|
|
33886
|
+
});
|
|
33074
33887
|
```
|
|
33075
33888
|
|
|
33076
|
-
**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests. One boolean set during `
|
|
33889
|
+
**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests: `onNotice` emits locally, the host's local subscription picks it up, and without a guard it would loop. One boolean set during `onNotice` and checked in `serializeNotice` is sufficient: the consumer owns this because only they know their local event system.
|
|
33077
33890
|
|
|
33078
33891
|
## Observe with tap()
|
|
33079
33892
|
|
|
33080
|
-
Both handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle
|
|
33893
|
+
Both handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle stays out of the observability stream: `ready` covers the opening transition on the guest, and `onEnded` covers the closing transition on both handles.
|
|
33081
33894
|
|
|
33082
33895
|
```ts
|
|
33083
33896
|
import type { TavernGuestEvent, TavernHostEvent } from '@vielzeug/tavern';
|
|
33084
33897
|
|
|
33085
33898
|
host.tap((event: TavernHostEvent) => {
|
|
33086
33899
|
if (event.type === 'warning') log.warn(event.message, event.error); // the original error, not just text
|
|
33900
|
+
if (event.type === 'dispose') log.info('hosting ended');
|
|
33087
33901
|
});
|
|
33088
33902
|
guest.tap((event: TavernGuestEvent) => {
|
|
33089
33903
|
if (event.type === 'rejected') log.info(`command ${event.commandId} rejected: ${event.message}`);
|
|
@@ -33092,13 +33906,13 @@ guest.tap((event: TavernGuestEvent) => {
|
|
|
33092
33906
|
|
|
33093
33907
|
## Handle Pairing Mistakes
|
|
33094
33908
|
|
|
33095
|
-
Every user-input pairing failure surfaces as `TavernPairingError` from both `
|
|
33909
|
+
Every user-input pairing failure surfaces as `TavernPairingError` from both `acceptAnswerCode` and `joinTavern`: a garbage code, the wrong code kind, an expired invitation, or an answer the host refuses. Catch it to show a helpful message instead of a raw error; the underlying mesh failure is chained as `cause` when you need it.
|
|
33096
33910
|
|
|
33097
33911
|
```ts
|
|
33098
33912
|
import { hostTavern, TavernPairingError } from '@vielzeug/tavern';
|
|
33099
33913
|
|
|
33100
33914
|
try {
|
|
33101
|
-
await host.
|
|
33915
|
+
await host.acceptAnswerCode(pastedCode);
|
|
33102
33916
|
} catch (error) {
|
|
33103
33917
|
if (error instanceof TavernPairingError) {
|
|
33104
33918
|
showToast(error.message); // "That code is an invitation, not a guest answer."
|
|
@@ -33110,16 +33924,15 @@ try {
|
|
|
33110
33924
|
|
|
33111
33925
|
## Working with Other Vielzeug Libraries
|
|
33112
33926
|
|
|
33113
|
-
Tavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes
|
|
33927
|
+
Tavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes. The peers carried by tap events and the {@link TavernHost.peers} getter are mesh types, re-exported by tavern so one import types everything.
|
|
33114
33928
|
|
|
33115
33929
|
```ts
|
|
33116
33930
|
import type { MeshRtcFactory } from '@vielzeug/mesh';
|
|
33117
33931
|
import { hostTavern } from '@vielzeug/tavern';
|
|
33118
33932
|
|
|
33119
33933
|
const host = hostTavern({
|
|
33120
|
-
// ... commands,
|
|
33934
|
+
// ... commands, subject
|
|
33121
33935
|
rtc: myTestRtcFactory, // inject an in-memory WebRTC fake
|
|
33122
|
-
subjectId: 'doc-1',
|
|
33123
33936
|
});
|
|
33124
33937
|
```
|
|
33125
33938
|
|
|
@@ -33127,11 +33940,12 @@ Pair `@vielzeug/ledger` on the host to give the commands tavern applies an undo
|
|
|
33127
33940
|
|
|
33128
33941
|
## Best Practices
|
|
33129
33942
|
|
|
33130
|
-
- Keep the command table the same
|
|
33943
|
+
- Keep the command table the same functions the host's own UI calls, so guest actions cannot bypass local validation.
|
|
33131
33944
|
- Return `null` from `snapshot` while the subject is missing: the broadcast simply skips.
|
|
33132
33945
|
- Reset host-side session UI in `onEnded`: it fires exactly once for subject removal and explicit disposal alike, so you never need to double-wire your own `onRemoved` seam.
|
|
33946
|
+
- Await `ready` before trusting the mirror: it names the exact reason a session never came up, and its rejection is safe to ignore when you do not care.
|
|
33133
33947
|
- Treat notices as catalog keys, not prose: each client translates locally.
|
|
33134
|
-
- Guard against notice echo if a tab can both host and guest: one boolean in `
|
|
33948
|
+
- Guard against notice echo if a tab can both host and guest: one boolean in `serializeNotice` is sufficient.
|
|
33135
33949
|
- Dispose guests and hosts when their screen unmounts; channels also clean up on disconnect through `onEnded`, which fires exactly once on both sides.
|
|
33136
33950
|
- Catch `TavernPairingError` separately from other errors: it means the pasted code could not be used, not that something is broken.
|
|
33137
33951
|
|
|
@@ -33208,18 +34022,17 @@ const text = format(reminder, {
|
|
|
33208
34022
|
## Features
|
|
33209
34023
|
|
|
33210
34024
|
- `parse()`: Requires an explicit ISO target: instant, zoned date-time, plain date-time, or plain date.
|
|
33211
|
-
- `toInstant()` / `
|
|
34025
|
+
- `toInstant()` / `toZoned()`: Convert wall-clock and absolute values with explicit timezone semantics.
|
|
33212
34026
|
- `shift()` / `difference()`: Apply DST-safe arithmetic across instant, zoned, and wall-clock inputs.
|
|
33213
|
-
- `contains()` / `clamp()`: Compare normalized ranges with optional calendar-unit precision.
|
|
33214
34027
|
- `startOf()` / `endOf()`: Resolve timezone-aware calendar boundaries, including configurable week starts.
|
|
33215
|
-
- `dateRange()` / `recurrence()`: Generate validated, lazy zoned calendar sequences.
|
|
33216
34028
|
- `format()` / `formatRelative()` / `formatDuration()`: Render localized values through `Intl`, including calendar-aware relative months and years.
|
|
33217
34029
|
- `formatTimer()`: Deterministic stopwatch clocks (`47:12`, `1:02:35`) for elapsed-time UI.
|
|
33218
|
-
-
|
|
34030
|
+
- `@vielzeug/tempo/cadence`: RFC 5545 RRULE engine — parse, lazy DST-correct expansion, and `RDATE`/`EXDATE` merging.
|
|
33219
34031
|
|
|
33220
34032
|
## Documentation
|
|
33221
34033
|
|
|
33222
34034
|
- [Usage Guide](./usage.md)
|
|
34035
|
+
- [Cadence (RRULE)](./cadence.md)
|
|
33223
34036
|
- [API Reference](./api.md)
|
|
33224
34037
|
- [Examples](./examples.md)
|
|
33225
34038
|
- [Migration Guide](./migration.md)
|
|
@@ -33238,20 +34051,20 @@ const text = format(reminder, {
|
|
|
33238
34051
|
| `parse()` | Parse ISO text to an explicit Temporal kind | Sync | `as` is required |
|
|
33239
34052
|
| `isValid()` | Narrow an unknown runtime value to `TimeInput` | Sync | Does not parse strings |
|
|
33240
34053
|
| `toInstant()` | Resolve a value as an absolute instant | Sync | Plain values require `timeZone` |
|
|
33241
|
-
| `
|
|
34054
|
+
| `toZoned()` | Project a value to a zone | Sync | Preserves instant, changes wall-clock fields |
|
|
33242
34055
|
| `shift()` / `difference()` | Timezone-aware arithmetic | Sync | Calendar operations require a timezone |
|
|
33243
34056
|
| `isBefore()` / `isAfter()` / `isSame()` | Compare absolute values or calendar units | Sync | Plain values require `timeZone` |
|
|
33244
|
-
| `contains()` / `clamp()` | Compare normalized ranges | Sync | Bounds normalize automatically |
|
|
33245
34057
|
| `startOf()` / `endOf()` | Resolve calendar boundaries | Sync | Weeks default to Monday |
|
|
33246
|
-
| `dateRange()` / `recurrence()` | Generate lazy zoned sequences | Sync | Steps and intervals must advance |
|
|
33247
|
-
| `classifyExpiry()` | Classify fixed elapsed-time thresholds | Sync | Months and years are rejected |
|
|
33248
34058
|
| `format()` family | Localized and machine formatting | Sync | Use `timeZone`, not `tz` |
|
|
33249
34059
|
|
|
33250
34060
|
## Package Entry Point
|
|
33251
34061
|
|
|
33252
|
-
| Import
|
|
33253
|
-
|
|
|
33254
|
-
| `@vielzeug/tempo`
|
|
34062
|
+
| Import | Purpose |
|
|
34063
|
+
| ------------------------- | ---------------------------------------------------------------------------------------- |
|
|
34064
|
+
| `@vielzeug/tempo` | Tempo utilities, errors, types, and shared `Temporal` namespace |
|
|
34065
|
+
| `@vielzeug/tempo/cadence` | RFC 5545 recurrence: `parseCadence`, `toCadence`, `expandCadence`, `resolveCadenceDates` |
|
|
34066
|
+
|
|
34067
|
+
Cadence has its own reference: [Cadence](./cadence.md).
|
|
33255
34068
|
|
|
33256
34069
|
## Core Functions
|
|
33257
34070
|
|
|
@@ -33324,24 +34137,24 @@ nowInstant();
|
|
|
33324
34137
|
|
|
33325
34138
|
---
|
|
33326
34139
|
|
|
33327
|
-
### `toInstant(input, options?)` / `
|
|
34140
|
+
### `toInstant(input, options?)` / `toZoned(input, options)`
|
|
33328
34141
|
|
|
33329
34142
|
```ts
|
|
33330
34143
|
toInstant(input: AbsoluteTime): Temporal.Instant;
|
|
33331
34144
|
toInstant(input: WallTime, options: { timeZone: string } & DisambiguationOptions): Temporal.Instant;
|
|
33332
|
-
|
|
34145
|
+
toZoned(input: TimeInput, options: { timeZone: string } & DisambiguationOptions): Temporal.ZonedDateTime;
|
|
33333
34146
|
```
|
|
33334
34147
|
|
|
33335
|
-
`toInstant()` resolves wall-clock values. `
|
|
34148
|
+
`toInstant()` resolves wall-clock values to an absolute instant. `toZoned()` projects any value into a required timezone, preserving the instant.
|
|
33336
34149
|
|
|
33337
34150
|
**Example:**
|
|
33338
34151
|
|
|
33339
34152
|
```ts
|
|
33340
|
-
import {
|
|
34153
|
+
import { parse, toInstant, toZoned } from '@vielzeug/tempo';
|
|
33341
34154
|
|
|
33342
34155
|
const local = parse('2026-11-01T01:30:00', { as: 'plainDateTime' });
|
|
33343
34156
|
const instant = toInstant(local, { disambiguation: 'later', timeZone: 'America/New_York' });
|
|
33344
|
-
|
|
34157
|
+
toZoned(instant, { timeZone: 'Europe/Berlin' });
|
|
33345
34158
|
```
|
|
33346
34159
|
|
|
33347
34160
|
---
|
|
@@ -33387,20 +34200,6 @@ Compare absolute instants or their containing calendar units.
|
|
|
33387
34200
|
|
|
33388
34201
|
---
|
|
33389
34202
|
|
|
33390
|
-
### `contains({ value, start, end, ...options })` / `clamp({ value, start, end, ...options })`
|
|
33391
|
-
|
|
33392
|
-
```ts
|
|
33393
|
-
contains(input: ContainsInput): boolean;
|
|
33394
|
-
clamp(input: ClampInput & { value: Temporal.ZonedDateTime }): Temporal.ZonedDateTime;
|
|
33395
|
-
clamp(input: ClampInput): Temporal.Instant;
|
|
33396
|
-
```
|
|
33397
|
-
|
|
33398
|
-
Normalizes reversed bounds, then checks or constrains the value.
|
|
33399
|
-
|
|
33400
|
-
**Returns:** `contains()` returns `boolean`; `clamp()` returns the normalized value or nearest bound.
|
|
33401
|
-
|
|
33402
|
-
---
|
|
33403
|
-
|
|
33404
34203
|
### `startOf()` / `endOf()`
|
|
33405
34204
|
|
|
33406
34205
|
```ts
|
|
@@ -33412,30 +34211,6 @@ Returns the first or last nanosecond of a timezone-aware calendar unit.
|
|
|
33412
34211
|
|
|
33413
34212
|
**Returns:** `Temporal.ZonedDateTime`.
|
|
33414
34213
|
|
|
33415
|
-
## Calendar Sequences
|
|
33416
|
-
|
|
33417
|
-
### `dateRange(start, end, step, options?)`
|
|
33418
|
-
|
|
33419
|
-
```ts
|
|
33420
|
-
dateRange(start: TimeInput, end: TimeInput, step: Temporal.DurationLike, options?: TimeZoneOptions): Generator;
|
|
33421
|
-
```
|
|
33422
|
-
|
|
33423
|
-
Returns an inclusive lazy zoned range and rejects steps that do not advance time.
|
|
33424
|
-
|
|
33425
|
-
**Returns:** `Generator`.
|
|
33426
|
-
|
|
33427
|
-
---
|
|
33428
|
-
|
|
33429
|
-
### `recurrence(start, rule, options?)`
|
|
33430
|
-
|
|
33431
|
-
```ts
|
|
33432
|
-
recurrence(start: TimeInput, rule: RecurrenceRule, options?: TimeZoneOptions): Generator;
|
|
33433
|
-
```
|
|
33434
|
-
|
|
33435
|
-
Returns a count- or date-limited lazy recurrence. Intervals must be positive safe integers; counts must be non-negative safe integers.
|
|
33436
|
-
|
|
33437
|
-
**Returns:** `Generator`.
|
|
33438
|
-
|
|
33439
34214
|
## Formatting
|
|
33440
34215
|
|
|
33441
34216
|
### `format(input, options?)`
|
|
@@ -33463,7 +34238,7 @@ format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), {
|
|
|
33463
34238
|
```ts
|
|
33464
34239
|
formatInstant(input: TimeInput, options?: TimeZoneOptions): string;
|
|
33465
34240
|
formatZoned(input: TimeInput, options?: TimeZoneOptions): string;
|
|
33466
|
-
formatRelative(input:
|
|
34241
|
+
formatRelative(input: AbsoluteTime, options?: RelativeFormatOptions): string;
|
|
33467
34242
|
formatDuration(input: string | Temporal.DurationLike, options?: DurationFormatOptions): string;
|
|
33468
34243
|
formatTimer(input: string | Temporal.DurationLike, options?: TimerFormatOptions): string;
|
|
33469
34244
|
```
|
|
@@ -33482,34 +34257,15 @@ formatRangeParts(
|
|
|
33482
34257
|
): ReturnType;
|
|
33483
34258
|
```
|
|
33484
34259
|
|
|
33485
|
-
Return `Intl` parts or localized range strings using `FormatOptions`.
|
|
34260
|
+
Return `Intl` parts or localized range strings using `FormatOptions`. Range inputs are order-free: reversed bounds format like the sorted pair.
|
|
33486
34261
|
|
|
33487
|
-
### `parseDuration()`
|
|
34262
|
+
### `parseDuration()`
|
|
33488
34263
|
|
|
33489
34264
|
```ts
|
|
33490
34265
|
parseDuration(input: string | Temporal.DurationLike): Temporal.Duration;
|
|
33491
|
-
humanize(diff: TimeDiffResult, options?: { locale?: Intl.LocalesArgument }): string;
|
|
33492
34266
|
```
|
|
33493
34267
|
|
|
33494
|
-
|
|
33495
|
-
|
|
33496
|
-
## Classification
|
|
33497
|
-
|
|
33498
|
-
### `classifyExpiry({ value, thresholds, relativeTo?, timeZone? })`
|
|
33499
|
-
|
|
33500
|
-
```ts
|
|
33501
|
-
classifyExpiry(input: ClassifyExpiryInput): K | null;
|
|
33502
|
-
```
|
|
33503
|
-
|
|
33504
|
-
Classifies an expiry against fixed elapsed-time thresholds in milliseconds or larger units. Months and years throw `TempoInvalidInputError`.
|
|
33505
|
-
|
|
33506
|
-
### `timeDiff(a, b?, options?)`
|
|
33507
|
-
|
|
33508
|
-
```ts
|
|
33509
|
-
timeDiff(a: TimeInput, b?: TimeInput, options?: TimeZoneOptions): TimeDiffResult;
|
|
33510
|
-
```
|
|
33511
|
-
|
|
33512
|
-
Returns absolute calendar difference in its largest meaningful unit. Uses Temporal's calendar-aware `.since()` for correct month and year handling.
|
|
34268
|
+
Parses an ISO 8601 duration string or `Temporal.DurationLike` into a `Temporal.Duration`.
|
|
33513
34269
|
|
|
33514
34270
|
## Types
|
|
33515
34271
|
|
|
@@ -33517,7 +34273,6 @@ Returns absolute calendar difference in its largest meaningful unit. Uses Tempor
|
|
|
33517
34273
|
type AbsoluteTime = Temporal.Instant | Temporal.ZonedDateTime;
|
|
33518
34274
|
type WallTime = Temporal.PlainDate | Temporal.PlainDateTime;
|
|
33519
34275
|
type TimeInput = AbsoluteTime | WallTime;
|
|
33520
|
-
type RelativeTimeInput = AbsoluteTime;
|
|
33521
34276
|
type ParseAs = 'instant' | 'plainDate' | 'plainDateTime' | 'zonedDateTime';
|
|
33522
34277
|
type Disambiguation = 'compatible' | 'earlier' | 'later' | 'reject';
|
|
33523
34278
|
type CalendarUnit = 'day' | 'month' | 'week' | 'year';
|
|
@@ -33535,11 +34290,6 @@ type TempoUnit =
|
|
|
33535
34290
|
| 'second'
|
|
33536
34291
|
| 'week'
|
|
33537
34292
|
| 'year';
|
|
33538
|
-
type FixedDuration = Pick;
|
|
33539
|
-
type ExpiryThresholds = Record;
|
|
33540
|
-
type TimeDiffUnit = Exclude;
|
|
33541
|
-
type TimeDiffResult = { unit: TimeDiffUnit; value: number };
|
|
33542
|
-
|
|
33543
34293
|
interface TimeZoneOptions {
|
|
33544
34294
|
timeZone?: string;
|
|
33545
34295
|
}
|
|
@@ -33562,21 +34312,11 @@ interface CompareOptions extends TimeZoneOptions {
|
|
|
33562
34312
|
unit?: BoundaryUnit;
|
|
33563
34313
|
weekStartsOn?: WeekStartDay;
|
|
33564
34314
|
}
|
|
33565
|
-
interface ContainsInput extends CompareOptions {
|
|
33566
|
-
end: TimeInput;
|
|
33567
|
-
start: TimeInput;
|
|
33568
|
-
value: TimeInput;
|
|
33569
|
-
}
|
|
33570
|
-
interface ClampInput extends CompareOptions {
|
|
33571
|
-
end: TimeInput;
|
|
33572
|
-
start: TimeInput;
|
|
33573
|
-
value: TimeInput;
|
|
33574
|
-
}
|
|
33575
34315
|
type FormatOptions =
|
|
33576
34316
|
| { intl: Intl.DateTimeFormatOptions; locale?: Intl.LocalesArgument; pattern?: never; timeZone?: string }
|
|
33577
34317
|
| { intl?: never; locale?: Intl.LocalesArgument; pattern?: FormatPattern; timeZone?: string };
|
|
33578
34318
|
interface RelativeFormatOptions extends TimeZoneOptions {
|
|
33579
|
-
base?:
|
|
34319
|
+
base?: AbsoluteTime;
|
|
33580
34320
|
locale?: Intl.LocalesArgument;
|
|
33581
34321
|
numeric?: Intl.RelativeTimeFormatNumeric;
|
|
33582
34322
|
style?: Intl.RelativeTimeFormatStyle;
|
|
@@ -33585,26 +34325,18 @@ interface DurationFormatOptions {
|
|
|
33585
34325
|
locale?: Intl.LocalesArgument;
|
|
33586
34326
|
style?: 'digital' | 'long' | 'narrow' | 'short';
|
|
33587
34327
|
}
|
|
33588
|
-
interface ClassifyExpiryInput extends TimeZoneOptions {
|
|
33589
|
-
value: TimeInput;
|
|
33590
|
-
thresholds: ExpiryThresholds;
|
|
33591
|
-
relativeTo?: Temporal.Instant;
|
|
33592
|
-
}
|
|
33593
|
-
type RecurrenceRule = { frequency: 'daily' | 'monthly' | 'weekly' | 'yearly'; interval?: number } & (
|
|
33594
|
-
| { count: number; until?: TimeInput }
|
|
33595
|
-
| { count?: number; until: TimeInput }
|
|
33596
|
-
);
|
|
33597
34328
|
```
|
|
33598
34329
|
|
|
33599
34330
|
## Errors
|
|
33600
34331
|
|
|
33601
|
-
| Error | Trigger
|
|
33602
|
-
| ---------------------------- |
|
|
33603
|
-
| `TempoError` | Base Tempo error
|
|
33604
|
-
| `
|
|
33605
|
-
| `
|
|
33606
|
-
| `
|
|
33607
|
-
| `
|
|
34332
|
+
| Error | Trigger | Notable properties |
|
|
34333
|
+
| ---------------------------- | --------------------------------------- | --------------------------------------------- |
|
|
34334
|
+
| `TempoError` | Base Tempo error | `instanceof TempoError` narrows every subtype |
|
|
34335
|
+
| `CadenceError` | Cadence rule cannot be parsed/expanded | Also exported from `@vielzeug/tempo/cadence` |
|
|
34336
|
+
| `TempoInvalidInputError` | Invalid parse or duration input | Extends `TempoError` |
|
|
34337
|
+
| `TempoInvalidTzError` | Invalid IANA zone or offset | Extends `TempoError` |
|
|
34338
|
+
| `TempoMissingTzError` | Wall time without required `timeZone` | Extends `TempoError` |
|
|
34339
|
+
| `TempoUnsupportedInputError` | Non-Temporal input passed to conversion | Extends `TempoError` |
|
|
33608
34340
|
|
|
33609
34341
|
Every Tempo error thrown from `parse()`, `parseDuration()`, and timezone validation carries the original Temporal error on its `cause` property (ES2022). Inspect `err.cause` for root-cause details when debugging.
|
|
33610
34342
|
|
|
@@ -33638,10 +34370,10 @@ const birthday = parse('2026-03-21', { as: 'plainDate' });
|
|
|
33638
34370
|
|
|
33639
34371
|
## Convert Timezones
|
|
33640
34372
|
|
|
33641
|
-
Use `
|
|
34373
|
+
Use `toZoned()` to project a value into a display timezone. Use `toInstant()` only when resolving a wall-clock value.
|
|
33642
34374
|
|
|
33643
34375
|
```ts
|
|
33644
|
-
import {
|
|
34376
|
+
import { parse, toInstant, toZoned } from '@vielzeug/tempo';
|
|
33645
34377
|
|
|
33646
34378
|
const local = parse('2026-11-01T01:30:00', { as: 'plainDateTime' });
|
|
33647
34379
|
const firstOccurrence = toInstant(local, {
|
|
@@ -33649,48 +34381,28 @@ const firstOccurrence = toInstant(local, {
|
|
|
33649
34381
|
timeZone: 'America/New_York',
|
|
33650
34382
|
});
|
|
33651
34383
|
|
|
33652
|
-
const berlin =
|
|
34384
|
+
const berlin = toZoned(firstOccurrence, { timeZone: 'Europe/Berlin' });
|
|
33653
34385
|
```
|
|
33654
34386
|
|
|
33655
34387
|
## Calculate and Compare
|
|
33656
34388
|
|
|
33657
|
-
Use Tempo helpers when an operation must resolve timezones
|
|
34389
|
+
Use Tempo helpers when an operation must resolve timezones or compare calendar units. Use Temporal methods directly when values are already the exact kind and timezone you need.
|
|
33658
34390
|
|
|
33659
34391
|
```ts
|
|
33660
|
-
import {
|
|
34392
|
+
import { difference, isAfter, isBefore, isSame, parse, shift } from '@vielzeug/tempo';
|
|
33661
34393
|
|
|
33662
34394
|
const start = parse('2026-03-21T10:00:00Z', { as: 'instant' });
|
|
33663
34395
|
const end = parse('2026-03-21T12:00:00Z', { as: 'instant' });
|
|
33664
|
-
const value = parse('2026-03-21T13:00:00Z', { as: 'instant' });
|
|
33665
34396
|
|
|
33666
34397
|
const duration = difference({ end, largestUnit: 'hour', start });
|
|
33667
|
-
const
|
|
33668
|
-
|
|
34398
|
+
const isWithinWindow = isAfter(end, start) && isBefore(end, parse('2026-03-21T14:00:00Z', { as: 'instant' }));
|
|
34399
|
+
|
|
34400
|
+
const sameDay = isSame(start, end, { timeZone: 'UTC', unit: 'day' });
|
|
33669
34401
|
|
|
33670
34402
|
const local = parse('2026-03-08T01:30:00', { as: 'plainDateTime' });
|
|
33671
34403
|
const tomorrow = shift(local, { days: 1 }, { timeZone: 'America/New_York' });
|
|
33672
34404
|
```
|
|
33673
34405
|
|
|
33674
|
-
## Classify Expiry
|
|
33675
|
-
|
|
33676
|
-
Use fixed elapsed-time thresholds in milliseconds or larger units. Handle `null` as the unclassified state instead of adding a far-future catch-all.
|
|
33677
|
-
|
|
33678
|
-
```ts
|
|
33679
|
-
import { classifyExpiry, parse } from '@vielzeug/tempo';
|
|
33680
|
-
|
|
33681
|
-
const status = classifyExpiry({
|
|
33682
|
-
relativeTo: parse('2026-06-01T00:00:00Z', { as: 'instant' }),
|
|
33683
|
-
thresholds: {
|
|
33684
|
-
expired: { days: 0 },
|
|
33685
|
-
critical: { days: 3 },
|
|
33686
|
-
warning: { days: 14 },
|
|
33687
|
-
},
|
|
33688
|
-
value: parse('2026-06-04T00:00:00Z', { as: 'instant' }),
|
|
33689
|
-
});
|
|
33690
|
-
|
|
33691
|
-
const label = status ?? 'safe';
|
|
33692
|
-
```
|
|
33693
|
-
|
|
33694
34406
|
## Format Values
|
|
33695
34407
|
|
|
33696
34408
|
Use `format()` for UI, `formatInstant()` for transport, and `formatZoned()` for a zoned ISO string.
|
|
@@ -33718,33 +34430,18 @@ formatTimer({ milliseconds: 3_753_000 }); // '1:02:33'
|
|
|
33718
34430
|
formatTimer('PT5M', { hours: 'always' }); // '0:05:00'
|
|
33719
34431
|
```
|
|
33720
34432
|
|
|
33721
|
-
## Generate Calendar Sequences
|
|
33722
|
-
|
|
33723
|
-
Use zoned values when the sequence already has a timezone. Plain and instant starts require `timeZone`.
|
|
33724
|
-
|
|
33725
|
-
```ts
|
|
33726
|
-
import { dateRange, parse, recurrence } from '@vielzeug/tempo';
|
|
33727
|
-
|
|
33728
|
-
const start = parse('2026-03-01T09:00:00[America/New_York]', { as: 'zonedDateTime' });
|
|
33729
|
-
const end = parse('2026-03-03T09:00:00[America/New_York]', { as: 'zonedDateTime' });
|
|
33730
|
-
|
|
33731
|
-
const days = [...dateRange(start, end, { days: 1 })];
|
|
33732
|
-
const meetings = [...recurrence(start, { count: 4, frequency: 'weekly', interval: 2 })];
|
|
33733
|
-
```
|
|
33734
|
-
|
|
33735
|
-
Both functions advance with zoned calendar arithmetic. Non-advancing range steps, invalid recurrence intervals, and negative or fractional counts throw `TempoInvalidInputError`.
|
|
33736
|
-
|
|
33737
34433
|
## Testing
|
|
33738
34434
|
|
|
33739
|
-
Pin
|
|
34435
|
+
Pin reference instants so relative and boundary assertions stay deterministic.
|
|
33740
34436
|
|
|
33741
34437
|
```ts
|
|
33742
|
-
import {
|
|
34438
|
+
import { formatRelative, parse, startOf } from '@vielzeug/tempo';
|
|
33743
34439
|
|
|
33744
|
-
const
|
|
33745
|
-
const value = parse('2026-
|
|
34440
|
+
const base = parse('2026-06-01T00:00:00Z', { as: 'instant' });
|
|
34441
|
+
const value = parse('2026-06-04T00:00:00Z', { as: 'instant' });
|
|
33746
34442
|
|
|
33747
|
-
|
|
34443
|
+
formatRelative(value, { base, locale: 'en-US' }); // 'in 3 days'
|
|
34444
|
+
startOf(value, 'month').toString(); // '2026-06-01T00:00:00+00:00[UTC]'
|
|
33748
34445
|
```
|
|
33749
34446
|
|
|
33750
34447
|
## Framework Integration
|
|
@@ -33800,9 +34497,7 @@ const expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();
|
|
|
33800
34497
|
|
|
33801
34498
|
- Parse strings with their actual temporal meaning and pass `timeZone` when resolving plain values.
|
|
33802
34499
|
- Use `disambiguation` for DST overlap and gap handling.
|
|
33803
|
-
- Use Tempo helpers for timezone resolution
|
|
33804
|
-
- Use fixed duration units for expiry thresholds.
|
|
33805
|
-
- Reject non-advancing range and recurrence configuration.
|
|
34500
|
+
- Use Tempo helpers for timezone resolution and calendar units; use Temporal directly for already-normalized values.
|
|
33806
34501
|
- Store instants for transport and database values.
|
|
33807
34502
|
- Use `formatInstant()` for machine output and `format()` for user-facing text.
|
|
33808
34503
|
- Pass `timeZone` to `formatRelative()` when month and year boundaries must use a specific region.
|
|
@@ -33812,14 +34507,12 @@ const expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();
|
|
|
33812
34507
|
## Examples
|
|
33813
34508
|
|
|
33814
34509
|
- [DST-Safe Arithmetic](./examples/dst-safe-arithmetic.md)
|
|
33815
|
-
- [Date Ranges and Recurrence](./examples/date-ranges-and-recurrence.md)
|
|
33816
34510
|
- [Locale Formatting](./examples/locale-formatting.md)
|
|
33817
34511
|
- [Timezone Conversion](./examples/timezone-conversion.md)
|
|
33818
|
-
- [Expiry Classification](./examples/expiry-classification.md)
|
|
33819
34512
|
|
|
33820
34513
|
### REPL Examples
|
|
33821
34514
|
|
|
33822
|
-
- Timezone-Aware Arithmetic and
|
|
34515
|
+
- Timezone-Aware Arithmetic and Formatting (id: `meeting-duration`)
|
|
33823
34516
|
|
|
33824
34517
|
---
|
|
33825
34518
|
|
|
@@ -33831,7 +34524,7 @@ const expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();
|
|
|
33831
34524
|
|
|
33832
34525
|
## Why Vault?
|
|
33833
34526
|
|
|
33834
|
-
Vault gives browser and SQLite persistence one typed schema while keeping backend guarantees explicit. Use `KeyValueVaultStore` for portable CRUD and observation; choose IndexedDB or the opt-in SQLite subpath when you need atomic transactions or lazy iteration. Durable adapters require
|
|
34527
|
+
Vault gives browser and SQLite persistence one typed schema while keeping backend guarantees explicit. Use `KeyValueVaultStore` for portable CRUD and observation; choose IndexedDB or the opt-in SQLite subpath when you need atomic transactions or lazy iteration. Durable adapters require parsers so invalid stored data never enters typed code.
|
|
33835
34528
|
|
|
33836
34529
|
```ts
|
|
33837
34530
|
// Before
|
|
@@ -33850,10 +34543,10 @@ const theme = await store.get('preferences', 'theme');
|
|
|
33850
34543
|
| Typed schema and keys | | Application-defined | |
|
|
33851
34544
|
| Portable key-value store API | | | IndexedDB only |
|
|
33852
34545
|
| Explicit atomic transactions | IndexedDB + SQLite capability | | |
|
|
33853
|
-
| Required durable
|
|
34546
|
+
| Required durable parsers | | | |
|
|
33854
34547
|
| Driver-neutral SQLite | Opt-in subpath | | |
|
|
33855
34548
|
|
|
33856
|
-
**Use Vault when** you need typed browser persistence or application-owned SQLite with honest storage capabilities and required durable
|
|
34549
|
+
**Use Vault when** you need typed browser persistence or application-owned SQLite with honest storage capabilities and required durable parsers.
|
|
33857
34550
|
|
|
33858
34551
|
**Consider raw Web Storage when** you only persist one or two unstructured values. **Consider Dexie when** you need a broader IndexedDB ecosystem.
|
|
33859
34552
|
|
|
@@ -33873,7 +34566,7 @@ yarn add @vielzeug/vault
|
|
|
33873
34566
|
|
|
33874
34567
|
## Quick Start
|
|
33875
34568
|
|
|
33876
|
-
Define a schema, create a key-value store with
|
|
34569
|
+
Define a schema, create a key-value store with parsers, and dispose it with its owner.
|
|
33877
34570
|
|
|
33878
34571
|
```ts
|
|
33879
34572
|
import { s } from '@vielzeug/spell';
|
|
@@ -33884,7 +34577,7 @@ const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'ligh
|
|
|
33884
34577
|
const store = createLocalStorage({
|
|
33885
34578
|
name: 'app-v2',
|
|
33886
34579
|
schema: { preferences: table('id') },
|
|
33887
|
-
|
|
34580
|
+
parsers: { preferences: PreferenceSchema },
|
|
33888
34581
|
});
|
|
33889
34582
|
|
|
33890
34583
|
try {
|
|
@@ -33898,12 +34591,12 @@ try {
|
|
|
33898
34591
|
## Features
|
|
33899
34592
|
|
|
33900
34593
|
- `table()` defines typed records with portable string or number keys.
|
|
33901
|
-
- Spell and other parser schemas work directly as
|
|
33902
|
-
- `/memory` returns a portable `DocumentVaultStore` with `batch()` and `iterate()`:
|
|
33903
|
-
- `/local-storage` and `/session-storage` return `KeyValueVaultStore`:
|
|
34594
|
+
- Spell and other parser schemas work directly as per-table parsers.
|
|
34595
|
+
- `/memory` returns a portable `DocumentVaultStore` with `batch()` and `iterate()`: parsers optional (in-memory, no trust boundary).
|
|
34596
|
+
- `/local-storage` and `/session-storage` return `KeyValueVaultStore`: parsers required.
|
|
33904
34597
|
- `observe()` emits current and changed table snapshots.
|
|
33905
34598
|
- `ttl` creates validated expiration durations.
|
|
33906
|
-
- `/indexeddb` and `/sqlite` return `DocumentVaultStore` with `batch()` and `iterate()`:
|
|
34599
|
+
- `/indexeddb` and `/sqlite` return `DocumentVaultStore` with `batch()` and `iterate()`: parsers required. `/memory` shares the same contract without parsers.
|
|
33907
34600
|
- `/indexeddb` accepts a `migrate` hook for schema upgrades the table schema cannot express.
|
|
33908
34601
|
- `pruneExpired()` removes stale TTL entries on demand.
|
|
33909
34602
|
- Bound helpers (`has`, `count`, `update`, `upsert`, `getMany`, `keys`, `deleteMany`) are available on every store and transaction context.
|
|
@@ -33925,28 +34618,27 @@ try {
|
|
|
33925
34618
|
|
|
33926
34619
|
## API Overview
|
|
33927
34620
|
|
|
33928
|
-
| Symbol | Purpose | Execution mode | Common gotcha
|
|
33929
|
-
| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- |
|
|
33930
|
-
| `createMemory()` | In-memory document store | Async API | Import from `/memory`;
|
|
33931
|
-
| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API |
|
|
33932
|
-
| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`;
|
|
33933
|
-
| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`;
|
|
33934
|
-
| `table()` | Typed record schema | Sync | The key field must be a string or finite number
|
|
33935
|
-
| `
|
|
33936
|
-
| `ttl` | Valid expiration durations | Sync | Durations must be positive |
|
|
34621
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
34622
|
+
| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- |
|
|
34623
|
+
| `createMemory()` | In-memory document store | Async API | Import from `/memory`; parsers optional |
|
|
34624
|
+
| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API | Parsers required; available only where the corresponding Web API exists |
|
|
34625
|
+
| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`; parsers required |
|
|
34626
|
+
| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`; parsers required |
|
|
34627
|
+
| `table()` | Typed record schema | Sync | The key field must be a string or finite number |
|
|
34628
|
+
| `ttl` | Valid expiration durations | Sync | Durations must be positive |
|
|
33937
34629
|
|
|
33938
34630
|
## Package Entry Points
|
|
33939
34631
|
|
|
33940
34632
|
| Import | Purpose |
|
|
33941
34633
|
| --------------------------------- | ----------------------------------------------------------------------------- |
|
|
33942
|
-
| `@vielzeug/vault` | Adapter-free schemas, TTL, errors,
|
|
34634
|
+
| `@vielzeug/vault` | Adapter-free schemas, TTL, errors, parsers, derived helpers, and shared types |
|
|
33943
34635
|
| `@vielzeug/vault/memory` | `createMemory` |
|
|
33944
34636
|
| `@vielzeug/vault/local-storage` | `createLocalStorage` |
|
|
33945
34637
|
| `@vielzeug/vault/session-storage` | `createSessionStorage` |
|
|
33946
34638
|
| `@vielzeug/vault/indexeddb` | `createIndexedDB`, the `migrate` upgrade-hook types, and IndexedDB-only types |
|
|
33947
34639
|
| `@vielzeug/vault/sqlite` | `createSQLite`, the SQLite driver protocol types, and `TransactionContext` |
|
|
33948
34640
|
|
|
33949
|
-
## Schemas,
|
|
34641
|
+
## Schemas, Parsers, and TTL
|
|
33950
34642
|
|
|
33951
34643
|
### `table()`
|
|
33952
34644
|
|
|
@@ -33963,7 +34655,7 @@ Defines a typed table and its primary-key field.
|
|
|
33963
34655
|
| -------------------- | ---------------------------------------------------------------- |
|
|
33964
34656
|
| `key` | A record field whose values are `string` or finite `number` keys |
|
|
33965
34657
|
| `options.defaultTtl` | Per-table default TTL in milliseconds |
|
|
33966
|
-
| `options.indexes` | IndexedDB secondary index fields
|
|
34658
|
+
| `options.indexes` | IndexedDB-only secondary index fields (`getAllByIndex()`) |
|
|
33967
34659
|
|
|
33968
34660
|
**Returns:** A `SchemaEntry` describing the table.
|
|
33969
34661
|
|
|
@@ -33978,31 +34670,6 @@ const users = table('id', {
|
|
|
33978
34670
|
|
|
33979
34671
|
---
|
|
33980
34672
|
|
|
33981
|
-
### `validatorCodec()`
|
|
33982
|
-
|
|
33983
|
-
```ts
|
|
33984
|
-
function validatorCodec(validator: { parse(value: unknown): T }): RecordCodec;
|
|
33985
|
-
```
|
|
33986
|
-
|
|
33987
|
-
Wraps any object with a `parse(value): T` method as an identity-encoding `RecordCodec`. Parser schemas can also be passed directly in `codecs`; a Spell schema requires no adapter.
|
|
33988
|
-
|
|
33989
|
-
**Returns:** A `RecordCodec`.
|
|
33990
|
-
|
|
33991
|
-
```ts
|
|
33992
|
-
import { s } from '@vielzeug/spell';
|
|
33993
|
-
|
|
33994
|
-
const UserSchema = s.object({ id: s.number(), name: s.string() });
|
|
33995
|
-
const store = createLocalStorage({
|
|
33996
|
-
name: 'app',
|
|
33997
|
-
schema: { users: table('id') },
|
|
33998
|
-
codecs: { users: UserSchema },
|
|
33999
|
-
});
|
|
34000
|
-
```
|
|
34001
|
-
|
|
34002
|
-
Custom `RecordCodec` values validate writes by round-tripping `decode(encode(value))`. IndexedDB codecs must preserve declared indexed field names and values in their encoded object.
|
|
34003
|
-
|
|
34004
|
-
---
|
|
34005
|
-
|
|
34006
34673
|
### `ttl`
|
|
34007
34674
|
|
|
34008
34675
|
```ts
|
|
@@ -34027,7 +34694,7 @@ const cacheLifetime = ttl.minutes(5);
|
|
|
34027
34694
|
|
|
34028
34695
|
## Factories
|
|
34029
34696
|
|
|
34030
|
-
Durable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `
|
|
34697
|
+
Durable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `parsers`. Memory may omit them.
|
|
34031
34698
|
|
|
34032
34699
|
### `createMemory()`
|
|
34033
34700
|
|
|
@@ -34035,12 +34702,12 @@ Durable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `cod
|
|
|
34035
34702
|
function createMemory(options: MemoryStoreOptions): DocumentVaultStore;
|
|
34036
34703
|
```
|
|
34037
34704
|
|
|
34038
|
-
Creates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws.
|
|
34705
|
+
Creates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws. Parsers are optional because memory values never cross a trust boundary.
|
|
34039
34706
|
|
|
34040
34707
|
| Parameter | Description |
|
|
34041
34708
|
| --------- | --------------------------- |
|
|
34042
34709
|
| `schema` | Tables created by `table()` |
|
|
34043
|
-
| `
|
|
34710
|
+
| `parsers` | Optional per-table parsers |
|
|
34044
34711
|
|
|
34045
34712
|
**Returns:** `DocumentVaultStore`.
|
|
34046
34713
|
|
|
@@ -34063,12 +34730,12 @@ function createLocalStorage(
|
|
|
34063
34730
|
): KeyValueVaultStore;
|
|
34064
34731
|
```
|
|
34065
34732
|
|
|
34066
|
-
Creates a namespaced `localStorage` store.
|
|
34733
|
+
Creates a namespaced `localStorage` store. Parsers are required.
|
|
34067
34734
|
|
|
34068
34735
|
| Parameter | Description |
|
|
34069
34736
|
| --------- | --------------------------- |
|
|
34070
34737
|
| `schema` | Tables created by `table()` |
|
|
34071
|
-
| `
|
|
34738
|
+
| `parsers` | Required per-table parsers |
|
|
34072
34739
|
| `name` | Required storage namespace |
|
|
34073
34740
|
|
|
34074
34741
|
A write that exceeds the browser quota rejects with `VaultQuotaError`.
|
|
@@ -34082,7 +34749,7 @@ import { createLocalStorage } from '@vielzeug/vault/local-storage';
|
|
|
34082
34749
|
const store = createLocalStorage({
|
|
34083
34750
|
name: 'app',
|
|
34084
34751
|
schema: { settings: table('id') },
|
|
34085
|
-
|
|
34752
|
+
parsers: { settings: SettingsSchema },
|
|
34086
34753
|
});
|
|
34087
34754
|
```
|
|
34088
34755
|
|
|
@@ -34109,7 +34776,7 @@ import { createSessionStorage } from '@vielzeug/vault/session-storage';
|
|
|
34109
34776
|
const store = createSessionStorage({
|
|
34110
34777
|
name: 'checkout',
|
|
34111
34778
|
schema: { cart: table('id') },
|
|
34112
|
-
|
|
34779
|
+
parsers: { cart: CartSchema },
|
|
34113
34780
|
});
|
|
34114
34781
|
```
|
|
34115
34782
|
|
|
@@ -34127,12 +34794,12 @@ function createIndexedDB(
|
|
|
34127
34794
|
): IndexedDbVaultStore;
|
|
34128
34795
|
```
|
|
34129
34796
|
|
|
34130
|
-
Creates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations.
|
|
34797
|
+
Creates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations. Parsers are required.
|
|
34131
34798
|
|
|
34132
34799
|
| Parameter | Description |
|
|
34133
34800
|
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
34134
34801
|
| `schema` | Tables and IndexedDB secondary indexes |
|
|
34135
|
-
| `
|
|
34802
|
+
| `parsers` | Required per-table parsers |
|
|
34136
34803
|
| `name` | Required database name |
|
|
34137
34804
|
| `version` | Positive schema version; defaults to `1` |
|
|
34138
34805
|
| `migrate` | Synchronous `onupgradeneeded` callback. Object stores and schema-declared indexes are created automatically; use the hook only for deletes or record transforms |
|
|
@@ -34146,7 +34813,7 @@ import { createIndexedDB } from '@vielzeug/vault/indexeddb';
|
|
|
34146
34813
|
const store = createIndexedDB({
|
|
34147
34814
|
name: 'app',
|
|
34148
34815
|
schema: { users: table('id', { indexes: ['role'] }) },
|
|
34149
|
-
|
|
34816
|
+
parsers: { users: UserSchema },
|
|
34150
34817
|
});
|
|
34151
34818
|
|
|
34152
34819
|
const admins = await store.getAllByIndex('users', 'role', 'admin');
|
|
@@ -34160,12 +34827,12 @@ const admins = await store.getAllByIndex('users', 'role', 'admin');
|
|
|
34160
34827
|
function createSQLite(options: SQLiteVaultOptions): DocumentVaultStore;
|
|
34161
34828
|
```
|
|
34162
34829
|
|
|
34163
|
-
Creates a namespaced SQLite document store with atomic batches and keyset-paginated iteration.
|
|
34830
|
+
Creates a namespaced SQLite document store with atomic batches and keyset-paginated iteration. Parsers are required. It accepts an application-provided positional-parameter driver and never opens or imports a runtime driver.
|
|
34164
34831
|
|
|
34165
34832
|
| Parameter | Description |
|
|
34166
34833
|
| ---------------- | ---------------------------------------------------------- |
|
|
34167
34834
|
| `schema` | Tables created by `table()` |
|
|
34168
|
-
| `
|
|
34835
|
+
| `parsers` | Required per-table parsers |
|
|
34169
34836
|
| `database` | Caller-provided `SQLiteDatabase` connection |
|
|
34170
34837
|
| `name` | Namespace within the connection |
|
|
34171
34838
|
| `closeOnDispose` | Closes the connection during disposal; defaults to `false` |
|
|
@@ -34182,11 +34849,11 @@ const store = createSQLite({
|
|
|
34182
34849
|
database: new DatabaseSync(':memory:'),
|
|
34183
34850
|
name: 'tests',
|
|
34184
34851
|
schema: { users: table('id') },
|
|
34185
|
-
|
|
34852
|
+
parsers: { users: UserSchema },
|
|
34186
34853
|
});
|
|
34187
34854
|
```
|
|
34188
34855
|
|
|
34189
|
-
Node `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol.
|
|
34856
|
+
Node `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol. Records must be JSON-compatible values. During a `batch()` callback, calls on every Vault store sharing that connection reject; use `tx.*` instead.
|
|
34190
34857
|
|
|
34191
34858
|
## Store Capabilities
|
|
34192
34859
|
|
|
@@ -34217,7 +34884,7 @@ interface KeyValueVaultStore {
|
|
|
34217
34884
|
}
|
|
34218
34885
|
```
|
|
34219
34886
|
|
|
34220
|
-
The portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by
|
|
34887
|
+
The portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by the table parser. `observe()` emits the current table snapshot by default and then emits after mutations. Listener errors never break the snapshot stream; pass `onObserverError` to the factory to report them.
|
|
34221
34888
|
|
|
34222
34889
|
---
|
|
34223
34890
|
|
|
@@ -34304,29 +34971,29 @@ type KeyOf = K extends unknown
|
|
|
34304
34971
|
```
|
|
34305
34972
|
|
|
34306
34973
|
```ts
|
|
34307
|
-
type RecordCodec = {
|
|
34308
|
-
decode(value: unknown): T;
|
|
34309
|
-
encode(value: T): unknown;
|
|
34310
|
-
};
|
|
34311
|
-
|
|
34312
34974
|
type RecordParser = { parse(value: unknown): T };
|
|
34313
|
-
type CodecInput = RecordCodec | RecordParser;
|
|
34314
34975
|
|
|
34315
|
-
type
|
|
34316
|
-
[K in keyof S]:
|
|
34976
|
+
type TableParsers = {
|
|
34977
|
+
[K in keyof S]: RecordParser>;
|
|
34317
34978
|
};
|
|
34318
34979
|
|
|
34980
|
+
type ObserverErrorHandler = (error: unknown) => void;
|
|
34981
|
+
|
|
34319
34982
|
type MemoryStoreOptions = {
|
|
34320
34983
|
schema: S;
|
|
34321
|
-
|
|
34984
|
+
parsers?: TableParsers;
|
|
34985
|
+
onObserverError?: ObserverErrorHandler;
|
|
34322
34986
|
};
|
|
34323
34987
|
|
|
34324
34988
|
type DurableStoreOptions = {
|
|
34325
34989
|
schema: S;
|
|
34326
|
-
|
|
34990
|
+
parsers: TableParsers;
|
|
34991
|
+
onObserverError?: ObserverErrorHandler;
|
|
34327
34992
|
};
|
|
34328
34993
|
```
|
|
34329
34994
|
|
|
34995
|
+
Parsers validate writes and decode persisted values: `put()` stores the parser's canonical output, so a record that parses can always be read back. Records must be JSON-safe (use ISO strings for dates) to survive every adapter's serialization. Spell schemas satisfy `RecordParser` directly.
|
|
34996
|
+
|
|
34330
34997
|
```ts
|
|
34331
34998
|
type MigrationContext = {
|
|
34332
34999
|
db: IDBDatabase;
|
|
@@ -34379,13 +35046,13 @@ interface TransactionContext {
|
|
|
34379
35046
|
|
|
34380
35047
|
## Errors
|
|
34381
35048
|
|
|
34382
|
-
| Error | Trigger
|
|
34383
|
-
| --------------------- |
|
|
34384
|
-
| `VaultError` | Any Vault-originated validation, serialization, storage, or
|
|
34385
|
-
| `VaultDisposedError` | An operation after the store or observer hub is disposed
|
|
34386
|
-
| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope
|
|
34387
|
-
| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota
|
|
34388
|
-
| `VaultMigrationError` | An IndexedDB migration callback throws
|
|
35049
|
+
| Error | Trigger |
|
|
35050
|
+
| --------------------- | ------------------------------------------------------------------------ |
|
|
35051
|
+
| `VaultError` | Any Vault-originated validation, serialization, storage, or parser error |
|
|
35052
|
+
| `VaultDisposedError` | An operation after the store or observer hub is disposed |
|
|
35053
|
+
| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope |
|
|
35054
|
+
| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota |
|
|
35055
|
+
| `VaultMigrationError` | An IndexedDB migration callback throws |
|
|
34389
35056
|
|
|
34390
35057
|
Every listed error extends `VaultError`.
|
|
34391
35058
|
|
|
@@ -34393,7 +35060,7 @@ Every listed error extends `VaultError`.
|
|
|
34393
35060
|
|
|
34394
35061
|
## Basic Usage
|
|
34395
35062
|
|
|
34396
|
-
Create a key-value store with a schema and
|
|
35063
|
+
Create a key-value store with a schema and parsers, then write a typed row.
|
|
34397
35064
|
|
|
34398
35065
|
```ts
|
|
34399
35066
|
import { s } from '@vielzeug/spell';
|
|
@@ -34409,7 +35076,7 @@ const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'ligh
|
|
|
34409
35076
|
const store = createLocalStorage({
|
|
34410
35077
|
name: 'app-v2',
|
|
34411
35078
|
schema: { preferences: table('id') },
|
|
34412
|
-
|
|
35079
|
+
parsers: { preferences: PreferenceSchema },
|
|
34413
35080
|
});
|
|
34414
35081
|
|
|
34415
35082
|
await store.put('preferences', { id: 'theme', theme: 'dark' });
|
|
@@ -34418,7 +35085,7 @@ console.log(await store.get('preferences', 'theme'));
|
|
|
34418
35085
|
|
|
34419
35086
|
## Create a Key-Value Store
|
|
34420
35087
|
|
|
34421
|
-
LocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit
|
|
35088
|
+
LocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit parsers; Web Storage requires them. Malformed storage envelopes are evicted lazily, while parser validation failures are surfaced without deleting persisted data.
|
|
34422
35089
|
|
|
34423
35090
|
The root entry is adapter-free. Import `createMemory` from `@vielzeug/vault/memory`, `createLocalStorage` from `@vielzeug/vault/local-storage`, or `createSessionStorage` from `@vielzeug/vault/session-storage`. Import each adapter from its focused subpath so unused backends stay out of the bundle.
|
|
34424
35091
|
|
|
@@ -34428,7 +35095,7 @@ Use a new storage name when upgrading from Vault 1. Old key and envelope formats
|
|
|
34428
35095
|
const store = createLocalStorage({
|
|
34429
35096
|
name: 'app-v2',
|
|
34430
35097
|
schema: { preferences: table('id') },
|
|
34431
|
-
|
|
35098
|
+
parsers: { preferences: PreferenceSchema },
|
|
34432
35099
|
});
|
|
34433
35100
|
```
|
|
34434
35101
|
|
|
@@ -34510,7 +35177,7 @@ const EventSchema = s.object({ id: s.number(), type: s.string() });
|
|
|
34510
35177
|
const db = createIndexedDB({
|
|
34511
35178
|
name: 'app-v2',
|
|
34512
35179
|
schema: { events: table('id') },
|
|
34513
|
-
|
|
35180
|
+
parsers: { events: EventSchema },
|
|
34514
35181
|
});
|
|
34515
35182
|
|
|
34516
35183
|
await db.batch(['events'], async (tx) => {
|
|
@@ -34538,7 +35205,7 @@ const store = createSQLite({
|
|
|
34538
35205
|
database,
|
|
34539
35206
|
name: 'app-v2',
|
|
34540
35207
|
schema: { events: table('id') },
|
|
34541
|
-
|
|
35208
|
+
parsers: { events: EventSchema },
|
|
34542
35209
|
});
|
|
34543
35210
|
|
|
34544
35211
|
await store.batch(['events'], async (tx) => {
|
|
@@ -34553,13 +35220,13 @@ SQLite stores serialize all access through the injected connection. `batch()` st
|
|
|
34553
35220
|
|
|
34554
35221
|
## Store SQLite Values and Observe Changes
|
|
34555
35222
|
|
|
34556
|
-
SQLite
|
|
35223
|
+
SQLite stores records as JSON, so records must be JSON-compatible: circular values, `bigint`, and functions fail serialization, and parsers should reject anything a schema cannot represent (use ISO strings for dates). Number and string primary keys remain distinct.
|
|
34557
35224
|
|
|
34558
35225
|
`observe()` sees mutations written through Vault stores sharing the same injected connection after a commit. It cannot detect direct SQL changes, writes from another process, or writes through another connection. The connection belongs to the caller by default; use `closeOnDispose: true` only when the store owns it.
|
|
34559
35226
|
|
|
34560
35227
|
## Handle IndexedDB Schema Migrations
|
|
34561
35228
|
|
|
34562
|
-
Declare IndexedDB indexes in the schema.
|
|
35229
|
+
Declare IndexedDB indexes in the schema; other adapters ignore them and `getAllByIndex()` is IndexedDB-only. Because writes store the parser's canonical output, indexed fields always match what readers see. Use `migrate` only for IndexedDB version upgrades and mirror Vault's fixed `value.` index path.
|
|
34563
35230
|
|
|
34564
35231
|
```ts
|
|
34565
35232
|
import { s } from '@vielzeug/spell';
|
|
@@ -34611,7 +35278,7 @@ Keep Ripple signals as application state and persist selected changes through Va
|
|
|
34611
35278
|
|
|
34612
35279
|
- Define one schema per storage namespace.
|
|
34613
35280
|
- Use string or finite-number primary keys only.
|
|
34614
|
-
- Provide
|
|
35281
|
+
- Provide parsers for every durable adapter; pass a Spell schema directly for validation or a bare `{ parse }` for passthrough.
|
|
34615
35282
|
- Use `observe()` for table snapshots.
|
|
34616
35283
|
- Use IndexedDB or SQLite for atomic work.
|
|
34617
35284
|
- Keep external asynchronous work outside `batch()` callbacks.
|
|
@@ -34637,7 +35304,7 @@ const SessionSchema = s.object({ id: s.string(), token: s.string() });
|
|
|
34637
35304
|
const store = createLocalStorage({
|
|
34638
35305
|
name: 'app-v2',
|
|
34639
35306
|
schema: { sessions: table('id', { defaultTtl: ttl.hours(1) }) },
|
|
34640
|
-
|
|
35307
|
+
parsers: { sessions: SessionSchema },
|
|
34641
35308
|
});
|
|
34642
35309
|
|
|
34643
35310
|
await store.put('sessions', { id: 'current', token: 'FAKE-TOKEN-FOR-DOCS' });
|
|
@@ -34661,7 +35328,7 @@ const EventSchema = s.object({ createdAt: s.number(), id: s.number(), type: s.st
|
|
|
34661
35328
|
const db = createIndexedDB({
|
|
34662
35329
|
name: 'events',
|
|
34663
35330
|
schema: { events: table('id', { indexes: ['type'] }) },
|
|
34664
|
-
|
|
35331
|
+
parsers: { events: EventSchema },
|
|
34665
35332
|
});
|
|
34666
35333
|
|
|
34667
35334
|
await db.batch(['events'], async (tx) => {
|
|
@@ -34694,7 +35361,7 @@ const store = createSQLite({
|
|
|
34694
35361
|
database,
|
|
34695
35362
|
name: 'app',
|
|
34696
35363
|
schema: { jobs: table('id') },
|
|
34697
|
-
|
|
35364
|
+
parsers: { jobs: JobSchema },
|
|
34698
35365
|
});
|
|
34699
35366
|
|
|
34700
35367
|
await store.batch(['jobs'], async (tx) => {
|
|
@@ -34773,7 +35440,7 @@ const db = createIndexedDB({
|
|
|
34773
35440
|
migrate({ db, oldVersion, tx }) {
|
|
34774
35441
|
// The 'users' store and its 'email' index already exist; drop a retired store.
|
|
34775
35442
|
if (oldVersion ('id', { indexes: ['email'] }) },
|
|
34776
|
-
|
|
35443
|
+
parsers: { users: UserSchema },
|
|
34777
35444
|
});
|
|
34778
35445
|
```
|
|
34779
35446
|
|
|
@@ -35603,7 +36270,7 @@ const controller = new AbortController();
|
|
|
35603
36270
|
const state = await router.load('/dashboard', { signal: controller.signal });
|
|
35604
36271
|
```
|
|
35605
36272
|
|
|
35606
|
-
Load a
|
|
36273
|
+
Load a router-internal URL into a `RouteState` including data loader results, without modifying router state or history. Follows declarative redirects (up to five hops). Returns `null` for unmatched URLs, except when a `notFound` route is configured: then the fallback route's state (with its `data` loaded) is returned instead.
|
|
35607
36274
|
|
|
35608
36275
|
Middleware is **not** executed: `load` is a data-only prefetch for SSR and pre-rendering where middleware side effects are not wanted. If your data loaders depend on `ctx.locals` set by middleware, use `navigate()` instead.
|
|
35609
36276
|
|
|
@@ -35688,16 +36355,6 @@ The guard fires when the router is leaving any route whose name appears in the `
|
|
|
35688
36355
|
|
|
35689
36356
|
**Returns:** `() => void`
|
|
35690
36357
|
|
|
35691
|
-
## `createPhaseMirror(options)`
|
|
35692
|
-
|
|
35693
|
-
Mirrors a domain state machine's phase into a `/:subject/:id/:phase` route segment: the shared routing approach for stepped flows (wizards, chapters, onboarding). Two-way, with the state machine as the sole source of truth:
|
|
35694
|
-
|
|
35695
|
-
- **Domain → URL**: every phase change lands on the phase's route, replacing so the browser back button exits the flow rather than stepping between phases.
|
|
35696
|
-
- **URL → domain**: a mismatched phase route is a revisit request (`requestRevisit`: the consumer owns its confirm dialog) when `canRevisit(current, target)` allows it, otherwise a bounce back to the actual phase. Reacts to the URL and to the domain loading, never to domain-led changes. The mirror stops following entirely when the route leaves the flow or names a different subject.
|
|
35697
|
-
- **Canonicalization**: the bare `detailRoute` URL redirects onto the current phase's route, so every arrival is shareable and reload-safe.
|
|
35698
|
-
|
|
35699
|
-
Options carry the router, the valid `phases`, both route names, and ripple `Readable`s for `currentPhase` and `subjectId` (`null` while the subject is missing). The mirror exposes `routePhase`, `revisitPhases` (readables), `phaseHref`, `followPhase`, `bounceIfMismatched` (the dialog cancel path), and `dispose()`.
|
|
35700
|
-
|
|
35701
36358
|
## `createRouteSignals(router)`
|
|
35702
36359
|
|
|
35703
36360
|
```ts
|
|
@@ -36199,35 +36856,6 @@ Thrown on middleware misuse: currently only when a middleware function calls its
|
|
|
36199
36856
|
|
|
36200
36857
|
Start with the [Overview](./index.md), then use this page for the day-to-day API.
|
|
36201
36858
|
|
|
36202
|
-
## Mirror a State Machine into the URL
|
|
36203
|
-
|
|
36204
|
-
A stepped flow's URL should name the step the domain is on: shareable, reload-safe, and never ahead of the truth. `createPhaseMirror` wires a `Router` to the domain phase as a ripple `Readable`, replacing (never pushing) so back exits the flow.
|
|
36205
|
-
|
|
36206
|
-
```ts
|
|
36207
|
-
import { createPhaseMirror } from '@vielzeug/wayfinder';
|
|
36208
|
-
import { signal } from '@vielzeug/ripple';
|
|
36209
|
-
|
|
36210
|
-
const currentPhase = signal(null);
|
|
36211
|
-
const subjectId = signal(null);
|
|
36212
|
-
|
|
36213
|
-
const mirror = createPhaseMirror({
|
|
36214
|
-
canRevisit: (current, target) => current === 'fight' && target === 'preparing',
|
|
36215
|
-
currentPhase,
|
|
36216
|
-
detailRoute: 'easyPathDetail',
|
|
36217
|
-
phases: ['story', 'preparing', 'fight'],
|
|
36218
|
-
phaseRoute: 'easyPathPhase',
|
|
36219
|
-
requestRevisit: (phase) => openConfirmDialog(phase),
|
|
36220
|
-
router,
|
|
36221
|
-
subjectId,
|
|
36222
|
-
});
|
|
36223
|
-
|
|
36224
|
-
mirror.routePhase.value; // the phase segment of the current route, or null
|
|
36225
|
-
mirror.phaseHref('preparing'); // anchor href for a tracker link
|
|
36226
|
-
mirror.dispose(); // stop mirroring
|
|
36227
|
-
```
|
|
36228
|
-
|
|
36229
|
-
The consumer supplies reactivity; the mirror never writes history. A Vue app bridges its reactive getters into ripple signals and disposes the mirror with its component scope.
|
|
36230
|
-
|
|
36231
36859
|
## Basic Usage
|
|
36232
36860
|
|
|
36233
36861
|
Create a deterministic router with memory history, wait for startup, and navigate by route name.
|
|
@@ -36612,7 +37240,7 @@ const controller = new AbortController();
|
|
|
36612
37240
|
const state = await router.load('/users/42', { signal: controller.signal });
|
|
36613
37241
|
```
|
|
36614
37242
|
|
|
36615
|
-
`load()` follows declarative redirects (up to five hops)
|
|
37243
|
+
`load()` follows declarative redirects (up to five hops) and accepts the same router-internal URLs as `url()`/`href()`. Middleware is not executed and its result is not reused by client navigation. When a `notFound` route is configured, an unmatched URL returns that fallback route's state; otherwise `load()` returns `null`.
|
|
36616
37244
|
|
|
36617
37245
|
## Preload Client Navigation
|
|
36618
37246
|
|