@vielzeug/codex 26.11.15 → 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 +337 -225
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +2 -2
- package/data/packages/lingua.json +25 -22
- 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/data/refine.json +115 -115
- 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
|
|
|
@@ -313,8 +313,8 @@ Magic links expire after 15 minutes and work once. The durable per-email budget
|
|
|
313
313
|
The issuer-global admission budget is durable D1 state in `auth_sign_in_budget`:
|
|
314
314
|
20 requests per 60-second window before account creation or email delivery.
|
|
315
315
|
This supplements, rather than replaces, the durable per-email budget. No external
|
|
316
|
-
rate-limiter binding is required for sign-in admission; the budgets do not cover
|
|
317
|
-
`POST /auth/verify
|
|
316
|
+
rate-limiter binding is required for either sign-in admission route; the budgets do not cover
|
|
317
|
+
`POST /auth/verify`, the device approval and claim routes, or `GET /auth/session`, which deployments rate-limit at the
|
|
318
318
|
edge. Edge rules should block rather than challenge `GET /auth/session`: clients
|
|
319
319
|
check it with a `fetch`, which cannot solve a challenge interstitial. The verify
|
|
320
320
|
GET is a browser navigation from the email link, so a challenge is solvable there.
|
|
@@ -323,6 +323,20 @@ Request emails are trimmed and lowercased before validation. `SENDER_ADDRESS`
|
|
|
323
323
|
must already be canonical; `OPERATOR_EMAILS` entries are trimmed and lowercased
|
|
324
324
|
before validation.
|
|
325
325
|
|
|
326
|
+
For isolated browser storage, device sign-in binds approval to a secret held by
|
|
327
|
+
the initiating app. Generate 32 random bytes, encode them as an unpadded base64url
|
|
328
|
+
proof, and send the lowercase SHA-256 hex of its UTF-8 representation as
|
|
329
|
+
`challenge`. The email approval page shows the first eight uppercase hex digits;
|
|
330
|
+
the app must show the same code and ask the user to compare them. Approval is
|
|
331
|
+
an explicit POST and does not sign in the confirming browser. The app claims
|
|
332
|
+
with its proof; a pending claim returns 202 and an approved one returns 204 with
|
|
333
|
+
the normal session cookie. Claim returns 409 without consuming the proof if the
|
|
334
|
+
request already carries a valid session, so it cannot replace that account.
|
|
335
|
+
Both requests require the marker and an allowed
|
|
336
|
+
origin. The proof is a credential: do not log it; retain it only until claim,
|
|
337
|
+
cancellation or expiration. Sign-out-all and account deletion revoke pending
|
|
338
|
+
approvals. Existing browser sign-in is unchanged.
|
|
339
|
+
|
|
326
340
|
Sign-in requests create pending account rows with `lastSignInAt: null`. Successful
|
|
327
341
|
redemption atomically claims the one-use link and stamps the account's sign-in
|
|
328
342
|
time. The sweep deletes expired links and closed per-user send windows, then
|
|
@@ -415,6 +429,10 @@ Every route below is mounted under `/api/v1`. Mutation guards require an exact a
|
|
|
415
429
|
| `POST /auth/sign-out-all` | Requires marker, exact origin, session and captured `ACCOUNT_HEADER`; atomically increments `session_version`, deletes outstanding links, preserves account and catalog data; 200 `{ ok: true }` with an expired cookie only on durable success |
|
|
416
430
|
| `GET /auth/jwks.json` | Active and configured retired public verification keys |
|
|
417
431
|
| `POST /auth/sign-in` | `{ email }` (trimmed and lowercased); 202 `{ ok: true }` |
|
|
432
|
+
| `POST /auth/device/sign-in` | `{ email, challenge }`; 64 lowercase SHA-256 hex digits; shared admission and email budgets; 202 `{ ok: true }` |
|
|
433
|
+
| `GET /auth/device/approve?token=…` | Non-destructive confirmation page displaying the matching code; no cookie; expired/invalid signatures return 410 recovery HTML |
|
|
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 |
|
|
418
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 |
|
|
419
437
|
| `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |
|
|
420
438
|
| `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |
|
|
@@ -845,6 +863,9 @@ type AuthEvent =
|
|
|
845
863
|
readonly requestId: string;
|
|
846
864
|
readonly route:
|
|
847
865
|
| '/auth/account'
|
|
866
|
+
| '/auth/device/approve'
|
|
867
|
+
| '/auth/device/claim'
|
|
868
|
+
| '/auth/device/sign-in'
|
|
848
869
|
| '/auth/health'
|
|
849
870
|
| '/auth/jwks.json'
|
|
850
871
|
| '/auth/session'
|
|
@@ -1089,13 +1110,14 @@ The issuer first admits sign-in requests through its singleton durable
|
|
|
1089
1110
|
`auth_sign_in_budget` table: 20 requests per 60 seconds before creating accounts
|
|
1090
1111
|
or delivering email. No rate-limiter binding is required. It then
|
|
1091
1112
|
permits three sign-in emails per email in an hourly durable window.
|
|
1092
|
-
Those durable budgets guard `POST /auth/sign-in`
|
|
1113
|
+
Those durable budgets guard `POST /auth/sign-in` and `POST /auth/device/sign-in`.
|
|
1114
|
+
`POST /auth/verify`, the device approval and claim routes, and
|
|
1093
1115
|
`GET /auth/session` stay public: tokens are 256-bit, single-use and expire in
|
|
1094
1116
|
15 minutes, so guessing is not the risk — but every request still costs the
|
|
1095
1117
|
issuer: the verify GET renders the confirmation page, the verify POST performs a
|
|
1096
1118
|
D1 token write, and the session check performs an RS256 verification plus an
|
|
1097
1119
|
account read for a well-formed signed token. Put per-client-IP Cloudflare
|
|
1098
|
-
rate-limit rules (or an equivalent edge control) in front of
|
|
1120
|
+
rate-limit rules (or an equivalent edge control) in front of those routes in
|
|
1099
1121
|
production. Prefer a block action: applications check `GET /auth/session` with
|
|
1100
1122
|
a `fetch`, and a fetch cannot solve a challenge interstitial, so challenging
|
|
1101
1123
|
that route breaks legitimate sign-in. The verify GET is a browser navigation
|
|
@@ -1133,6 +1155,28 @@ announces pending, success and recovery states. Without JavaScript it links to
|
|
|
1133
1155
|
`${PUBLIC_ORIGIN}/account` as “Request a new sign-in link” and does not pretend
|
|
1134
1156
|
to complete sign-in.
|
|
1135
1157
|
|
|
1158
|
+
### Sign in an isolated installed app
|
|
1159
|
+
|
|
1160
|
+
When the app and email browser do not share cookies, generate a random 32-byte
|
|
1161
|
+
base64url proof in the app and compute the SHA-256 hex digest of the proof's
|
|
1162
|
+
UTF-8 text. Send `{ email, challenge }` to `POST /auth/device/sign-in` with the
|
|
1163
|
+
request marker. Show the first eight uppercase characters of the digest in the
|
|
1164
|
+
app: the approval page shows the same code, and users should approve only when
|
|
1165
|
+
they match. The link's GET is non-destructive; its confirmation POST authorizes
|
|
1166
|
+
the app but does not sign in the browser.
|
|
1167
|
+
|
|
1168
|
+
The app sends `{ token: proof }` to `POST /auth/device/claim` with credentials,
|
|
1169
|
+
the request marker and an allowed origin. `202 { ok: false }` means no claimable
|
|
1170
|
+
approval; `204` sets the normal cookie in the app. Poll only while needed and
|
|
1171
|
+
while the app is visible, stop after 15 minutes, and serialize a claim with
|
|
1172
|
+
account changes so a late cookie cannot overwrite another choice. Clear the
|
|
1173
|
+
proof on cancellation or completion. Do not log the proof or approval URL.
|
|
1174
|
+
An existing valid session returns 409 without consuming the proof; recheck the
|
|
1175
|
+
session rather than replacing that account.
|
|
1176
|
+
Pending requests share the usual email budgets and are revoked by account
|
|
1177
|
+
deletion or sign-out-all. Add edge rate limits for device approval and claim
|
|
1178
|
+
before enabling the feature; block rather than challenge the programmatic claim.
|
|
1179
|
+
|
|
1136
1180
|
Archive only serves the confirmation endpoint. Your application must serve its
|
|
1137
1181
|
sign-in entry at the fixed `${PUBLIC_ORIGIN}/account` recovery destination and
|
|
1138
1182
|
the success page at `${PUBLIC_ORIGIN}/signed-in`. These are reference issuer
|
|
@@ -1261,6 +1305,10 @@ GET /api/v1/me/reports (cursor, limit)
|
|
|
1261
1305
|
GET /api/v1/auth/account
|
|
1262
1306
|
GET /api/v1/auth/jwks.json
|
|
1263
1307
|
POST /api/v1/auth/sign-in (email)
|
|
1308
|
+
POST /api/v1/auth/device/sign-in (email and challenge)
|
|
1309
|
+
GET /api/v1/auth/device/approve?token=… (confirmation only)
|
|
1310
|
+
POST /api/v1/auth/device/approve (authorizes device)
|
|
1311
|
+
POST /api/v1/auth/device/claim (proof, then session cookie)
|
|
1264
1312
|
DELETE /api/v1/auth/account (coordinated full erasure)
|
|
1265
1313
|
DELETE /api/v1/me/account (issuer erasure seam; revokes subject)
|
|
1266
1314
|
GET /api/v1/auth/verify?token=… (confirmation only)
|
|
@@ -14124,11 +14172,13 @@ const translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });
|
|
|
14124
14172
|
translator.translate('save');
|
|
14125
14173
|
```
|
|
14126
14174
|
|
|
14127
|
-
| Method | Signature
|
|
14128
|
-
| ------------------ |
|
|
14129
|
-
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })`
|
|
14130
|
-
| `translateUnkeyed` | `(key: string, options?)`
|
|
14131
|
-
| `
|
|
14175
|
+
| Method | Signature | Returns |
|
|
14176
|
+
| ------------------ | ----------------------------------------------------------------------- | --------------------------- |
|
|
14177
|
+
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |
|
|
14178
|
+
| `translateUnkeyed` | `(key: string, options?)` | Rendered string |
|
|
14179
|
+
| `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 |
|
|
14132
14182
|
|
|
14133
14183
|
---
|
|
14134
14184
|
|
|
@@ -14168,6 +14218,8 @@ i18n.translate('title');
|
|
|
14168
14218
|
| ------------------ | ------------------------------------- | -------------------------------------------------------------- |
|
|
14169
14219
|
| `translate` | Translator method | Rendered string |
|
|
14170
14220
|
| `translateUnkeyed` | Translator method | Rendered string for a runtime key outside the typed key set |
|
|
14221
|
+
| `parts` | Translator method | Render-order `Segment[]` for the committed locale |
|
|
14222
|
+
| `partsUnkeyed` | Translator method | Render-order `Segment[]` for a runtime key |
|
|
14171
14223
|
| `load` | `({ locale? })` | `Promise` after the locale and configured fallbacks load |
|
|
14172
14224
|
| `setLocale` | `(locale)` | `Promise` after an atomic loaded-locale commit |
|
|
14173
14225
|
| `isLoaded` | `({ locale? })` | `boolean` |
|
|
@@ -14180,6 +14232,33 @@ i18n.translate('title');
|
|
|
14180
14232
|
| `disposalSignal` | `AbortSignal` | Aborts on disposal |
|
|
14181
14233
|
| `[Symbol.dispose]` | `()` | Delegates to `dispose()` |
|
|
14182
14234
|
|
|
14235
|
+
**Memoization rule:** `translate` and `parts` have a deliberately stable function identity across `setLocale()` — they read the committed engine at call time, while `getSnapshot()` returns the locale string whose identity changes exactly when the locale does. Memoize derived translations on the **locale**, never on the function's identity (`useMemo(..., [i18n.translate])` keeps the previous language).
|
|
14236
|
+
|
|
14237
|
+
---
|
|
14238
|
+
|
|
14239
|
+
## Rich content (`parts`)
|
|
14240
|
+
|
|
14241
|
+
`parts()` resolves a message exactly like `translate()` — same plural selection, locale fallback, and `missing` strategy — but returns the message as render-order segments, so framework nodes can enter a sentence without ever being stringified.
|
|
14242
|
+
|
|
14243
|
+
```ts
|
|
14244
|
+
const segments = i18n.parts('link', { values: { label: Sync } });
|
|
14245
|
+
// [ { type: 'text', value: 'Go to ' }, { type: 'value', name: 'label', value: }, { type: 'text', value: ' now.' } ]
|
|
14246
|
+
```
|
|
14247
|
+
|
|
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
|
+
|
|
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
|
+
|
|
14260
|
+
`V` defaults to `string`; pass your node type to keep rendering type-safe: `i18n.parts('link', { values: { label: } })`.
|
|
14261
|
+
|
|
14183
14262
|
---
|
|
14184
14263
|
|
|
14185
14264
|
## Reactive bridge (`@vielzeug/lingua/ripple`)
|
|
@@ -14190,7 +14269,7 @@ i18n.translate('title');
|
|
|
14190
14269
|
function createReactiveI18n(i18n: I18n): ReactiveI18n;
|
|
14191
14270
|
```
|
|
14192
14271
|
|
|
14193
|
-
Bridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate` and `
|
|
14272
|
+
Bridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate`, `translateUnkeyed`, `parts`, and `partsUnkeyed` first read the reactive `locale` readable, so any binding built on them re-evaluates the instant `setLocale()` resolves. For runtime-assembled keys inside reactive bindings use the bridge's `translateUnkeyed`/`partsUnkeyed`: calling `i18n.translateUnkeyed` directly skips the reactive locale and caches the first result.
|
|
14194
14273
|
|
|
14195
14274
|
`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.
|
|
14196
14275
|
|
|
@@ -14211,6 +14290,8 @@ await reactive.i18n.setLocale('fr');
|
|
|
14211
14290
|
| `locale` | `Readable` | Reactive locale: reading it inside a computed/template registers the dependency |
|
|
14212
14291
|
| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |
|
|
14213
14292
|
| `translateUnkeyed` | `(key, options?)` | Rendered string for a runtime key; re-evaluates whenever the locale changes |
|
|
14293
|
+
| `parts` | `(key, options?)` | Render-order `Segment[]`; re-evaluates whenever the locale changes |
|
|
14294
|
+
| `partsUnkeyed` | `(key, options?)` | `Segment[]` for a runtime key; re-evaluates whenever the locale changes |
|
|
14214
14295
|
|
|
14215
14296
|
---
|
|
14216
14297
|
|
|
@@ -14359,6 +14440,9 @@ type Translator = {
|
|
|
14359
14440
|
translate(key: TextKey, options?: TranslateOptions): string;
|
|
14360
14441
|
translate(key: PluralKey, options: PluralOptions): string;
|
|
14361
14442
|
translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;
|
|
14443
|
+
parts(key: TextKey, options?: PartsOptions): readonly Segment[];
|
|
14444
|
+
parts(key: PluralKey, options: PluralPartsOptions): readonly Segment[];
|
|
14445
|
+
partsUnkeyed(key: string, options?: PartsOptions | PluralPartsOptions): readonly Segment[];
|
|
14362
14446
|
};
|
|
14363
14447
|
```
|
|
14364
14448
|
|
|
@@ -14368,6 +14452,12 @@ type TranslateOptions = { values?: Values };
|
|
|
14368
14452
|
type PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };
|
|
14369
14453
|
type SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };
|
|
14370
14454
|
|
|
14455
|
+
type Segment =
|
|
14456
|
+
| { readonly type: 'text'; readonly value: string }
|
|
14457
|
+
| { readonly type: 'value'; readonly name: string; readonly value: V };
|
|
14458
|
+
type PartsOptions = { values?: Record };
|
|
14459
|
+
type PluralPartsOptions = PartsOptions & { count: number; ordinal?: boolean };
|
|
14460
|
+
|
|
14371
14461
|
type CatalogPaths = Depth extends readonly [unknown, ...infer Rest]
|
|
14372
14462
|
? C extends Leaf
|
|
14373
14463
|
? Prefix
|
|
@@ -14654,6 +14744,59 @@ export function localeStore(i18n: I18n) {
|
|
|
14654
14744
|
}
|
|
14655
14745
|
```
|
|
14656
14746
|
|
|
14747
|
+
## Rich Content
|
|
14748
|
+
|
|
14749
|
+
`parts()` resolves a message like `translate()` — same plural selection, fallback, and `missing` strategy — but returns render-order segments so framework nodes can enter a sentence without being stringified. Values pass through untouched; joining the segments with `String()` reproduces `translate()` exactly.
|
|
14750
|
+
|
|
14751
|
+
```ts
|
|
14752
|
+
import { createI18n } from '@vielzeug/lingua';
|
|
14753
|
+
|
|
14754
|
+
const i18n = createI18n({
|
|
14755
|
+
catalogs: { en: { sync: 'Click {link} to sync now.' } },
|
|
14756
|
+
locale: 'en',
|
|
14757
|
+
});
|
|
14758
|
+
|
|
14759
|
+
console.log(i18n.parts('sync', { values: { link: 'here' } }));
|
|
14760
|
+
// [ { type: 'text', value: 'Click ' }, { type: 'value', name: 'link', value: 'here' }, { type: 'text', value: ' to sync now.' } ]
|
|
14761
|
+
```
|
|
14762
|
+
|
|
14763
|
+
In React, mirror the locale with `useSyncExternalStore` and key memoized translations on the **locale snapshot** — `i18n.translate`/`i18n.parts` keep a stable identity across `setLocale()` on purpose, so `[t]`-style dependency arrays keep the previous language:
|
|
14764
|
+
|
|
14765
|
+
```tsx
|
|
14766
|
+
import { Fragment, useMemo, useSyncExternalStore } from 'react';
|
|
14767
|
+
import type { ReactNode } from 'react';
|
|
14768
|
+
|
|
14769
|
+
import type { Catalog, I18n, TextKey } from '@vielzeug/lingua';
|
|
14770
|
+
|
|
14771
|
+
export function useI18n(i18n: I18n) {
|
|
14772
|
+
const locale = useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);
|
|
14773
|
+
|
|
14774
|
+
// The fresh memo per locale gives `t` a locale-keyed identity, so downstream `[t]` memos recompute correctly.
|
|
14775
|
+
return useMemo(
|
|
14776
|
+
() => ({
|
|
14777
|
+
locale,
|
|
14778
|
+
t: i18n.translate.bind(i18n),
|
|
14779
|
+
rich: (key: TextKey, values: Record) =>
|
|
14780
|
+
i18n
|
|
14781
|
+
.parts(key, { values })
|
|
14782
|
+
.map((segment, index) =>
|
|
14783
|
+
segment.type === 'text' ? (
|
|
14784
|
+
segment.value
|
|
14785
|
+
) : (
|
|
14786
|
+
{segment.value}
|
|
14787
|
+
),
|
|
14788
|
+
),
|
|
14789
|
+
}),
|
|
14790
|
+
[locale],
|
|
14791
|
+
);
|
|
14792
|
+
}
|
|
14793
|
+
|
|
14794
|
+
// {t('sync')}
|
|
14795
|
+
// {rich('sync', { link: here })}
|
|
14796
|
+
```
|
|
14797
|
+
|
|
14798
|
+
The same segment shape maps directly onto `h()` vnodes in Vue or `{#each}` blocks in Svelte — only the value-segment wrapper is framework-specific. Because values never enter the concatenated string, rich rendering via `parts` also keeps user data out of any HTML-interpolation sink that marker-and-split workarounds would expose.
|
|
14799
|
+
|
|
14657
14800
|
## Working with Other Vielzeug Libraries
|
|
14658
14801
|
|
|
14659
14802
|
Bridge Lingua's `getSnapshot()`/`subscribe()` pair directly when templates need reactive locale reads.
|
|
@@ -14679,6 +14822,8 @@ Use Courier loaders when locale catalogs come from HTTP rather than bundled modu
|
|
|
14679
14822
|
- Keep loader functions out of SSR payloads.
|
|
14680
14823
|
- Dispose temporary instances after requests, tests, and route lifetimes.
|
|
14681
14824
|
- Use `missing: 'throw'` in development to catch missing keys and values early.
|
|
14825
|
+
- Memoize derived translations on the `getSnapshot()` locale string, never on `translate` or `parts` function identity.
|
|
14826
|
+
- Render rich messages with `parts()` instead of smuggling markers through `translate()`.
|
|
14682
14827
|
|
|
14683
14828
|
### Examples
|
|
14684
14829
|
|
|
@@ -14711,7 +14856,7 @@ const pc = new RTCPeerConnection();
|
|
|
14711
14856
|
const dc = pc.createDataChannel('sync');
|
|
14712
14857
|
await pc.setLocalDescription(await pc.createOffer());
|
|
14713
14858
|
// …wait for ICE, hand the SDP to the other device, wire expiry, timeouts,
|
|
14714
|
-
// message framing
|
|
14859
|
+
// and message framing yourself: per guest
|
|
14715
14860
|
|
|
14716
14861
|
// After
|
|
14717
14862
|
const host = createMeshHost();
|
|
@@ -14834,9 +14979,10 @@ try {
|
|
|
14834
14979
|
|
|
14835
14980
|
## Package Entry Point
|
|
14836
14981
|
|
|
14837
|
-
| Import
|
|
14838
|
-
|
|
|
14839
|
-
| `@vielzeug/mesh`
|
|
14982
|
+
| Import | Purpose |
|
|
14983
|
+
| ------------------------ | --------------------------------------------- |
|
|
14984
|
+
| `@vielzeug/mesh` | Complete public Mesh API |
|
|
14985
|
+
| `@vielzeug/mesh/testing` | In-memory WebRTC fake for browserless testing |
|
|
14840
14986
|
|
|
14841
14987
|
## Factory Functions
|
|
14842
14988
|
|
|
@@ -14896,15 +15042,15 @@ const answer = await guest.acceptInvitation(meshCodec.decode(invitationText), {
|
|
|
14896
15042
|
|
|
14897
15043
|
`MeshHost` extends `MeshNode`.
|
|
14898
15044
|
|
|
14899
|
-
| Member | Signature | Purpose
|
|
14900
|
-
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
14901
|
-
| `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.
|
|
14902
|
-
| `acceptAnswer` | `(answer: MeshAnswer) => Promise` | Verifies proof + approval, then resolves once the channel opens. Rejects `MeshPairingError` (unknown/expired
|
|
14903
|
-
| `peers` | `ReadonlyMap` | Live peer inventory keyed by peer id.
|
|
14904
|
-
| `send` | `(peerId: string, type: K, payload: P['toGuest'][K]) => void` | Typed unicast; throws `MeshConnectionError` for unknown/unconnected peers, `MeshPayloadError` over the cap.
|
|
14905
|
-
| `broadcast` | `(type: K, payload: P['toGuest'][K], options?: { except?: readonly string[] }) => void` | Sends to every connected peer not in `except`.
|
|
14906
|
-
| `on` | `(type: K, handler: (message: MeshInbound) => void) => Unsubscribe` | Typed inbound subscription from any guest.
|
|
14907
|
-
| `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'`. |
|
|
14908
15054
|
|
|
14909
15055
|
## Guest Surface
|
|
14910
15056
|
|
|
@@ -15018,7 +15164,7 @@ interface MeshPeer extends MeshPeerInfo {
|
|
|
15018
15164
|
|
|
15019
15165
|
interface MeshInbound {
|
|
15020
15166
|
readonly peerId: string;
|
|
15021
|
-
|
|
15167
|
+
/** Sender's clock at send time in epoch milliseconds: informational only, the peer clock is untrusted. */
|
|
15022
15168
|
readonly sentAt: number;
|
|
15023
15169
|
readonly payload: T;
|
|
15024
15170
|
}
|
|
@@ -15045,7 +15191,7 @@ type MeshEvent =
|
|
|
15045
15191
|
| {
|
|
15046
15192
|
readonly type: 'message-rejected';
|
|
15047
15193
|
readonly peerId: string;
|
|
15048
|
-
readonly reason: 'too-large' | '
|
|
15194
|
+
readonly reason: 'too-large' | 'malformed' | 'unknown-type';
|
|
15049
15195
|
}
|
|
15050
15196
|
| { readonly type: 'ice-state'; readonly peerId: string; readonly state: string }
|
|
15051
15197
|
| { readonly type: 'error'; readonly error: MeshError }
|
|
@@ -15132,6 +15278,24 @@ interface MeshRtcEvent {
|
|
|
15132
15278
|
}
|
|
15133
15279
|
```
|
|
15134
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
|
+
|
|
15135
15299
|
## Errors
|
|
15136
15300
|
|
|
15137
15301
|
| Class | Thrown when | Notable properties |
|
|
@@ -15241,10 +15405,9 @@ host.broadcast('ack', { ok: true }, { except: [peerId] }); // all but one
|
|
|
15241
15405
|
guest.send('note', 'from the guest');
|
|
15242
15406
|
```
|
|
15243
15407
|
|
|
15244
|
-
Inbound messages arrive as `MeshInbound`: `{ peerId,
|
|
15408
|
+
Inbound messages arrive as `MeshInbound`: `{ peerId, sentAt, payload }`. Rules:
|
|
15245
15409
|
|
|
15246
15410
|
- Payloads over `maxMessageBytes` (default 65 536) throw `MeshPayloadError` outbound; oversized inbound frames are dropped and tapped as `'message-rejected'` with reason `'too-large'`.
|
|
15247
|
-
- Duplicate message ids (e.g. after a retry) are dropped and tapped as `'duplicate'`.
|
|
15248
15411
|
- A type with no registered `on` handler is tapped as `'unknown-type'`: never thrown.
|
|
15249
15412
|
- `send` to an unknown or unconnected peer throws `MeshConnectionError`.
|
|
15250
15413
|
|
|
@@ -15269,7 +15432,7 @@ host.tap((event) => {
|
|
|
15269
15432
|
host.kick(peerId, 'bye'); // guest observes 'disconnected'
|
|
15270
15433
|
```
|
|
15271
15434
|
|
|
15272
|
-
`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.
|
|
15273
15436
|
|
|
15274
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.
|
|
15275
15438
|
|
|
@@ -15296,7 +15459,7 @@ Mesh reduces the manual-pairing attack surface but does not remove it:
|
|
|
15296
15459
|
|
|
15297
15460
|
## Testing
|
|
15298
15461
|
|
|
15299
|
-
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.
|
|
15300
15463
|
|
|
15301
15464
|
```ts
|
|
15302
15465
|
import { createFakeRtc } from '@vielzeug/mesh/testing';
|
|
@@ -15304,6 +15467,10 @@ import { createFakeRtc } from '@vielzeug/mesh/testing';
|
|
|
15304
15467
|
const fx = createFakeRtc();
|
|
15305
15468
|
const host = createMeshHost({ rtc: fx.rtc, clock: () => now });
|
|
15306
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);
|
|
15307
15474
|
```
|
|
15308
15475
|
|
|
15309
15476
|
The [REPL examples](/repl) include a runnable in-memory pairing you can copy as a starting point.
|
|
@@ -25556,7 +25723,7 @@ const matches = index.search(query);
|
|
|
25556
25723
|
| ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |
|
|
25557
25724
|
| Bundle size | ~3 KB | | ~23 KB |
|
|
25558
25725
|
| Zero dependencies | | | |
|
|
25559
|
-
| Algorithm | Levenshtein | Trigram +
|
|
25726
|
+
| Algorithm | Levenshtein | Trigram + query coverage | Bitap |
|
|
25560
25727
|
| Query time | O(n·m) | O(candidates) | O(n·m) |
|
|
25561
25728
|
| Stateful index | | | |
|
|
25562
25729
|
| Match highlighting | | | |
|
|
@@ -25603,15 +25770,15 @@ console.log(results[0]?.item.name); // Ada Lovelace
|
|
|
25603
25770
|
|
|
25604
25771
|
- `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)
|
|
25605
25772
|
- Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported
|
|
25606
|
-
- `
|
|
25607
|
-
- `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
|
|
25608
25774
|
- `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering
|
|
25609
25775
|
- `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)
|
|
25610
25776
|
- `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`
|
|
25611
25777
|
- `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries
|
|
25612
|
-
- `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
|
|
25613
25780
|
- Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)
|
|
25614
|
-
- `
|
|
25781
|
+
- `subscribe()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation
|
|
25615
25782
|
- `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`
|
|
25616
25783
|
|
|
25617
25784
|
## Documentation
|
|
@@ -25629,25 +25796,25 @@ console.log(results[0]?.item.name); // Ada Lovelace
|
|
|
25629
25796
|
|
|
25630
25797
|
## API Overview
|
|
25631
25798
|
|
|
25632
|
-
| Symbol | Purpose | Execution mode | Common gotcha
|
|
25633
|
-
| ------------------------ | --------------------------------------------------------- | -------------- |
|
|
25634
|
-
| `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items
|
|
25635
|
-
| `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1`
|
|
25636
|
-
| `ScoutIndex.add()` | Add one item to the index | Sync |
|
|
25637
|
-
| `ScoutIndex.remove()` | Remove
|
|
25638
|
-
| `ScoutIndex.
|
|
25639
|
-
| `ScoutIndex.
|
|
25640
|
-
| `ScoutIndex.
|
|
25641
|
-
| `ScoutIndex.
|
|
25642
|
-
| `ScoutIndex.
|
|
25643
|
-
| `
|
|
25644
|
-
| `
|
|
25645
|
-
| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end
|
|
25646
|
-
| `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping
|
|
25647
|
-
| `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern
|
|
25648
|
-
| `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation
|
|
25649
|
-
| `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes
|
|
25650
|
-
| `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) |
|
|
25651
25818
|
|
|
25652
25819
|
## Package Entry Point
|
|
25653
25820
|
|
|
@@ -25659,19 +25826,20 @@ console.log(results[0]?.item.name); // Ada Lovelace
|
|
|
25659
25826
|
|
|
25660
25827
|
## `createIndex(items, options)`
|
|
25661
25828
|
|
|
25662
|
-
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()`.
|
|
25663
25830
|
|
|
25664
25831
|
```ts
|
|
25665
|
-
function createIndex(items: T[], options: ScoutIndexOptions): ScoutIndex;
|
|
25832
|
+
function createIndex(items: readonly T[], options: ScoutIndexOptions): ScoutIndex;
|
|
25666
25833
|
```
|
|
25667
25834
|
|
|
25668
25835
|
**Parameters**
|
|
25669
25836
|
|
|
25670
25837
|
| Param | Type | Description |
|
|
25671
25838
|
| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
25672
|
-
| `items` | `T[]`
|
|
25839
|
+
| `items` | `readonly T[]` | Initial corpus to index. |
|
|
25673
25840
|
| `options.fields` | `ReadonlyArray>` | Fields to index. Required; at least one entry. |
|
|
25674
|
-
| `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`). |
|
|
25675
25843
|
| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |
|
|
25676
25844
|
| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |
|
|
25677
25845
|
|
|
@@ -25713,15 +25881,23 @@ const results = index.search('alice');
|
|
|
25713
25881
|
|
|
25714
25882
|
### `.add(item)`
|
|
25715
25883
|
|
|
25716
|
-
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).
|
|
25717
25885
|
|
|
25718
25886
|
### `.remove(item)`
|
|
25719
25887
|
|
|
25720
|
-
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`.
|
|
25721
25897
|
|
|
25722
25898
|
### `.reindex(item)`
|
|
25723
25899
|
|
|
25724
|
-
|
|
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.
|
|
25725
25901
|
|
|
25726
25902
|
```ts
|
|
25727
25903
|
item.name = 'new name';
|
|
@@ -25734,7 +25910,7 @@ index.reindex(item);
|
|
|
25734
25910
|
setItems(items: readonly T[]): void
|
|
25735
25911
|
```
|
|
25736
25912
|
|
|
25737
|
-
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.
|
|
25738
25914
|
|
|
25739
25915
|
```ts
|
|
25740
25916
|
index.setItems(latestUsers);
|
|
@@ -25746,22 +25922,22 @@ index.setItems(latestUsers);
|
|
|
25746
25922
|
|
|
25747
25923
|
### `.items`
|
|
25748
25924
|
|
|
25749
|
-
`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.
|
|
25750
25926
|
|
|
25751
25927
|
```ts
|
|
25752
25928
|
const all = index.items;
|
|
25753
25929
|
```
|
|
25754
25930
|
|
|
25755
|
-
### `.
|
|
25931
|
+
### `.subscribe(listener)`
|
|
25756
25932
|
|
|
25757
25933
|
```ts
|
|
25758
|
-
|
|
25934
|
+
subscribe(listener: () => void): () => void
|
|
25759
25935
|
```
|
|
25760
25936
|
|
|
25761
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.
|
|
25762
25938
|
|
|
25763
25939
|
```ts
|
|
25764
|
-
const unsubscribe = index.
|
|
25940
|
+
const unsubscribe = index.subscribe(() => {
|
|
25765
25941
|
console.log(`Index changed: now ${index.size} items`);
|
|
25766
25942
|
});
|
|
25767
25943
|
|
|
@@ -25799,7 +25975,6 @@ function createSearch(index: ScoutIndex, options?: CreateSearchOptions): SearchS
|
|
|
25799
25975
|
| `getSnapshot()` | `() => SearchSnapshot` | Returns the stable current snapshot. Identity changes only after a state transition. |
|
|
25800
25976
|
| `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |
|
|
25801
25977
|
| `subscribe(listener, options?)` | `(listener, options?) => () => void` | Notifies after an atomic snapshot commit. Supports `{ signal }` cleanup. |
|
|
25802
|
-
| `tap(handler, options?)` | `(handler, options?) => () => void` | Observes typed state and disposal events. Handler errors are swallowed. |
|
|
25803
25978
|
| `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |
|
|
25804
25979
|
| `disposed` | `boolean` | `true` after `dispose()` has been called. |
|
|
25805
25980
|
| `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |
|
|
@@ -25824,53 +25999,9 @@ search.setQuery('ada');
|
|
|
25824
25999
|
|
|
25825
26000
|
---
|
|
25826
26001
|
|
|
25827
|
-
## `createReactiveSearch(items, options)`
|
|
25828
|
-
|
|
25829
|
-
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.
|
|
25830
|
-
|
|
25831
|
-
```ts
|
|
25832
|
-
function createReactiveSearch(items: T[], options: ScoutIndexOptions & { debounce?: number }): ReactiveSearch;
|
|
25833
|
-
```
|
|
25834
|
-
|
|
25835
|
-
**Parameters**
|
|
25836
|
-
|
|
25837
|
-
| Param | Type | Description |
|
|
25838
|
-
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------- |
|
|
25839
|
-
| `items` | `T[]` | Initial corpus to index. |
|
|
25840
|
-
| `options.fields` | `ReadonlyArray>` | Fields to index. Required. |
|
|
25841
|
-
| `options.debounce` | `number` | Finite non-negative integer debounce milliseconds (default `200`). |
|
|
25842
|
-
| `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |
|
|
25843
|
-
| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |
|
|
25844
|
-
| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring (default `3`). |
|
|
25845
|
-
|
|
25846
|
-
**Returns `ReactiveSearch`**: all `SearchState` members plus:
|
|
25847
|
-
|
|
25848
|
-
| Member | Type | Description |
|
|
25849
|
-
| ------- | --------------- | ---------------------------------------------------- |
|
|
25850
|
-
| `index` | `ScoutIndex` | The underlying index for `add`, `remove`, `reindex`. |
|
|
25851
|
-
|
|
25852
|
-
**Example**
|
|
25853
|
-
|
|
25854
|
-
```ts
|
|
25855
|
-
import { createReactiveSearch } from '@vielzeug/scout';
|
|
25856
|
-
|
|
25857
|
-
const users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];
|
|
25858
|
-
const search = createReactiveSearch(users, {
|
|
25859
|
-
fields: [{ field: 'name', weight: 2 }, 'email'],
|
|
25860
|
-
debounce: 150,
|
|
25861
|
-
});
|
|
25862
|
-
|
|
25863
|
-
search.subscribe(() => console.log(search.getSnapshot().results.map((result) => result.item.name)));
|
|
25864
|
-
|
|
25865
|
-
search.index.add({ email: 'grace@example.com', name: 'Grace Hopper' });
|
|
25866
|
-
search.dispose();
|
|
25867
|
-
```
|
|
25868
|
-
|
|
25869
|
-
---
|
|
25870
|
-
|
|
25871
26002
|
## `findMatchRanges(text, query)`
|
|
25872
26003
|
|
|
25873
|
-
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).
|
|
25874
26005
|
|
|
25875
26006
|
```ts
|
|
25876
26007
|
function findMatchRanges(text: string, query: string): [number, number][];
|
|
@@ -25992,7 +26123,7 @@ Splits `text` into whitespace-joined word segments using the runtime's native `I
|
|
|
25992
26123
|
function segmentWords(text: string): string;
|
|
25993
26124
|
```
|
|
25994
26125
|
|
|
25995
|
-
`
|
|
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.
|
|
25996
26127
|
|
|
25997
26128
|
**Example**
|
|
25998
26129
|
|
|
@@ -26038,6 +26169,7 @@ type FieldDef =
|
|
|
26038
26169
|
```ts
|
|
26039
26170
|
type ScoutIndexOptions = SearchConstraints & {
|
|
26040
26171
|
fields: ReadonlyArray>;
|
|
26172
|
+
key?: (item: T) => unknown; // stable identity; default (item) => item
|
|
26041
26173
|
};
|
|
26042
26174
|
```
|
|
26043
26175
|
|
|
@@ -26054,8 +26186,8 @@ type CreateSearchOptions = SearchConstraints & {
|
|
|
26054
26186
|
```ts
|
|
26055
26187
|
type SearchResult = {
|
|
26056
26188
|
item: T;
|
|
26057
|
-
matches: FieldMatch[]; // literal
|
|
26058
|
-
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
|
|
26059
26191
|
};
|
|
26060
26192
|
```
|
|
26061
26193
|
|
|
@@ -26066,7 +26198,7 @@ Generic over the union of field names: `match.field` is typed to the actual fiel
|
|
|
26066
26198
|
```ts
|
|
26067
26199
|
type FieldMatch = {
|
|
26068
26200
|
field: F;
|
|
26069
|
-
ranges: [number, number][]; // literal
|
|
26201
|
+
ranges: [number, number][]; // literal [start, end) ranges in the original field value
|
|
26070
26202
|
};
|
|
26071
26203
|
```
|
|
26072
26204
|
|
|
@@ -26088,12 +26220,6 @@ type SearchSnapshot = Readonly>;
|
|
|
26088
26220
|
|
|
26089
26221
|
Snapshots and their result arrays are frozen at runtime.
|
|
26090
26222
|
|
|
26091
|
-
### `ScoutEvent`
|
|
26092
|
-
|
|
26093
|
-
```ts
|
|
26094
|
-
type ScoutEvent = { readonly snapshot: SearchSnapshot; readonly type: 'state-change' };
|
|
26095
|
-
```
|
|
26096
|
-
|
|
26097
26223
|
### `SearchState`
|
|
26098
26224
|
|
|
26099
26225
|
```ts
|
|
@@ -26105,22 +26231,11 @@ type SearchState = {
|
|
|
26105
26231
|
getSnapshot(): SearchSnapshot;
|
|
26106
26232
|
setQuery(query: string): void;
|
|
26107
26233
|
subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;
|
|
26108
|
-
tap(handler: (event: ScoutEvent) => void, options?: { signal?: AbortSignal }): () => void;
|
|
26109
26234
|
[Symbol.dispose](): void;
|
|
26110
26235
|
};
|
|
26111
26236
|
```
|
|
26112
26237
|
|
|
26113
|
-
`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.
|
|
26114
|
-
|
|
26115
|
-
### `ReactiveSearch`
|
|
26116
|
-
|
|
26117
|
-
```ts
|
|
26118
|
-
type ReactiveSearch = SearchState & {
|
|
26119
|
-
readonly index: ScoutIndex;
|
|
26120
|
-
};
|
|
26121
|
-
```
|
|
26122
|
-
|
|
26123
|
-
See `createReactiveSearch()` above.
|
|
26238
|
+
`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.
|
|
26124
26239
|
|
|
26125
26240
|
---
|
|
26126
26241
|
|
|
@@ -26136,10 +26251,10 @@ class ScoutError extends Error {}
|
|
|
26136
26251
|
|
|
26137
26252
|
**Named subclasses**
|
|
26138
26253
|
|
|
26139
|
-
| Class | Thrown when
|
|
26140
|
-
| -------------------- |
|
|
26141
|
-
| `ScoutConfigError` | An index
|
|
26142
|
-
| `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 |
|
|
26143
26258
|
|
|
26144
26259
|
## Entry Ranking
|
|
26145
26260
|
|
|
@@ -26230,7 +26345,7 @@ const index = createIndex(products, {
|
|
|
26230
26345
|
|
|
26231
26346
|
### Non-Latin scripts (CJK, Thai, ...)
|
|
26232
26347
|
|
|
26233
|
-
|
|
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()`:
|
|
26234
26349
|
|
|
26235
26350
|
```ts
|
|
26236
26351
|
import { createIndex, segmentWords } from '@vielzeug/scout';
|
|
@@ -26244,24 +26359,26 @@ const index = createIndex(docs, {
|
|
|
26244
26359
|
index.search('日本語'); // matches the first document
|
|
26245
26360
|
```
|
|
26246
26361
|
|
|
26247
|
-
`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.
|
|
26248
26363
|
|
|
26249
26364
|
### Limiting results
|
|
26250
26365
|
|
|
26251
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`.
|
|
26252
26367
|
|
|
26253
26368
|
```ts
|
|
26254
|
-
// At most 10 results, minimum
|
|
26369
|
+
// At most 10 results, minimum query-coverage score 0.3
|
|
26255
26370
|
const results = index.search('widget', { limit: 10, threshold: 0.3 });
|
|
26256
26371
|
```
|
|
26257
26372
|
|
|
26258
26373
|
Per-call options override the index-level defaults set in `createIndex`.
|
|
26259
26374
|
|
|
26260
|
-
Scores
|
|
26261
|
-
|
|
26262
|
-
|
|
26263
|
-
|
|
26264
|
-
|
|
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.
|
|
26265
26382
|
|
|
26266
26383
|
### Controlling short-query behaviour
|
|
26267
26384
|
|
|
@@ -26277,17 +26394,13 @@ const results = index.search('alice', { minQueryLength: 8 });
|
|
|
26277
26394
|
|
|
26278
26395
|
## Reactive Search
|
|
26279
26396
|
|
|
26280
|
-
|
|
26281
|
-
|
|
26282
|
-
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:
|
|
26283
26398
|
|
|
26284
26399
|
```ts
|
|
26285
|
-
import {
|
|
26400
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26286
26401
|
|
|
26287
|
-
const
|
|
26288
|
-
|
|
26289
|
-
debounce: 150,
|
|
26290
|
-
});
|
|
26402
|
+
const index = createIndex(users, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26403
|
+
const search = createSearch(index, { debounce: 150 });
|
|
26291
26404
|
|
|
26292
26405
|
search.subscribe(() => {
|
|
26293
26406
|
const { isSearching, results } = search.getSnapshot();
|
|
@@ -26299,28 +26412,17 @@ input.addEventListener('input', (event) => {
|
|
|
26299
26412
|
search.setQuery((event.currentTarget as HTMLInputElement).value);
|
|
26300
26413
|
});
|
|
26301
26414
|
|
|
26302
|
-
|
|
26415
|
+
index.add(newUser); // the search state re-runs the committed query
|
|
26303
26416
|
search.dispose();
|
|
26304
26417
|
```
|
|
26305
26418
|
|
|
26306
|
-
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.
|
|
26307
|
-
|
|
26308
|
-
### `createSearch()`: separate index and state
|
|
26309
|
-
|
|
26310
|
-
Use `createSearch` when sharing one index across multiple search stores:
|
|
26311
|
-
|
|
26312
|
-
```ts
|
|
26313
|
-
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26314
|
-
|
|
26315
|
-
const index = createIndex(users, { fields: ['name', 'email'] });
|
|
26316
|
-
const search = createSearch(index, { debounce: 150 });
|
|
26317
|
-
```
|
|
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()`.
|
|
26318
26420
|
|
|
26319
26421
|
### `using` declaration
|
|
26320
26422
|
|
|
26321
26423
|
```ts
|
|
26322
26424
|
{
|
|
26323
|
-
using search =
|
|
26425
|
+
using search = createSearch(index, { debounce: 150 });
|
|
26324
26426
|
// search.dispose() called automatically at scope exit
|
|
26325
26427
|
}
|
|
26326
26428
|
```
|
|
@@ -26330,7 +26432,7 @@ const search = createSearch(index, { debounce: 150 });
|
|
|
26330
26432
|
Pass `debounce: 0` for synchronous commits with no searching transition:
|
|
26331
26433
|
|
|
26332
26434
|
```ts
|
|
26333
|
-
const search =
|
|
26435
|
+
const search = createSearch(index, { debounce: 0 });
|
|
26334
26436
|
|
|
26335
26437
|
search.setQuery('alice');
|
|
26336
26438
|
console.log(search.getSnapshot().results); // Already updated
|
|
@@ -26356,7 +26458,7 @@ const topResult = ripple.computed(() => state.value.results[0]?.item ?? null);
|
|
|
26356
26458
|
|
|
26357
26459
|
## Incremental Updates
|
|
26358
26460
|
|
|
26359
|
-
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.
|
|
26360
26462
|
|
|
26361
26463
|
```ts
|
|
26362
26464
|
const index = createIndex(products, { fields: ['title'] });
|
|
@@ -26365,7 +26467,7 @@ const index = createIndex(products, { fields: ['title'] });
|
|
|
26365
26467
|
const newProduct = { id: 99, title: 'New Widget' };
|
|
26366
26468
|
index.add(newProduct);
|
|
26367
26469
|
|
|
26368
|
-
// Remove a deleted item (by reference)
|
|
26470
|
+
// Remove a deleted item (by key; the default key is the reference)
|
|
26369
26471
|
index.remove(products[0]);
|
|
26370
26472
|
|
|
26371
26473
|
// Re-index a mutated item after in-place mutation
|
|
@@ -26373,7 +26475,30 @@ products[1].title = 'Updated Title';
|
|
|
26373
26475
|
index.reindex(products[1]);
|
|
26374
26476
|
```
|
|
26375
26477
|
|
|
26376
|
-
> `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.
|
|
26377
26502
|
|
|
26378
26503
|
### Replacing a refreshed corpus
|
|
26379
26504
|
|
|
@@ -26383,7 +26508,7 @@ const latestProducts = await loadProducts();
|
|
|
26383
26508
|
index.setItems(latestProducts);
|
|
26384
26509
|
```
|
|
26385
26510
|
|
|
26386
|
-
`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.
|
|
26387
26512
|
|
|
26388
26513
|
### Inspecting the corpus
|
|
26389
26514
|
|
|
@@ -26396,10 +26521,10 @@ console.log(index.items); // [{ id: 1, title: ... }, ...]
|
|
|
26396
26521
|
|
|
26397
26522
|
### Reacting to mutations directly
|
|
26398
26523
|
|
|
26399
|
-
`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()`:
|
|
26400
26525
|
|
|
26401
26526
|
```ts
|
|
26402
|
-
const unsubscribe = index.
|
|
26527
|
+
const unsubscribe = index.subscribe(() => {
|
|
26403
26528
|
rerenderResultsList();
|
|
26404
26529
|
});
|
|
26405
26530
|
|
|
@@ -26408,11 +26533,11 @@ index.add(newProduct); // triggers rerenderResultsList()
|
|
|
26408
26533
|
unsubscribe(); // when done
|
|
26409
26534
|
```
|
|
26410
26535
|
|
|
26411
|
-
`
|
|
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.
|
|
26412
26537
|
|
|
26413
26538
|
## Match Highlighting
|
|
26414
26539
|
|
|
26415
|
-
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.
|
|
26416
26541
|
|
|
26417
26542
|
### `highlightField()`: recommended
|
|
26418
26543
|
|
|
@@ -26493,43 +26618,20 @@ for (const entry of results) {
|
|
|
26493
26618
|
|
|
26494
26619
|
Dedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.
|
|
26495
26620
|
|
|
26496
|
-
## Debug Logging
|
|
26497
|
-
|
|
26498
|
-
Use `tap()` for typed runtime observation without affecting search behavior:
|
|
26499
|
-
|
|
26500
|
-
```ts
|
|
26501
|
-
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26502
|
-
|
|
26503
|
-
const search = createSearch(index, { debounce: 150 });
|
|
26504
|
-
const stop = search.tap((event) => {
|
|
26505
|
-
console.debug(event.snapshot.query, event.snapshot.isSearching, event.snapshot.results.length);
|
|
26506
|
-
});
|
|
26507
|
-
|
|
26508
|
-
search.setQuery('alice');
|
|
26509
|
-
stop();
|
|
26510
|
-
```
|
|
26511
|
-
|
|
26512
|
-
`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.
|
|
26513
|
-
|
|
26514
|
-
`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.
|
|
26515
|
-
|
|
26516
26621
|
## Framework Integration
|
|
26517
26622
|
|
|
26518
26623
|
```tsx [React]
|
|
26519
|
-
import {
|
|
26624
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26520
26625
|
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
|
26521
26626
|
|
|
26522
26627
|
type User = { id: number; name: string; email: string };
|
|
26523
26628
|
|
|
26524
26629
|
function useScoutSearch(items: User[]) {
|
|
26525
|
-
const search = useMemo(
|
|
26526
|
-
()
|
|
26527
|
-
|
|
26528
|
-
|
|
26529
|
-
|
|
26530
|
-
}),
|
|
26531
|
-
[items],
|
|
26532
|
-
);
|
|
26630
|
+
const search = useMemo(() => {
|
|
26631
|
+
const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26632
|
+
|
|
26633
|
+
return createSearch(index, { debounce: 150 });
|
|
26634
|
+
}, [items]);
|
|
26533
26635
|
const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);
|
|
26534
26636
|
|
|
26535
26637
|
useEffect(() => () => search.dispose(), [search]);
|
|
@@ -26539,16 +26641,14 @@ function useScoutSearch(items: User[]) {
|
|
|
26539
26641
|
```
|
|
26540
26642
|
|
|
26541
26643
|
```ts [Vue 3]
|
|
26542
|
-
import {
|
|
26644
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26543
26645
|
import { onScopeDispose, shallowRef } from 'vue';
|
|
26544
26646
|
|
|
26545
26647
|
type User = { id: number; name: string; email: string };
|
|
26546
26648
|
|
|
26547
26649
|
function useScoutSearch(items: User[]) {
|
|
26548
|
-
const
|
|
26549
|
-
|
|
26550
|
-
debounce: 150,
|
|
26551
|
-
});
|
|
26650
|
+
const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26651
|
+
const search = createSearch(index, { debounce: 150 });
|
|
26552
26652
|
const snapshot = shallowRef(search.getSnapshot());
|
|
26553
26653
|
const stop = search.subscribe(() => {
|
|
26554
26654
|
snapshot.value = search.getSnapshot();
|
|
@@ -26565,17 +26665,15 @@ function useScoutSearch(items: User[]) {
|
|
|
26565
26665
|
|
|
26566
26666
|
```svelte [Svelte]
|
|
26567
26667
|
|
|
26568
|
-
import {
|
|
26668
|
+
import { createIndex, createSearch } from '@vielzeug/scout';
|
|
26569
26669
|
import { onDestroy } from 'svelte';
|
|
26570
26670
|
|
|
26571
26671
|
type User = { id: number; name: string; email: string };
|
|
26572
26672
|
|
|
26573
26673
|
export let items: User[];
|
|
26574
26674
|
|
|
26575
|
-
const
|
|
26576
|
-
|
|
26577
|
-
debounce: 150,
|
|
26578
|
-
});
|
|
26675
|
+
const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });
|
|
26676
|
+
const search = createSearch(index, { debounce: 150 });
|
|
26579
26677
|
let snapshot = search.getSnapshot();
|
|
26580
26678
|
const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });
|
|
26581
26679
|
|
|
@@ -26627,7 +26725,8 @@ Call `toFilterPredicate` again whenever the query or corpus changes: the predica
|
|
|
26627
26725
|
## Best Practices
|
|
26628
26726
|
|
|
26629
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.
|
|
26630
|
-
- **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.
|
|
26631
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.
|
|
26632
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.
|
|
26633
26732
|
- **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.
|
|
@@ -33071,7 +33170,7 @@ sync.dispose();
|
|
|
33071
33170
|
- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.
|
|
33072
33171
|
- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.
|
|
33073
33172
|
- **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.
|
|
33074
|
-
- **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.
|
|
33075
33174
|
- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.
|
|
33076
33175
|
- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.
|
|
33077
33176
|
|
|
@@ -33110,13 +33209,15 @@ sync.dispose();
|
|
|
33110
33209
|
function createSync(options: SyncOptions): SyncHandle;
|
|
33111
33210
|
```
|
|
33112
33211
|
|
|
33113
|
-
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.
|
|
33114
33213
|
|
|
33115
|
-
| Parameter | Type | Description
|
|
33116
|
-
| --------------------- | ---------------------- |
|
|
33117
|
-
| `options.
|
|
33118
|
-
| `options.
|
|
33119
|
-
| `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 |
|
|
33120
33221
|
|
|
33121
33222
|
**Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.
|
|
33122
33223
|
|
|
@@ -33239,6 +33340,8 @@ interface SyncPullResult {
|
|
|
33239
33340
|
|
|
33240
33341
|
```ts
|
|
33241
33342
|
interface SyncOptions {
|
|
33343
|
+
ambient?: boolean;
|
|
33344
|
+
autoStart?: boolean;
|
|
33242
33345
|
gateway: SyncGateway;
|
|
33243
33346
|
idleDelayMs?: number;
|
|
33244
33347
|
port: SyncPort;
|
|
@@ -33365,6 +33468,15 @@ try {
|
|
|
33365
33468
|
|
|
33366
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.
|
|
33367
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
|
+
|
|
33368
33480
|
## Reconcile a Rejected Push
|
|
33369
33481
|
|
|
33370
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.
|
|
@@ -33557,7 +33669,7 @@ const host = hostTavern({
|
|
|
33557
33669
|
|
|
33558
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.
|
|
33559
33671
|
|
|
33560
|
-
**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.
|
|
33561
33673
|
|
|
33562
33674
|
## Installation
|
|
33563
33675
|
|