@vielzeug/codex 26.11.16 → 26.11.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  # Vielzeug: Full Documentation
2
2
 
3
- > Complete documentation for 46 packages. Version: 26.11.15
3
+ > Complete documentation for 47 packages. Version: 26.11.17
4
4
 
5
5
  ---
6
6
 
@@ -432,7 +432,7 @@ Every route below is mounted under `/api/v1`. Mutation guards require an exact a
432
432
  | `POST /auth/device/sign-in` | `{ email, challenge }`; 64 lowercase SHA-256 hex digits; shared admission and email budgets; 202 `{ ok: true }` |
433
433
  | `GET /auth/device/approve?token=…` | Non-destructive confirmation page displaying the matching code; no cookie; expired/invalid signatures return 410 recovery HTML |
434
434
  | `POST /auth/device/approve` | `{ token }`; marker and allowed or public origin; atomically authorizes the proof; 204 without a cookie |
435
- | `POST /auth/device/claim` | `{ token: proof }`; marker and allowed origin; 202 `{ ok: false }` if not claimable, 204 with session cookie when claimed; 409 if the request has a valid session |
435
+ | `POST /auth/device/claim` | `{ token: proof }`; marker and allowed origin; 202 `{ ok: false }` if not claimable, 204 with session cookie when claimed; 409 if the request has a valid session |
436
436
  | `GET /auth/verify?token=…` | Safe no-store click-confirmation HTML; with valid issuer configuration, invalid queries return 400 recovery HTML; no token consumption or session change |
437
437
  | `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |
438
438
  | `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |
@@ -1506,6 +1506,11 @@ export function useRecipes() {
1506
1506
  - [Client Error Mapping](./examples/client-error-mapping.md)
1507
1507
  - [GDPR Erasure and Export](./examples/gdpr-erasure-and-export.md)
1508
1508
 
1509
+ ### REPL Examples
1510
+
1511
+ - Shared Contract Schemas (id: `contract-schemas`)
1512
+ - Define A Collection (id: `define-collection`)
1513
+
1509
1514
  ---
1510
1515
 
1511
1516
  ## @vielzeug/arsenal
@@ -2772,6 +2777,497 @@ use the flat tree for DOM algorithms; this helper is for test code that needs eq
2772
2777
  - [Custom Element Interaction](./examples/custom-element-interaction.md)
2773
2778
  - [Waiting for Async Updates](./examples/waiting-for-async-updates.md)
2774
2779
 
2780
+ ### REPL Examples
2781
+
2782
+ - Scoped Queries And Events (id: `scoped-queries`)
2783
+ - Cancellable Waiting (id: `waiting`)
2784
+
2785
+ ---
2786
+
2787
+ ## @vielzeug/bard
2788
+
2789
+ **Category:** utilities
2790
+
2791
+ ### Overview
2792
+
2793
+ ## Why Bard?
2794
+
2795
+ The Web Audio API gives you nodes and params but no lifecycle: nothing stops voices, removes gesture listeners, or closes the context when your feature unmounts. Bard wraps a lazily created `AudioContext` in one disposable engine with named buses, ducking, voice caps, and a crossfading music deck.
2796
+
2797
+ ```ts
2798
+ // Before: hand-rolled graph, listeners, and teardown you must remember
2799
+ const ctx = new AudioContext();
2800
+ const source = ctx.createBufferSource();
2801
+ source.connect(ctx.destination);
2802
+ // ...who disconnects this on unmount?
2803
+
2804
+ // After
2805
+ const bard = createBard({ ducking: [{ source: 'voice', target: 'music', gain: 0.3 }] });
2806
+ await bard.load({ confirm: '/confirm.wav' });
2807
+ bard.play('confirm');
2808
+ bard.dispose(); // stops voices, removes listeners, closes the context
2809
+ ```
2810
+
2811
+ | Feature | Native Web Audio | Bard | Howler.js |
2812
+ | ----------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |
2813
+ | Bundle size | 0 B | | ~30 kB |
2814
+ | Root dependencies | | | |
2815
+ | Lifecycle | Manual node teardown | `dispose()` + `Symbol.dispose` | Per-sound unload |
2816
+ | Mixing | Hand-built gain graph | Named buses, ducking rules, voice caps | Per-sound volume only |
2817
+ | Music transitions | Manual crossfade scheduling | `deck.transition()` with loop points, queue | Not built in |
2818
+
2819
+ **Use Bard when** an interactive app needs owned audio: UI SFX with voice caps, narration that ducks music, or game-state music transitions with crossfades and loop points.
2820
+
2821
+ **Consider a plain `HTMLAudioElement` when** you need one background track with no mixing, sprites, or lifecycle requirements.
2822
+
2823
+ ## Installation
2824
+
2825
+ ```sh [pnpm]
2826
+ pnpm add @vielzeug/bard
2827
+ ```
2828
+
2829
+ ```sh [npm]
2830
+ npm install @vielzeug/bard
2831
+ ```
2832
+
2833
+ ```sh [yarn]
2834
+ yarn add @vielzeug/bard
2835
+ ```
2836
+
2837
+ ## Quick Start
2838
+
2839
+ Create the engine once per app, load assets, and dispose it when the owning feature unmounts. Nothing touches `AudioContext` or the DOM until the first call that needs audio, so server rendering is safe.
2840
+
2841
+ ```ts
2842
+ import { createBard } from '@vielzeug/bard';
2843
+
2844
+ const bard = createBard({
2845
+ ducking: [{ source: 'voice', target: 'music', gain: 0.3 }],
2846
+ });
2847
+
2848
+ await bard.load({
2849
+ music: { src: '/theme.mp3', stream: true },
2850
+ dice: { src: '/sfx.wav', sprites: { roll: [0, 1.2] } },
2851
+ });
2852
+
2853
+ const deck = bard.createDeck();
2854
+ deck.transition('music', { loop: true });
2855
+ bard.play('dice:roll', { detune: [-60, 60] });
2856
+
2857
+ bard.dispose();
2858
+ ```
2859
+
2860
+ ## Features
2861
+
2862
+ - **`createBard()`**: one disposable owner for the context, buses, voices, and decks.
2863
+ - **`bus()`**: named gain buses (`music`, `sfx`, `voice`) with click-free volume ramps.
2864
+ - **`ducking`**: declarative rules that ramp a target bus while a source bus has active voices.
2865
+ - **`play()`**: buffered playback with sprites, voice caps, oldest-first stealing, and detune/rate variance.
2866
+ - **`synth()`**: zero-asset oscillator and noise voices with ADSR and frequency sweeps.
2867
+ - **`createDeck()`**: two-slot crossfader with loop points, queue with shuffle, and opt-in Media Session.
2868
+ - **`tap()`**: observability events for state changes, steals, ducks, and track changes.
2869
+
2870
+ ## Documentation
2871
+
2872
+ - [Usage Guide](./usage.md)
2873
+ - [API Reference](./api.md)
2874
+ - [Examples](./examples.md)
2875
+ - [Migration](./migration.md)
2876
+
2877
+ ## See Also
2878
+
2879
+ - [Necromancer](/necromancer/): pair visual transitions with deck music transitions from the same game-state change.
2880
+ - [Arsenal](/arsenal/): general-purpose utilities used across the monorepo.
2881
+
2882
+ ### API Reference
2883
+
2884
+ ## API Overview
2885
+
2886
+ | Symbol | Purpose | Execution | Common gotcha |
2887
+ | ---------------------- | ------------------------------------------- | --------- | ------------------------------------------------------------------------ |
2888
+ | `createBard` | Creates the disposable audio engine | Sync | Context is still created lazily on first audio use |
2889
+ | `BardError` | Base error for invalid keys, buses, regions | — | Subclasses: `BardLoadError`, `BardDisposedError`, `BardUnsupportedError` |
2890
+ | `BardLoadError` | A manifest entry failed to fetch or decode | — | Original failure is in `cause` |
2891
+ | `BardDisposedError` | A method ran after `dispose()` | — | Thrown by every engine method except `dispose` |
2892
+ | `BardUnsupportedError` | No `AudioContext` in the runtime | — | `unlock()` rejects with it on servers without Web Audio |
2893
+
2894
+ ## Package Entry Point
2895
+
2896
+ | Import | Purpose |
2897
+ | ------------------------ | --------------------------------------- |
2898
+ | `@vielzeug/bard` | Complete public Bard API |
2899
+ | `@vielzeug/bard/testing` | Deterministic Web Audio fakes for tests |
2900
+
2901
+ ## Engine
2902
+
2903
+ ### createBard
2904
+
2905
+ ```ts
2906
+ function createBard(options?: BardOptions): Bard;
2907
+ ```
2908
+
2909
+ Creates the engine. Touches no browser global until the first method that needs audio.
2910
+
2911
+ | Option | Type | Default | Notes |
2912
+ | --------------------- | ------------------------ | --------------------------- | --------------------------------------------------------------------------- |
2913
+ | `buses` | `readonly string[]` | `['music', 'sfx', 'voice']` | `'master'` is reserved and throws if declared |
2914
+ | `volume` | `number` | `1` | Master volume, linear 0..1 |
2915
+ | `ducking` | `readonly DuckingRule[]` | `[]` | See Ducking |
2916
+ | `maxVoices` | `number` | `32` | Engine-wide concurrent voice cap |
2917
+ | `autoUnlock` | `boolean` | `true` | Gesture listeners resume a suspended context |
2918
+ | `autoSuspendOnHidden` | `boolean` | `false` | Suspend on page hide, resume on show (only resumes its own suspends) |
2919
+ | `context` | `() => AudioContext` | lazy `new AudioContext()` | Injection seam for tests; injected contexts are never closed by `dispose()` |
2920
+
2921
+ Returns the `Bard` engine.
2922
+
2923
+ ```ts
2924
+ import { createBard } from '@vielzeug/bard';
2925
+
2926
+ const bard = createBard({ volume: 0.9 });
2927
+ ```
2928
+
2929
+ ### Bard
2930
+
2931
+ | Member | Signature | Notes |
2932
+ | ----------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
2933
+ | `state` | `'idle' \| 'suspended' \| 'running' \| 'interrupted' \| 'closed'` | `'idle'` until first lazy context creation; `'interrupted'` occurs on iOS calls |
2934
+ | `context` | `AudioContext \| null` | Native context for advanced graph work |
2935
+ | `unlock()` | `() => Promise` | Creates and resumes the context |
2936
+ | `load(manifest, options?)` | `(AssetManifest, { signal? }) => Promise` | Deduplicates concurrent fetches per URL |
2937
+ | `unload(keys?)` | `(string \| readonly string[]) => void` | Stops active voices for the dropped keys |
2938
+ | `has(key)` | `(string) => boolean` | Resolves `'key:sprite'` to its parent asset |
2939
+ | `play(key, options?)` | `(string, PlayOptions?) => SoundHandle` | Throws `BardError` for unknown keys and streamed assets |
2940
+ | `synth(options)` | `(SynthOptions) => SoundHandle` | Procedural voice, self-cleaning |
2941
+ | `bus(name)` | `(string) => BusController` | `'master'` is valid; unknown names throw |
2942
+ | `createDeck(options?)` | `(DeckOptions?) => MusicDeck` | Multiple decks share the engine |
2943
+ | `suspend()` / `resume()` | `() => Promise` | Engine-wide pause for the whole context |
2944
+ | `tap(handler, options?)` | `(BardEvent) => void` → unsubscribe | Handler errors are swallowed; auto-detaches on `signal` |
2945
+ | `dispose()` | `() => void` | Stops voices and decks, aborts loads, removes listeners, closes an owned context; idempotent |
2946
+ | `disposed` / `disposalSignal` | `boolean` / `AbortSignal` | Standard disposal contract |
2947
+
2948
+ ---
2949
+
2950
+ ## Playback
2951
+
2952
+ ### SoundHandle
2953
+
2954
+ Returned by `play()` and `synth()`.
2955
+
2956
+ | Member | Signature | Notes |
2957
+ | --------------------------------------------- | -------------------------------- | ------------------------------------------- |
2958
+ | `stop(options?)` | `(FadeOptions?) => void` | Fades (default 15 ms micro-fade) then stops |
2959
+ | `setVolume(volume, options?)` | `(number, FadeOptions?) => void` | Ramped, never clicks |
2960
+ | `setPan(pan)` | `(-1..1) => void` | No-op when the voice has no panner |
2961
+ | `finished` | `Promise` | Resolves on natural end, stop, or dispose |
2962
+ | `dispose()` / `disposed` / `[Symbol.dispose]` | | Immediate stop and node release |
2963
+
2964
+ ### PlayOptions
2965
+
2966
+ | Option | Type | Default | Notes |
2967
+ | ----------------------- | ---------------------- | ------------- | -------------------------------------- |
2968
+ | `bus` | `string` | `'sfx'` | Destination bus |
2969
+ | `volume` | `number` | `1` | Linear 0..1 |
2970
+ | `pan` | `number` | — | -1..1; adds a `StereoPannerNode` |
2971
+ | `loop` | `boolean` | `false` | Loops the buffer or sprite region |
2972
+ | `loopStart` / `loopEnd` | `number` | — | Absolute buffer seconds |
2973
+ | `offset` | `number` | `0` | Start offset in seconds |
2974
+ | `detune` | `number \| [min, max]` | — | Cents; ranges sampled per voice |
2975
+ | `rate` | `number \| [min, max]` | — | Playback rate; shifts pitch on buffers |
2976
+ | `maxVoices` | `number` | — | Per-key cap; oldest copy is stolen |
2977
+ | `fadeIn` | `number` | — | Seconds from 0 to `volume` |
2978
+ | `random` | `() => number` | `Math.random` | Deterministic sampling in tests |
2979
+
2980
+ ### SynthOptions
2981
+
2982
+ | Option | Type | Default | Notes |
2983
+ | ---------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------- |
2984
+ | `type` | `'sine' \| 'square' \| 'sawtooth' \| 'triangle' \| 'noise'` | `'sine'` | `'noise'` uses a cached white-noise buffer |
2985
+ | `freq` | `number \| [from, to]` | `440` | Tuple sweeps exponentially; maps to filter cutoff for `'noise'` |
2986
+ | `duration` | `number` | `0.3` | Total seconds including release; must be positive |
2987
+ | `envelope` | `SynthEnvelope` | `{ attack: 0.005, decay: 0.05, sustain: 0.6, release: 0.1 }` | ADSR; `sustain` is a level |
2988
+ | `filter` | `SynthFilter` | — | Biquad stage before the envelope |
2989
+ | `bus` / `volume` / `pan` / `detune` / `random` | as in `PlayOptions` | | |
2990
+
2991
+ ---
2992
+
2993
+ ## Mixing
2994
+
2995
+ ### DuckingRule
2996
+
2997
+ ```ts
2998
+ interface DuckingRule {
2999
+ readonly source: string;
3000
+ readonly target: string;
3001
+ readonly gain: number; // duck level, linear 0..1
3002
+ readonly attack?: number; // seconds, default 0.2
3003
+ readonly release?: number; // seconds, default 0.8
3004
+ }
3005
+ ```
3006
+
3007
+ While the `source` bus has active voices, `target` ramps to `gain`; when they end it ramps back to 1. Multiple rules on one target take the lowest active gain.
3008
+
3009
+ ### BusController
3010
+
3011
+ | Member | Notes |
3012
+ | ----------------------------------- | -------------------------------------- |
3013
+ | `name` | Bus name |
3014
+ | `volume` / `setVolume(v, options?)` | User volume stage, ramped |
3015
+ | `muted` / `mute()` / `unmute()` | Ramped mute |
3016
+ | `duckLevel` | Current duck multiplier (1 = unducked) |
3017
+
3018
+ ---
3019
+
3020
+ ## Music Deck
3021
+
3022
+ ### MusicDeck
3023
+
3024
+ | Member | Signature | Notes |
3025
+ | --------------------------------------------- | --------------------------------------------- | ----------------------------------------------- |
3026
+ | `current` | `string \| null` | Active track key |
3027
+ | `playing` | `boolean` | `false` while paused or stopped |
3028
+ | `transition(key, options?)` | `(string, TransitionOptions?) => SoundHandle` | Crossfades; same key returns the current handle |
3029
+ | `queue(keys, options?)` | `(readonly string[], QueueOptions?) => void` | Replaces the queue and starts its first track |
3030
+ | `next()` / `previous()` | `() => void` | No-op without a queue |
3031
+ | `pause()` / `play()` | `() => void` | `play()` resumes from the paused offset |
3032
+ | `stop(options?)` | `(FadeOptions?) => void` | Stops and clears queue and slot |
3033
+ | `dispose()` / `disposed` / `[Symbol.dispose]` | | Releases a Media Session claim |
3034
+
3035
+ `TransitionOptions`: `fade`, `loop`, `loopStart`, `loopEnd`, `offset`.
3036
+ `QueueOptions`: `shuffle`, `crossfade`, `repeat`, `random`.
3037
+
3038
+ ### DeckOptions
3039
+
3040
+ | Option | Type | Default | Notes |
3041
+ | -------------- | --------- | --------- | ------------------------------------------------------ |
3042
+ | `bus` | `string` | `'music'` | Destination bus |
3043
+ | `mediaSession` | `boolean` | `false` | Claims `navigator.mediaSession`; a second claim throws |
3044
+ | `fade` | `number` | `2` | Default crossfade seconds |
3045
+
3046
+ ---
3047
+
3048
+ ## Assets
3049
+
3050
+ ### AssetManifest
3051
+
3052
+ ```ts
3053
+ type AssetManifest = Readonly>;
3054
+
3055
+ interface AssetDefinition {
3056
+ readonly src: string;
3057
+ readonly sprites?: Readonly>;
3058
+ readonly stream?: boolean; // deck-only playback via an owned element
3059
+ readonly meta?: AssetMeta; // Media Session metadata
3060
+ }
3061
+ ```
3062
+
3063
+ A bare string is shorthand for `{ src }`. Sprite regions are `[startSeconds, durationSeconds]` and play as `'key:sprite'`; out-of-bounds regions throw `BardError`.
3064
+
3065
+ ---
3066
+
3067
+ ## Observability
3068
+
3069
+ ### BardEvent
3070
+
3071
+ | Event | Payload | Fires |
3072
+ | ------------ | ---------------------- | ---------------------------------------- |
3073
+ | `state` | `state` | Context lifecycle changes |
3074
+ | `load` | `key` | A manifest entry finished loading |
3075
+ | `load-error` | `key`, `error` | A load failed |
3076
+ | `steal` | `key` | A voice was stolen past a cap |
3077
+ | `duck` | `bus`, `level`, `ramp` | A bus duck level changed |
3078
+ | `track` | `key \| null` | The deck changed tracks |
3079
+ | `dispose` | — | Emitted once at the start of `dispose()` |
3080
+
3081
+ ---
3082
+
3083
+ ## Testing
3084
+
3085
+ `@vielzeug/bard/testing` exports `FakeAudioContext` (manual clock via `advance(seconds)`, recorded `FakeAudioParam` automation), `FakeMediaElement`, `FakeMediaSession`, and `flush()`. Inject the fake with `createBard({ context: () => fake })`.
3086
+
3087
+ ---
3088
+
3089
+ ## Errors
3090
+
3091
+ | Error | Trigger | Notes |
3092
+ | ------------------- | ---------------------------------------------------------------- | --------------------------------------------------------- |
3093
+ | `BardError` | Unknown key/bus/sprite, reserved bus name, streamed-asset misuse | Base class |
3094
+ | `BardLoadError` | Fetch or `decodeAudioData` failure | `cause` carries the original error or `{ status }` |
3095
+ | `BardDisposedError` | Engine use after `dispose()` | Also `BardUnsupportedError` when no `AudioContext` exists |
3096
+
3097
+ ### Usage Guide
3098
+
3099
+ ## Basic Usage
3100
+
3101
+ Create one engine per app, load a manifest, and play through a bus. Dispose the engine when its owning feature unmounts.
3102
+
3103
+ ```ts
3104
+ import { createBard } from '@vielzeug/bard';
3105
+
3106
+ const bard = createBard();
3107
+ await bard.load({ click: '/click.wav', boom: '/boom.wav' });
3108
+
3109
+ const handle = bard.play('boom', { volume: 0.8, pan: -0.3 });
3110
+ await handle.finished;
3111
+ bard.dispose();
3112
+ ```
3113
+
3114
+ `play()` returns a `SoundHandle` immediately; audio starts once the browser allows it. `finished` resolves when the voice ends, is stopped, or is disposed.
3115
+
3116
+ ## Unlocking Audio
3117
+
3118
+ Browsers start the `AudioContext` suspended until a user gesture. Bard attaches capture-phase listeners for `pointerup`, `touchend`, `keydown`, and `click` and resumes the context inside the first one. All listeners are removed once the context is running.
3119
+
3120
+ ```ts
3121
+ const bard = createBard(); // listeners attach on first audio use
3122
+ await bard.unlock(); // or resume programmatically inside your own handler
3123
+ ```
3124
+
3125
+ `autoUnlock: false` skips the gesture listeners entirely; call `resume()` from your own gesture handler instead.
3126
+
3127
+ ## Buses and Volume
3128
+
3129
+ Voices route to a named bus: `voice -> [pan] -> bus -> master -> destination`. The defaults are `music`, `sfx`, and `voice`; override with `buses`. Volume changes always ramp, so they never click.
3130
+
3131
+ ```ts
3132
+ const music = bard.bus('music');
3133
+ music.setVolume(0.6, { fade: 0.5 });
3134
+ music.mute();
3135
+ music.unmute();
3136
+ ```
3137
+
3138
+ `bard.bus('master')` controls the output stage for every bus.
3139
+
3140
+ ## Ducking
3141
+
3142
+ A ducking rule ramps a target bus down while the source bus has active voices, and back up when they end. Narration over music is the canonical case.
3143
+
3144
+ ```ts
3145
+ const bard = createBard({
3146
+ ducking: [{ source: 'voice', target: 'music', gain: 0.3, attack: 0.2, release: 0.8 }],
3147
+ });
3148
+
3149
+ await bard.load({ announce: '/announce.wav' });
3150
+ const voice = bard.play('announce', { bus: 'voice' });
3151
+ // music is now at 30% until the announcement ends
3152
+ await voice.finished; // music ramps back to 100%
3153
+ ```
3154
+
3155
+ Ducking uses its own gain stage per bus, so it never fights user volume automation.
3156
+
3157
+ ## Sound Sprites
3158
+
3159
+ Bundle many short SFX into one file and address regions with `key:sprite`. The region is `[startSeconds, durationSeconds]`.
3160
+
3161
+ ```ts
3162
+ await bard.load({
3163
+ ui: { src: '/ui.wav', sprites: { open: [0, 0.4], close: [0.5, 0.4] } },
3164
+ });
3165
+
3166
+ bard.play('ui:open');
3167
+ bard.play('ui:close', { bus: 'sfx' });
3168
+ ```
3169
+
3170
+ ## Voice Caps and Variance
3171
+
3172
+ `maxVoices` caps concurrent copies of one key; the oldest copy is stolen with a micro-fade. The engine-wide cap is `maxVoices` in `createBard` (default 32). Ranges for `detune` and `rate` keep repeated hits from sounding identical.
3173
+
3174
+ ```ts
3175
+ for (let i = 0; i ` element instead of decoding it into an `AudioBuffer`. Mobile devices never spike RAM on ten-minute ambient tracks. Streamed assets are deck-only; `play()` on them throws.
3176
+
3177
+ ```ts
3178
+ await bard.load({
3179
+ ambient: { src: 'https://cdn.example.com/forest.mp3', stream: true },
3180
+ });
3181
+ bard.createDeck().transition('ambient', { loop: true });
3182
+ ```
3183
+
3184
+ The element requests CORS (`crossOrigin: 'anonymous'`); a CDN without CORS headers plays silent through Web Audio. Streamed loops cover the whole file: `loopStart`/`loopEnd` throw.
3185
+
3186
+ ## Media Session
3187
+
3188
+ `mediaSession: true` claims `navigator.mediaSession` for one deck: metadata from the asset's `meta`, hardware play/pause/next/previous. A second claim throws instead of stealing controls; disposing the deck releases the claim.
3189
+
3190
+ ```ts
3191
+ await bard.load({
3192
+ theme: { src: '/theme.mp3', meta: { title: 'Hunt Theme', artist: 'Bard' } },
3193
+ });
3194
+ const deck = bard.createDeck({ mediaSession: true });
3195
+ deck.transition('theme');
3196
+ ```
3197
+
3198
+ ## Testing
3199
+
3200
+ `@vielzeug/bard/testing` ships deterministic fakes: a context with a manual clock, recorded param automation, and fake media elements. Bard's own suite uses them.
3201
+
3202
+ ```ts
3203
+ import { createBard } from '@vielzeug/bard';
3204
+ import { FakeAudioContext } from '@vielzeug/bard/testing';
3205
+
3206
+ const ctx = new FakeAudioContext();
3207
+ const bard = createBard({ context: () => ctx });
3208
+ await bard.load({ ping: '/ping.wav' });
3209
+ bard.play('ping');
3210
+ ctx.advance(2); // clock moves, sources past their stop time fire 'ended'
3211
+ ```
3212
+
3213
+ ## Framework Integration
3214
+
3215
+ ```tsx [React]
3216
+ import { useEffect, useState } from 'react';
3217
+ import { createBard, type Bard } from '@vielzeug/bard';
3218
+
3219
+ export function useBard() {
3220
+ const [bard, setBard] = useState(null);
3221
+ useEffect(() => {
3222
+ const engine = createBard();
3223
+ setBard(engine);
3224
+ return () => engine.dispose();
3225
+ }, []);
3226
+ return bard;
3227
+ }
3228
+ ```
3229
+
3230
+ ```vue [Vue 3]
3231
+
3232
+ import { onMounted, onUnmounted, shallowRef } from 'vue';
3233
+ import { createBard } from '@vielzeug/bard';
3234
+
3235
+ const bard = shallowRef | null>(null);
3236
+ onMounted(() => (bard.value = createBard()));
3237
+ onUnmounted(() => bard.value?.dispose());
3238
+
3239
+ ```
3240
+
3241
+ ```svelte [Svelte]
3242
+
3243
+ import { createBard } from '@vielzeug/bard';
3244
+ import { onDestroy } from 'svelte';
3245
+
3246
+ const bard = createBard();
3247
+ onDestroy(() => bard.dispose());
3248
+
3249
+ ```
3250
+
3251
+ Create the engine in a mount hook, not at module scope: only mount lifecycle proves a browser runtime exists.
3252
+
3253
+ ## Best Practices
3254
+
3255
+ - Create one engine per app and pass it down; contexts are a limited hardware resource.
3256
+ - Dispose the engine with its owning feature; `using` works via `Symbol.dispose`.
3257
+ - Keep streamed assets for tracks longer than a few minutes; buffers are better for SFX.
3258
+ - Give narration its own `voice` bus and duck `music` from it, rather than fading tracks by hand.
3259
+ - Inject `random` in tests so detune, rate, and shuffle are deterministic.
3260
+ - Watch `tap()` events (`steal`, `duck`, `load-error`) in development to catch mixing problems early.
3261
+ - Call `unlock()` from your own first-gesture UI when you want audio live before the next interaction.
3262
+
3263
+ ### Examples
3264
+
3265
+ ## Examples
3266
+
3267
+ - [Game-State Music Transitions](./examples/game-state-music-transitions.md)
3268
+ - [Duck Music Under Narration](./examples/duck-music-under-narration.md)
3269
+ - [UI SFX Without Assets](./examples/ui-sfx-without-assets.md)
3270
+
2775
3271
  ---
2776
3272
 
2777
3273
  ## @vielzeug/beacon
@@ -10234,6 +10730,7 @@ The owner that creates the form disposes it. Framework subscriptions own only th
10234
10730
  - Form Submission (id: `form-submission`)
10235
10731
  - Form and Field Subscriptions (id: `form-subscriptions`)
10236
10732
  - Whole-Value Validation (id: `form-validation`)
10733
+ - Forge state + Refine elements (id: `refine-elements`)
10237
10734
  - Nested Field Handles (id: `scoped-sub-forms`)
10238
10735
 
10239
10736
  ---
@@ -14172,13 +14669,13 @@ const translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });
14172
14669
  translator.translate('save');
14173
14670
  ```
14174
14671
 
14175
- | Method | Signature | Returns |
14176
- | ------------------ | -------------------------------------------------------------------- | ---------------------- |
14177
- | `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |
14178
- | `translateUnkeyed` | `(key: string, options?)` | Rendered string |
14672
+ | Method | Signature | Returns |
14673
+ | ------------------ | ----------------------------------------------------------------------- | --------------------------- |
14674
+ | `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |
14675
+ | `translateUnkeyed` | `(key: string, options?)` | Rendered string |
14179
14676
  | `parts` | `(textKey, { values? })` or `(pluralKey, { count, ordinal?, values? })` | Render-order `Segment[]` |
14180
- | `partsUnkeyed` | `(key: string, options?)` | Render-order `Segment[]` |
14181
- | `locale` | `Locale` | Resolved active locale |
14677
+ | `partsUnkeyed` | `(key: string, options?)` | Render-order `Segment[]` |
14678
+ | `locale` | `Locale` | Resolved active locale |
14182
14679
 
14183
14680
  ---
14184
14681
 
@@ -14245,15 +14742,15 @@ const segments = i18n.parts('link', { values: { label: Sync } });
14245
14742
  // [ { type: 'text', value: 'Go to ' }, { type: 'value', name: 'label', value: }, { type: 'text', value: ' now.' } ]
14246
14743
  ```
14247
14744
 
14248
- | Contract | Behavior |
14249
- | ------------ | ------------------------------------------------------------------------------------------------- |
14250
- | Order | Segments are in render order; a value used twice produces two value segments; unreferenced values are ignored |
14251
- | Text | Text segments are never empty — adjacent placeholders yield adjacent value segments |
14252
- | Values | Passed through untouched with identity preserved; never `String()`-ified, escaped, or merged with neighbors |
14253
- | Missing value | Becomes a **text** segment holding the `missing` strategy's output (`null`/`undefined` count as missing; `''` is a real value) |
14254
- | Missing key | One text segment holding the strategy's output; `'throw'` still throws |
14255
- | Plural | `parts(key, { count, ordinal?, values? })`; `count` is interpolated into the selected form and can be overridden by an explicit `count` in `values` |
14256
- | Equivalence | Joining segments with `String()` reproduces `translate()` exactly, so `parts` is safe as your single resolution path |
14745
+ | Contract | Behavior |
14746
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
14747
+ | Order | Segments are in render order; a value used twice produces two value segments; unreferenced values are ignored |
14748
+ | Text | Text segments are never empty — adjacent placeholders yield adjacent value segments |
14749
+ | Values | Passed through untouched with identity preserved; never `String()`-ified, escaped, or merged with neighbors |
14750
+ | Missing value | Becomes a **text** segment holding the `missing` strategy's output (`null`/`undefined` count as missing; `''` is a real value) |
14751
+ | Missing key | One text segment holding the strategy's output; `'throw'` still throws |
14752
+ | Plural | `parts(key, { count, ordinal?, values? })`; `count` is interpolated into the selected form and can be overridden by an explicit `count` in `values` |
14753
+ | Equivalence | Joining segments with `String()` reproduces `translate()` exactly, so `parts` is safe as your single resolution path |
14257
14754
 
14258
14755
  The interpolation contract shared by `translate()` and `parts()`: string values are inserted verbatim (no HTML or entity escaping), non-string values are `String(value)`-ified, and nullish values follow the `missing` strategy. Rich UIs should render `parts` segments instead of smuggling placeholders through a translated string: because values never enter the concatenated string, user data cannot reach an HTML sink through it.
14259
14756
 
@@ -14777,11 +15274,15 @@ export function useI18n(i18n: I18n) {
14777
15274
  locale,
14778
15275
  t: i18n.translate.bind(i18n),
14779
15276
  rich: (key: TextKey, values: Record) =>
14780
- i18n.parts(key, { values }).map((segment, index) =>
14781
- segment.type === 'text'
14782
- ? segment.value
14783
- : {segment.value},
14784
- ),
15277
+ i18n
15278
+ .parts(key, { values })
15279
+ .map((segment, index) =>
15280
+ segment.type === 'text' ? (
15281
+ segment.value
15282
+ ) : (
15283
+ {segment.value}
15284
+ ),
15285
+ ),
14785
15286
  }),
14786
15287
  [locale],
14787
15288
  );
@@ -14852,7 +15353,7 @@ const pc = new RTCPeerConnection();
14852
15353
  const dc = pc.createDataChannel('sync');
14853
15354
  await pc.setLocalDescription(await pc.createOffer());
14854
15355
  // …wait for ICE, hand the SDP to the other device, wire expiry, timeouts,
14855
- // message framing, and dedupe yourself: per guest
15356
+ // and message framing yourself: per guest
14856
15357
 
14857
15358
  // After
14858
15359
  const host = createMeshHost();
@@ -14975,9 +15476,10 @@ try {
14975
15476
 
14976
15477
  ## Package Entry Point
14977
15478
 
14978
- | Import | Purpose |
14979
- | ---------------- | ------------------------ |
14980
- | `@vielzeug/mesh` | Complete public Mesh API |
15479
+ | Import | Purpose |
15480
+ | ------------------------ | --------------------------------------------- |
15481
+ | `@vielzeug/mesh` | Complete public Mesh API |
15482
+ | `@vielzeug/mesh/testing` | In-memory WebRTC fake for browserless testing |
14981
15483
 
14982
15484
  ## Factory Functions
14983
15485
 
@@ -15037,15 +15539,15 @@ const answer = await guest.acceptInvitation(meshCodec.decode(invitationText), {
15037
15539
 
15038
15540
  `MeshHost` extends `MeshNode`.
15039
15541
 
15040
- | Member | Signature | Purpose |
15041
- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15042
- | `createInvitation` | `(meta?: { name?: string }) => Promise` | Single-use invitation for one guest; repeatable: one per guest. `meta.name` becomes this host's peer name on the guest side. |
15043
- | `acceptAnswer` | `(answer: MeshAnswer) => Promise` | Verifies proof + approval, then resolves once the channel opens. Rejects `MeshPairingError` (unknown/expired/duplicate session, duplicate peer id, proof mismatch, refusal) or `MeshTimeoutError`. |
15044
- | `peers` | `ReadonlyMap` | Live peer inventory keyed by peer id. |
15045
- | `send` | `(peerId: string, type: K, payload: P['toGuest'][K]) => void` | Typed unicast; throws `MeshConnectionError` for unknown/unconnected peers, `MeshPayloadError` over the cap. |
15046
- | `broadcast` | `(type: K, payload: P['toGuest'][K], options?: { except?: readonly string[] }) => void` | Sends to every connected peer not in `except`. |
15047
- | `on` | `(type: K, handler: (message: MeshInbound) => void) => Unsubscribe` | Typed inbound subscription from any guest. |
15048
- | `kick` | `(peerId: string, reason?: string) => void` | Disconnects a peer; the guest observes `'disconnected'`. |
15542
+ | Member | Signature | Purpose |
15543
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15544
+ | `createInvitation` | `(meta?: { name?: string }) => Promise` | Single-use invitation for one guest; repeatable: one per guest. `meta.name` becomes this host's peer name on the guest side. |
15545
+ | `acceptAnswer` | `(answer: MeshAnswer) => Promise` | Verifies proof + approval, then resolves once the channel opens. Rejects `MeshPairingError` (unknown/expired session, already-answered, duplicate peer id, proof mismatch, refusal) or `MeshTimeoutError`. Concurrent answers for one session serialize to a single winner; a proof mismatch leaves the invitation answerable, an `approvePeer` refusal consumes it. |
15546
+ | `peers` | `ReadonlyMap` | Live peer inventory keyed by peer id. |
15547
+ | `send` | `(peerId: string, type: K, payload: P['toGuest'][K]) => void` | Typed unicast; throws `MeshConnectionError` for unknown/unconnected peers, `MeshPayloadError` over the cap. |
15548
+ | `broadcast` | `(type: K, payload: P['toGuest'][K], options?: { except?: readonly string[] }) => void` | Sends to every connected peer not in `except`. |
15549
+ | `on` | `(type: K, handler: (message: MeshInbound) => void) => Unsubscribe` | Typed inbound subscription from any guest. |
15550
+ | `kick` | `(peerId: string, reason?: string) => void` | Disconnects a peer; the guest observes `'disconnected'`. |
15049
15551
 
15050
15552
  ## Guest Surface
15051
15553
 
@@ -15159,7 +15661,7 @@ interface MeshPeer extends MeshPeerInfo {
15159
15661
 
15160
15662
  interface MeshInbound {
15161
15663
  readonly peerId: string;
15162
- readonly messageId: string;
15664
+ /** Sender's clock at send time in epoch milliseconds: informational only, the peer clock is untrusted. */
15163
15665
  readonly sentAt: number;
15164
15666
  readonly payload: T;
15165
15667
  }
@@ -15186,7 +15688,7 @@ type MeshEvent =
15186
15688
  | {
15187
15689
  readonly type: 'message-rejected';
15188
15690
  readonly peerId: string;
15189
- readonly reason: 'too-large' | 'duplicate' | 'malformed' | 'unknown-type';
15691
+ readonly reason: 'too-large' | 'malformed' | 'unknown-type';
15190
15692
  }
15191
15693
  | { readonly type: 'ice-state'; readonly peerId: string; readonly state: string }
15192
15694
  | { readonly type: 'error'; readonly error: MeshError }
@@ -15273,6 +15775,24 @@ interface MeshRtcEvent {
15273
15775
  }
15274
15776
  ```
15275
15777
 
15778
+ ## Testing (`@vielzeug/mesh/testing`)
15779
+
15780
+ `createFakeRtc(options?: { latencyMs?: number })` returns a `FakeRtc`: an in-memory WebRTC stand-in whose peer connections wire together through fake SDP tokens. Pass `fx.rtc` as the `rtc` option of `createMeshHost`/`createMeshGuest`. Links are indexed by pairing order (the first created offer is link `0`).
15781
+
15782
+ | Member | Signature | Purpose |
15783
+ | -------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15784
+ | `rtc` | `MeshRtcFactory` | The factory to inject. |
15785
+ | `latencyMs` | `number` | Delivery delay for messages and channel-open. Default `0` (microtask). |
15786
+ | `linkCount` | `number` | Number of links initiated (one per created offer). |
15787
+ | `remoteSdps` | `readonly string[]` | Every SDP handed to `setRemoteDescription`, in call order. |
15788
+ | `closeChannel` | `(index: number) => void` | Closes both ends of link `index` and moves its ICE to `disconnected`: the real disconnect path. |
15789
+ | `blipIce` | `(index: number) => void` | Transient ICE blip on link `index`: both connections go `disconnected` then back to `connected` on the next scheduled delivery, leaving the data channels open. |
15790
+ | `dropNext` | `(n: number) => void` | Silently drops the next `n` channel sends. |
15791
+ | `failIce` | `() => void` | Makes the next pairing fail at the ICE stage. |
15792
+ | `stallIce` | `() => void` | Makes the next `setLocalDescription` never finish ICE gathering. |
15793
+ | `hangOpen` | `() => void` | Makes the next completed link connect at ICE level but never open the channel. |
15794
+ | `tick` | `() => void` | Drains all latency-queued deliveries immediately. |
15795
+
15276
15796
  ## Errors
15277
15797
 
15278
15798
  | Class | Thrown when | Notable properties |
@@ -15382,10 +15902,9 @@ host.broadcast('ack', { ok: true }, { except: [peerId] }); // all but one
15382
15902
  guest.send('note', 'from the guest');
15383
15903
  ```
15384
15904
 
15385
- Inbound messages arrive as `MeshInbound`: `{ peerId, messageId, sentAt, payload }`. Rules:
15905
+ Inbound messages arrive as `MeshInbound`: `{ peerId, sentAt, payload }`. Rules:
15386
15906
 
15387
15907
  - Payloads over `maxMessageBytes` (default 65 536) throw `MeshPayloadError` outbound; oversized inbound frames are dropped and tapped as `'message-rejected'` with reason `'too-large'`.
15388
- - Duplicate message ids (e.g. after a retry) are dropped and tapped as `'duplicate'`.
15389
15908
  - A type with no registered `on` handler is tapped as `'unknown-type'`: never thrown.
15390
15909
  - `send` to an unknown or unconnected peer throws `MeshConnectionError`.
15391
15910
 
@@ -15410,7 +15929,7 @@ host.tap((event) => {
15410
15929
  host.kick(peerId, 'bye'); // guest observes 'disconnected'
15411
15930
  ```
15412
15931
 
15413
- `status-change` reports node-level transitions; `peer-status-change` reports a single peer moving between `'connecting' | 'connected' | 'disconnected' | 'failed'`. A guest whose host peer failed or disconnected can re-pair on the same node: call `acceptInvitation` again with a fresh invitation and existing `on`/`tap` listeners keep working.
15932
+ `status-change` reports node-level transitions; `peer-status-change` reports a single peer moving between `'connecting' | 'connected' | 'disconnected' | 'failed'`. A peer reports `'disconnected'` when its data channel closes: transient ICE `disconnected` blips that recover leave the peer untouched and surface only as `'ice-state'` tap events. A guest whose host peer failed or disconnected can re-pair on the same node: call `acceptInvitation` again with a fresh invitation and existing `on`/`tap` listeners keep working.
15414
15933
 
15415
15934
  Dispose nodes deterministically: `dispose()` is idempotent, aborts `disposalSignal`, emits a final `'dispose'` event, and detaches all tappers. Passing an `AbortSignal` option disposes on abort; `using` works too.
15416
15935
 
@@ -15437,7 +15956,7 @@ Mesh reduces the manual-pairing attack surface but does not remove it:
15437
15956
 
15438
15957
  ## Testing
15439
15958
 
15440
- Every WebRTC object comes from the injectable `rtc` factory: tests pair nodes fully in memory, with no browser. `@vielzeug/mesh/testing` ships the in-memory fake the package's own tests use: two peer connections wired through token SDP, with knobs for latency, drops, ICE failure, stalled gathering, and a never-opening channel.
15959
+ Every WebRTC object comes from the injectable `rtc` factory: tests pair nodes fully in memory, with no browser. `@vielzeug/mesh/testing` ships the in-memory fake the package's own tests use: two peer connections wired through token SDP, with knobs for latency, drops, ICE failure, transient ICE blips, stalled gathering, and a never-opening channel.
15441
15960
 
15442
15961
  ```ts
15443
15962
  import { createFakeRtc } from '@vielzeug/mesh/testing';
@@ -15445,6 +15964,10 @@ import { createFakeRtc } from '@vielzeug/mesh/testing';
15445
15964
  const fx = createFakeRtc();
15446
15965
  const host = createMeshHost({ rtc: fx.rtc, clock: () => now });
15447
15966
  const guest = createMeshGuest({ rtc: fx.rtc });
15967
+
15968
+ // Link 0 goes ICE `disconnected` and back to `connected` on the next
15969
+ // scheduled delivery, without touching the data channels.
15970
+ fx.blipIce(0);
15448
15971
  ```
15449
15972
 
15450
15973
  The [REPL examples](/repl) include a runnable in-memory pairing you can copy as a starting point.
@@ -18103,6 +18626,11 @@ define('signup-form', {
18103
18626
  - [Form Associated Rating Input](./examples/form-associated-rating-input.md)
18104
18627
  - [Test Example With @vielzeug/ore/testing](./examples/test-example-at-vielzeug-ore-testing.md)
18105
18628
 
18629
+ ### REPL Examples
18630
+
18631
+ - Counter chip (id: `counter-chip`)
18632
+ - Todo list (id: `todo-list`)
18633
+
18106
18634
  ---
18107
18635
 
18108
18636
  ## @vielzeug/patchwork
@@ -18429,6 +18957,7 @@ that is the `from` location when the source was missing.
18429
18957
  - Apply - Immutable patches and guarded test (id: `apply-basic`)
18430
18958
  - Diff - Structural patches (id: `diff-basic`)
18431
18959
  - Merge - Three-way field-level reconciliation (id: `merge-basic`)
18960
+ - getIn - JSON Pointer Round-Trips (id: `pointers-basic`)
18432
18961
 
18433
18962
  ---
18434
18963
 
@@ -21346,6 +21875,11 @@ Use Refine components for dashboard controls and keep Prism in a sized host elem
21346
21875
  - [Render a custom tooltip](./examples/custom-tooltip.md)
21347
21876
  - [Match charts to your design system](./examples/theming.md)
21348
21877
 
21878
+ ### REPL Examples
21879
+
21880
+ - Bar chart (id: `bar-chart`)
21881
+ - Line chart (id: `line-chart`)
21882
+
21349
21883
  ---
21350
21884
 
21351
21885
  ## @vielzeug/pulse
@@ -22965,6 +23499,11 @@ Use Necromancer directly when you need animation handles, groups, or explicit ke
22965
23499
  - **Working with AI agents?** Install the `vielzeug` skill (`npx -y @vielzeug/codex skills install`) so agents reach for Refine components and tokens instead of custom widgets: see the [Codex usage guide](../codex/usage.md#agent-skill).
22966
23500
  - **Rendering model-authored UI?** Validate it through the [on-demand UI document contract](./on-demand-ui) instead of trusting model output; never build DOM from unvalidated JSON.
22967
23501
 
23502
+ ### REPL Examples
23503
+
23504
+ - Themed components (id: `components`)
23505
+ - Form controls (id: `form`)
23506
+
22968
23507
  ---
22969
23508
 
22970
23509
  ## @vielzeug/ripple
@@ -25697,7 +26236,7 @@ const matches = index.search(query);
25697
26236
  | ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |
25698
26237
  | Bundle size | ~3 KB | | ~23 KB |
25699
26238
  | Zero dependencies | | | |
25700
- | Algorithm | Levenshtein | Trigram + overlap coefficient | Bitap |
26239
+ | Algorithm | Levenshtein | Trigram + query coverage | Bitap |
25701
26240
  | Query time | O(n·m) | O(candidates) | O(n·m) |
25702
26241
  | Stateful index | | | |
25703
26242
  | Match highlighting | | | |
@@ -25744,15 +26283,15 @@ console.log(results[0]?.item.name); // Ada Lovelace
25744
26283
 
25745
26284
  - `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)
25746
26285
  - Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported
25747
- - `createReactiveSearch()`: Index + reactive `SearchState` in one call; `.index` for incremental mutations
25748
- - `createSearch()`: Reactive search state backed by an existing `ScoutIndex`; share one index across many states
26286
+ - `createSearch()`: Reactive search state backed by a `ScoutIndex`; share one index across many states
25749
26287
  - `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering
25750
26288
  - `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)
25751
26289
  - `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`
25752
26290
  - `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries
25753
- - `setItems()`: Reconcile a refreshed corpus by reference, preserve incoming order, and notify once
26291
+ - `setItems()`: Reconcile a refreshed corpus by key, preserve incoming order, and notify once
26292
+ - `key` option + `removeKey()`: Stable item identity for immutable data; skip unchanged work with fresh copies and delete by id
25754
26293
  - Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)
25755
- - `onMutate()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation
26294
+ - `subscribe()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation
25756
26295
  - `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`
25757
26296
 
25758
26297
  ## Documentation
@@ -25770,25 +26309,25 @@ console.log(results[0]?.item.name); // Ada Lovelace
25770
26309
 
25771
26310
  ## API Overview
25772
26311
 
25773
- | Symbol | Purpose | Execution mode | Common gotcha |
25774
- | ------------------------ | --------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------- |
25775
- | `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |
25776
- | `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |
25777
- | `ScoutIndex.add()` | Add one item to the index | Sync | No-op if same reference already indexed |
25778
- | `ScoutIndex.remove()` | Remove one item by reference | Sync | No-op for unknown references |
25779
- | `ScoutIndex.reindex()` | Re-index a mutated item in-place; preserves order | Sync | Call after mutating item properties; no-op if not in index |
25780
- | `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses reference identity; duplicate references collapse |
25781
- | `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |
25782
- | `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |
25783
- | `ScoutIndex.onMutate()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |
25784
- | `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |
25785
- | `createReactiveSearch()` | One-call index + reactive search state | Sync | Exposes `.index` for incremental mutations |
25786
- | `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end]` ranges |
25787
- | `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |
25788
- | `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |
25789
- | `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |
25790
- | `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |
25791
- | `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `tokenize()` itself (see Pitfalls) |
26312
+ | Symbol | Purpose | Execution mode | Common gotcha |
26313
+ | ------------------------ | --------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------ |
26314
+ | `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |
26315
+ | `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |
26316
+ | `ScoutIndex.add()` | Add one item to the index | Sync | An existing key adopts the new object; without a `key`, same reference is a no-op |
26317
+ | `ScoutIndex.remove()` | Remove the item stored under `key(item)` | Sync | No-op for unknown keys |
26318
+ | `ScoutIndex.removeKey()` | Remove the item stored under a raw key | Sync | Returns whether an item was removed |
26319
+ | `ScoutIndex.reindex()` | Store `item` under its key and reindex changed fields | Sync | With a `key`, a fresh copy of the item is enough; no-op for unknown keys |
26320
+ | `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses key identity (reference by default); equal fresh copies notify nothing |
26321
+ | `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |
26322
+ | `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |
26323
+ | `ScoutIndex.subscribe()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |
26324
+ | `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |
26325
+ | `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end)` ranges in the original text |
26326
+ | `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |
26327
+ | `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |
26328
+ | `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |
26329
+ | `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |
26330
+ | `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `normalize()` itself (see Pitfalls) |
25792
26331
 
25793
26332
  ## Package Entry Point
25794
26333
 
@@ -25800,19 +26339,20 @@ console.log(results[0]?.item.name); // Ada Lovelace
25800
26339
 
25801
26340
  ## `createIndex(items, options)`
25802
26341
 
25803
- Builds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates).
26342
+ Builds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates). With a `key`, construction throws `ScoutConfigError` when two different items share one key, matching `setItems()`.
25804
26343
 
25805
26344
  ```ts
25806
- function createIndex(items: T[], options: ScoutIndexOptions): ScoutIndex;
26345
+ function createIndex(items: readonly T[], options: ScoutIndexOptions): ScoutIndex;
25807
26346
  ```
25808
26347
 
25809
26348
  **Parameters**
25810
26349
 
25811
26350
  | Param | Type | Description |
25812
26351
  | ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |
25813
- | `items` | `T[]` | Initial corpus to index. |
26352
+ | `items` | `readonly T[]` | Initial corpus to index. |
25814
26353
  | `options.fields` | `ReadonlyArray>` | Fields to index. Required; at least one entry. |
25815
- | `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |
26354
+ | `options.key` | `(item: T) => unknown` | Stable item identity for `add`/`remove`/`reindex`/`setItems` (default: object reference). |
26355
+ | `options.threshold` | `number` | Finite query-coverage score in `0..1` (default `0.2`). |
25816
26356
  | `options.limit` | `number` | Finite non-negative integer max results (default `50`). |
25817
26357
  | `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |
25818
26358
 
@@ -25854,15 +26394,23 @@ const results = index.search('alice');
25854
26394
 
25855
26395
  ### `.add(item)`
25856
26396
 
25857
- Adds `item` to the index. No-op if the same reference is already indexed. O(field_length).
26397
+ Adds `item` to the index. If another object is already stored under `key(item)`, that record adopts `item` and its changed fields are reindexed (no notification when nothing changed); without a custom `key`, re-adding the same reference is a no-op. O(field_length).
25858
26398
 
25859
26399
  ### `.remove(item)`
25860
26400
 
25861
- Removes `item` by reference equality. No-op if not found. O(field_length).
26401
+ Removes the item stored under `key(item)`. No-op if not found. O(field_length).
26402
+
26403
+ ### `.removeKey(key)`
26404
+
26405
+ ```ts
26406
+ removeKey(key: unknown): boolean
26407
+ ```
26408
+
26409
+ Removes the item stored under `key` and returns whether an item was removed. Use with a custom `key` to delete by id without fabricating a `T`.
25862
26410
 
25863
26411
  ### `.reindex(item)`
25864
26412
 
25865
- Re-reads the item's current field values and rebuilds its index entry in-place, updating only fields whose values changed. Preserves insertion order. No-op if the item is not in the index.
26413
+ Stores `item` under `key(item)`, re-reads its field values, and rebuilds its index entry in-place, updating only fields whose text changed. Preserves insertion order. With a custom `key`, passing a fresh copy of the item is enough. No-op if the key is not in the index.
25866
26414
 
25867
26415
  ```ts
25868
26416
  item.name = 'new name';
@@ -25875,7 +26423,7 @@ index.reindex(item);
25875
26423
  setItems(items: readonly T[]): void
25876
26424
  ```
25877
26425
 
25878
- Reconciles the index to a refreshed corpus in one mutation. Existing references are reindexed, missing references are removed, added references are indexed, and incoming first-occurrence order becomes index order. Duplicate references collapse to one item. Calls `onMutate()` once when indexed values, membership, or order changes.
26426
+ Reconciles the index to a refreshed corpus in one mutation by key identity (reference identity by default). Retained items adopt their incoming object and are reindexed, missing keys are removed, added keys are indexed, and incoming first-occurrence order becomes index order. Duplicate references collapse to one item; two different objects sharing one key throw `ScoutConfigError`. Calls `subscribe()` listeners once when indexed field text, membership, or order changed — reconciling an equal corpus of fresh copies notifies nothing.
25879
26427
 
25880
26428
  ```ts
25881
26429
  index.setItems(latestUsers);
@@ -25887,22 +26435,22 @@ index.setItems(latestUsers);
25887
26435
 
25888
26436
  ### `.items`
25889
26437
 
25890
- `readonly T[]`: all indexed items in insertion order. Returns a new array snapshot each call.
26438
+ `readonly T[]`: all indexed items in insertion order — the latest object stored for each key. Returns a new array snapshot each call.
25891
26439
 
25892
26440
  ```ts
25893
26441
  const all = index.items;
25894
26442
  ```
25895
26443
 
25896
- ### `.onMutate(listener)`
26444
+ ### `.subscribe(listener)`
25897
26445
 
25898
26446
  ```ts
25899
- onMutate(listener: () => void): () => void
26447
+ subscribe(listener: () => void): () => void
25900
26448
  ```
25901
26449
 
25902
26450
  Subscribes `listener` to run after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. No-ops, including unchanged bulk reconciliation, do not fire it. A changed `setItems()` reconciliation fires once. `createSearch()` uses this internally to keep `results` in sync with index mutations; most callers building on `createIndex()` directly will not need it.
25903
26451
 
25904
26452
  ```ts
25905
- const unsubscribe = index.onMutate(() => {
26453
+ const unsubscribe = index.subscribe(() => {
25906
26454
  console.log(`Index changed: now ${index.size} items`);
25907
26455
  });
25908
26456
 
@@ -25940,7 +26488,6 @@ function createSearch(index: ScoutIndex, options?: CreateSearchOptions): SearchS
25940
26488
  | `getSnapshot()` | `() => SearchSnapshot` | Returns the stable current snapshot. Identity changes only after a state transition. |
25941
26489
  | `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |
25942
26490
  | `subscribe(listener, options?)` | `(listener, options?) => () => void` | Notifies after an atomic snapshot commit. Supports `{ signal }` cleanup. |
25943
- | `tap(handler, options?)` | `(handler, options?) => () => void` | Observes typed state and disposal events. Handler errors are swallowed. |
25944
26491
  | `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |
25945
26492
  | `disposed` | `boolean` | `true` after `dispose()` has been called. |
25946
26493
  | `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |
@@ -25965,53 +26512,9 @@ search.setQuery('ada');
25965
26512
 
25966
26513
  ---
25967
26514
 
25968
- ## `createReactiveSearch(items, options)`
25969
-
25970
- Creates a `ScoutIndex` and a reactive `SearchState` in one call: the shorthand for `createIndex` + `createSearch`. Returns a `ReactiveSearch` which extends `SearchState` with a `.index` property for incremental mutations.
25971
-
25972
- ```ts
25973
- function createReactiveSearch(items: T[], options: ScoutIndexOptions & { debounce?: number }): ReactiveSearch;
25974
- ```
25975
-
25976
- **Parameters**
25977
-
25978
- | Param | Type | Description |
25979
- | ------------------------ | ---------------------------- | ----------------------------------------------------------------------- |
25980
- | `items` | `T[]` | Initial corpus to index. |
25981
- | `options.fields` | `ReadonlyArray>` | Fields to index. Required. |
25982
- | `options.debounce` | `number` | Finite non-negative integer debounce milliseconds (default `200`). |
25983
- | `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |
25984
- | `options.limit` | `number` | Finite non-negative integer max results (default `50`). |
25985
- | `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring (default `3`). |
25986
-
25987
- **Returns `ReactiveSearch`**: all `SearchState` members plus:
25988
-
25989
- | Member | Type | Description |
25990
- | ------- | --------------- | ---------------------------------------------------- |
25991
- | `index` | `ScoutIndex` | The underlying index for `add`, `remove`, `reindex`. |
25992
-
25993
- **Example**
25994
-
25995
- ```ts
25996
- import { createReactiveSearch } from '@vielzeug/scout';
25997
-
25998
- const users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];
25999
- const search = createReactiveSearch(users, {
26000
- fields: [{ field: 'name', weight: 2 }, 'email'],
26001
- debounce: 150,
26002
- });
26003
-
26004
- search.subscribe(() => console.log(search.getSnapshot().results.map((result) => result.item.name)));
26005
-
26006
- search.index.add({ email: 'grace@example.com', name: 'Grace Hopper' });
26007
- search.dispose();
26008
- ```
26009
-
26010
- ---
26011
-
26012
26515
  ## `findMatchRanges(text, query)`
26013
26516
 
26014
- Normalizes raw `query` with Scout's tokenizer, then computes sorted, non-overlapping literal ranges for each normalized token within `text`. Useful when you need to apply highlighting to a different string than the indexed field value (e.g. a truncated preview or a differently formatted display string).
26517
+ Normalizes `text` and `query` with Scout's shared normalization (lowercase, punctuation to single spaces, Latin-only accent folding), matches the whole normalized query as a phrase first, then each word individually — a one-character word matches only at a word start — merges overlaps, and maps the ranges back to the original string. Useful when you need to apply highlighting to a different string than the indexed field value (e.g. a truncated preview or a differently formatted display string).
26015
26518
 
26016
26519
  ```ts
26017
26520
  function findMatchRanges(text: string, query: string): [number, number][];
@@ -26133,7 +26636,7 @@ Splits `text` into whitespace-joined word segments using the runtime's native `I
26133
26636
  function segmentWords(text: string): string;
26134
26637
  ```
26135
26638
 
26136
- `tokenize()`'s trigram-based scoring already works on unsegmented scripts (Chinese, Japanese, Thai, ...) without this: trigrams are generated per-character, not per-word. `segmentWords()` is for `findMatchRanges()` / highlighting and the multi-word query semantics on `SearchConstraints`, which assume space-separated words. **Not applied inside `tokenize()` itself**: benchmarked at ~15x slower than the plain regex path for the common whitespace-delimited case, which would regress `createIndex()`'s construction cost for every caller, not just those indexing unsegmented scripts.
26639
+ `normalize()`'s trigram-based scoring already works on unsegmented scripts (Chinese, Japanese, Thai, ...) without this: trigrams are generated per-character, not per-word. `segmentWords()` is for `findMatchRanges()` highlighting and its phrase matching, which assume space-separated words. **Not applied inside `normalize()` itself**: benchmarked at ~15x slower than the plain regex path for the common whitespace-delimited case, which would regress `createIndex()`'s construction cost for every caller, not just those indexing unsegmented scripts.
26137
26640
 
26138
26641
  **Example**
26139
26642
 
@@ -26179,6 +26682,7 @@ type FieldDef =
26179
26682
  ```ts
26180
26683
  type ScoutIndexOptions = SearchConstraints & {
26181
26684
  fields: ReadonlyArray>;
26685
+ key?: (item: T) => unknown; // stable identity; default (item) => item
26182
26686
  };
26183
26687
  ```
26184
26688
 
@@ -26195,8 +26699,8 @@ type CreateSearchOptions = SearchConstraints & {
26195
26699
  ```ts
26196
26700
  type SearchResult = {
26197
26701
  item: T;
26198
- matches: FieldMatch[]; // literal normalized-token ranges; may be empty for fuzzy-only results
26199
- score: number; // [0, 1]; 1 when query is empty
26702
+ matches: FieldMatch[]; // literal [start, end) ranges in original field values; empty for fuzzy-only results
26703
+ score: number; // weighted query coverage in [0, 1]; 1 when query is empty
26200
26704
  };
26201
26705
  ```
26202
26706
 
@@ -26207,7 +26711,7 @@ Generic over the union of field names: `match.field` is typed to the actual fiel
26207
26711
  ```ts
26208
26712
  type FieldMatch = {
26209
26713
  field: F;
26210
- ranges: [number, number][]; // literal normalized-token [start, end] ranges in original field value
26714
+ ranges: [number, number][]; // literal [start, end) ranges in the original field value
26211
26715
  };
26212
26716
  ```
26213
26717
 
@@ -26229,12 +26733,6 @@ type SearchSnapshot = Readonly>;
26229
26733
 
26230
26734
  Snapshots and their result arrays are frozen at runtime.
26231
26735
 
26232
- ### `ScoutEvent`
26233
-
26234
- ```ts
26235
- type ScoutEvent = { readonly snapshot: SearchSnapshot; readonly type: 'state-change' };
26236
- ```
26237
-
26238
26736
  ### `SearchState`
26239
26737
 
26240
26738
  ```ts
@@ -26246,22 +26744,11 @@ type SearchState = {
26246
26744
  getSnapshot(): SearchSnapshot;
26247
26745
  setQuery(query: string): void;
26248
26746
  subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;
26249
- tap(handler: (event: ScoutEvent) => void, options?: { signal?: AbortSignal }): () => void;
26250
26747
  [Symbol.dispose](): void;
26251
26748
  };
26252
26749
  ```
26253
26750
 
26254
- `subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run. `tap()` emits `state-change` only: disposal is observable through `disposed` and `disposalSignal`; tapper errors are swallowed.
26255
-
26256
- ### `ReactiveSearch`
26257
-
26258
- ```ts
26259
- type ReactiveSearch = SearchState & {
26260
- readonly index: ScoutIndex;
26261
- };
26262
- ```
26263
-
26264
- See `createReactiveSearch()` above.
26751
+ `subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.
26265
26752
 
26266
26753
  ---
26267
26754
 
@@ -26277,10 +26764,10 @@ class ScoutError extends Error {}
26277
26764
 
26278
26765
  **Named subclasses**
26279
26766
 
26280
- | Class | Thrown when |
26281
- | -------------------- | ------------------------------------------------------------------------------- |
26282
- | `ScoutConfigError` | An index, search, or reactive search receives invalid fields or numeric options |
26283
- | `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |
26767
+ | Class | Thrown when |
26768
+ | -------------------- | ------------------------------------------------------------------------------ |
26769
+ | `ScoutConfigError` | An index or search receives invalid fields, numeric options, or duplicate keys |
26770
+ | `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |
26284
26771
 
26285
26772
  ## Entry Ranking
26286
26773
 
@@ -26371,7 +26858,7 @@ const index = createIndex(products, {
26371
26858
 
26372
26859
  ### Non-Latin scripts (CJK, Thai, ...)
26373
26860
 
26374
- `tokenize()` indexes any script correctly: trigrams are generated per-character, so Chinese, Japanese, Cyrillic, and accented Latin text are all searchable out of the box. What it doesn't do is insert word boundaries for scripts that don't use spaces (Chinese, Japanese, Thai, ...), which affects `findMatchRanges()` / highlighting and multi-word query semantics. Pre-segment those fields with `segmentWords()`:
26861
+ Scout's normalization indexes any script correctly: trigrams are generated per-character, so Chinese, Japanese, Cyrillic, and accented Latin text are all searchable out of the box. What it doesn't do is insert word boundaries for scripts that don't use spaces (Chinese, Japanese, Thai, ...), which affects `findMatchRanges()` / highlighting and multi-word phrase matching. Pre-segment those fields with `segmentWords()`:
26375
26862
 
26376
26863
  ```ts
26377
26864
  import { createIndex, segmentWords } from '@vielzeug/scout';
@@ -26385,24 +26872,26 @@ const index = createIndex(docs, {
26385
26872
  index.search('日本語'); // matches the first document
26386
26873
  ```
26387
26874
 
26388
- `segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into `tokenize()` because it benchmarks ~15x slower than the default regex path for ordinary whitespace-delimited text.
26875
+ `segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into the shared normalization because it benchmarks ~15x slower than the default regex path for ordinary whitespace-delimited text.
26389
26876
 
26390
26877
  ### Limiting results
26391
26878
 
26392
26879
  Pass `limit`, `threshold`, and `minQueryLength` in options to control result count and quality. `limit` must be a finite non-negative integer, `threshold` a finite value in `0..1`, and `minQueryLength` a finite positive integer; invalid values throw `ScoutConfigError`.
26393
26880
 
26394
26881
  ```ts
26395
- // At most 10 results, minimum overlap score 0.3
26882
+ // At most 10 results, minimum query-coverage score 0.3
26396
26883
  const results = index.search('widget', { limit: 10, threshold: 0.3 });
26397
26884
  ```
26398
26885
 
26399
26886
  Per-call options override the index-level defaults set in `createIndex`.
26400
26887
 
26401
- Scores come from the overlap (Szymkiewicz–Simpson) coefficient: the fraction of the _shorter_
26402
- trigram set (almost always the query) found in the longer one. This is deliberate for the
26403
- autocomplete/command-palette use case `createIndex` targets: a short query that's a clean prefix
26404
- of a much longer field value (e.g. `'fin'` against `'Finalize Q3 budget report'`) scores on how
26405
- much of the query matched, not diluted by how much longer the target field happens to be.
26888
+ Scores are query coverage: the fraction of the **query's** trigrams found in a field, scaled by
26889
+ that field's relative weight. `'fin'` against `'Finalize Q3 roadmap'` scores how much of the
26890
+ query was found (about `0.67`), independent of how long the field is; conversely, a long query
26891
+ like `'tomato soup recipe'` does not reward a field that merely contains part of it. Each item
26892
+ is also scored against the union of all its fields' text at the smallest field weight, so a
26893
+ cross-field query like `'alice smith'` finds `{ first: 'Alice', last: 'Smith' }` as well as one
26894
+ combined `Alice Smith` field.
26406
26895
 
26407
26896
  ### Controlling short-query behaviour
26408
26897
 
@@ -26418,17 +26907,13 @@ const results = index.search('alice', { minQueryLength: 8 });
26418
26907
 
26419
26908
  ## Reactive Search
26420
26909
 
26421
- ### `createReactiveSearch()`: recommended
26422
-
26423
- For most use cases, `createReactiveSearch` builds the index and state together. It returns one external store whose snapshot contains `query`, `isSearching`, and `results`, plus `.index` for incremental mutations:
26910
+ `createSearch()` wraps a `ScoutIndex` in one external store whose snapshot contains `query`, `isSearching`, and `results`. The index stays in your hands for incremental mutations, and one index can back several search stores:
26424
26911
 
26425
26912
  ```ts
26426
- import { createReactiveSearch } from '@vielzeug/scout';
26913
+ import { createIndex, createSearch } from '@vielzeug/scout';
26427
26914
 
26428
- const search = createReactiveSearch(users, {
26429
- fields: [{ field: 'name', weight: 2 }, 'email'],
26430
- debounce: 150,
26431
- });
26915
+ const index = createIndex(users, { fields: [{ field: 'name', weight: 2 }, 'email'] });
26916
+ const search = createSearch(index, { debounce: 150 });
26432
26917
 
26433
26918
  search.subscribe(() => {
26434
26919
  const { isSearching, results } = search.getSnapshot();
@@ -26440,28 +26925,17 @@ input.addEventListener('input', (event) => {
26440
26925
  search.setQuery((event.currentTarget as HTMLInputElement).value);
26441
26926
  });
26442
26927
 
26443
- search.index.add(newUser);
26928
+ index.add(newUser); // the search state re-runs the committed query
26444
26929
  search.dispose();
26445
26930
  ```
26446
26931
 
26447
- Each notification observes a complete committed snapshot. During a debounce window, `query` contains the latest input, `isSearching` is `true`, and `results` remain the last committed results.
26448
-
26449
- ### `createSearch()`: separate index and state
26450
-
26451
- Use `createSearch` when sharing one index across multiple search stores:
26452
-
26453
- ```ts
26454
- import { createIndex, createSearch } from '@vielzeug/scout';
26455
-
26456
- const index = createIndex(users, { fields: ['name', 'email'] });
26457
- const search = createSearch(index, { debounce: 150 });
26458
- ```
26932
+ Each notification observes a complete committed snapshot. During a debounce window, `query` contains the latest input, `isSearching` is `true`, and `results` remain the last committed results. Index mutations re-run the last committed query, so new items surface without another `setQuery()`.
26459
26933
 
26460
26934
  ### `using` declaration
26461
26935
 
26462
26936
  ```ts
26463
26937
  {
26464
- using search = createReactiveSearch(users, { fields: ['name'] });
26938
+ using search = createSearch(index, { debounce: 150 });
26465
26939
  // search.dispose() called automatically at scope exit
26466
26940
  }
26467
26941
  ```
@@ -26471,7 +26945,7 @@ const search = createSearch(index, { debounce: 150 });
26471
26945
  Pass `debounce: 0` for synchronous commits with no searching transition:
26472
26946
 
26473
26947
  ```ts
26474
- const search = createReactiveSearch(users, { fields: ['name'], debounce: 0 });
26948
+ const search = createSearch(index, { debounce: 0 });
26475
26949
 
26476
26950
  search.setQuery('alice');
26477
26951
  console.log(search.getSnapshot().results); // Already updated
@@ -26497,7 +26971,7 @@ const topResult = ripple.computed(() => state.value.results[0]?.item ?? null);
26497
26971
 
26498
26972
  ## Incremental Updates
26499
26973
 
26500
- Use `add()`, `remove()`, and `reindex()` for individual reference-based mutations. Use `setItems()` when a refreshed collection replaces the current corpus; Scout reconciles membership, current field values, and source order in one notification.
26974
+ Use `add()`, `remove()`, and `reindex()` for individual mutations. Use `setItems()` when a refreshed collection replaces the current corpus; Scout reconciles membership, current field values, and source order in one notification.
26501
26975
 
26502
26976
  ```ts
26503
26977
  const index = createIndex(products, { fields: ['title'] });
@@ -26506,7 +26980,7 @@ const index = createIndex(products, { fields: ['title'] });
26506
26980
  const newProduct = { id: 99, title: 'New Widget' };
26507
26981
  index.add(newProduct);
26508
26982
 
26509
- // Remove a deleted item (by reference)
26983
+ // Remove a deleted item (by key; the default key is the reference)
26510
26984
  index.remove(products[0]);
26511
26985
 
26512
26986
  // Re-index a mutated item after in-place mutation
@@ -26514,7 +26988,30 @@ products[1].title = 'Updated Title';
26514
26988
  index.reindex(products[1]);
26515
26989
  ```
26516
26990
 
26517
- > `remove()`, `reindex()`, and `setItems()` use **reference equality** (`===`). Pass retained object references from the current corpus; `setItems()` collapses duplicate references.
26991
+ > Without a `key`, `remove()`, `reindex()`, and `setItems()` identify items by **reference equality** (`===`): pass retained object references from the current corpus, and `setItems()` collapses duplicate references. With a `key`, any object carrying the same key works: see [Immutable data and stable keys](#immutable-data-and-stable-keys).
26992
+
26993
+ ### Immutable data and stable keys
26994
+
26995
+ If your pipeline creates fresh objects on every update (framework stores, immutable reducers, mapped projections), pass a `key` that identifies each item across generations:
26996
+
26997
+ ```ts
26998
+ const index = createIndex(products, {
26999
+ fields: ['title'],
27000
+ key: (product) => product.id,
27001
+ });
27002
+
27003
+ // setItems() with fresh copies of unchanged items: no reindex, no notification.
27004
+ // Changed keys reindex only their changed fields; missing keys drop out.
27005
+ index.setItems(await loadProducts()); // [{ id: 7, title: 'New title' }, ...]
27006
+
27007
+ // reindex() accepts any fresh object carrying the key:
27008
+ index.reindex({ id: 7, title: 'Retitled' });
27009
+
27010
+ // Or delete by key directly, without fabricating a Product:
27011
+ index.removeKey(7);
27012
+ ```
27013
+
27014
+ Two different objects that share one key — inside a single `setItems()` call or the initial `createIndex()` corpus — throw `ScoutConfigError`. Search results always return the latest object stored for each key.
26518
27015
 
26519
27016
  ### Replacing a refreshed corpus
26520
27017
 
@@ -26524,7 +27021,7 @@ const latestProducts = await loadProducts();
26524
27021
  index.setItems(latestProducts);
26525
27022
  ```
26526
27023
 
26527
- `setItems()` removes references absent from `latestProducts`, adds new references, reindexes retained references, and adopts the incoming order. It calls `onMutate()` once only when index membership, field values, or order changes.
27024
+ `setItems()` removes keys absent from `latestProducts`, indexes new keys, reindexes retained keys against their incoming objects, and adopts the incoming order. It notifies `subscribe()` listeners once, only when index membership, field text, or order changed.
26528
27025
 
26529
27026
  ### Inspecting the corpus
26530
27027
 
@@ -26537,10 +27034,10 @@ console.log(index.items); // [{ id: 1, title: ... }, ...]
26537
27034
 
26538
27035
  ### Reacting to mutations directly
26539
27036
 
26540
- `createSearch()` already keeps `results` in sync with `add()`/`remove()`/`reindex()`/`setItems()` internally. `toSearchMatcher()` also invalidates its query cache after index mutation. If you're building your own reactivity on top of a plain `ScoutIndex` (no `ripple` involved), subscribe with `onMutate()`:
27037
+ `createSearch()` already keeps `results` in sync with `add()`/`remove()`/`reindex()`/`setItems()` internally. `toSearchMatcher()` also invalidates its query cache after index mutation. If you're building your own reactivity on top of a plain `ScoutIndex` (no `ripple` involved), subscribe with `subscribe()`:
26541
27038
 
26542
27039
  ```ts
26543
- const unsubscribe = index.onMutate(() => {
27040
+ const unsubscribe = index.subscribe(() => {
26544
27041
  rerenderResultsList();
26545
27042
  });
26546
27043
 
@@ -26549,11 +27046,11 @@ index.add(newProduct); // triggers rerenderResultsList()
26549
27046
  unsubscribe(); // when done
26550
27047
  ```
26551
27048
 
26552
- `onMutate()` only fires for mutations that actually change the index: a duplicate `add()` or a `remove()` of an unindexed item is a no-op and doesn't notify listeners.
27049
+ `subscribe()` only fires for mutations that actually change the index: a duplicate `add()` or a `remove()` of an unindexed item is a no-op and doesn't notify listeners.
26553
27050
 
26554
27051
  ## Match Highlighting
26555
27052
 
26556
- Every `SearchResult` carries `matches`: per-field literal normalized-token ranges. A fuzzy trigram candidate can have `matches: []` when no literal query token appears in its field text.
27053
+ Every `SearchResult` carries `matches`: per-field literal `[start, end)` ranges into the original field value. A fuzzy trigram candidate can have `matches: []` when no literal query text appears in its field value.
26557
27054
 
26558
27055
  ### `highlightField()`: recommended
26559
27056
 
@@ -26634,43 +27131,20 @@ for (const entry of results) {
26634
27131
 
26635
27132
  Dedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.
26636
27133
 
26637
- ## Debug Logging
26638
-
26639
- Use `tap()` for typed runtime observation without affecting search behavior:
26640
-
26641
- ```ts
26642
- import { createIndex, createSearch } from '@vielzeug/scout';
26643
-
26644
- const search = createSearch(index, { debounce: 150 });
26645
- const stop = search.tap((event) => {
26646
- console.debug(event.snapshot.query, event.snapshot.isSearching, event.snapshot.results.length);
26647
- });
26648
-
26649
- search.setQuery('alice');
26650
- stop();
26651
- ```
26652
-
26653
- `tap()` emits only `state-change`; observe disposal through `disposed` or `disposalSignal`. Tapper errors are swallowed. Use `subscribe()` instead when application state must update after each snapshot commit.
26654
-
26655
- `query` carries the full, literal search query string: if your queries may carry PII (names, emails, medical/financial terms typed by end users), don't log them in production.
26656
-
26657
27134
  ## Framework Integration
26658
27135
 
26659
27136
  ```tsx [React]
26660
- import { createReactiveSearch } from '@vielzeug/scout';
27137
+ import { createIndex, createSearch } from '@vielzeug/scout';
26661
27138
  import { useEffect, useMemo, useSyncExternalStore } from 'react';
26662
27139
 
26663
27140
  type User = { id: number; name: string; email: string };
26664
27141
 
26665
27142
  function useScoutSearch(items: User[]) {
26666
- const search = useMemo(
26667
- () =>
26668
- createReactiveSearch(items, {
26669
- fields: [{ field: 'name', weight: 2 }, 'email'],
26670
- debounce: 150,
26671
- }),
26672
- [items],
26673
- );
27143
+ const search = useMemo(() => {
27144
+ const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
27145
+
27146
+ return createSearch(index, { debounce: 150 });
27147
+ }, [items]);
26674
27148
  const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);
26675
27149
 
26676
27150
  useEffect(() => () => search.dispose(), [search]);
@@ -26680,16 +27154,14 @@ function useScoutSearch(items: User[]) {
26680
27154
  ```
26681
27155
 
26682
27156
  ```ts [Vue 3]
26683
- import { createReactiveSearch } from '@vielzeug/scout';
27157
+ import { createIndex, createSearch } from '@vielzeug/scout';
26684
27158
  import { onScopeDispose, shallowRef } from 'vue';
26685
27159
 
26686
27160
  type User = { id: number; name: string; email: string };
26687
27161
 
26688
27162
  function useScoutSearch(items: User[]) {
26689
- const search = createReactiveSearch(items, {
26690
- fields: [{ field: 'name', weight: 2 }, 'email'],
26691
- debounce: 150,
26692
- });
27163
+ const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
27164
+ const search = createSearch(index, { debounce: 150 });
26693
27165
  const snapshot = shallowRef(search.getSnapshot());
26694
27166
  const stop = search.subscribe(() => {
26695
27167
  snapshot.value = search.getSnapshot();
@@ -26706,17 +27178,15 @@ function useScoutSearch(items: User[]) {
26706
27178
 
26707
27179
  ```svelte [Svelte]
26708
27180
 
26709
- import { createReactiveSearch } from '@vielzeug/scout';
27181
+ import { createIndex, createSearch } from '@vielzeug/scout';
26710
27182
  import { onDestroy } from 'svelte';
26711
27183
 
26712
27184
  type User = { id: number; name: string; email: string };
26713
27185
 
26714
27186
  export let items: User[];
26715
27187
 
26716
- const search = createReactiveSearch(items, {
26717
- fields: [{ field: 'name', weight: 2 }, 'email'],
26718
- debounce: 150,
26719
- });
27188
+ const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
27189
+ const search = createSearch(index, { debounce: 150 });
26720
27190
  let snapshot = search.getSnapshot();
26721
27191
  const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });
26722
27192
 
@@ -26768,7 +27238,8 @@ Call `toFilterPredicate` again whenever the query or corpus changes: the predica
26768
27238
  ## Best Practices
26769
27239
 
26770
27240
  - **Build the index once**: `createIndex()` runs in O(corpus × field_length). Create it at module level or in an effect, not inside render loops.
26771
- - **Keep the index in sync**: call `index.add()` / `remove()` / `reindex()` when items mutate. Stale index entries return wrong scores.
27241
+ - **Keep the index in sync**: call `index.add()` / `remove()` / `reindex()` when items mutate, or `index.setItems()` with the refreshed collection. Stale index entries return wrong scores.
27242
+ - **Set a `key` for immutable data**: when updates create fresh objects, `key: (item) => item.id` lets `setItems()` skip unchanged items and `removeKey()` delete by id.
26772
27243
  - **Tune threshold before limit**: set a meaningful `threshold` (e.g. `0.25–0.4`) to suppress noise, then use `limit` to cap the list length.
26773
27244
  - **Set `minQueryLength` for your corpus size**: the default `3` works well for most cases. Lower it for small corpora where single-char queries are expected; raise it for large corpora to avoid expensive O(n) scans.
26774
27245
  - **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.
@@ -33212,7 +33683,7 @@ sync.dispose();
33212
33683
  - **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.
33213
33684
  - **`changed()`**: wire it to your write path; the engine debounces a burst into one push.
33214
33685
  - **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.
33215
- - **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground.
33686
+ - **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground; `ambient: false` plus `autoStart: false` turn the scheduler into a pull-when-told engine for short-lived connections.
33216
33687
  - **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.
33217
33688
  - **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.
33218
33689
 
@@ -33251,13 +33722,15 @@ sync.dispose();
33251
33722
  function createSync(options: SyncOptions): SyncHandle;
33252
33723
  ```
33253
33724
 
33254
- Starts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return.
33725
+ Starts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return. `autoStart: false` defers the opening cycle to the first explicit `flush()`; `ambient: false` drops the tab-lifecycle hooks.
33255
33726
 
33256
- | Parameter | Type | Description |
33257
- | --------------------- | ---------------------- | -------------------------------------------- |
33258
- | `options.gateway` | `SyncGateway` | The device's storage seam |
33259
- | `options.idleDelayMs` | `number \| undefined` | Quiet period before a flush (default `3000`) |
33260
- | `options.port` | `SyncPort` | The server seam |
33727
+ | Parameter | Type | Description |
33728
+ | --------------------- | ---------------------- | ------------------------------------------------------------------ |
33729
+ | `options.ambient` | `boolean \| undefined` | Wire tab hide/close and foreground return to sync (default `true`) |
33730
+ | `options.autoStart` | `boolean \| undefined` | Run a full cycle on creation (default `true`) |
33731
+ | `options.gateway` | `SyncGateway` | The device's storage seam |
33732
+ | `options.idleDelayMs` | `number \| undefined` | Quiet period before a flush (default `3000`) |
33733
+ | `options.port` | `SyncPort` | The server seam |
33261
33734
 
33262
33735
  **Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.
33263
33736
 
@@ -33380,6 +33853,8 @@ interface SyncPullResult {
33380
33853
 
33381
33854
  ```ts
33382
33855
  interface SyncOptions {
33856
+ ambient?: boolean;
33857
+ autoStart?: boolean;
33383
33858
  gateway: SyncGateway;
33384
33859
  idleDelayMs?: number;
33385
33860
  port: SyncPort;
@@ -33506,6 +33981,15 @@ try {
33506
33981
 
33507
33982
  Tandem also flushes on its own: it pushes with `keepalive: true` when the tab hides or closes, and runs a full cycle when the tab returns to the foreground. Serve the keepalive push with `navigator.sendBeacon` or a `keepalive` fetch so it survives the tab closing.
33508
33983
 
33984
+ For a connection that cannot survive an ambient flush, both behaviors are options: `ambient: false` drops the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to your first `flush()` call. The boot job still loads the persisted baseline, so dirt detection works from the first tick:
33985
+
33986
+ ```ts
33987
+ const sync = createSync({ ambient: false, autoStart: false, gateway, port });
33988
+
33989
+ // Pull and push only when the app says the connection is ready:
33990
+ await sync.flush();
33991
+ ```
33992
+
33509
33993
  ## Reconcile a Rejected Push
33510
33994
 
33511
33995
  When the server is ahead of the lineage you pushed, reject the push. Tandem immediately pulls to reconcile, then the next flush retries with the merged state. Ambient flushes (debounce, hide) report the failure as a `warning` event; `flush()` additionally rejects with the port's error.
@@ -33698,7 +34182,7 @@ const host = hostTavern({
33698
34182
 
33699
34183
  **Use Tavern when** one device should own the canonical state of something: a shared document, a live dashboard, a record under review, and every other device should mirror it and send commands back through the host's own command table, which stays the single validation path.
33700
34184
 
33701
- **Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, file transfer, or custom topologies.
34185
+ **Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, or custom topologies. Mesh carries bounded typed messages (capped by `maxMessageBytes`, 65 536 by default) with no chunking or acknowledgements: file transfer needs app-level chunking and acknowledgements built on top.
33702
34186
 
33703
34187
  ## Installation
33704
34188
 
@@ -34178,6 +34662,10 @@ Pair `@vielzeug/ledger` on the host to give the commands tavern applies an undo
34178
34662
 
34179
34663
  - [Share State Across Devices](./examples/share-state-across-devices.md)
34180
34664
 
34665
+ ### REPL Examples
34666
+
34667
+ - Host & Guest Session (id: `session-basic`)
34668
+
34181
34669
  ---
34182
34670
 
34183
34671
  ## @vielzeug/tempo