@vielzeug/codex 26.11.16 → 26.11.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +47 -48
- package/data/llms-full.txt +207 -236
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +1 -1
- package/data/packages/lingua.json +2 -2
- package/data/packages/mesh.json +3 -3
- package/data/packages/scout.json +17 -20
- package/data/packages/tandem.json +3 -3
- package/data/packages/tavern.json +1 -1
- package/package.json +2 -2
package/data/llms-full.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug: Full Documentation
|
|
2
2
|
|
|
3
|
-
> Complete documentation for 46 packages. Version: 26.11.
|
|
3
|
+
> Complete documentation for 46 packages. Version: 26.11.16
|
|
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 |
|
|
@@ -14172,13 +14172,13 @@ const translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });
|
|
|
14172
14172
|
translator.translate('save');
|
|
14173
14173
|
```
|
|
14174
14174
|
|
|
14175
|
-
| Method | Signature
|
|
14176
|
-
| ------------------ |
|
|
14177
|
-
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })`
|
|
14178
|
-
| `translateUnkeyed` | `(key: string, options?)`
|
|
14175
|
+
| Method | Signature | Returns |
|
|
14176
|
+
| ------------------ | ----------------------------------------------------------------------- | --------------------------- |
|
|
14177
|
+
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |
|
|
14178
|
+
| `translateUnkeyed` | `(key: string, options?)` | Rendered string |
|
|
14179
14179
|
| `parts` | `(textKey, { values? })` or `(pluralKey, { count, ordinal?, values? })` | Render-order `Segment[]` |
|
|
14180
|
-
| `partsUnkeyed` | `(key: string, options?)`
|
|
14181
|
-
| `locale` | `Locale`
|
|
14180
|
+
| `partsUnkeyed` | `(key: string, options?)` | Render-order `Segment[]` |
|
|
14181
|
+
| `locale` | `Locale` | Resolved active locale |
|
|
14182
14182
|
|
|
14183
14183
|
---
|
|
14184
14184
|
|
|
@@ -14245,15 +14245,15 @@ const segments = i18n.parts('link', { values: { label: Sync } });
|
|
|
14245
14245
|
// [ { type: 'text', value: 'Go to ' }, { type: 'value', name: 'label', value: }, { type: 'text', value: ' now.' } ]
|
|
14246
14246
|
```
|
|
14247
14247
|
|
|
14248
|
-
| Contract
|
|
14249
|
-
|
|
|
14250
|
-
| Order
|
|
14251
|
-
| Text
|
|
14252
|
-
| Values
|
|
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
|
|
14255
|
-
| Plural
|
|
14256
|
-
| Equivalence
|
|
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 |
|
|
14257
14257
|
|
|
14258
14258
|
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
14259
|
|
|
@@ -14777,11 +14777,15 @@ export function useI18n(i18n: I18n) {
|
|
|
14777
14777
|
locale,
|
|
14778
14778
|
t: i18n.translate.bind(i18n),
|
|
14779
14779
|
rich: (key: TextKey, values: Record) =>
|
|
14780
|
-
i18n
|
|
14781
|
-
|
|
14782
|
-
|
|
14783
|
-
|
|
14784
|
-
|
|
14780
|
+
i18n
|
|
14781
|
+
.parts(key, { values })
|
|
14782
|
+
.map((segment, index) =>
|
|
14783
|
+
segment.type === 'text' ? (
|
|
14784
|
+
segment.value
|
|
14785
|
+
) : (
|
|
14786
|
+
{segment.value}
|
|
14787
|
+
),
|
|
14788
|
+
),
|
|
14785
14789
|
}),
|
|
14786
14790
|
[locale],
|
|
14787
14791
|
);
|
|
@@ -14852,7 +14856,7 @@ const pc = new RTCPeerConnection();
|
|
|
14852
14856
|
const dc = pc.createDataChannel('sync');
|
|
14853
14857
|
await pc.setLocalDescription(await pc.createOffer());
|
|
14854
14858
|
// …wait for ICE, hand the SDP to the other device, wire expiry, timeouts,
|
|
14855
|
-
// message framing
|
|
14859
|
+
// and message framing yourself: per guest
|
|
14856
14860
|
|
|
14857
14861
|
// After
|
|
14858
14862
|
const host = createMeshHost();
|
|
@@ -14975,9 +14979,10 @@ try {
|
|
|
14975
14979
|
|
|
14976
14980
|
## Package Entry Point
|
|
14977
14981
|
|
|
14978
|
-
| Import
|
|
14979
|
-
|
|
|
14980
|
-
| `@vielzeug/mesh`
|
|
14982
|
+
| Import | Purpose |
|
|
14983
|
+
| ------------------------ | --------------------------------------------- |
|
|
14984
|
+
| `@vielzeug/mesh` | Complete public Mesh API |
|
|
14985
|
+
| `@vielzeug/mesh/testing` | In-memory WebRTC fake for browserless testing |
|
|
14981
14986
|
|
|
14982
14987
|
## Factory Functions
|
|
14983
14988
|
|
|
@@ -15037,15 +15042,15 @@ const answer = await guest.acceptInvitation(meshCodec.decode(invitationText), {
|
|
|
15037
15042
|
|
|
15038
15043
|
`MeshHost` extends `MeshNode`.
|
|
15039
15044
|
|
|
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
|
|
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'`.
|
|
15045
|
+
| Member | Signature | Purpose |
|
|
15046
|
+
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
15047
|
+
| `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. |
|
|
15048
|
+
| `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. |
|
|
15049
|
+
| `peers` | `ReadonlyMap` | Live peer inventory keyed by peer id. |
|
|
15050
|
+
| `send` | `(peerId: string, type: K, payload: P['toGuest'][K]) => void` | Typed unicast; throws `MeshConnectionError` for unknown/unconnected peers, `MeshPayloadError` over the cap. |
|
|
15051
|
+
| `broadcast` | `(type: K, payload: P['toGuest'][K], options?: { except?: readonly string[] }) => void` | Sends to every connected peer not in `except`. |
|
|
15052
|
+
| `on` | `(type: K, handler: (message: MeshInbound) => void) => Unsubscribe` | Typed inbound subscription from any guest. |
|
|
15053
|
+
| `kick` | `(peerId: string, reason?: string) => void` | Disconnects a peer; the guest observes `'disconnected'`. |
|
|
15049
15054
|
|
|
15050
15055
|
## Guest Surface
|
|
15051
15056
|
|
|
@@ -15159,7 +15164,7 @@ interface MeshPeer extends MeshPeerInfo {
|
|
|
15159
15164
|
|
|
15160
15165
|
interface MeshInbound {
|
|
15161
15166
|
readonly peerId: string;
|
|
15162
|
-
|
|
15167
|
+
/** Sender's clock at send time in epoch milliseconds: informational only, the peer clock is untrusted. */
|
|
15163
15168
|
readonly sentAt: number;
|
|
15164
15169
|
readonly payload: T;
|
|
15165
15170
|
}
|
|
@@ -15186,7 +15191,7 @@ type MeshEvent =
|
|
|
15186
15191
|
| {
|
|
15187
15192
|
readonly type: 'message-rejected';
|
|
15188
15193
|
readonly peerId: string;
|
|
15189
|
-
readonly reason: 'too-large' | '
|
|
15194
|
+
readonly reason: 'too-large' | 'malformed' | 'unknown-type';
|
|
15190
15195
|
}
|
|
15191
15196
|
| { readonly type: 'ice-state'; readonly peerId: string; readonly state: string }
|
|
15192
15197
|
| { readonly type: 'error'; readonly error: MeshError }
|
|
@@ -15273,6 +15278,24 @@ interface MeshRtcEvent {
|
|
|
15273
15278
|
}
|
|
15274
15279
|
```
|
|
15275
15280
|
|
|
15281
|
+
## Testing (`@vielzeug/mesh/testing`)
|
|
15282
|
+
|
|
15283
|
+
`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`).
|
|
15284
|
+
|
|
15285
|
+
| Member | Signature | Purpose |
|
|
15286
|
+
| -------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
15287
|
+
| `rtc` | `MeshRtcFactory` | The factory to inject. |
|
|
15288
|
+
| `latencyMs` | `number` | Delivery delay for messages and channel-open. Default `0` (microtask). |
|
|
15289
|
+
| `linkCount` | `number` | Number of links initiated (one per created offer). |
|
|
15290
|
+
| `remoteSdps` | `readonly string[]` | Every SDP handed to `setRemoteDescription`, in call order. |
|
|
15291
|
+
| `closeChannel` | `(index: number) => void` | Closes both ends of link `index` and moves its ICE to `disconnected`: the real disconnect path. |
|
|
15292
|
+
| `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. |
|
|
15293
|
+
| `dropNext` | `(n: number) => void` | Silently drops the next `n` channel sends. |
|
|
15294
|
+
| `failIce` | `() => void` | Makes the next pairing fail at the ICE stage. |
|
|
15295
|
+
| `stallIce` | `() => void` | Makes the next `setLocalDescription` never finish ICE gathering. |
|
|
15296
|
+
| `hangOpen` | `() => void` | Makes the next completed link connect at ICE level but never open the channel. |
|
|
15297
|
+
| `tick` | `() => void` | Drains all latency-queued deliveries immediately. |
|
|
15298
|
+
|
|
15276
15299
|
## Errors
|
|
15277
15300
|
|
|
15278
15301
|
| Class | Thrown when | Notable properties |
|
|
@@ -15382,10 +15405,9 @@ host.broadcast('ack', { ok: true }, { except: [peerId] }); // all but one
|
|
|
15382
15405
|
guest.send('note', 'from the guest');
|
|
15383
15406
|
```
|
|
15384
15407
|
|
|
15385
|
-
Inbound messages arrive as `MeshInbound`: `{ peerId,
|
|
15408
|
+
Inbound messages arrive as `MeshInbound`: `{ peerId, sentAt, payload }`. Rules:
|
|
15386
15409
|
|
|
15387
15410
|
- 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
15411
|
- A type with no registered `on` handler is tapped as `'unknown-type'`: never thrown.
|
|
15390
15412
|
- `send` to an unknown or unconnected peer throws `MeshConnectionError`.
|
|
15391
15413
|
|
|
@@ -15410,7 +15432,7 @@ host.tap((event) => {
|
|
|
15410
15432
|
host.kick(peerId, 'bye'); // guest observes 'disconnected'
|
|
15411
15433
|
```
|
|
15412
15434
|
|
|
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.
|
|
15435
|
+
`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
15436
|
|
|
15415
15437
|
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
15438
|
|
|
@@ -15437,7 +15459,7 @@ Mesh reduces the manual-pairing attack surface but does not remove it:
|
|
|
15437
15459
|
|
|
15438
15460
|
## Testing
|
|
15439
15461
|
|
|
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.
|
|
15462
|
+
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
15463
|
|
|
15442
15464
|
```ts
|
|
15443
15465
|
import { createFakeRtc } from '@vielzeug/mesh/testing';
|
|
@@ -15445,6 +15467,10 @@ import { createFakeRtc } from '@vielzeug/mesh/testing';
|
|
|
15445
15467
|
const fx = createFakeRtc();
|
|
15446
15468
|
const host = createMeshHost({ rtc: fx.rtc, clock: () => now });
|
|
15447
15469
|
const guest = createMeshGuest({ rtc: fx.rtc });
|
|
15470
|
+
|
|
15471
|
+
// Link 0 goes ICE `disconnected` and back to `connected` on the next
|
|
15472
|
+
// scheduled delivery, without touching the data channels.
|
|
15473
|
+
fx.blipIce(0);
|
|
15448
15474
|
```
|
|
15449
15475
|
|
|
15450
15476
|
The [REPL examples](/repl) include a runnable in-memory pairing you can copy as a starting point.
|
|
@@ -25697,7 +25723,7 @@ const matches = index.search(query);
|
|
|
25697
25723
|
| ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |
|
|
25698
25724
|
| Bundle size | ~3 KB | | ~23 KB |
|
|
25699
25725
|
| Zero dependencies | | | |
|
|
25700
|
-
| Algorithm | Levenshtein | Trigram +
|
|
25726
|
+
| Algorithm | Levenshtein | Trigram + query coverage | Bitap |
|
|
25701
25727
|
| Query time | O(n·m) | O(candidates) | O(n·m) |
|
|
25702
25728
|
| Stateful index | | | |
|
|
25703
25729
|
| Match highlighting | | | |
|
|
@@ -25744,15 +25770,15 @@ console.log(results[0]?.item.name); // Ada Lovelace
|
|
|
25744
25770
|
|
|
25745
25771
|
- `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)
|
|
25746
25772
|
- Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported
|
|
25747
|
-
- `
|
|
25748
|
-
- `createSearch()`: Reactive search state backed by an existing `ScoutIndex`; share one index across many states
|
|
25773
|
+
- `createSearch()`: Reactive search state backed by a `ScoutIndex`; share one index across many states
|
|
25749
25774
|
- `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering
|
|
25750
25775
|
- `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)
|
|
25751
25776
|
- `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`
|
|
25752
25777
|
- `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries
|
|
25753
|
-
- `setItems()`: Reconcile a refreshed corpus by
|
|
25778
|
+
- `setItems()`: Reconcile a refreshed corpus by key, preserve incoming order, and notify once
|
|
25779
|
+
- `key` option + `removeKey()`: Stable item identity for immutable data; skip unchanged work with fresh copies and delete by id
|
|
25754
25780
|
- Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)
|
|
25755
|
-
- `
|
|
25781
|
+
- `subscribe()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation
|
|
25756
25782
|
- `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`
|
|
25757
25783
|
|
|
25758
25784
|
## Documentation
|
|
@@ -25770,25 +25796,25 @@ console.log(results[0]?.item.name); // Ada Lovelace
|
|
|
25770
25796
|
|
|
25771
25797
|
## API Overview
|
|
25772
25798
|
|
|
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 |
|
|
25778
|
-
| `ScoutIndex.remove()` | Remove
|
|
25779
|
-
| `ScoutIndex.
|
|
25780
|
-
| `ScoutIndex.
|
|
25781
|
-
| `ScoutIndex.
|
|
25782
|
-
| `ScoutIndex.
|
|
25783
|
-
| `ScoutIndex.
|
|
25784
|
-
| `
|
|
25785
|
-
| `
|
|
25786
|
-
| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end
|
|
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 `
|
|
25799
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
25800
|
+
| ------------------------ | --------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------ |
|
|
25801
|
+
| `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |
|
|
25802
|
+
| `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |
|
|
25803
|
+
| `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 |
|
|
25804
|
+
| `ScoutIndex.remove()` | Remove the item stored under `key(item)` | Sync | No-op for unknown keys |
|
|
25805
|
+
| `ScoutIndex.removeKey()` | Remove the item stored under a raw key | Sync | Returns whether an item was removed |
|
|
25806
|
+
| `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 |
|
|
25807
|
+
| `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses key identity (reference by default); equal fresh copies notify nothing |
|
|
25808
|
+
| `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |
|
|
25809
|
+
| `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |
|
|
25810
|
+
| `ScoutIndex.subscribe()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |
|
|
25811
|
+
| `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |
|
|
25812
|
+
| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end)` ranges in the original text |
|
|
25813
|
+
| `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |
|
|
25814
|
+
| `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |
|
|
25815
|
+
| `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |
|
|
25816
|
+
| `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |
|
|
25817
|
+
| `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `normalize()` itself (see Pitfalls) |
|
|
25792
25818
|
|
|
25793
25819
|
## Package Entry Point
|
|
25794
25820
|
|
|
@@ -25800,19 +25826,20 @@ console.log(results[0]?.item.name); // Ada Lovelace
|
|
|
25800
25826
|
|
|
25801
25827
|
## `createIndex(items, options)`
|
|
25802
25828
|
|
|
25803
|
-
Builds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates).
|
|
25829
|
+
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
25830
|
|
|
25805
25831
|
```ts
|
|
25806
|
-
function createIndex(items: T[], options: ScoutIndexOptions): ScoutIndex;
|
|
25832
|
+
function createIndex(items: readonly T[], options: ScoutIndexOptions): ScoutIndex;
|
|
25807
25833
|
```
|
|
25808
25834
|
|
|
25809
25835
|
**Parameters**
|
|
25810
25836
|
|
|
25811
25837
|
| Param | Type | Description |
|
|
25812
25838
|
| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
25813
|
-
| `items` | `T[]`
|
|
25839
|
+
| `items` | `readonly T[]` | Initial corpus to index. |
|
|
25814
25840
|
| `options.fields` | `ReadonlyArray>` | Fields to index. Required; at least one entry. |
|
|
25815
|
-
| `options.
|
|
25841
|
+
| `options.key` | `(item: T) => unknown` | Stable item identity for `add`/`remove`/`reindex`/`setItems` (default: object reference). |
|
|
25842
|
+
| `options.threshold` | `number` | Finite query-coverage score in `0..1` (default `0.2`). |
|
|
25816
25843
|
| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |
|
|
25817
25844
|
| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |
|
|
25818
25845
|
|
|
@@ -25854,15 +25881,23 @@ const results = index.search('alice');
|
|
|
25854
25881
|
|
|
25855
25882
|
### `.add(item)`
|
|
25856
25883
|
|
|
25857
|
-
Adds `item` to the index.
|
|
25884
|
+
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
25885
|
|
|
25859
25886
|
### `.remove(item)`
|
|
25860
25887
|
|
|
25861
|
-
Removes
|
|
25888
|
+
Removes the item stored under `key(item)`. No-op if not found. O(field_length).
|
|
25889
|
+
|
|
25890
|
+
### `.removeKey(key)`
|
|
25891
|
+
|
|
25892
|
+
```ts
|
|
25893
|
+
removeKey(key: unknown): boolean
|
|
25894
|
+
```
|
|
25895
|
+
|
|
25896
|
+
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
25897
|
|
|
25863
25898
|
### `.reindex(item)`
|
|
25864
25899
|
|
|
25865
|
-
|
|
25900
|
+
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
25901
|
|
|
25867
25902
|
```ts
|
|
25868
25903
|
item.name = 'new name';
|
|
@@ -25875,7 +25910,7 @@ index.reindex(item);
|
|
|
25875
25910
|
setItems(items: readonly T[]): void
|
|
25876
25911
|
```
|
|
25877
25912
|
|
|
25878
|
-
Reconciles the index to a refreshed corpus in one mutation.
|
|
25913
|
+
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
25914
|
|
|
25880
25915
|
```ts
|
|
25881
25916
|
index.setItems(latestUsers);
|
|
@@ -25887,22 +25922,22 @@ index.setItems(latestUsers);
|
|
|
25887
25922
|
|
|
25888
25923
|
### `.items`
|
|
25889
25924
|
|
|
25890
|
-
`readonly T[]`: all indexed items in insertion order. Returns a new array snapshot each call.
|
|
25925
|
+
`readonly T[]`: all indexed items in insertion order — the latest object stored for each key. Returns a new array snapshot each call.
|
|
25891
25926
|
|
|
25892
25927
|
```ts
|
|
25893
25928
|
const all = index.items;
|
|
25894
25929
|
```
|
|
25895
25930
|
|
|
25896
|
-
### `.
|
|
25931
|
+
### `.subscribe(listener)`
|
|
25897
25932
|
|
|
25898
25933
|
```ts
|
|
25899
|
-
|
|
25934
|
+
subscribe(listener: () => void): () => void
|
|
25900
25935
|
```
|
|
25901
25936
|
|
|
25902
25937
|
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
25938
|
|
|
25904
25939
|
```ts
|
|
25905
|
-
const unsubscribe = index.
|
|
25940
|
+
const unsubscribe = index.subscribe(() => {
|
|
25906
25941
|
console.log(`Index changed: now ${index.size} items`);
|
|
25907
25942
|
});
|
|
25908
25943
|
|
|
@@ -25940,7 +25975,6 @@ function createSearch(index: ScoutIndex, options?: CreateSearchOptions): SearchS
|
|
|
25940
25975
|
| `getSnapshot()` | `() => SearchSnapshot` | Returns the stable current snapshot. Identity changes only after a state transition. |
|
|
25941
25976
|
| `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |
|
|
25942
25977
|
| `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
25978
|
| `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |
|
|
25945
25979
|
| `disposed` | `boolean` | `true` after `dispose()` has been called. |
|
|
25946
25980
|
| `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |
|
|
@@ -25965,53 +25999,9 @@ search.setQuery('ada');
|
|
|
25965
25999
|
|
|
25966
26000
|
---
|
|
25967
26001
|
|
|
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
26002
|
## `findMatchRanges(text, query)`
|
|
26013
26003
|
|
|
26014
|
-
Normalizes
|
|
26004
|
+
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
26005
|
|
|
26016
26006
|
```ts
|
|
26017
26007
|
function findMatchRanges(text: string, query: string): [number, number][];
|
|
@@ -26133,7 +26123,7 @@ Splits `text` into whitespace-joined word segments using the runtime's native `I
|
|
|
26133
26123
|
function segmentWords(text: string): string;
|
|
26134
26124
|
```
|
|
26135
26125
|
|
|
26136
|
-
`
|
|
26126
|
+
`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
26127
|
|
|
26138
26128
|
**Example**
|
|
26139
26129
|
|
|
@@ -26179,6 +26169,7 @@ type FieldDef =
|
|
|
26179
26169
|
```ts
|
|
26180
26170
|
type ScoutIndexOptions = SearchConstraints & {
|
|
26181
26171
|
fields: ReadonlyArray>;
|
|
26172
|
+
key?: (item: T) => unknown; // stable identity; default (item) => item
|
|
26182
26173
|
};
|
|
26183
26174
|
```
|
|
26184
26175
|
|
|
@@ -26195,8 +26186,8 @@ type CreateSearchOptions = SearchConstraints & {
|
|
|
26195
26186
|
```ts
|
|
26196
26187
|
type SearchResult = {
|
|
26197
26188
|
item: T;
|
|
26198
|
-
matches: FieldMatch[]; // literal
|
|
26199
|
-
score: number; // [0, 1]; 1 when query is empty
|
|
26189
|
+
matches: FieldMatch[]; // literal [start, end) ranges in original field values; empty for fuzzy-only results
|
|
26190
|
+
score: number; // weighted query coverage in [0, 1]; 1 when query is empty
|
|
26200
26191
|
};
|
|
26201
26192
|
```
|
|
26202
26193
|
|
|
@@ -26207,7 +26198,7 @@ Generic over the union of field names: `match.field` is typed to the actual fiel
|
|
|
26207
26198
|
```ts
|
|
26208
26199
|
type FieldMatch = {
|
|
26209
26200
|
field: F;
|
|
26210
|
-
ranges: [number, number][]; // literal
|
|
26201
|
+
ranges: [number, number][]; // literal [start, end) ranges in the original field value
|
|
26211
26202
|
};
|
|
26212
26203
|
```
|
|
26213
26204
|
|
|
@@ -26229,12 +26220,6 @@ type SearchSnapshot = Readonly>;
|
|
|
26229
26220
|
|
|
26230
26221
|
Snapshots and their result arrays are frozen at runtime.
|
|
26231
26222
|
|
|
26232
|
-
### `ScoutEvent`
|
|
26233
|
-
|
|
26234
|
-
```ts
|
|
26235
|
-
type ScoutEvent = { readonly snapshot: SearchSnapshot; readonly type: 'state-change' };
|
|
26236
|
-
```
|
|
26237
|
-
|
|
26238
26223
|
### `SearchState`
|
|
26239
26224
|
|
|
26240
26225
|
```ts
|
|
@@ -26246,22 +26231,11 @@ type SearchState = {
|
|
|
26246
26231
|
getSnapshot(): SearchSnapshot;
|
|
26247
26232
|
setQuery(query: string): void;
|
|
26248
26233
|
subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;
|
|
26249
|
-
tap(handler: (event: ScoutEvent) => void, options?: { signal?: AbortSignal }): () => void;
|
|
26250
26234
|
[Symbol.dispose](): void;
|
|
26251
26235
|
};
|
|
26252
26236
|
```
|
|
26253
26237
|
|
|
26254
|
-
`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.
|
|
26255
|
-
|
|
26256
|
-
### `ReactiveSearch`
|
|
26257
|
-
|
|
26258
|
-
```ts
|
|
26259
|
-
type ReactiveSearch = SearchState & {
|
|
26260
|
-
readonly index: ScoutIndex;
|
|
26261
|
-
};
|
|
26262
|
-
```
|
|
26263
|
-
|
|
26264
|
-
See `createReactiveSearch()` above.
|
|
26238
|
+
`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.
|
|
26265
26239
|
|
|
26266
26240
|
---
|
|
26267
26241
|
|
|
@@ -26277,10 +26251,10 @@ class ScoutError extends Error {}
|
|
|
26277
26251
|
|
|
26278
26252
|
**Named subclasses**
|
|
26279
26253
|
|
|
26280
|
-
| Class | Thrown when
|
|
26281
|
-
| -------------------- |
|
|
26282
|
-
| `ScoutConfigError` | An index
|
|
26283
|
-
| `ScoutDisposedError` | A method is called on a disposed `SearchState` instance
|
|
26254
|
+
| Class | Thrown when |
|
|
26255
|
+
| -------------------- | ------------------------------------------------------------------------------ |
|
|
26256
|
+
| `ScoutConfigError` | An index or search receives invalid fields, numeric options, or duplicate keys |
|
|
26257
|
+
| `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |
|
|
26284
26258
|
|
|
26285
26259
|
## Entry Ranking
|
|
26286
26260
|
|
|
@@ -26371,7 +26345,7 @@ const index = createIndex(products, {
|
|
|
26371
26345
|
|
|
26372
26346
|
### Non-Latin scripts (CJK, Thai, ...)
|
|
26373
26347
|
|
|
26374
|
-
|
|
26348
|
+
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
26349
|
|
|
26376
26350
|
```ts
|
|
26377
26351
|
import { createIndex, segmentWords } from '@vielzeug/scout';
|
|
@@ -26385,24 +26359,26 @@ const index = createIndex(docs, {
|
|
|
26385
26359
|
index.search('日本語'); // matches the first document
|
|
26386
26360
|
```
|
|
26387
26361
|
|
|
26388
|
-
`segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into
|
|
26362
|
+
`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
26363
|
|
|
26390
26364
|
### Limiting results
|
|
26391
26365
|
|
|
26392
26366
|
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
26367
|
|
|
26394
26368
|
```ts
|
|
26395
|
-
// At most 10 results, minimum
|
|
26369
|
+
// At most 10 results, minimum query-coverage score 0.3
|
|
26396
26370
|
const results = index.search('widget', { limit: 10, threshold: 0.3 });
|
|
26397
26371
|
```
|
|
26398
26372
|
|
|
26399
26373
|
Per-call options override the index-level defaults set in `createIndex`.
|
|
26400
26374
|
|
|
26401
|
-
Scores
|
|
26402
|
-
|
|
26403
|
-
|
|
26404
|
-
|
|
26405
|
-
|
|
26375
|
+
Scores are query coverage: the fraction of the **query's** trigrams found in a field, scaled by
|
|
26376
|
+
that field's relative weight. `'fin'` against `'Finalize Q3 roadmap'` scores how much of the
|
|
26377
|
+
query was found (about `0.67`), independent of how long the field is; conversely, a long query
|
|
26378
|
+
like `'tomato soup recipe'` does not reward a field that merely contains part of it. Each item
|
|
26379
|
+
is also scored against the union of all its fields' text at the smallest field weight, so a
|
|
26380
|
+
cross-field query like `'alice smith'` finds `{ first: 'Alice', last: 'Smith' }` as well as one
|
|
26381
|
+
combined `Alice Smith` field.
|
|
26406
26382
|
|
|
26407
26383
|
### Controlling short-query behaviour
|
|
26408
26384
|
|
|
@@ -26418,17 +26394,13 @@ const results = index.search('alice', { minQueryLength: 8 });
|
|
|
26418
26394
|
|
|
26419
26395
|
## Reactive Search
|
|
26420
26396
|
|
|
26421
|
-
|
|
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:
|
|
26397
|
+
`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
26398
|
|
|
26425
26399
|
```ts
|
|
26426
|
-
import {
|
|
26400
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26427
26401
|
|
|
26428
|
-
const
|
|
26429
|
-
|
|
26430
|
-
debounce: 150,
|
|
26431
|
-
});
|
|
26402
|
+
const index = createIndex(users, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26403
|
+
const search = createSearch(index, { debounce: 150 });
|
|
26432
26404
|
|
|
26433
26405
|
search.subscribe(() => {
|
|
26434
26406
|
const { isSearching, results } = search.getSnapshot();
|
|
@@ -26440,28 +26412,17 @@ input.addEventListener('input', (event) => {
|
|
|
26440
26412
|
search.setQuery((event.currentTarget as HTMLInputElement).value);
|
|
26441
26413
|
});
|
|
26442
26414
|
|
|
26443
|
-
|
|
26415
|
+
index.add(newUser); // the search state re-runs the committed query
|
|
26444
26416
|
search.dispose();
|
|
26445
26417
|
```
|
|
26446
26418
|
|
|
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
|
-
```
|
|
26419
|
+
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
26420
|
|
|
26460
26421
|
### `using` declaration
|
|
26461
26422
|
|
|
26462
26423
|
```ts
|
|
26463
26424
|
{
|
|
26464
|
-
using search =
|
|
26425
|
+
using search = createSearch(index, { debounce: 150 });
|
|
26465
26426
|
// search.dispose() called automatically at scope exit
|
|
26466
26427
|
}
|
|
26467
26428
|
```
|
|
@@ -26471,7 +26432,7 @@ const search = createSearch(index, { debounce: 150 });
|
|
|
26471
26432
|
Pass `debounce: 0` for synchronous commits with no searching transition:
|
|
26472
26433
|
|
|
26473
26434
|
```ts
|
|
26474
|
-
const search =
|
|
26435
|
+
const search = createSearch(index, { debounce: 0 });
|
|
26475
26436
|
|
|
26476
26437
|
search.setQuery('alice');
|
|
26477
26438
|
console.log(search.getSnapshot().results); // Already updated
|
|
@@ -26497,7 +26458,7 @@ const topResult = ripple.computed(() => state.value.results[0]?.item ?? null);
|
|
|
26497
26458
|
|
|
26498
26459
|
## Incremental Updates
|
|
26499
26460
|
|
|
26500
|
-
Use `add()`, `remove()`, and `reindex()` for individual
|
|
26461
|
+
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
26462
|
|
|
26502
26463
|
```ts
|
|
26503
26464
|
const index = createIndex(products, { fields: ['title'] });
|
|
@@ -26506,7 +26467,7 @@ const index = createIndex(products, { fields: ['title'] });
|
|
|
26506
26467
|
const newProduct = { id: 99, title: 'New Widget' };
|
|
26507
26468
|
index.add(newProduct);
|
|
26508
26469
|
|
|
26509
|
-
// Remove a deleted item (by reference)
|
|
26470
|
+
// Remove a deleted item (by key; the default key is the reference)
|
|
26510
26471
|
index.remove(products[0]);
|
|
26511
26472
|
|
|
26512
26473
|
// Re-index a mutated item after in-place mutation
|
|
@@ -26514,7 +26475,30 @@ products[1].title = 'Updated Title';
|
|
|
26514
26475
|
index.reindex(products[1]);
|
|
26515
26476
|
```
|
|
26516
26477
|
|
|
26517
|
-
> `remove()`, `reindex()`, and `setItems()`
|
|
26478
|
+
> 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).
|
|
26479
|
+
|
|
26480
|
+
### Immutable data and stable keys
|
|
26481
|
+
|
|
26482
|
+
If your pipeline creates fresh objects on every update (framework stores, immutable reducers, mapped projections), pass a `key` that identifies each item across generations:
|
|
26483
|
+
|
|
26484
|
+
```ts
|
|
26485
|
+
const index = createIndex(products, {
|
|
26486
|
+
fields: ['title'],
|
|
26487
|
+
key: (product) => product.id,
|
|
26488
|
+
});
|
|
26489
|
+
|
|
26490
|
+
// setItems() with fresh copies of unchanged items: no reindex, no notification.
|
|
26491
|
+
// Changed keys reindex only their changed fields; missing keys drop out.
|
|
26492
|
+
index.setItems(await loadProducts()); // [{ id: 7, title: 'New title' }, ...]
|
|
26493
|
+
|
|
26494
|
+
// reindex() accepts any fresh object carrying the key:
|
|
26495
|
+
index.reindex({ id: 7, title: 'Retitled' });
|
|
26496
|
+
|
|
26497
|
+
// Or delete by key directly, without fabricating a Product:
|
|
26498
|
+
index.removeKey(7);
|
|
26499
|
+
```
|
|
26500
|
+
|
|
26501
|
+
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
26502
|
|
|
26519
26503
|
### Replacing a refreshed corpus
|
|
26520
26504
|
|
|
@@ -26524,7 +26508,7 @@ const latestProducts = await loadProducts();
|
|
|
26524
26508
|
index.setItems(latestProducts);
|
|
26525
26509
|
```
|
|
26526
26510
|
|
|
26527
|
-
`setItems()` removes
|
|
26511
|
+
`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
26512
|
|
|
26529
26513
|
### Inspecting the corpus
|
|
26530
26514
|
|
|
@@ -26537,10 +26521,10 @@ console.log(index.items); // [{ id: 1, title: ... }, ...]
|
|
|
26537
26521
|
|
|
26538
26522
|
### Reacting to mutations directly
|
|
26539
26523
|
|
|
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 `
|
|
26524
|
+
`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
26525
|
|
|
26542
26526
|
```ts
|
|
26543
|
-
const unsubscribe = index.
|
|
26527
|
+
const unsubscribe = index.subscribe(() => {
|
|
26544
26528
|
rerenderResultsList();
|
|
26545
26529
|
});
|
|
26546
26530
|
|
|
@@ -26549,11 +26533,11 @@ index.add(newProduct); // triggers rerenderResultsList()
|
|
|
26549
26533
|
unsubscribe(); // when done
|
|
26550
26534
|
```
|
|
26551
26535
|
|
|
26552
|
-
`
|
|
26536
|
+
`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
26537
|
|
|
26554
26538
|
## Match Highlighting
|
|
26555
26539
|
|
|
26556
|
-
Every `SearchResult` carries `matches`: per-field literal
|
|
26540
|
+
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
26541
|
|
|
26558
26542
|
### `highlightField()`: recommended
|
|
26559
26543
|
|
|
@@ -26634,43 +26618,20 @@ for (const entry of results) {
|
|
|
26634
26618
|
|
|
26635
26619
|
Dedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.
|
|
26636
26620
|
|
|
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
26621
|
## Framework Integration
|
|
26658
26622
|
|
|
26659
26623
|
```tsx [React]
|
|
26660
|
-
import {
|
|
26624
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26661
26625
|
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
|
26662
26626
|
|
|
26663
26627
|
type User = { id: number; name: string; email: string };
|
|
26664
26628
|
|
|
26665
26629
|
function useScoutSearch(items: User[]) {
|
|
26666
|
-
const search = useMemo(
|
|
26667
|
-
()
|
|
26668
|
-
|
|
26669
|
-
|
|
26670
|
-
|
|
26671
|
-
}),
|
|
26672
|
-
[items],
|
|
26673
|
-
);
|
|
26630
|
+
const search = useMemo(() => {
|
|
26631
|
+
const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26632
|
+
|
|
26633
|
+
return createSearch(index, { debounce: 150 });
|
|
26634
|
+
}, [items]);
|
|
26674
26635
|
const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);
|
|
26675
26636
|
|
|
26676
26637
|
useEffect(() => () => search.dispose(), [search]);
|
|
@@ -26680,16 +26641,14 @@ function useScoutSearch(items: User[]) {
|
|
|
26680
26641
|
```
|
|
26681
26642
|
|
|
26682
26643
|
```ts [Vue 3]
|
|
26683
|
-
import {
|
|
26644
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26684
26645
|
import { onScopeDispose, shallowRef } from 'vue';
|
|
26685
26646
|
|
|
26686
26647
|
type User = { id: number; name: string; email: string };
|
|
26687
26648
|
|
|
26688
26649
|
function useScoutSearch(items: User[]) {
|
|
26689
|
-
const
|
|
26690
|
-
|
|
26691
|
-
debounce: 150,
|
|
26692
|
-
});
|
|
26650
|
+
const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26651
|
+
const search = createSearch(index, { debounce: 150 });
|
|
26693
26652
|
const snapshot = shallowRef(search.getSnapshot());
|
|
26694
26653
|
const stop = search.subscribe(() => {
|
|
26695
26654
|
snapshot.value = search.getSnapshot();
|
|
@@ -26706,17 +26665,15 @@ function useScoutSearch(items: User[]) {
|
|
|
26706
26665
|
|
|
26707
26666
|
```svelte [Svelte]
|
|
26708
26667
|
|
|
26709
|
-
import {
|
|
26668
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26710
26669
|
import { onDestroy } from 'svelte';
|
|
26711
26670
|
|
|
26712
26671
|
type User = { id: number; name: string; email: string };
|
|
26713
26672
|
|
|
26714
26673
|
export let items: User[];
|
|
26715
26674
|
|
|
26716
|
-
const
|
|
26717
|
-
|
|
26718
|
-
debounce: 150,
|
|
26719
|
-
});
|
|
26675
|
+
const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26676
|
+
const search = createSearch(index, { debounce: 150 });
|
|
26720
26677
|
let snapshot = search.getSnapshot();
|
|
26721
26678
|
const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });
|
|
26722
26679
|
|
|
@@ -26768,7 +26725,8 @@ Call `toFilterPredicate` again whenever the query or corpus changes: the predica
|
|
|
26768
26725
|
## Best Practices
|
|
26769
26726
|
|
|
26770
26727
|
- **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.
|
|
26728
|
+
- **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.
|
|
26729
|
+
- **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
26730
|
- **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
26731
|
- **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
26732
|
- **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.
|
|
@@ -33212,7 +33170,7 @@ sync.dispose();
|
|
|
33212
33170
|
- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.
|
|
33213
33171
|
- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.
|
|
33214
33172
|
- **`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.
|
|
33173
|
+
- **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
33174
|
- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.
|
|
33217
33175
|
- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.
|
|
33218
33176
|
|
|
@@ -33251,13 +33209,15 @@ sync.dispose();
|
|
|
33251
33209
|
function createSync(options: SyncOptions): SyncHandle;
|
|
33252
33210
|
```
|
|
33253
33211
|
|
|
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.
|
|
33212
|
+
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
33213
|
|
|
33256
|
-
| Parameter | Type | Description
|
|
33257
|
-
| --------------------- | ---------------------- |
|
|
33258
|
-
| `options.
|
|
33259
|
-
| `options.
|
|
33260
|
-
| `options.
|
|
33214
|
+
| Parameter | Type | Description |
|
|
33215
|
+
| --------------------- | ---------------------- | ------------------------------------------------------------------ |
|
|
33216
|
+
| `options.ambient` | `boolean \| undefined` | Wire tab hide/close and foreground return to sync (default `true`) |
|
|
33217
|
+
| `options.autoStart` | `boolean \| undefined` | Run a full cycle on creation (default `true`) |
|
|
33218
|
+
| `options.gateway` | `SyncGateway` | The device's storage seam |
|
|
33219
|
+
| `options.idleDelayMs` | `number \| undefined` | Quiet period before a flush (default `3000`) |
|
|
33220
|
+
| `options.port` | `SyncPort` | The server seam |
|
|
33261
33221
|
|
|
33262
33222
|
**Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.
|
|
33263
33223
|
|
|
@@ -33380,6 +33340,8 @@ interface SyncPullResult {
|
|
|
33380
33340
|
|
|
33381
33341
|
```ts
|
|
33382
33342
|
interface SyncOptions {
|
|
33343
|
+
ambient?: boolean;
|
|
33344
|
+
autoStart?: boolean;
|
|
33383
33345
|
gateway: SyncGateway;
|
|
33384
33346
|
idleDelayMs?: number;
|
|
33385
33347
|
port: SyncPort;
|
|
@@ -33506,6 +33468,15 @@ try {
|
|
|
33506
33468
|
|
|
33507
33469
|
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
33470
|
|
|
33471
|
+
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:
|
|
33472
|
+
|
|
33473
|
+
```ts
|
|
33474
|
+
const sync = createSync({ ambient: false, autoStart: false, gateway, port });
|
|
33475
|
+
|
|
33476
|
+
// Pull and push only when the app says the connection is ready:
|
|
33477
|
+
await sync.flush();
|
|
33478
|
+
```
|
|
33479
|
+
|
|
33509
33480
|
## Reconcile a Rejected Push
|
|
33510
33481
|
|
|
33511
33482
|
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 +33669,7 @@ const host = hostTavern({
|
|
|
33698
33669
|
|
|
33699
33670
|
**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
33671
|
|
|
33701
|
-
**Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, file transfer
|
|
33672
|
+
**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
33673
|
|
|
33703
33674
|
## Installation
|
|
33704
33675
|
|