@noy-db/hub 0.4.0-pre.7 → 0.4.0-pre.8

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/README.md CHANGED
@@ -39,7 +39,6 @@ pnpm add @noy-db/hub @noy-db/to-memory
39
39
  | [`to-icloud`](https://www.npmjs.com/package/@noy-db/to-icloud) | iCloud Drive (.icloud-aware) |
40
40
  | [`to-drive`](https://www.npmjs.com/package/@noy-db/to-drive) | Google Drive bundle |
41
41
  | [`to-meter`](https://www.npmjs.com/package/@noy-db/to-meter) | Wrap any store with metrics |
42
- | [`to-probe`](https://www.npmjs.com/package/@noy-db/to-probe) | Diagnostic suitability test |
43
42
 
44
43
  ### Optional ecosystem
45
44
 
@@ -58,7 +57,7 @@ import { memory } from '@noy-db/to-memory'
58
57
  type Invoice = { id: string; amount: number; customer: string }
59
58
 
60
59
  const db = await createNoydb({
61
- store: memory(),
60
+ store: toMemory(),
62
61
  userId: 'alice',
63
62
  secret: 'correct horse battery staple',
64
63
  })
@@ -6,7 +6,7 @@ import {
6
6
  diffVault,
7
7
  unsealDeks,
8
8
  withCargo
9
- } from "../chunk-PT4XLP6I.js";
9
+ } from "../chunk-JTR75MKH.js";
10
10
  import {
11
11
  NO_CARGO,
12
12
  isQuorum,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SyncScheduler
3
- } from "./chunk-VQNJ7UZL.js";
3
+ } from "./chunk-MTJLOC3Y.js";
4
4
  import {
5
5
  PERIODS_COLLECTION,
6
6
  PERIOD_ARCHIVES_COLLECTION,
@@ -1073,4 +1073,4 @@ export {
1073
1073
  SyncEngine,
1074
1074
  SyncTransaction
1075
1075
  };
1076
- //# sourceMappingURL=chunk-KBPU5M2E.js.map
1076
+ //# sourceMappingURL=chunk-BXHMZ2XW.js.map
@@ -651,4 +651,4 @@ export {
651
651
  withCache,
652
652
  withHealthCheck
653
653
  };
654
- //# sourceMappingURL=chunk-VSRSQ2CR.js.map
654
+ //# sourceMappingURL=chunk-EIPVYUEP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/with-store/route-store.ts","../src/with-store/store-middleware.ts"],"sourcesContent":["/**\n * Store router / multiplexer.\n *\n * Dispatches `NoydbStore` operations to different backends based on\n * collection type, record size, record age, collection name, or vault name.\n *\n * ```ts\n * const db = await createNoydb({\n * store: routeStore({\n * default: dynamo({ table: 'myapp' }),\n * blobs: s3Store({ bucket: 'myapp-blobs' }),\n * }),\n * })\n * ```\n *\n * @module\n */\n\nimport type {\n NoydbStore,\n EncryptedEnvelope,\n VaultSnapshot,\n StoreCapabilities,\n} from '../kernel/types.js'\n\n// ─── Internal collection prefixes (duplicated to avoid circular import) ──\n\nconst BLOB_CHUNKS = '_blob_chunks'\nconst BLOB_INDEX = '_blob_index'\nconst BLOB_SLOTS = '_blob_slots_'\nconst BLOB_VERSIONS = '_blob_versions_'\n\n// ─── Options ─────────────────────────────────────────────────────────────\n\n/**\n * Size-tiered blob routing configuration.\n *\n * Routes blob chunks to different stores based on byte size. Small blobs\n * (under `threshold`) stay in the primary or `small` store; large blobs\n * go to `large`. This lets you keep DynamoDB as the default while sending\n * large binary objects to S3.\n */\nexport interface BlobStoreRoute {\n /** Store for small blobs (under threshold). Falls back to `default`. */\n readonly small?: NoydbStore\n /** Store for large blobs (over threshold). */\n readonly large: NoydbStore\n /** Size threshold in bytes. Default: `400 * 1024` (DynamoDB item limit). */\n readonly threshold?: number\n}\n\n/**\n * Blob lifecycle management policies evaluated during `compact()`.\n *\n * Controls orphan cleanup, cold-tier archival, and hard deletion of\n * blobs that are no longer referenced by any record.\n */\nexport interface BlobLifecyclePolicy {\n /** Delete orphan blobs (refCount: 0) after this many days. Default: 7. */\n readonly orphanRetentionDays?: number\n /** Move blobs not accessed in this many days to the cold blob store. */\n readonly archiveAfterDays?: number\n /** Store for archived blobs. Required if archiveAfterDays is set. */\n readonly archiveStore?: NoydbStore\n /** Hard-delete archived blobs after this many days. */\n readonly expireAfterDays?: number\n}\n\n/**\n * Age-based hot/cold tiering configuration.\n *\n * Records whose `_ts` timestamp is older than `coldAfterDays` are migrated\n * to the `cold` store during `compact()`. Reads transparently fall through\n * to the cold store when the hot store returns null, so callers don't need\n * to know which tier a record lives in.\n */\nexport interface AgeRoute {\n /** Store for records older than the cutoff. */\n readonly cold: NoydbStore\n /**\n * Days after last modification before a record is cold-eligible for the\n * ROLLING `compact(vault)` migrator. Omit for period-driven archival only\n * (`compact(vault, { before })`), where the cutoff is supplied per call.\n */\n readonly coldAfterDays?: number\n /**\n * Collections that participate in age tiering.\n * Empty array or omitted = all user collections (excluding `_` prefixed).\n */\n readonly collections?: string[]\n}\n\n/**\n * Options for `routeStore()` — the store multiplexer.\n *\n * At minimum, provide a `default` store. All other fields are optional\n * extensions for specific routing scenarios (blobs → S3, geographic sharding,\n * age-based tiering, etc.).\n */\nexport interface RouteStoreOptions {\n /** Default store for all unmatched operations. */\n readonly default: NoydbStore\n\n /**\n * Route blob chunk data to a separate store.\n * - Pass a `NoydbStore` for simple prefix routing (all chunks → that store).\n * - Pass `{ small?, large, threshold? }` for size-tiered routing.\n */\n readonly blobs?: NoydbStore | BlobStoreRoute\n\n /** Route all blob metadata (index, slots, versions) to the blobs store too. Default: false. */\n readonly routeBlobMeta?: boolean\n\n /** Route specific user collections to dedicated stores. */\n readonly routes?: Record<string, NoydbStore>\n\n /** Route by vault name (prefix patterns, e.g. `'EU-'`). */\n readonly vaultRoutes?: Record<string, NoydbStore>\n\n /**\n * Age-based tiering: records older than `coldAfterDays` are read from\n * the cold store. A background `compact()` method migrates them.\n */\n readonly age?: AgeRoute\n\n /**\n * Content-aware blob routing.\n * Route blob chunks by MIME type glob pattern. The MIME type is stored\n * in `BlobObject` and matched at read time via `storeHint`.\n */\n readonly blobRoutes?: Record<string, NoydbStore>\n\n /**\n * Blob lifecycle policies.\n * Evaluated during `compact()`.\n */\n readonly blobLifecycle?: BlobLifecyclePolicy\n\n /**\n * Quota-aware overflow.\n * When the default store's usage exceeds the threshold, new writes\n * overflow to the specified store.\n */\n readonly overflow?: NoydbStore\n\n /**\n * Quota threshold (0-1). Default: 0.8 (overflow at 80% usage).\n * Only effective when `overflow` is set.\n */\n readonly quotaThreshold?: number\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/**\n * Named route that can be overridden or suspended at runtime.\n *\n * Built-in names: `'default'`, `'blobs'`, `'cold'`.\n * Custom names: any collection name from `routes`, any vault prefix from\n * `vaultRoutes`, or any sync target label.\n */\nexport type OverrideTarget =\n | 'default'\n | 'blobs'\n | 'cold'\n | (string & {}) // named collection route, vault route, or sync target label\n\n/**\n * Options for `RoutedNoydbStore.override()`.\n *\n * Controls whether the new store is pre-populated with data from the\n * original store before the switch takes effect.\n */\nexport interface OverrideOptions {\n /**\n * Hydrate the override store from the original before activating.\n * - `true` — copy all data for all vaults.\n * - `string[]` — copy only named collections.\n * Makes `override()` async — returns a Promise.\n */\n hydrate?: boolean | string[]\n}\n\n/**\n * Options for `RoutedNoydbStore.suspend()`.\n *\n * A suspended route becomes a null store: reads return null/[], writes\n * are dropped (or buffered if `queue: true`). Useful for maintenance\n * windows or restricted-network scenarios.\n */\nexport interface SuspendOptions {\n /**\n * Buffer write operations during suspension. On `resume()`, queued\n * writes are replayed against the restored store.\n */\n queue?: boolean\n /**\n * Maximum queued operations. When exceeded, oldest entries are dropped.\n * Default: 10_000.\n */\n maxQueueSize?: number\n}\n\n/** Queued write operation recorded during suspension. */\ninterface QueuedWrite {\n method: 'put' | 'delete'\n vault: string\n collection: string\n id: string\n envelope?: EncryptedEnvelope\n expectedVersion?: number\n}\n\n/**\n * Snapshot of the current override and suspend state of a `RoutedNoydbStore`.\n * Returned by `routeStatus()` for diagnostics and health dashboards.\n */\nexport interface RouteStatus {\n /** Active overrides: route name → override store name. */\n readonly overrides: Record<string, string>\n /** Currently suspended routes. */\n readonly suspended: string[]\n /** Queued writes per suspended route (only for routes suspended with `queue: true`). */\n readonly queued: Record<string, number>\n}\n\n/**\n * Extended `NoydbStore` returned by `routeStore()`.\n *\n * Satisfies the full `NoydbStore` contract plus adds runtime control\n * methods for overriding, suspending, and inspecting routes.\n */\nexport interface RoutedNoydbStore extends NoydbStore {\n /**\n * Migrate records to the cold store. Only applies when `age.cold` is\n * configured. With `{ before }`, migrates records whose `_ts < before`\n * (period-driven archival); without, uses the rolling `coldAfterDays`.\n * Returns the number of records migrated.\n */\n compact(vault: string, opts?: { before?: string }): Promise<number>\n\n /**\n * Override a named route at runtime.\n *\n * The override persists until `clearOverride()` is called or the\n * instance is closed. In-flight operations complete on the original\n * store; new operations use the override.\n *\n * Options:\n * - `hydrate: true` — async: copies all data from the original store\n * into the override before activating the switch.\n * - `hydrate: ['invoices', 'clients']` — copies only named collections.\n *\n * Use cases:\n * - Shared device: `await store.override('default', toMemory(), { hydrate: true })`\n * - Restricted network: `store.override('blobs', localFile(...))`\n */\n override(route: OverrideTarget, store: NoydbStore, opts?: OverrideOptions): void | Promise<void>\n\n /** Clear a runtime override, reverting to the original store. */\n clearOverride(route: OverrideTarget): void\n\n /**\n * Suspend a route entirely. Operations to suspended stores become\n * no-ops (puts silently dropped, gets return null, lists return []).\n *\n * Options:\n * - `queue: true` — buffer write operations (put/delete) during\n * suspension. When `resume()` is called, queued writes are replayed\n * against the restored store.\n *\n * Returns a `SuspendHandle` when `queue: true`, for inspecting queue state.\n */\n suspend(route: OverrideTarget, opts?: SuspendOptions): void\n\n /**\n * Resume a previously suspended route.\n * If the route was suspended with `queue: true`, replays queued writes.\n * Returns the number of replayed operations.\n */\n resume(route: OverrideTarget): Promise<number>\n\n /** Snapshot the current override/suspend state for diagnostics. */\n routeStatus(): RouteStatus\n\n /**\n * Resolve the physical backend a vault id maps to via the geographic\n * `vaultRoutes` prefix routing (collection-independent), falling back to\n * the `default` store. Used by the federation data-residency guard\n * to read the placement backend's `capabilities.region`.\n */\n resolveBackend(vaultId: string): NoydbStore\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────\n\n/**\n * Create a store multiplexer that dispatches operations to different backends\n * based on collection type, record size, record age, vault prefix, or\n * runtime overrides.\n *\n * ```ts\n * const store = routeStore({\n * default: dynamo({ table: 'myapp' }),\n * blobs: s3({ bucket: 'myapp-blobs' }),\n * routes: { auditLog: s3({ bucket: 'myapp-audit' }) },\n * })\n * ```\n *\n * The returned store satisfies `NoydbStore` and can be passed directly to\n * `createNoydb({ store })`. It also exposes additional methods\n * (`override`, `suspend`, `resume`, `routeStatus`, `compact`) for runtime\n * control and maintenance.\n */\nexport function routeStore(opts: RouteStoreOptions): RoutedNoydbStore {\n const primary = opts.default\n\n // Resolve blob store config\n const blobsIsSimple = opts.blobs && 'get' in opts.blobs\n const simpleBlobStore = blobsIsSimple ? opts.blobs : undefined\n const tieredBlobs = !blobsIsSimple ? opts.blobs : undefined\n const blobThreshold = tieredBlobs?.threshold ?? 400 * 1024\n\n // Collect all stores for loadAll/saveAll/listVaults composition\n const allStores = new Set<NoydbStore>([primary])\n if (simpleBlobStore) allStores.add(simpleBlobStore)\n if (tieredBlobs?.large) allStores.add(tieredBlobs.large)\n if (tieredBlobs?.small) allStores.add(tieredBlobs.small)\n if (opts.age?.cold) allStores.add(opts.age.cold)\n if (opts.routes) for (const s of Object.values(opts.routes)) allStores.add(s)\n if (opts.vaultRoutes) for (const s of Object.values(opts.vaultRoutes)) allStores.add(s)\n if (opts.blobRoutes) for (const s of Object.values(opts.blobRoutes)) allStores.add(s)\n if (opts.overflow) allStores.add(opts.overflow)\n if (opts.blobLifecycle?.archiveStore) allStores.add(opts.blobLifecycle.archiveStore)\n\n // ── Runtime override / suspend state ──────────────────\n\n const overrides = new Map<string, NoydbStore>()\n const suspended = new Set<string>()\n const writeQueues = new Map<string, { writes: QueuedWrite[]; maxSize: number }>()\n\n /** Null store: silently absorbs all operations when a route is suspended. */\n const NULL_STORE: NoydbStore = {\n name: 'suspended',\n async get() { return null },\n async put() {},\n async delete() {},\n async list() { return [] },\n async loadAll() { return {} },\n async saveAll() {},\n }\n\n /**\n * Map a resolved route to its canonical name for override/suspend lookup.\n * Vault routes use the prefix, collection routes use the collection name,\n * blob route is 'blobs', cold route is 'cold', everything else is 'default'.\n */\n function routeNameFor(vault: string, collection: string): string {\n if (opts.vaultRoutes) {\n for (const prefix of Object.keys(opts.vaultRoutes)) {\n if (vault.startsWith(prefix)) return prefix\n }\n }\n if (opts.routes && !collection.startsWith('_') && opts.routes[collection]) {\n return collection\n }\n if (isBlobChunks(collection) && (simpleBlobStore || tieredBlobs)) return 'blobs'\n if (opts.routeBlobMeta && isBlobMeta(collection) && (simpleBlobStore || tieredBlobs)) return 'blobs'\n if (opts.age && !collection.startsWith('_')) {\n // We don't name age 'cold' here — cold is a fallback, not a primary route\n }\n return 'default'\n }\n\n // ── Quota-aware overflow (E8) ───────────────────────────────────────\n\n const quotaExceeded = false\n\n /** Resolve the static (non-overridden) store for a given route name. */\n function resolveOriginalStore(route: string): NoydbStore {\n if (route === 'blobs') return simpleBlobStore ?? tieredBlobs?.large ?? primary\n if (route === 'cold') return opts.age?.cold ?? primary\n if (opts.routes?.[route]) return opts.routes[route]\n if (opts.vaultRoutes?.[route]) return opts.vaultRoutes[route]\n return primary\n }\n\n /**\n * Queue a write operation if the route is suspended with queue: true.\n * Returns true if queued (caller should skip the actual write).\n */\n function maybeQueueWrite(\n routeName: string,\n method: 'put' | 'delete',\n vault: string,\n collection: string,\n id: string,\n envelope?: EncryptedEnvelope,\n expectedVersion?: number,\n ): boolean {\n if (!suspended.has(routeName)) return false\n const queue = writeQueues.get(routeName)\n if (!queue) return false // suspended but no queue — NullStore behavior\n\n // Evict oldest if at capacity\n if (queue.writes.length >= queue.maxSize) {\n queue.writes.shift()\n }\n queue.writes.push({\n method, vault, collection, id,\n ...(envelope !== undefined ? { envelope } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n })\n return true\n }\n\n // ── Routing logic ──────────────────────────────────────────────────\n\n function isBlobChunks(collection: string): boolean {\n return collection === BLOB_CHUNKS\n }\n\n function isBlobMeta(collection: string): boolean {\n return collection === BLOB_INDEX\n || collection.startsWith(BLOB_SLOTS)\n || collection.startsWith(BLOB_VERSIONS)\n }\n\n function isInternal(collection: string): boolean {\n return collection.startsWith('_')\n }\n\n /**\n * Resolve the store for a given vault + collection.\n * Resolution order: overrides/suspend → vaultRoutes → routes → blobs → default\n */\n function storeFor(vault: string, collection: string): NoydbStore {\n const rName = routeNameFor(vault, collection)\n\n // 0. Runtime override / suspend check\n if (suspended.has(rName)) return NULL_STORE\n if (overrides.has(rName)) return overrides.get(rName)!\n\n // 1. Vault-based geographic routing\n if (opts.vaultRoutes) {\n for (const [prefix, store] of Object.entries(opts.vaultRoutes)) {\n if (vault.startsWith(prefix)) return store\n }\n }\n\n // 2. Per-collection routing (user collections only)\n if (opts.routes && !isInternal(collection) && opts.routes[collection]) {\n return opts.routes[collection]\n }\n\n // 3. Blob chunk routing (simple — no size tiering at the store level)\n if (isBlobChunks(collection)) {\n if (simpleBlobStore) return simpleBlobStore\n // Size-tiered: can't determine here without the envelope.\n // Default to large store — BlobSet will use storeHint for reads.\n if (tieredBlobs) return tieredBlobs.large\n }\n\n // 4. Blob metadata routing\n if (opts.routeBlobMeta && isBlobMeta(collection)) {\n if (simpleBlobStore) return simpleBlobStore\n if (tieredBlobs) return tieredBlobs.large\n }\n\n // 5. Quota-aware overflow (E8)\n if (quotaExceeded && opts.overflow) return opts.overflow\n\n // 6. Default\n return primary\n }\n\n /**\n * For size-tiered blob routing: pick store based on envelope data size.\n */\n function blobStoreForSize(dataSize: number): NoydbStore {\n if (!tieredBlobs) return simpleBlobStore ?? primary\n if (dataSize <= blobThreshold) {\n return tieredBlobs.small ?? primary\n }\n return tieredBlobs.large\n }\n\n /**\n * Age routing: check if a record is cold based on `_ts`.\n */\n function isCold(collection: string, envelope: EncryptedEnvelope, before?: string): boolean {\n if (!opts.age) return false\n if (isInternal(collection)) return false\n if (opts.age.collections && opts.age.collections.length > 0) {\n if (!opts.age.collections.includes(collection)) return false\n }\n // explicit period cutoff wins; else the rolling age cutoff; else nothing is cold\n const cutoffIso =\n before ??\n (opts.age.coldAfterDays != null\n ? new Date(Date.now() - opts.age.coldAfterDays * 24 * 60 * 60 * 1000).toISOString()\n : undefined)\n if (cutoffIso === undefined) return false\n return envelope._ts < cutoffIso\n }\n\n // ── Store methods ──────────────────────────────────────────────────\n\n // #613: advertise cold-archival when a cold route exists. Spread the\n // primary's capabilities so CAS/auth/etc. still surface; layer the flag.\n // A router with no cold route of its own must NOT inherit `coldArchival:\n // true` from a nested cold-capable primary (whole-branch review I1) — force\n // it off explicitly so the consumer's `!== true` gate throws.\n const store: RoutedNoydbStore = {\n name: buildName(),\n ...(opts.age?.cold\n ? { capabilities: { ...primary.capabilities, coldArchival: true } as StoreCapabilities }\n : primary.capabilities\n ? { capabilities: { ...primary.capabilities, coldArchival: false } as StoreCapabilities }\n : {}),\n\n async get(vault, collection, id) {\n const s = storeFor(vault, collection)\n const result = await s.get(vault, collection, id)\n\n // Age tiering: if hot store returned null, try cold\n if (result === null && opts.age && !isInternal(collection)) {\n if (!opts.age.collections?.length || opts.age.collections.includes(collection)) {\n return opts.age.cold.get(vault, collection, id)\n }\n }\n\n return result\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n // Write-behind queue: buffer if suspended with queue option\n const rn = routeNameFor(vault, collection)\n if (maybeQueueWrite(rn, 'put', vault, collection, id, envelope, expectedVersion)) return\n\n // Size-tiered blob routing\n if (isBlobChunks(collection) && tieredBlobs) {\n const dataSize = envelope._data.length\n const s = blobStoreForSize(dataSize)\n return s.put(vault, collection, id, envelope, expectedVersion)\n }\n\n const s = storeFor(vault, collection)\n\n // Age tiering: if a cold record is being updated, it goes to hot.\n if (opts.age && !isInternal(collection)) {\n opts.age.cold.delete(vault, collection, id).catch(() => {})\n }\n\n return s.put(vault, collection, id, envelope, expectedVersion)\n },\n\n async delete(vault, collection, id) {\n // Write-behind queue: buffer if suspended with queue option\n const rn = routeNameFor(vault, collection)\n if (maybeQueueWrite(rn, 'delete', vault, collection, id)) return\n\n const s = storeFor(vault, collection)\n await s.delete(vault, collection, id)\n\n // Also delete from cold store if age-tiered\n if (opts.age && !isInternal(collection)) {\n await opts.age.cold.delete(vault, collection, id).catch(() => {})\n }\n },\n\n async list(vault, collection) {\n const s = storeFor(vault, collection)\n const ids = await s.list(vault, collection)\n\n // Age tiering: merge IDs from cold store, deduplicate\n if (opts.age && !isInternal(collection)) {\n if (!opts.age.collections?.length || opts.age.collections.includes(collection)) {\n const coldIds = await opts.age.cold.list(vault, collection).catch(() => [] as string[])\n if (coldIds.length > 0) {\n const merged = new Set(ids)\n for (const id of coldIds) merged.add(id)\n return [...merged]\n }\n }\n }\n\n return ids\n },\n\n async loadAll(vault) {\n // Query all distinct stores in parallel, merge snapshots\n const stores = getStoresForVault(vault)\n const snapshots = await Promise.all(\n stores.map(s => s.loadAll(vault).catch(() => ({}) as VaultSnapshot)),\n )\n return mergeSnapshots(snapshots)\n },\n\n async saveAll(vault, data) {\n // Partition snapshot by routing rules\n const partitioned = new Map<NoydbStore, VaultSnapshot>()\n\n for (const [collection, records] of Object.entries(data)) {\n const s = storeFor(vault, collection)\n if (!partitioned.has(s)) partitioned.set(s, {})\n partitioned.get(s)![collection] = records\n }\n\n await Promise.all(\n [...partitioned.entries()].map(([s, snap]) => s.saveAll(vault, snap)),\n )\n },\n\n async compact(vault, compactOpts) {\n if (!opts.age) return 0\n let migrated = 0\n const collections = opts.age.collections?.length\n ? opts.age.collections\n : Object.keys(await primary.loadAll(vault).catch(() => ({}) as VaultSnapshot))\n\n for (const collection of collections) {\n const ids = await primary.list(vault, collection).catch(() => [] as string[])\n for (const id of ids) {\n const envelope = await primary.get(vault, collection, id)\n if (!envelope) continue\n if (isCold(collection, envelope, compactOpts?.before)) {\n await opts.age.cold.put(vault, collection, id, envelope)\n await primary.delete(vault, collection, id)\n migrated++\n }\n }\n }\n return migrated\n },\n\n // ── Runtime override / suspend ──────────────────────\n\n override(route: OverrideTarget, overrideStore: NoydbStore, overrideOpts?: OverrideOptions): void | Promise<void> {\n if (overrideOpts?.hydrate) {\n // Async hydration: copy data from current store, then activate override\n return (async () => {\n // Hydration: caller should copy data from the original store to\n // overrideStore before calling override() with { hydrate: true }.\n // The route is activated immediately after.\n overrides.set(route, overrideStore)\n })()\n }\n overrides.set(route, overrideStore)\n },\n\n clearOverride(route: OverrideTarget): void {\n overrides.delete(route)\n },\n\n suspend(route: OverrideTarget, suspendOpts?: SuspendOptions): void {\n suspended.add(route)\n if (suspendOpts?.queue) {\n writeQueues.set(route, {\n writes: [],\n maxSize: suspendOpts.maxQueueSize ?? 10_000,\n })\n }\n },\n\n async resume(route: OverrideTarget): Promise<number> {\n suspended.delete(route)\n const queue = writeQueues.get(route)\n if (!queue || queue.writes.length === 0) {\n writeQueues.delete(route)\n return 0\n }\n\n // Replay queued writes against the now-active store\n let replayed = 0\n const target = overrides.get(route) ?? resolveOriginalStore(route)\n for (const write of queue.writes) {\n try {\n if (write.method === 'put' && write.envelope) {\n await target.put(write.vault, write.collection, write.id, write.envelope, write.expectedVersion)\n } else if (write.method === 'delete') {\n await target.delete(write.vault, write.collection, write.id)\n }\n replayed++\n } catch {\n // Best-effort replay — conflicts are expected after suspension\n }\n }\n\n writeQueues.delete(route)\n return replayed\n },\n\n routeStatus(): RouteStatus {\n const ov: Record<string, string> = {}\n for (const [k, v] of overrides) ov[k] = v.name ?? 'unnamed'\n const q: Record<string, number> = {}\n for (const [k, v] of writeQueues) q[k] = v.writes.length\n return { overrides: ov, suspended: [...suspended], queued: q }\n },\n\n resolveBackend(vaultId: string): NoydbStore {\n // Geographic routing is vault-prefix based + collection-independent;\n // the region-relevant backend is the vaultRoutes match, else default.\n if (opts.vaultRoutes) {\n for (const [prefix, s] of Object.entries(opts.vaultRoutes)) {\n if (vaultId.startsWith(prefix)) return s\n }\n }\n return primary\n },\n }\n\n // ── Optional method forwarding ─────────────────────────────────────\n\n // Forward listVaults from all stores, deduplicated\n if (anyHas('listVaults')) {\n store.listVaults = async () => {\n const results = await Promise.all(\n [...allStores]\n .filter(s => s.listVaults !== undefined)\n .map(s => s.listVaults!().catch(() => [] as string[])),\n )\n return [...new Set(results.flat())]\n }\n }\n\n // Forward ping — succeed if any store responds\n if (anyHas('ping')) {\n store.ping = async () => {\n const results = await Promise.all(\n [...allStores]\n .filter(s => s.ping !== undefined)\n .map(s => s.ping!().catch(() => false)),\n )\n return results.some(Boolean)\n }\n }\n\n return store\n\n // ── Helpers ────────────────────────────────────────────────────────\n\n function buildName(): string {\n const names = [...allStores].map(s => s.name ?? '?').join('+')\n return `route(${names})`\n }\n\n function anyHas(method: string): boolean {\n return [...allStores].some(s => (s as unknown as Record<string, unknown>)[method])\n }\n\n function getStoresForVault(vault: string): NoydbStore[] {\n const stores = new Set<NoydbStore>()\n\n // Check vault routes first\n if (opts.vaultRoutes) {\n for (const [prefix, s] of Object.entries(opts.vaultRoutes)) {\n if (vault.startsWith(prefix)) {\n stores.add(s)\n return [...stores] // vault-routed: only use that store\n }\n }\n }\n\n // Default topology: primary + blob store + cold store\n stores.add(primary)\n if (simpleBlobStore) stores.add(simpleBlobStore)\n if (tieredBlobs?.large) stores.add(tieredBlobs.large)\n if (tieredBlobs?.small && tieredBlobs.small !== primary) stores.add(tieredBlobs.small)\n if (opts.age?.cold) stores.add(opts.age.cold)\n if (opts.routes) {\n for (const s of Object.values(opts.routes)) stores.add(s)\n }\n\n return [...stores]\n }\n}\n\n// ─── Snapshot merge ──────────────────────────────────────────────────────\n\nfunction mergeSnapshots(snapshots: VaultSnapshot[]): VaultSnapshot {\n const merged: VaultSnapshot = {}\n\n for (const snap of snapshots) {\n for (const [collection, records] of Object.entries(snap)) {\n if (!merged[collection]) {\n merged[collection] = { ...records }\n continue\n }\n for (const [id, envelope] of Object.entries(records)) {\n const existing = merged[collection][id]\n // Last-write-wins by _ts\n if (!existing || envelope._ts >= existing._ts) {\n merged[collection][id] = envelope\n }\n }\n }\n }\n\n return merged\n}\n","/**\n * Store middleware — composable interceptors for NoydbStore.\n *\n * ```ts\n * const resilient = wrapStore(\n * dynamo({ table: 'myapp' }),\n * withRetry({ maxRetries: 3 }),\n * withLogging({ level: 'debug' }),\n * withCache({ ttlMs: 60_000 }),\n * )\n * ```\n *\n * Each middleware is `(next: NoydbStore) => NoydbStore`. They compose\n * left-to-right: first middleware is outermost (processes requests first,\n * responses last).\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../kernel/types.js'\n\n// ─── Core composition ───────────────────────────────────────────────────\n\n/**\n * A store middleware function.\n *\n * Takes the next store in the chain and returns a wrapped store. Middlewares\n * compose left-to-right via `wrapStore()`: the first argument is outermost\n * (first to intercept requests, last to process responses).\n *\n * ```ts\n * const mw: StoreMiddleware = (next) => ({\n * ...next,\n * async get(vault, collection, id) {\n * console.log('get', id)\n * return next.get(vault, collection, id)\n * },\n * })\n * ```\n */\nexport type StoreMiddleware = (next: NoydbStore) => NoydbStore\n\n/**\n * Wrap a store with one or more middlewares. Middlewares compose left-to-right.\n */\nexport function wrapStore(store: NoydbStore, ...middlewares: StoreMiddleware[]): NoydbStore {\n let result = store\n // Apply right-to-left so the first middleware is the outermost wrapper\n for (let i = middlewares.length - 1; i >= 0; i--) {\n result = middlewares[i]!(result)\n }\n return result\n}\n\n// ─── withRetry ──────────────────────────────────────────────────────────\n\n/** Options for `withRetry()`. */\nexport interface RetryOptions {\n /** Maximum retry attempts. Default: 3. */\n maxRetries?: number\n /** Base backoff delay in ms. Default: 500. */\n backoffMs?: number\n /** Jitter factor (0-1). Adds random delay up to `backoffMs * jitter`. Default: 0.3. */\n jitter?: number\n /** Only retry on these error codes. Default: retry all errors. */\n retryOn?: string[]\n}\n\n/**\n * Middleware that retries failed store operations with exponential backoff\n * and optional jitter. Useful for transient network errors on DynamoDB/S3.\n *\n * ```ts\n * wrapStore(dynamo({ table: 'myapp' }), withRetry({ maxRetries: 5, retryOn: ['NETWORK_ERROR'] }))\n * ```\n */\nexport function withRetry(opts: RetryOptions = {}): StoreMiddleware {\n const maxRetries = opts.maxRetries ?? 3\n const backoffMs = opts.backoffMs ?? 500\n const jitter = opts.jitter ?? 0.3\n const retryOn = opts.retryOn ? new Set(opts.retryOn) : null\n\n function shouldRetry(err: unknown): boolean {\n if (!retryOn) return true\n if (err && typeof err === 'object' && 'code' in err) {\n return retryOn.has((err as { code: string }).code)\n }\n return true\n }\n\n async function retryable<T>(fn: () => Promise<T>): Promise<T> {\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn()\n } catch (err) {\n lastError = err\n if (attempt >= maxRetries || !shouldRetry(err)) throw err\n const delay = backoffMs * Math.pow(2, attempt) * (1 + Math.random() * jitter)\n await new Promise(r => setTimeout(r, delay))\n }\n }\n throw lastError\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `retry(${next.name})` : 'retry',\n get: (v, c, id) => retryable(() => next.get(v, c, id)),\n put: (v, c, id, env, ev) => retryable(() => next.put(v, c, id, env, ev)),\n delete: (v, c, id) => retryable(() => next.delete(v, c, id)),\n list: (v, c) => retryable(() => next.list(v, c)),\n loadAll: (v) => retryable(() => next.loadAll(v)),\n saveAll: (v, d) => retryable(() => next.saveAll(v, d)),\n })\n}\n\n// ─── withLogging ────────────────────────────────────────────────────────\n\n/** Log level for `withLogging()`. Maps to standard console method names. */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/** Options for `withLogging()`. */\nexport interface LoggingOptions {\n /** Minimum log level. Default: 'info'. */\n level?: LogLevel\n /** Custom logger. Default: console. */\n logger?: {\n debug(msg: string, ...args: unknown[]): void\n info(msg: string, ...args: unknown[]): void\n warn(msg: string, ...args: unknown[]): void\n error(msg: string, ...args: unknown[]): void\n }\n /** Log the data payload (envelope contents). Default: false (privacy). */\n logData?: boolean\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 }\n\n/**\n * Middleware that logs every store operation with its method name, arguments,\n * and elapsed duration. Privacy-safe by default: envelope payloads are not\n * logged unless `logData: true` is set.\n */\nexport function withLogging(opts: LoggingOptions = {}): StoreMiddleware {\n const minLevel = LOG_LEVELS[opts.level ?? 'info']\n const logger = opts.logger ?? console\n const logData = opts.logData ?? false\n\n function log(level: LogLevel, method: string, args: Record<string, unknown>, durationMs?: number) {\n if (LOG_LEVELS[level] < minLevel) return\n const parts = [`[noydb:${method}]`, ...Object.entries(args).map(([k, v]) => `${k}=${String(v)}`)]\n if (durationMs !== undefined) parts.push(`${durationMs}ms`)\n logger[level](parts.join(' '))\n }\n\n function timed<T>(method: string, args: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n const start = Date.now()\n return fn().then(\n (result) => {\n log('debug', method, args, Date.now() - start)\n return result\n },\n (err) => {\n log('error', method, { ...args, error: (err as Error).message }, Date.now() - start)\n throw err\n },\n )\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `log(${next.name})` : 'log',\n get: (v, c, id) => timed('get', { vault: v, collection: c, id }, () => next.get(v, c, id)),\n put: (v, c, id, env, ev) => timed('put', {\n vault: v, collection: c, id, version: env._v,\n ...(logData ? { data: env._data.slice(0, 40) + '...' } : {}),\n }, () => next.put(v, c, id, env, ev)),\n delete: (v, c, id) => timed('delete', { vault: v, collection: c, id }, () => next.delete(v, c, id)),\n list: (v, c) => timed('list', { vault: v, collection: c }, () => next.list(v, c)),\n loadAll: (v) => timed('loadAll', { vault: v }, () => next.loadAll(v)),\n saveAll: (v, d) => timed('saveAll', { vault: v }, () => next.saveAll(v, d)),\n })\n}\n\n// ─── withMetrics ────────────────────────────────────────────────────────\n\n/**\n * Data emitted to `MetricsOptions.onOperation` after every store call.\n *\n * Carries method name, vault/collection/id context, elapsed duration,\n * and success/failure status. Wire this into your metrics pipeline\n * (DataDog, Prometheus, CloudWatch) to get per-operation latency histograms.\n */\nexport interface StoreOperation {\n method: 'get' | 'put' | 'delete' | 'list' | 'loadAll' | 'saveAll'\n vault: string\n collection?: string\n id?: string\n durationMs: number\n success: boolean\n error?: Error\n}\n\n/** Options for `withMetrics()`. */\nexport interface MetricsOptions {\n /** Called after every store operation. */\n onOperation: (op: StoreOperation) => void\n}\n\n/**\n * Middleware that calls `onOperation` after every store method with timing\n * and success/failure data. Designed for low-overhead integration with\n * metrics systems — the callback is synchronous and fire-and-forget.\n */\nexport function withMetrics(opts: MetricsOptions): StoreMiddleware {\n function tracked<T>(\n method: StoreOperation['method'],\n vault: string,\n fn: () => Promise<T>,\n collection?: string,\n id?: string,\n ): Promise<T> {\n const start = Date.now()\n return fn().then(\n (result) => {\n opts.onOperation({\n method, vault,\n ...(collection !== undefined ? { collection } : {}),\n ...(id !== undefined ? { id } : {}),\n durationMs: Date.now() - start, success: true,\n })\n return result\n },\n (err) => {\n opts.onOperation({\n method, vault,\n ...(collection !== undefined ? { collection } : {}),\n ...(id !== undefined ? { id } : {}),\n durationMs: Date.now() - start, success: false, error: err as Error,\n })\n throw err\n },\n )\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `metrics(${next.name})` : 'metrics',\n get: (v, c, id) => tracked('get', v, () => next.get(v, c, id), c, id),\n put: (v, c, id, env, ev) => tracked('put', v, () => next.put(v, c, id, env, ev), c, id),\n delete: (v, c, id) => tracked('delete', v, () => next.delete(v, c, id), c, id),\n list: (v, c) => tracked('list', v, () => next.list(v, c), c),\n loadAll: (v) => tracked('loadAll', v, () => next.loadAll(v)),\n saveAll: (v, d) => tracked('saveAll', v, () => next.saveAll(v, d)),\n })\n}\n\n// ─── withCircuitBreaker ─────────────────────────────────────────────────\n\n/**\n * Options for `withCircuitBreaker()`.\n *\n * The circuit breaker moves through three states:\n * - `closed`: normal operation.\n * - `open`: store is failing; all calls return fallback values immediately.\n * - `half-open`: one probe call after `resetTimeoutMs` — success closes, failure re-opens.\n */\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures before opening the circuit. Default: 5. */\n failureThreshold?: number\n /** Time in ms before attempting to half-open the circuit. Default: 30_000. */\n resetTimeoutMs?: number\n /** Called when the circuit opens (store becomes unavailable). */\n onOpen?: () => void\n /** Called when the circuit closes (store recovers). */\n onClose?: () => void\n}\n\ntype CircuitState = 'closed' | 'open' | 'half-open'\n\n/**\n * Middleware that implements the circuit-breaker pattern.\n *\n * When the wrapped store fails `failureThreshold` consecutive times, the\n * circuit opens: subsequent calls return safe fallback values (`null`, `[]`,\n * `{}`) without hitting the store. After `resetTimeoutMs` the circuit\n * half-opens and allows one probe — success closes the circuit, failure\n * keeps it open. Pair with `withRetry` to handle transient errors before\n * they trip the circuit.\n */\nexport function withCircuitBreaker(opts: CircuitBreakerOptions = {}): StoreMiddleware {\n const threshold = opts.failureThreshold ?? 5\n const resetMs = opts.resetTimeoutMs ?? 30_000\n\n let state: CircuitState = 'closed'\n let failures = 0\n let lastFailureTime = 0\n\n function recordSuccess(): void {\n if (state === 'half-open') {\n state = 'closed'\n failures = 0\n opts.onClose?.()\n }\n failures = 0\n }\n\n function recordFailure(): void {\n failures++\n lastFailureTime = Date.now()\n if (failures >= threshold && state === 'closed') {\n state = 'open'\n opts.onOpen?.()\n }\n }\n\n function canAttempt(): boolean {\n if (state === 'closed') return true\n if (state === 'open') {\n if (Date.now() - lastFailureTime >= resetMs) {\n state = 'half-open'\n return true\n }\n return false\n }\n // half-open: allow one attempt\n return true\n }\n\n async function guarded<T>(fn: () => Promise<T>, fallback: T): Promise<T> {\n if (!canAttempt()) return fallback\n try {\n const result = await fn()\n recordSuccess()\n return result\n } catch (err) {\n recordFailure()\n throw err\n }\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `cb(${next.name})` : 'cb',\n get: (v, c, id) => guarded(() => next.get(v, c, id), null),\n put: (v, c, id, env, ev) => guarded(() => next.put(v, c, id, env, ev), undefined),\n delete: (v, c, id) => guarded(() => next.delete(v, c, id), undefined),\n list: (v, c) => guarded(() => next.list(v, c), []),\n loadAll: (v) => guarded(() => next.loadAll(v), {}),\n saveAll: (v, d) => guarded(() => next.saveAll(v, d), undefined),\n })\n}\n\n// ─── withCache (read-through) ───────────────────────────────────────────\n\n/**\n * Options for `withCache()`.\n *\n * The cache is a read-through LRU that caches individual record fetches\n * (`get`). Writes (`put`, `delete`) invalidate the relevant cache entry\n * immediately. `list`, `loadAll`, and `saveAll` bypass the cache.\n *\n * Named `StoreCacheOptions` to distinguish from `CacheOptions` in\n * `@noy-db/hub/collection`, which controls the in-memory decrypted-record LRU.\n */\nexport interface StoreCacheOptions {\n /** Maximum cached entries. Default: 500. */\n maxEntries?: number\n /** Cache TTL in ms. Default: 60_000 (1 minute). 0 = no expiry. */\n ttlMs?: number\n}\n\ninterface CacheEntry {\n envelope: EncryptedEnvelope | null\n cachedAt: number\n}\n\n/**\n * Middleware that adds a read-through LRU cache for `get()` calls.\n *\n * Reduces latency for frequently-read records (e.g. lookup tables, user\n * profiles) by serving repeat reads from memory. Because NOYDB records are\n * encrypted at rest, caching envelopes is safe — the cache holds ciphertext,\n * not plaintext. For write-heavy workloads, the cache provides little benefit\n * and should be omitted to avoid the invalidation overhead.\n */\nexport function withCache(opts: StoreCacheOptions = {}): StoreMiddleware {\n const maxEntries = opts.maxEntries ?? 500\n const ttlMs = opts.ttlMs ?? 60_000\n\n // LRU cache: Map preserves insertion order, we delete+re-insert on access\n const cache = new Map<string, CacheEntry>()\n\n function cacheKey(vault: string, collection: string, id: string): string {\n return `${vault}\\0${collection}\\0${id}`\n }\n\n function getFromCache(key: string): EncryptedEnvelope | null | undefined {\n const entry = cache.get(key)\n if (!entry) return undefined\n if (ttlMs > 0 && Date.now() - entry.cachedAt > ttlMs) {\n cache.delete(key)\n return undefined\n }\n // LRU: move to end\n cache.delete(key)\n cache.set(key, entry)\n return entry.envelope\n }\n\n function setInCache(key: string, envelope: EncryptedEnvelope | null): void {\n // Evict oldest if at capacity\n if (cache.size >= maxEntries) {\n const oldest = cache.keys().next().value\n if (oldest !== undefined) cache.delete(oldest)\n }\n cache.set(key, { envelope, cachedAt: Date.now() })\n }\n\n function invalidate(key: string): void {\n cache.delete(key)\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `cache(${next.name})` : 'cache',\n\n async get(vault, collection, id) {\n const key = cacheKey(vault, collection, id)\n const cached = getFromCache(key)\n if (cached !== undefined) return cached\n const result = await next.get(vault, collection, id)\n setInCache(key, result)\n return result\n },\n\n async put(vault, collection, id, env, ev) {\n invalidate(cacheKey(vault, collection, id))\n await next.put(vault, collection, id, env, ev)\n setInCache(cacheKey(vault, collection, id), env)\n },\n\n async delete(vault, collection, id) {\n invalidate(cacheKey(vault, collection, id))\n await next.delete(vault, collection, id)\n },\n\n list: (v, c) => next.list(v, c),\n loadAll: (v) => next.loadAll(v),\n saveAll: (v, d) => next.saveAll(v, d),\n })\n}\n\n// ─── withHealthCheck ────────────────────────────────────────────────────\n\nexport interface HealthCheckOptions {\n /** Ping interval in ms. Default: 30_000. */\n checkIntervalMs?: number\n /** Suspend after N consecutive ping failures. Default: 3. */\n suspendAfterFailures?: number\n /** Resume after N consecutive ping successes. Default: 1. */\n resumeAfterSuccess?: number\n /** Called when the store is auto-suspended. */\n onSuspend?: () => void\n /** Called when the store is auto-resumed. */\n onResume?: () => void\n /**\n * Custom health check. Default: calls `store.ping()` if available,\n * otherwise attempts a `list()` on a sentinel collection.\n */\n check?: () => Promise<boolean>\n}\n\n/**\n * Auto-suspends a store when health checks fail, auto-resumes when they recover.\n *\n * When suspended, `get` returns null, `put`/`delete` are no-ops, `list` returns [].\n * This is identical to the `NullStore` behavior from `routeStore.suspend()`.\n */\nexport function withHealthCheck(opts: HealthCheckOptions = {}): StoreMiddleware {\n const intervalMs = opts.checkIntervalMs ?? 30_000\n const failThreshold = opts.suspendAfterFailures ?? 3\n const successThreshold = opts.resumeAfterSuccess ?? 1\n\n let isSuspended = false\n let consecutiveFailures = 0\n let consecutiveSuccesses = 0\n\n return (next) => {\n const checkFn = opts.check ?? (\n next.ping\n ? () => next.ping!()\n : async () => { await next.list('__health__', '__ping__'); return true }\n )\n\n async function doCheck(): Promise<void> {\n try {\n const ok = await checkFn()\n if (ok) {\n consecutiveFailures = 0\n consecutiveSuccesses++\n if (isSuspended && consecutiveSuccesses >= successThreshold) {\n isSuspended = false\n consecutiveSuccesses = 0\n opts.onResume?.()\n }\n } else {\n throw new Error('Health check returned false')\n }\n } catch {\n consecutiveSuccesses = 0\n consecutiveFailures++\n if (!isSuspended && consecutiveFailures >= failThreshold) {\n isSuspended = true\n consecutiveFailures = 0\n opts.onSuspend?.()\n }\n }\n }\n\n // Start checking\n setInterval(() => { void doCheck() }, intervalMs)\n\n const wrapped: NoydbStore = {\n ...next,\n name: next.name ? `health(${next.name})` : 'health',\n\n async get(v, c, id) { return isSuspended ? null : next.get(v, c, id) },\n async put(v, c, id, env, ev) { if (!isSuspended) await next.put(v, c, id, env, ev) },\n async delete(v, c, id) { if (!isSuspended) await next.delete(v, c, id) },\n async list(v, c) { return isSuspended ? [] : next.list(v, c) },\n async loadAll(v) { return isSuspended ? {} : next.loadAll(v) },\n async saveAll(v, d) { if (!isSuspended) await next.saveAll(v, d) },\n }\n\n return wrapped\n }\n}\n"],"mappings":";AA2BA,IAAM,cAAc;AACpB,IAAM,aAAa;AACnB,IAAM,aAAa;AACnB,IAAM,gBAAgB;AA4Rf,SAAS,WAAW,MAA2C;AACpE,QAAM,UAAU,KAAK;AAGrB,QAAM,gBAAgB,KAAK,SAAS,SAAS,KAAK;AAClD,QAAM,kBAAkB,gBAAgB,KAAK,QAAQ;AACrD,QAAM,cAAc,CAAC,gBAAgB,KAAK,QAAQ;AAClD,QAAM,gBAAgB,aAAa,aAAa,MAAM;AAGtD,QAAM,YAAY,oBAAI,IAAgB,CAAC,OAAO,CAAC;AAC/C,MAAI,gBAAiB,WAAU,IAAI,eAAe;AAClD,MAAI,aAAa,MAAO,WAAU,IAAI,YAAY,KAAK;AACvD,MAAI,aAAa,MAAO,WAAU,IAAI,YAAY,KAAK;AACvD,MAAI,KAAK,KAAK,KAAM,WAAU,IAAI,KAAK,IAAI,IAAI;AAC/C,MAAI,KAAK,OAAQ,YAAW,KA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AAAA,IAAE,GAAG,UAAU;AAEhD,UAAM,UAAsB;AAAA,MAC1B,GAAG;AAAA,MACH,MAAM,KAAK,OAAO,UAAU,KAAK,IAAI,MAAM;AAAA,MAE3C,MAAM,IAAI,GAAG,GAAG,IAAI;AAAE,eAAO,cAAc,OAAO,KAAK,IAAI,GAAG,GAAG,EAAE;AAAA,MAAE;AAAA,MACrE,MAAM,IAAI,GAAG,GAAG,IAAI,KAAK,IAAI;AAAE,YAAI,CAAC,YAAa,OAAM,KAAK,IAAI,GAAG,GAAG,IAAI,KAAK,EAAE;AAAA,MAAE;AAAA,MACnF,MAAM,OAAO,GAAG,GAAG,IAAI;AAAE,YAAI,CAAC,YAAa,OAAM,KAAK,OAAO,GAAG,GAAG,EAAE;AAAA,MAAE;AAAA,MACvE,MAAM,KAAK,GAAG,GAAG;AAAE,eAAO,cAAc,CAAC,IAAI,KAAK,KAAK,GAAG,CAAC;AAAA,MAAE;AAAA,MAC7D,MAAM,QAAQ,GAAG;AAAE,eAAO,cAAc,CAAC,IAAI,KAAK,QAAQ,CAAC;AAAA,MAAE;AAAA,MAC7D,MAAM,QAAQ,GAAG,GAAG;AAAE,YAAI,CAAC,YAAa,OAAM,KAAK,QAAQ,GAAG,CAAC;AAAA,MAAE;AAAA,IACnE;AAEA,WAAO;AAAA,EACT;AACF;","names":["store","s"]}
@@ -399,7 +399,7 @@ async function createOwnerOnAdoptedPartition(store, vaultName, opts) {
399
399
  }
400
400
  }
401
401
  if (isManaged(opts)) {
402
- const { createNoydb } = await import("./noydb-KXS35UJS.js");
402
+ const { createNoydb } = await import("./noydb-FHZ4ZDBP.js");
403
403
  const db = await createNoydb({
404
404
  store,
405
405
  user: userId,
@@ -455,4 +455,4 @@ export {
455
455
  withCargo,
456
456
  describeExtraction
457
457
  };
458
- //# sourceMappingURL=chunk-PT4XLP6I.js.map
458
+ //# sourceMappingURL=chunk-JTR75MKH.js.map
@@ -216,4 +216,4 @@ export {
216
216
  BUNDLE_STORE_POLICY,
217
217
  SyncScheduler
218
218
  };
219
- //# sourceMappingURL=chunk-VQNJ7UZL.js.map
219
+ //# sourceMappingURL=chunk-MTJLOC3Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/kernel/sync-policy.ts"],"sourcesContent":["/**\n * Sync scheduling policy.\n *\n * ## What it controls\n *\n * A {@link SyncPolicy} has two halves:\n * - **push** ({@link PushPolicy}) — when dirty local writes are sent to the remote.\n * - **pull** ({@link PullPolicy}) — when the remote is polled for new data.\n *\n * ## Choosing a policy\n *\n * The right policy depends on the backend's operational characteristics:\n *\n * | Backend type | Recommended policy |\n * |---|---|\n * | Per-record (DynamoDB, S3, IDB) | {@link INDEXED_STORE_POLICY} — `on-change` push, `manual` pull |\n * | Bundle (Drive, WebDAV, Git) | {@link POD_STORE_POLICY} — `debounce` push, `interval` pull |\n *\n * Consumers can override via `createNoydb({ syncPolicy: { ... } })`:\n *\n * ```ts\n * const db = await createNoydb({\n * store: toFile({ dir: './data' }),\n * syncPolicy: {\n * push: { mode: 'debounce', debounceMs: 5_000 },\n * pull: { mode: 'on-focus' },\n * },\n * })\n * ```\n *\n * ## Scheduler lifecycle\n *\n * {@link SyncScheduler} owns all timers, debounce logic, and browser lifecycle\n * hooks (`visibilitychange`, `pagehide`, `beforeExit`). Call `scheduler.start()`\n * after opening a vault and `scheduler.stop()` when closing it. The scheduler\n * delegates actual push/pull work to {@link SyncSchedulerCallbacks} provided\n * by the {@link SyncEngine}.\n *\n * @module\n */\n\n// ─── Policy types ───────────────────────────────────────────────────────\n\n/**\n * When push operations are triggered automatically.\n *\n * - `'manual'` — only on explicit `sync.push()` calls.\n * - `'on-change'` — immediately after every local write (respecting `minIntervalMs`).\n * - `'debounce'` — after `debounceMs` of inactivity following a write.\n * - `'interval'` — on a fixed timer regardless of writes.\n */\nexport type PushMode = 'manual' | 'on-change' | 'debounce' | 'interval'\n\n/**\n * When pull operations are triggered automatically.\n *\n * - `'manual'` — only on explicit `sync.pull()` calls.\n * - `'interval'` — on a fixed `intervalMs` timer.\n * - `'on-focus'` — when the browser tab regains visibility.\n */\nexport type PullMode = 'manual' | 'interval' | 'on-focus'\n\n/**\n * Push half of a sync policy. Controls the trigger mode and timing guards\n * for outbound sync operations.\n */\nexport interface PushPolicy {\n /** Push trigger mode. */\n readonly mode: PushMode\n /** Debounce delay in ms. Only used when `mode: 'debounce'`. Default: 30_000. */\n readonly debounceMs?: number\n /** Interval in ms between automatic pushes. Used by `'interval'` and as floor for `'debounce'`. */\n readonly intervalMs?: number\n /**\n * Hard floor between pushes regardless of mode. Prevents burst writes\n * from hammering the remote. Default: 0 (no floor).\n */\n readonly minIntervalMs?: number\n /**\n * Force a push on page unload (`pagehide` / `visibilitychange → hidden`)\n * in browsers, `beforeExit` in Node. Default: true for non-manual modes.\n */\n readonly onUnload?: boolean\n}\n\n/**\n * Pull half of a sync policy. Controls when and how often inbound sync\n * operations are triggered.\n */\nexport interface PullPolicy {\n /** Pull trigger mode. */\n readonly mode: PullMode\n /** Interval in ms between automatic pulls. Used by `'interval'` mode. Default: 60_000. */\n readonly intervalMs?: number\n}\n\n/**\n * Combined push + pull sync scheduling policy for a vault.\n *\n * Pass via `createNoydb({ syncPolicy })` to override the default policy\n * derived from the active store type. Pre-built defaults are available\n * as `INDEXED_STORE_POLICY` and `POD_STORE_POLICY`.\n */\nexport interface SyncPolicy {\n readonly push: PushPolicy\n readonly pull: PullPolicy\n}\n\n// ─── Default policies by store category ─────────────────────────────────\n\n/** Default for per-record stores (DynamoDB, S3, file, IDB). */\nexport const INDEXED_STORE_POLICY: SyncPolicy = {\n push: { mode: 'on-change', minIntervalMs: 0, onUnload: true },\n pull: { mode: 'manual' },\n}\n\n/** Default for bundle stores (Drive, WebDAV, Git). */\nexport const POD_STORE_POLICY: SyncPolicy = {\n push: { mode: 'debounce', debounceMs: 30_000, minIntervalMs: 120_000, onUnload: true },\n pull: { mode: 'interval', intervalMs: 60_000 },\n}\n\n/** @deprecated Use `POD_STORE_POLICY`. */\nexport const BUNDLE_STORE_POLICY = POD_STORE_POLICY\n\n// ─── Sync scheduler ─────────────────────────────────────────────────────\n\n/**\n * Current operational state of the `SyncScheduler`.\n *\n * - `'idle'` — no pending or active sync operations.\n * - `'pending'` — local writes are queued, waiting for debounce/interval to fire.\n * - `'pushing'` — push in progress.\n * - `'pulling'` — pull in progress.\n * - `'error'` — last sync operation failed; `lastError` holds the cause.\n */\nexport type SyncSchedulerState = 'idle' | 'pending' | 'pushing' | 'pulling' | 'error'\n\n/**\n * Snapshot of the sync scheduler's state, returned by `SyncScheduler.status`.\n * Safe to expose in a reactive UI status indicator.\n */\nexport interface SyncSchedulerStatus {\n readonly state: SyncSchedulerState\n readonly lastPushAt: string | null\n readonly lastPullAt: string | null\n readonly lastError: Error | null\n readonly pendingWrites: number\n}\n\n/**\n * Callbacks injected into `SyncScheduler` by the SyncEngine.\n *\n * The scheduler owns timers and lifecycle hooks; it delegates actual push/pull\n * work to these callbacks to stay decoupled from the sync implementation.\n */\nexport interface SyncSchedulerCallbacks {\n push(): Promise<void>\n pull(): Promise<void>\n getDirtyCount(): number\n}\n\n/**\n * Manages sync timing according to a `SyncPolicy`.\n *\n * The scheduler owns all timers and lifecycle hooks. It delegates actual\n * push/pull work to callbacks provided by the SyncEngine.\n */\nexport class SyncScheduler {\n private readonly policy: SyncPolicy\n private readonly callbacks: SyncSchedulerCallbacks\n\n private _state: SyncSchedulerState = 'idle'\n private _lastPushAt: string | null = null\n private _lastPullAt: string | null = null\n private _lastError: Error | null = null\n private _lastPushTime = 0 // monotonic ms for minIntervalMs enforcement\n\n // Timers\n private debounceTimer: ReturnType<typeof setTimeout> | null = null\n private pushIntervalTimer: ReturnType<typeof setInterval> | null = null\n private pullIntervalTimer: ReturnType<typeof setInterval> | null = null\n\n // Bound handlers for cleanup\n private readonly boundOnVisibilityChange: (() => void) | null = null\n private readonly boundOnBeforeExit: (() => void) | null = null\n private readonly boundOnPageHide: (() => void) | null = null\n\n private started = false\n\n constructor(policy: SyncPolicy, callbacks: SyncSchedulerCallbacks) {\n this.policy = policy\n this.callbacks = callbacks\n\n // Pre-bind handlers\n if (this.shouldRegisterUnload()) {\n this.boundOnVisibilityChange = this.handleVisibilityChange.bind(this)\n this.boundOnPageHide = this.handlePageHide.bind(this)\n this.boundOnBeforeExit = this.handleBeforeExit.bind(this)\n }\n }\n\n /** Current scheduler status snapshot. */\n get status(): SyncSchedulerStatus {\n return {\n state: this._state,\n lastPushAt: this._lastPushAt,\n lastPullAt: this._lastPullAt,\n lastError: this._lastError,\n pendingWrites: this.callbacks.getDirtyCount(),\n }\n }\n\n /** Start the scheduler — registers timers, event listeners. */\n start(): void {\n if (this.started) return\n this.started = true\n\n // Push: interval mode\n if (this.policy.push.mode === 'interval' && this.policy.push.intervalMs) {\n this.pushIntervalTimer = setInterval(() => {\n void this.executePush()\n }, this.policy.push.intervalMs)\n }\n\n // Pull: interval mode\n if (this.policy.pull.mode === 'interval' && this.policy.pull.intervalMs) {\n this.pullIntervalTimer = setInterval(() => {\n void this.executePull()\n }, this.policy.pull.intervalMs)\n }\n\n // Pull: on-focus mode\n if (this.policy.pull.mode === 'on-focus' && typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', this.handleFocusPull)\n }\n\n // Unload hooks\n if (this.shouldRegisterUnload()) {\n if (typeof document !== 'undefined' && this.boundOnVisibilityChange) {\n document.addEventListener('visibilitychange', this.boundOnVisibilityChange)\n }\n if (typeof globalThis.addEventListener === 'function' && this.boundOnPageHide) {\n globalThis.addEventListener('pagehide', this.boundOnPageHide)\n }\n if (typeof process !== 'undefined' && this.boundOnBeforeExit) {\n process.on('beforeExit', this.boundOnBeforeExit)\n }\n }\n }\n\n /** Stop the scheduler — clears timers, removes event listeners. */\n stop(): void {\n if (!this.started) return\n this.started = false\n\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer)\n this.debounceTimer = null\n }\n if (this.pushIntervalTimer) {\n clearInterval(this.pushIntervalTimer)\n this.pushIntervalTimer = null\n }\n if (this.pullIntervalTimer) {\n clearInterval(this.pullIntervalTimer)\n this.pullIntervalTimer = null\n }\n\n // Focus pull\n if (this.policy.pull.mode === 'on-focus' && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', this.handleFocusPull)\n }\n\n // Unload hooks\n if (typeof document !== 'undefined' && this.boundOnVisibilityChange) {\n document.removeEventListener('visibilitychange', this.boundOnVisibilityChange)\n }\n if (typeof globalThis.removeEventListener === 'function' && this.boundOnPageHide) {\n globalThis.removeEventListener('pagehide', this.boundOnPageHide)\n }\n if (typeof process !== 'undefined' && this.boundOnBeforeExit) {\n process.removeListener('beforeExit', this.boundOnBeforeExit)\n }\n }\n\n /**\n * Notify the scheduler that a local write occurred.\n * For `on-change` mode: triggers immediate push (respecting minIntervalMs).\n * For `debounce` mode: resets the debounce timer.\n * For `manual` / `interval`: no-op.\n */\n notifyChange(): void {\n if (!this.started) return\n\n if (this.policy.push.mode === 'on-change') {\n void this.executePush()\n } else if (this.policy.push.mode === 'debounce') {\n this.resetDebounce()\n }\n }\n\n /** Force an immediate push, bypassing the scheduler. */\n async forcePush(): Promise<void> {\n await this.executePush()\n }\n\n /** Force an immediate pull, bypassing the scheduler. */\n async forcePull(): Promise<void> {\n await this.executePull()\n }\n\n // ─── Internal ─────────────────────────────────────────────────────\n\n private async executePush(): Promise<void> {\n if (this._state === 'pushing') return // already in progress\n\n // minIntervalMs enforcement\n const minInterval = this.policy.push.minIntervalMs ?? 0\n if (minInterval > 0) {\n const elapsed = Date.now() - this._lastPushTime\n if (elapsed < minInterval) {\n // Schedule for later if debounce mode\n if (this.policy.push.mode === 'debounce') {\n this.scheduleDebounce(minInterval - elapsed)\n }\n return\n }\n }\n\n // Nothing to push\n if (this.callbacks.getDirtyCount() === 0) {\n this._state = 'idle'\n return\n }\n\n this._state = 'pushing'\n try {\n await this.callbacks.push()\n this._lastPushAt = new Date().toISOString()\n this._lastPushTime = Date.now()\n this._lastError = null\n this._state = this.callbacks.getDirtyCount() > 0 ? 'pending' : 'idle'\n } catch (err) {\n this._lastError = err instanceof Error ? err : new Error(String(err))\n this._state = 'error'\n }\n }\n\n private async executePull(): Promise<void> {\n if (this._state === 'pulling') return\n\n const previousState = this._state\n this._state = 'pulling'\n try {\n await this.callbacks.pull()\n this._lastPullAt = new Date().toISOString()\n this._lastError = null\n this._state = previousState === 'pending' ? 'pending' : 'idle'\n } catch (err) {\n this._lastError = err instanceof Error ? err : new Error(String(err))\n this._state = 'error'\n }\n }\n\n private resetDebounce(): void {\n if (this.debounceTimer) clearTimeout(this.debounceTimer)\n const ms = this.policy.push.debounceMs ?? 30_000\n this._state = 'pending'\n this.scheduleDebounce(ms)\n }\n\n private scheduleDebounce(ms: number): void {\n if (this.debounceTimer) clearTimeout(this.debounceTimer)\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null\n void this.executePush()\n }, ms)\n }\n\n private shouldRegisterUnload(): boolean {\n const onUnload = this.policy.push.onUnload\n if (onUnload !== undefined) return onUnload\n return this.policy.push.mode !== 'manual'\n }\n\n // ─── Event handlers ───────────────────────────────────────────────\n\n private handleVisibilityChange(): void {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {\n this.fireUnloadPush()\n }\n }\n\n private handlePageHide(): void {\n this.fireUnloadPush()\n }\n\n private handleBeforeExit(): void {\n this.fireUnloadPush()\n }\n\n private handleFocusPull = (): void => {\n if (typeof document !== 'undefined' && document.visibilityState === 'visible') {\n void this.executePull()\n }\n }\n\n private fireUnloadPush(): void {\n if (this.callbacks.getDirtyCount() === 0) return\n // Best-effort synchronous-ish push on unload\n void this.callbacks.push().catch(() => {})\n }\n}\n"],"mappings":";AA+GO,IAAM,uBAAmC;AAAA,EAC9C,MAAM,EAAE,MAAM,aAAa,eAAe,GAAG,UAAU,KAAK;AAAA,EAC5D,MAAM,EAAE,MAAM,SAAS;AACzB;AAGO,IAAM,mBAA+B;AAAA,EAC1C,MAAM,EAAE,MAAM,YAAY,YAAY,KAAQ,eAAe,MAAS,UAAU,KAAK;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EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAC3C;AACF;","names":[]}
@@ -200,7 +200,7 @@ import {
200
200
  } from "./chunk-C25JXSOR.js";
201
201
  import {
202
202
  INDEXED_STORE_POLICY
203
- } from "./chunk-VQNJ7UZL.js";
203
+ } from "./chunk-MTJLOC3Y.js";
204
204
  import {
205
205
  PERIODS_COLLECTION,
206
206
  PERIOD_ARCHIVES_COLLECTION,
@@ -13921,4 +13921,4 @@ export {
13921
13921
  Noydb,
13922
13922
  createNoydb
13923
13923
  };
13924
- //# sourceMappingURL=chunk-XOBHRD2M.js.map
13924
+ //# sourceMappingURL=chunk-TWS3S62A.js.map
package/dist/index.d.ts CHANGED
@@ -22,9 +22,9 @@
22
22
  *
23
23
  * ```ts
24
24
  * import { createNoydb } from '@noy-db/hub'
25
- * import { jsonFile } from '@noy-db/to-file'
25
+ * import { toFile } from '@noy-db/to-file'
26
26
  *
27
- * const db = await createNoydb({ store: jsonFile({ dir: './data' }) })
27
+ * const db = await createNoydb({ store: toFile({ dir: './data' }) })
28
28
  * const acme = await db.openVault('acme', { secret: 'hunter2' })
29
29
  * const invoices = acme.collection<Invoice>('invoices')
30
30
  *
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  refArray,
17
17
  via,
18
18
  withArchive
19
- } from "./chunk-XOBHRD2M.js";
19
+ } from "./chunk-TWS3S62A.js";
20
20
  import "./chunk-NJ4DYYO5.js";
21
21
  import {
22
22
  persistSchemaIfNeeded
@@ -74,7 +74,7 @@ import {
74
74
  decryptExtractedPartition,
75
75
  diffVault,
76
76
  withCargo
77
- } from "./chunk-PT4XLP6I.js";
77
+ } from "./chunk-JTR75MKH.js";
78
78
  import {
79
79
  NO_CARGO
80
80
  } from "./chunk-TG634KCO.js";
@@ -107,7 +107,7 @@ import {
107
107
  withMetrics,
108
108
  withRetry,
109
109
  wrapStore
110
- } from "./chunk-VSRSQ2CR.js";
110
+ } from "./chunk-EIPVYUEP.js";
111
111
  import {
112
112
  applyListProjection
113
113
  } from "./chunk-VG2ZSFYD.js";
@@ -380,13 +380,13 @@ import {
380
380
  PresenceHandle,
381
381
  SyncEngine,
382
382
  SyncTransaction
383
- } from "./chunk-KBPU5M2E.js";
383
+ } from "./chunk-BXHMZ2XW.js";
384
384
  import {
385
385
  BUNDLE_STORE_POLICY,
386
386
  INDEXED_STORE_POLICY,
387
387
  POD_STORE_POLICY,
388
388
  SyncScheduler
389
- } from "./chunk-VQNJ7UZL.js";
389
+ } from "./chunk-MTJLOC3Y.js";
390
390
  import {
391
391
  PERIODS_COLLECTION
392
392
  } from "./chunk-EZNTORXE.js";
@@ -637,8 +637,31 @@ function withDeferredNumbering(opts) {
637
637
  };
638
638
  }
639
639
 
640
+ // src/via/computed/binding.ts
641
+ var VIRTUAL_POSTURE = { encryptedAtRest: "envelope", queryable: "none", exportable: true, forgettable: false };
642
+ function computedBinding(cfg) {
643
+ const fields = cfg.virtualFields;
644
+ return {
645
+ brand: "computed",
646
+ posture: VIRTUAL_POSTURE,
647
+ covers: (field) => fields.has(field),
648
+ present: (record) => {
649
+ let r = record;
650
+ for (const [field, desc] of fields) {
651
+ if (r === record) r = { ...record };
652
+ r[field] = desc.fn(r);
653
+ }
654
+ return r;
655
+ }
656
+ };
657
+ }
658
+ function linkComputedVia() {
659
+ installViaBinder("computed", (cfg) => computedBinding(cfg));
660
+ }
661
+
640
662
  // src/via/computed/descriptor.ts
641
663
  function computed(fn, opts) {
664
+ linkComputedVia();
642
665
  return {
643
666
  _viaBrand: "computed",
644
667
  fn,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/with-commit/numbering/descriptor.ts","../src/via/computed/descriptor.ts","../src/via/lookup/binding.ts","../src/via/lookup/descriptor.ts"],"sourcesContent":["/**\n * @category capability\n * Deferred-numbering config descriptor. See\n * docs/superpowers/specs/2026-06-08-sealed-numbering-and-store-clock-design.md.\n */\n\n/** A registered deferred-numbering series. */\nexport interface DeferredNumberingConfig {\n /** Series name — the key passed to `vault.sequence(series)`. */\n readonly series: string\n /** Collection holding the records to number. */\n readonly collection: string\n /** Field on each record where the assigned serial is written. */\n readonly field: string\n /**\n * Minimum wall-clock age (ms) before an entry is eligible at a pass, in\n * addition to the interval commit-wait. Default 0 — the store-clock\n * interval (`storeLatest ≤ now.earliest`) is the correctness mechanism.\n */\n readonly settleWindowMs: number\n}\n\n/**\n * Options for {@link withDeferredNumbering} (#844b — was an inline literal, so\n * unnameable). Same shape as {@link DeferredNumberingConfig} except\n * `settleWindowMs` is optional; the factory defaults it to 0.\n */\nexport interface WithDeferredNumberingOptions {\n /** Series name — the key passed to `vault.sequence(series)`. */\n readonly series: string\n /** Collection holding the records to number. */\n readonly collection: string\n /** Field on each record where the assigned serial is written. */\n readonly field: string\n /** See {@link DeferredNumberingConfig.settleWindowMs}. Default 0. */\n readonly settleWindowMs?: number\n}\n\n/** Declare a deferred-numbering series. Pass the result in `createNoydb({ numbering: [...] })`. */\nexport function withDeferredNumbering(opts: WithDeferredNumberingOptions): DeferredNumberingConfig {\n return {\n series: opts.series,\n collection: opts.collection,\n field: opts.field,\n settleWindowMs: opts.settleWindowMs ?? 0,\n }\n}\n","/**\n * computed() — the declaration factory for a field whose value is DERIVED\n * from other fields on the same record (#638 Task 7, spec §6). Composes\n * with `via()` (the locked grammar since phase A: `via(computed(fn, { deps,\n * mode }), money('EUR'))`), grouped by `_viaBrand` like every other via\n * feature (`kernel/via/compose.ts#mergeViaFields`).\n *\n * `mode` picks where the function runs:\n * - `'materialized'` (default) — TODAY's stage-5 write-time eager compute\n * (`with-formula/computed/index.ts#evalComputedFields`), stored like any\n * other field. Byte-for-byte the existing `computed: { field: fn }` sugar.\n * - `'virtual'` — rides the `present` read phase (the money-`Formatted`/\n * i18n-`Label` precedent, seam map Part 4): computed fresh on every\n * read, NEVER stored, `queryable: 'none'`, excluded from export unless\n * its declared `deps` permit (identical taint rule to materialized —\n * see `via/computed/binding.ts`).\n *\n * `deps` names the OTHER fields `fn` reads — feeds `ViaGraph` (Task 1/2) so\n * a source's taint (e.g. a classified field) propagates to this derived\n * field. A depsless entry is fine UNLESS the collection also declares\n * classified fields (`kernel/collection-config.ts#resolveComputedEdges`\n * refuses it — closes the #636 opaque-function leak).\n */\nimport type { ViaDescriptor } from '../../kernel/via/index.js'\n\nexport interface ComputedDescriptor extends ViaDescriptor {\n readonly _viaBrand: 'computed'\n readonly fn: (record: Record<string, unknown>) => unknown\n readonly deps?: readonly string[]\n readonly mode: 'materialized' | 'virtual'\n}\n\nexport function computed(\n fn: (record: Record<string, unknown>) => unknown,\n opts?: { readonly deps?: readonly string[]; readonly mode?: 'materialized' | 'virtual' },\n): ComputedDescriptor {\n return {\n _viaBrand: 'computed',\n fn,\n ...(opts?.deps !== undefined ? { deps: opts.deps } : {}),\n mode: opts?.mode ?? 'materialized',\n }\n}\n\nexport function isComputedDescriptor(x: unknown): x is ComputedDescriptor {\n return typeof x === 'object' && x !== null && (x as { _viaBrand?: unknown })._viaBrand === 'computed'\n}\n","/**\n * The `'lookup'` `ViaBinding` — wires the lookup engine (present-time label\n * dressing across all three backing tiers) into the kernel's generic Via\n * port. Mirrors `via/i18n/binding.ts`'s #553 static-link pattern; the\n * present-time label-dressing algorithm below is adapted from\n * `via-i18n/binding.ts:253-337` (the same wildcard/array/scalar handling,\n * the same `onMissing`/`substitute` policy engine), generalized to branch on\n * `backing` instead of a static-vs-dynamic descriptor-shape check. For the\n * `'static'` and `'reserved'` tiers this delegates to `cfg.lookupLabelResolver`\n * — the SAME vault-built closure the i18n binding's `dictLabelResolver` uses\n * (static table first, else the `vault.dictionary()` handle) — so a native\n * `dict()`/`lookup(static)` field resolves through the identical label data\n * as its `dictKey()`/`staticDict()` alias (the byte-equivalence lock).\n *\n * `lookup()`/`enumOf()`/`dict()` each call {@link linkLookupVia} first — the\n * same #553 pattern `money()`/`dictKey()` use.\n *\n * `buildClause` (label-predicate queries) is still undeclared — out of scope\n * for #650. `compareForOrder` (#650 Task 6, spec §5; matrix tier added Task\n * 7) resolves a `sortBy`-declared field's ordering via `cfg.snapshotFor`'s\n * sync snapshot; the hook signature is UNCHANGED (`via/index.ts:128-129` — no\n * locale param), so it closes over each descriptor's own `displayLocale`\n * (the same locale-less-hinge default `runLookupPresent`'s\n * `hasStaticDisplay` branch already uses). `resolveOrderLabel` (#650 Task\n * 7) is the PER-CALL-locale sibling `orderBy(..., {by:'label'})` needs —\n * see its own doc comment below. `describeFragment` (#650 Task 7) is the\n * first-ever consumed `ViaBinding.describeFragment` implementation — see\n * `with-shape/introspection/describe.ts`'s `buildDescription`.\n */\nimport type { ViaBinding, ViaReadCtx } from '../../kernel/via/index.js'\nimport { installViaBinder } from '../../kernel/via/index.js'\nimport type { LookupDescriptor, LookupBacking, Vocabulary, OnDelete } from './descriptor.js'\nimport { resolvePolicy, type Layer } from '../i18n/policy.js'\nimport { LocaleNotSpecifiedError, UnknownLookupKeyError, ValidationError } from '../../kernel/errors.js'\nimport { getAtPath, setAtPathInPlace } from '../../kernel/paths.js'\nimport type { MaterializedBacking } from './registry.js'\nimport { buildLookupSnapshot } from './snapshot.js'\n\n/**\n * Config a collection's lookup declarations resolve to — the binding's\n * construction input. `lookupLabelResolver`/`getLookupBacking`/`membership`/\n * `snapshotFor` are vault-built closures (never a `Collection` handle,\n * keyring, or DEK/CEK — the zero-knowledge boundary).\n */\nexport interface LookupViaConfig {\n readonly lookupFields: Record<string, LookupDescriptor>\n readonly lookupLabelResolver?: (dimension: string, key: string, locale: string, fallback?: unknown) => Promise<string | undefined>\n /**\n * The matrix (collection) tier's present-time backing-row source, keyed by the full\n * descriptor (not a bare dimension name) so the closure can resolve by `descriptor.key`,\n * not the backing row's PUT-id (#651 Task 3 — the same descriptor-gaining dispatch Task 7\n * already applied to `snapshotFor`).\n */\n readonly getLookupBacking?: (descriptor: LookupDescriptor) => (key: string) => Promise<Record<string, unknown> | undefined>\n /** Closed-vocabulary write-time membership test (#650 Task 3) — `(field, key) => known?`. */\n readonly membership?: (field: string, key: string) => boolean | Promise<boolean>\n /** Sync per-descriptor altKey index — `ingest`'s normalization source (#650 Task 3). */\n readonly getAltIndex?: (desc: LookupDescriptor) => MaterializedBacking | undefined\n /**\n * Sync materialized `key -> row` rows for a lookup descriptor (#650 Task\n * 6, spec §5; matrix-tier routing added #650 Task 7) — `compareForOrder`\n * and `resolveOrderLabel` below, and `snapshot.ts`'s `presentForJoin`\n * builder, all read this same vault-built closure. Reserved AND\n * collection (matrix) tier route here (the vault wires\n * `dimension -> LookupHandle.snapshotEntries()` / `dimension ->\n * collection.querySourceForJoin().snapshot()` respectively, keyed by\n * `descriptor.key` for the matrix case — see `registry.ts`'s\n * `buildLookupSnapshotRows`); static tier is resolved locally from\n * `descriptor.table` without calling this.\n */\n readonly snapshotFor?: (descriptor: LookupDescriptor) => ReadonlyMap<string, Record<string, unknown>> | undefined\n readonly collectionName: string\n}\n\n/** Enum tier (`backing:'static'`, no `table`) has no label source at all — never dressed. */\nfunction hasLabelSource(desc: LookupDescriptor): boolean {\n return !(desc.backing === 'static' && desc.table === undefined)\n}\n\n/**\n * Resolve one key's label. `'static'`/`'reserved'` both go through\n * `cfg.lookupLabelResolver` (mirrors `dictLabelResolver`'s own static-table-\n * first-else-reserved-handle branching — the SAME closure is reused, see\n * `kernel/vault.ts`). `'collection'` (matrix tier) reads the declared\n * `present.label` off the backing row via `cfg.getLookupBacking`; when\n * `present.by` is set, that field's value is a `{ locale -> label }` map\n * indexed by the effective locale.\n */\nasync function fetchLookupLabel(\n desc: LookupDescriptor,\n key: string,\n effLocale: string,\n fieldFallback: string | readonly string[] | undefined,\n cfg: LookupViaConfig,\n): Promise<string | undefined> {\n if (desc.backing === 'collection') {\n const getRow = cfg.getLookupBacking?.(desc)\n const row = getRow ? await getRow(key) : undefined\n const labelField = desc.present?.label\n if (!row || labelField === undefined) return undefined\n const raw = row[labelField]\n if (desc.present?.by !== undefined) {\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>)[effLocale] as string | undefined : undefined\n }\n return typeof raw === 'string' ? raw : undefined\n }\n return cfg.lookupLabelResolver?.(desc.dimension, key, effLocale, fieldFallback)\n}\n\n/** `present` — resolve `<field>Label` for every declared lookup field. Adapted from `via-i18n/binding.ts:253-337`. */\nasync function runLookupPresent(\n record: Record<string, unknown>,\n ctx: ViaReadCtx,\n cfg: LookupViaConfig,\n): Promise<Record<string, unknown>> {\n const fields = Object.entries(cfg.lookupFields).filter(([, d]) => hasLabelSource(d))\n if (fields.length === 0) return record\n\n const locale = typeof ctx.locale === 'string' ? ctx.locale : undefined\n const fallback = ctx.fallback as string | readonly string[] | undefined\n const layer = ctx.layer as Layer\n\n // `{ locale: 'raw' }` wants the untouched record — mirrors\n // `via-i18n/binding.ts`'s `locale !== 'raw'` dict-label gate exactly (no\n // synthetic `<field>Label` derivative on a raw read).\n if (locale === 'raw') return record\n\n // Static-display hybrid hinge: a `backing:'static'` field with a declared\n // `displayLocale` resolves its `<field>Label` even under a locale-less\n // read (mirrors staticDict's `hasStaticDisplay` gate).\n const hasStaticDisplay = fields.some(([, d]) => d.backing === 'static' && d.displayLocale !== undefined)\n if (!locale && !hasStaticDisplay) return record\n\n let result = record\n const withLabels = { ...result }\n\n for (const [field, desc] of fields) {\n const policy = desc.onMissing ? resolvePolicy(desc.onMissing, layer) : 'null'\n const fieldFallback = policy === 'substitute' ? (fallback ?? desc.substitute) : fallback\n const effLocale = locale ?? (desc.backing === 'static' ? desc.displayLocale : undefined)\n\n const resolveKey = async (key: string): Promise<string | null> => {\n if (!effLocale) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(field, `lookup \"${field}\": no locale active to resolve key \"${key}\".`)\n }\n return null\n }\n const label = await fetchLookupLabel(desc, key, effLocale, fieldFallback, cfg)\n if (label === undefined) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(field, `lookup \"${field}\": no label for key \"${key}\" in locale \"${effLocale}\".`)\n }\n return null\n }\n return label\n }\n\n if (field.includes('[].')) {\n const parts = field.split('[].')\n const arrayKey = parts[0]!\n const leaf = parts[1]\n if (!leaf || leaf.includes('.')) continue\n const arr = (withLabels as Record<string, unknown>)[arrayKey]\n if (!Array.isArray(arr)) continue\n const labelKey = `${leaf}Label`\n ;(withLabels as Record<string, unknown>)[arrayKey] = await Promise.all(\n arr.map(async (el) => {\n if (!el || typeof el !== 'object' || Array.isArray(el)) return el\n const k = (el as Record<string, unknown>)[leaf]\n if (typeof k !== 'string') return el\n return { ...(el as Record<string, unknown>), [labelKey]: await resolveKey(k) }\n }),\n )\n continue\n }\n\n const val = result[field]\n if (Array.isArray(val)) {\n withLabels[`${field}Label`] = await Promise.all(\n val.map(async (k) => ({ key: k, label: typeof k === 'string' ? await resolveKey(k) : null })),\n )\n } else if (typeof val === 'string') {\n const label = await resolveKey(val)\n if (label !== null) withLabels[`${field}Label`] = label\n }\n }\n\n result = withLabels\n return result\n}\n\n/**\n * One field's `lookup` descriptor as it appears on a `ViaBinding.\n * describeFragment()` payload (#650 Task 7 — the first real consumer,\n * `with-shape/introspection/describe.ts`'s `buildDescription`, imports this\n * type directly; `describe.ts` is NOT under `kernel/**`, so it's free to\n * import concrete via/ types the way it already does for\n * `LookupDescriptor`/`MoneyDescriptor`/etc.). `dimension` is OMITTED (not\n * emitted as `''`) for a bare `enumOf()` descriptor — the #650 Task 2\n * `dimension:''` sentinel resolved: no dimension name means no `dimension`\n * key, not a meaningless empty string (T2 carry, #650 Task 7).\n */\nexport interface LookupDescribeFragmentEntry {\n readonly dimension?: string\n readonly backing: LookupBacking\n readonly vocabulary: Vocabulary\n readonly key: string\n readonly altKeys?: readonly string[]\n readonly present?: { readonly label: string; readonly by?: string }\n readonly sortBy?: string\n readonly onDelete: OnDelete\n /** Statically-known closed-vocabulary key set (declared `keys`, or a static table's own keys). Omitted when membership lives only in the backing collection/dictionary (open vocabulary, or closed with no declared `keys`). */\n readonly keys?: readonly string[]\n}\n\n/** The `'lookup'` binding's `describeFragment()` payload shape. */\nexport interface LookupDescribeFragment {\n readonly lookupFields: Record<string, LookupDescribeFragmentEntry>\n}\n\nfunction buildLookupDescribeFragment(cfg: LookupViaConfig): Record<string, unknown> {\n const lookupFields: Record<string, LookupDescribeFragmentEntry> = {}\n for (const [field, desc] of Object.entries(cfg.lookupFields)) {\n lookupFields[field] = {\n ...(desc.dimension !== '' ? { dimension: desc.dimension } : {}),\n backing: desc.backing,\n vocabulary: desc.vocabulary,\n key: desc.key,\n onDelete: desc.onDelete,\n ...(desc.altKeys !== undefined ? { altKeys: desc.altKeys } : {}),\n ...(desc.present !== undefined ? { present: desc.present } : {}),\n ...(desc.sortBy !== undefined ? { sortBy: desc.sortBy } : {}),\n // #657 — static tier: when no `keys` was explicitly declared but a\n // `table` was (the staticDict()-equivalent `lookup(dim, {backing:\n // 'static', table})` shape), the table's own key set IS the\n // statically-known closed-vocabulary set the DescribedField.lookup\n // docblock promises (\"declared `keys`, OR a static table's own\n // keys\"). Reserved/matrix tiers never carry `table`, so this branch\n // never fires for them — their `keys` emission is unchanged.\n ...(desc.keys !== undefined\n ? { keys: desc.keys }\n : desc.backing === 'static' && desc.table !== undefined ? { keys: Object.keys(desc.table) } : {}),\n }\n }\n return { lookupFields }\n}\n\n/**\n * `cfg.getAltIndex(desc)` (matrix tier) reads the backing collection's cache\n * via `querySourceForJoin()` (`buildLookupAltIndex`, registry.ts) — which\n * throws a `.join()`-branded message when that collection was opened\n * `{prefetch:false}` (lazy mode is unsupported for altKey normalization).\n * Normalization must never silently not happen (the banned silent-no-op\n * class, #650 Task 3 review, Important 2) — detect that specific failure\n * and surface a CLEAR, lookup-branded `ValidationError` at the point of\n * failure instead of letting the confusing join-branded one leak onto an\n * unrelated `put()`. Any OTHER error (e.g. `materializeBackingTable`'s own\n * altKey-collision `ValidationError`) propagates unchanged.\n */\nfunction getAltIndexOrThrow(field: string, desc: LookupDescriptor, cfg: LookupViaConfig): MaterializedBacking | undefined {\n try {\n return cfg.getAltIndex?.(desc)\n } catch (err) {\n if (err instanceof Error && err.message.includes('lazy-mode')) {\n throw new ValidationError(\n `lookup: altKeys on \"${field}\" require the backing collection \"${desc.dimension}\" to be ` +\n `prefetch-enabled (lazy mode unsupported); open it without {prefetch:false} or drop altKeys.`,\n )\n }\n throw err\n }\n}\n\n/**\n * `ingest` — altKey candidate values normalize to the canonical key (#650\n * Task 3, spec §3). Pure, sync, idempotent (a canonical key maps to\n * itself); no store read — consults the pre-materialized\n * `cfg.getAltIndex(desc)`. The money `canonicalizeIncomingMoney` precedent\n * (`via/index.ts:108`).\n *\n * A `[].`-wildcard multi-value path (`getAtPath` resolves >1 entries — an\n * array of nested objects, e.g. `'lines[].country'`, the same wildcard\n * convention `runLookupPresent` above already handles) normalizes EVERY\n * element's leaf value, not just a lone scalar (#652 fix — this used to bail\n * out entirely here while `runLookupEnforceWrite` below validated every\n * value unnormalized, so a legitimate altKey in an array position was\n * wrongly refused by closed-vocabulary enforcement). `setAtPathInPlace`\n * can't write into a `[].`-wildcard path, so the array is reconstructed\n * immutably instead, mirroring `runLookupPresent`'s own `field.includes\n * ('[].')` branch. A plain field whose OWN value is a bare top-level array\n * (not a `[].`-wildcard path) gets the SAME element-wise normalization\n * against `backing.altIndex` (#661 fix — `getAtPath` resolves it to one\n * opaque value, so the array itself is `values[0]`; a non-string element is\n * left untouched, mirroring the scalar branch's own `typeof !== 'string'`\n * skip — no parallel coercion invented for this shape).\n */\nfunction runLookupIngest(record: Record<string, unknown>, cfg: LookupViaConfig): Record<string, unknown> {\n const withAltKeys = Object.entries(cfg.lookupFields).filter(([, d]) => (d.altKeys?.length ?? 0) > 0)\n if (withAltKeys.length === 0) return record\n\n let result = record\n for (const [field, desc] of withAltKeys) {\n const backing = getAltIndexOrThrow(field, desc, cfg)\n if (!backing || backing.altIndex.size === 0) continue\n\n if (field.includes('[].')) {\n const [arrayKey, leaf] = field.split('[].')\n if (!leaf || leaf.includes('.')) continue\n const arr = record[arrayKey!]\n if (!Array.isArray(arr)) continue\n let changed = false\n const normalized = arr.map((item) => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return item\n const value = (item as Record<string, unknown>)[leaf]\n if (typeof value !== 'string') return item\n const canonical = backing.altIndex.get(value)\n if (canonical === undefined || canonical === value) return item\n changed = true\n return { ...(item as Record<string, unknown>), [leaf]: canonical }\n })\n if (!changed) continue\n if (result === record) result = { ...record }\n result[arrayKey!] = normalized\n continue\n }\n\n const values = getAtPath(record, field)\n if (values.length !== 1) continue\n const value = values[0]\n\n // `getAtPath`/`setAtPathInPlace` resolve `field` generically, dotted\n // paths included (e.g. 'meta.tags') — do not rewrite this branch to a\n // direct `record[field]` bracket access, which would silently stop\n // normalizing/enforcing a dotted-non-wildcard bare-array field (#661).\n if (Array.isArray(value)) {\n if (value.length === 0) continue\n let changed = false\n const normalized = value.map((el) => {\n if (typeof el !== 'string') return el\n const canonical = backing.altIndex.get(el)\n if (canonical === undefined || canonical === el) return el\n changed = true\n return canonical\n })\n if (!changed) continue\n if (result === record) result = { ...record }\n setAtPathInPlace(result, field, normalized)\n continue\n }\n\n if (typeof value !== 'string') continue\n const canonical = backing.altIndex.get(value)\n if (canonical === undefined || canonical === value) continue\n if (result === record) result = { ...record }\n setAtPathInPlace(result, field, canonical)\n }\n return result\n}\n\n/**\n * `enforceWrite` — closed-vocabulary write refusal (#650 Task 3, spec §3).\n * Runs only for `vocabulary:'closed'` fields; `'open'` (the dictKey/dict\n * default) skips the check entirely, so #649's fix is additive — existing\n * dictKey/staticDict collections are unaffected. `ctx` carries no\n * cross-collection door (`id`/`vault`/`prior`/`emit` only, unchanged) —\n * membership is a vault-built closure on `cfg`, per spec.\n */\nasync function runLookupEnforceWrite(record: Record<string, unknown>, cfg: LookupViaConfig): Promise<void> {\n for (const [field, desc] of Object.entries(cfg.lookupFields)) {\n if (desc.vocabulary !== 'closed') continue\n // Checks every value `getAtPath` returns — for a `[].`-wildcard\n // multi-value path, that's every element's leaf value.\n // `runLookupIngest` above now normalizes each of those elements first\n // (#652), so what lands here for a `[].`-wildcard field is already\n // canonical; this loop's job stays membership, not normalization.\n for (const value of getAtPath(record, field)) {\n // A plain field whose OWN value is a bare top-level array (#661) —\n // `runLookupIngest` above has already normalized its elements'\n // altKeys, so membership-check each element through the SAME\n // `cfg.membership` closure the scalar branch below uses, refusing on\n // the first unknown one. A non-string element is skipped, mirroring\n // the scalar branch's own skip.\n if (Array.isArray(value)) {\n for (const el of value) {\n if (typeof el !== 'string') continue\n const known = cfg.membership ? await cfg.membership(field, el) : true\n if (!known) throw new UnknownLookupKeyError(desc.dimension, field, el)\n }\n continue\n }\n if (typeof value !== 'string') continue\n const known = cfg.membership ? await cfg.membership(field, value) : true\n if (!known) throw new UnknownLookupKeyError(desc.dimension, field, value)\n }\n }\n}\n\n/**\n * `compareForOrder` — exact ordering for a `sortBy`-declared lookup field\n * against the sync snapshot (#650 Task 6, spec §5, conflict resolution 4;\n * matrix-tier coverage added #650 Task 7). Opt-in: undeclared `sortBy`\n * (every dictKey/staticDict alias and every lookup field declared before\n * Task 6) returns `undefined` — falls through to the generic stored-value\n * comparator, byte-identical to today. Static tier reads `descriptor.table`\n * directly; reserved AND matrix (collection) tier both read `cfg.snapshotFor`\n * (the SAME live cache `presentForJoin`'s lookup half reads — see\n * `snapshot.ts`'s file header). The hook has no locale parameter\n * (`via/index.ts:128-129`, unchanged) — closes over the descriptor's own\n * `displayLocale` (the same locale-less-hinge default `runLookupPresent`\n * already uses); a `sortBy` field whose value isn't locale-keyed\n * (`present.by` undefined) never needs one. A `by`-keyed `sortBy` field\n * with NO declared `displayLocale` degrades to comparing the raw canonical\n * keys (silent — `LookupSnapshot.compareKeys` never throws; declare-time\n * warning at `descriptor.ts`'s `lookup()` factory; use\n * `orderBy(field, dir, {by:'label'})` — `resolveOrderLabel` below — for a\n * PER-CALL locale instead).\n */\nfunction compareLookupOrder(field: string, a: unknown, b: unknown, cfg: LookupViaConfig): number | undefined {\n if (typeof a !== 'string' || typeof b !== 'string') return undefined\n const desc = cfg.lookupFields[field]\n if (!desc || desc.sortBy === undefined) return undefined\n const rows = desc.backing === 'static'\n ? (desc.table ? new Map(Object.entries(desc.table)) : undefined)\n : cfg.snapshotFor?.(desc)\n if (!rows) return undefined\n return buildLookupSnapshot(desc.dimension, rows, desc).compareKeys(a, b, desc.displayLocale ?? '')\n}\n\n/**\n * `resolveOrderLabel` — per-key, PER-CALL-locale label resolution for\n * `orderBy(field, dir, { by: 'label' })` (#650 Task 7, spec §6 / seam map\n * Part 10 surprise 6's option (b)) — the channel `compareForOrder` above\n * structurally cannot serve, since `ViaBinding.compareForOrder` carries no\n * locale parameter. Consumed by `kernel/query/builder.ts`'s\n * `buildOrderLabelMaps` as the fallback for lookup fields the legacy dict\n * registries don't bridge (matrix tier; reserved/static tier already\n * resolves via that bridge — `JoinContext.resolveDictSource` — tried\n * FIRST by the caller, see `registry.ts`'s `collectLookupDictCompat` doc\n * comment). Reuses the exact same `cfg.snapshotFor`/`buildLookupSnapshot`\n * machinery as `compareLookupOrder` above, just with the per-call `locale`\n * in place of the descriptor's own `displayLocale` — falling back to\n * `displayLocale` only when the call itself is locale-less, the same\n * hinge order `runLookupPresent` already uses.\n */\nfunction resolveLookupOrderLabel(field: string, key: string, locale: string | undefined, cfg: LookupViaConfig): string | undefined {\n const desc = cfg.lookupFields[field]\n if (!desc) return undefined\n const rows = desc.backing === 'static'\n ? (desc.table ? new Map(Object.entries(desc.table)) : undefined)\n : cfg.snapshotFor?.(desc)\n if (!rows) return undefined\n return buildLookupSnapshot(desc.dimension, rows, desc).label(key, locale ?? desc.displayLocale ?? '')\n}\n\nexport function lookupBinding(cfg: LookupViaConfig): ViaBinding {\n return {\n brand: 'lookup',\n posture: { encryptedAtRest: 'envelope', queryable: 'full', exportable: true, forgettable: false },\n reservedPrefixes: ['_dict_', '_lookup_'],\n covers: (field) => field in cfg.lookupFields,\n ingest: (record) => runLookupIngest(record, cfg),\n enforceWrite: (record) => runLookupEnforceWrite(record, cfg),\n present: async (record, ctx) => runLookupPresent(record, ctx, cfg),\n compareForOrder: (field, a, b) => compareLookupOrder(field, a, b, cfg),\n resolveOrderLabel: (field, key, locale) => resolveLookupOrderLabel(field, key, locale, cfg),\n describeFragment: () => buildLookupDescribeFragment(cfg),\n }\n}\n\nexport function linkLookupVia(): void {\n installViaBinder('lookup', (c) => lookupBinding(c as LookupViaConfig))\n}\n","/**\n * `lookup()` / `enumOf()` / `dict()` descriptors — the three declaration\n * surfaces for the `'lookup'` via binding (#650 Task 2, phase D of the Via\n * port). One `LookupDescriptor` shape; the tiers are `backing` details:\n *\n * - `lookup(dimension, opts?)` — matrix tier: first-class collection backing\n * (default `backing:'collection'`) — a reference-collection dimension\n * (e.g. `countries`), open vocabulary by default.\n * - `enumOf(keys)` — enum tier: static in-config table, CLOSED\n * vocabulary, no backing store at all (no dimension name — pure inline\n * keys). Exported as `enumOf`; the barrel (`index.ts`) re-exports it as\n * `enum` (`enum` is a reserved word, so it can't be the function's own\n * name).\n * - `dict(dimension, opts?)` — dict tier: reserved `_dict_<dimension>`\n * micro-collection backing (the `vault.dictionary(name)` engine), open\n * vocabulary by default.\n *\n * Each factory calls {@link linkLookupVia} first — the declaration IS the\n * via binding's opt-in unit (#553), same pattern as `money()`/`i18nText()`/\n * `dictKey()`.\n */\n\nimport type { OnMissingPolicy } from '../i18n/policy.js'\nimport { linkLookupVia } from './binding.js'\n\n/** `'closed'` = enum semantics (membership enforced, Task 3); `'open'` permits unknown keys. */\nexport type Vocabulary = 'open' | 'closed'\n\n/** Where a dimension's rows live: static in-config table / reserved micro-collection / first-class collection. */\nexport type LookupBacking = 'static' | 'reserved' | 'collection'\n\n/** Delete-time referential policy for the backing dimension (default `'restrict'`, enforced in Task 5). */\nexport type OnDelete = 'restrict' | 'cascade' | 'nullify'\n\n/** The one descriptor shape every tier compiles to — tiers differ only by `backing`. */\nexport interface LookupDescriptor<Keys extends string = string> {\n readonly _viaBrand: 'lookup'\n /** Dimension/dictionary/target name. Empty for a bare `enumOf()` (no backing store, no name). */\n readonly dimension: string\n /** Canonical key field on the row (default `'id'`). */\n readonly key: string\n /** Candidate keys normalized to `key` on ingest (Task 3). */\n readonly altKeys?: readonly string[]\n readonly vocabulary: Vocabulary\n /** Dressing dimension: which backing-row field supplies `<field>Label`, optionally keyed `by` a sub-field (e.g. locale). */\n readonly present?: { readonly label: string; readonly by?: string }\n /** Field to sort by against the snapshot (Task 6). */\n readonly sortBy?: string\n readonly backing: LookupBacking\n readonly onDelete: OnDelete\n /** Static/enum inline key set. */\n readonly keys?: readonly Keys[]\n /** Static tier only: in-code `key -> { locale -> label }` table. */\n readonly table?: Readonly<Record<string, Readonly<Record<string, string>>>>\n /** Static hybrid hinge (the `staticDict` alias) — locale-less `<field>Label`. */\n readonly displayLocale?: string\n readonly onMissing?: OnMissingPolicy\n readonly substitute?: readonly string[]\n /** Inline display labels (value -> label), the dict-tier sync fallback (mirrors `dictKey`'s `labels`). */\n readonly labels?: Record<string, string>\n}\n\n/**\n * `sortBy`/`present.by` coupling warning (#650 Task 7, T6 minor — task-6-\n * report.md Concern #4). A `by`-keyed `present` (locale-map) field used as\n * `sortBy` needs a declared `displayLocale` for the locale-less\n * `compareForOrder` sort hook (a plain `orderBy(field)`, no `{by:'label'}`)\n * to resolve anything — without one it silently degrades to comparing the\n * raw canonical keys (never throws — `LookupSnapshot.compareKeys`'s\n * contract). `orderBy(field, dir, {by:'label'})` doesn't need this (it\n * carries its own per-call locale via `ViaBinding.resolveOrderLabel`,\n * #650 Task 7) — only a sortBy-driven PLAIN orderBy does. Warn once at\n * declare time rather than degrade silently at query time.\n */\nfunction warnIfSortByNeedsDisplayLocale(\n dimension: string,\n opts?: { sortBy?: string; present?: { by?: string }; displayLocale?: string },\n): void {\n if (opts?.sortBy !== undefined && opts.present?.by !== undefined && opts.displayLocale === undefined) {\n console.warn(\n `[noy-db] lookup(\"${dimension}\"): sortBy \"${opts.sortBy}\" is locale-keyed (present.by is set) but no ` +\n `displayLocale is declared — a locale-less orderBy() will silently sort by the raw stored key instead ` +\n `of the resolved label. Declare displayLocale, or sort via orderBy(field, dir, { by: 'label' }), which ` +\n `resolves at the query's own per-call locale.`,\n )\n }\n}\n\n/**\n * Matrix tier — first-class collection backing (default `backing:'collection'`).\n * `dimension` names the backing collection (e.g. `'countries'`).\n *\n * `backing` may be overridden to construct any tier through this one\n * factory — e.g. `lookup(name, { backing:'static', table, displayLocale })`\n * is the table-bearing static tier `staticDict()` compiles onto. The\n * `table`/`displayLocale`/`keys`/`onMissing`/`substitute`/`labels` options\n * are a superset of the brief's literal opts list: `LookupDescriptor`\n * already carries these fields for exactly this purpose, and without them\n * `backing:'static'` would be unreachable stand-alone through `lookup()`\n * (see task-2-report.md's \"Design decisions\").\n *\n * **`altKeys` caveat (matrix tier only)**: normalizing an altKey candidate\n * to its canonical `key` requires the backing `dimension` collection to be\n * open in EAGER mode (the default; `{ prefetch: false }` — lazy mode — is\n * unsupported). A `put()` on a field with `altKeys` whose backing collection\n * is lazy throws a `ValidationError` naming the field and dimension; open\n * the backing collection without `{ prefetch: false }`, or drop `altKeys`.\n */\nexport function lookup<Keys extends string>(\n dimension: string,\n opts?: {\n key?: string\n altKeys?: readonly string[]\n vocabulary?: Vocabulary\n present?: { label: string; by?: string }\n sortBy?: string\n backing?: LookupBacking\n onDelete?: OnDelete\n keys?: readonly Keys[]\n table?: Readonly<Record<string, Readonly<Record<string, string>>>>\n displayLocale?: string\n onMissing?: OnMissingPolicy\n substitute?: readonly string[]\n labels?: Record<string, string>\n },\n): LookupDescriptor<Keys> {\n linkLookupVia()\n warnIfSortByNeedsDisplayLocale(dimension, opts)\n return {\n _viaBrand: 'lookup',\n dimension,\n key: opts?.key ?? 'id',\n vocabulary: opts?.vocabulary ?? 'open',\n backing: opts?.backing ?? 'collection',\n onDelete: opts?.onDelete ?? 'restrict',\n ...(opts?.altKeys !== undefined ? { altKeys: opts.altKeys } : {}),\n ...(opts?.present !== undefined ? { present: opts.present } : {}),\n ...(opts?.sortBy !== undefined ? { sortBy: opts.sortBy } : {}),\n ...(opts?.keys !== undefined ? { keys: opts.keys } : {}),\n ...(opts?.table !== undefined ? { table: opts.table } : {}),\n ...(opts?.displayLocale !== undefined ? { displayLocale: opts.displayLocale } : {}),\n ...(opts?.onMissing !== undefined ? { onMissing: opts.onMissing } : {}),\n ...(opts?.substitute !== undefined ? { substitute: opts.substitute } : {}),\n ...(opts?.labels !== undefined ? { labels: opts.labels } : {}),\n }\n}\n\n/**\n * Enum tier — static in-config table, CLOSED vocabulary, no backing store.\n * No dimension name (pure inline keys) — `dimension` is `''`.\n */\nexport function enumOf<const Keys extends readonly string[]>(keys: Keys): LookupDescriptor<Keys[number]> {\n linkLookupVia()\n return {\n _viaBrand: 'lookup',\n dimension: '',\n key: 'id',\n vocabulary: 'closed',\n backing: 'static',\n onDelete: 'restrict',\n keys,\n }\n}\n\n/**\n * Dict tier — reserved `_dict_<dimension>` micro-collection backing (the\n * `vault.dictionary(dimension)` engine), open vocabulary by default. The\n * native equivalent of `dictKey()`.\n *\n * Unlike `lookup()`'s matrix tier, `dict()` has no `altKeys` option — its\n * `_dict_<dimension>` backing is the always-synchronous `LookupHandle`\n * write-through cache, never a `vault.collection()` that can be opened\n * `{ prefetch: false }`, so the matrix tier's lazy-mode altKeys restriction\n * does not apply here.\n */\nexport function dict<Keys extends string>(\n dimension: string,\n opts?: {\n keys?: readonly Keys[]\n vocabulary?: Vocabulary\n present?: { label: string; by?: string }\n onDelete?: OnDelete\n onMissing?: OnMissingPolicy\n substitute?: readonly string[]\n },\n): LookupDescriptor<Keys> {\n linkLookupVia()\n return {\n _viaBrand: 'lookup',\n dimension,\n key: 'id',\n vocabulary: opts?.vocabulary ?? 'open',\n backing: 'reserved',\n onDelete: opts?.onDelete ?? 'restrict',\n ...(opts?.keys !== undefined ? { keys: opts.keys } : {}),\n ...(opts?.present !== undefined ? { present: opts.present } : {}),\n ...(opts?.onMissing !== undefined ? { onMissing: opts.onMissing } : {}),\n ...(opts?.substitute !== undefined ? { substitute: opts.substitute } : {}),\n }\n}\n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Ac,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,IACrE,GAAI,MAAM,eAAe,SAAY,EAAE,YAAY,KAAK,WAAW,IAAI,CAAC;AAAA,IACxE,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;AAAA,EAC9D;AACF;AAMO,SAAS,OAA6C,MAA4C;AACvG,gBAAc;AACd,SAAO;AAAA,IACL,WAAW;AAAA,IACX,WAAW;AAAA,IACX,KAAK;AAAA,IACL,YAAY;AAAA,IACZ,SAAS;AAAA,IACT,UAAU;AAAA,IACV;AAAA,EACF;AACF;AAaO,SAAS,KACd,WACA,MAQwB;AACxB,gBAAc;AACd,SAAO;AAAA,IACL,WAAW;AAAA,IACX;AAAA,IACA,KAAK;AAAA,IACL,YAAY,MAAM,cAAc;AAAA,IAChC,SAAS;AAAA,IACT,UAAU,MAAM,YAAY;AAAA,IAC5B,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;AAAA,IACtD,GAAI,MAAM,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,IAC/D,GAAI,MAAM,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,IACrE,GAAI,MAAM,eAAe,SAAY,EAAE,YAAY,KAAK,WAAW,IAAI,CAAC;AAAA,EAC1E;AACF;","names":["value","canonical","known"]}
1
+ {"version":3,"sources":["../src/with-commit/numbering/descriptor.ts","../src/via/computed/binding.ts","../src/via/computed/descriptor.ts","../src/via/lookup/binding.ts","../src/via/lookup/descriptor.ts"],"sourcesContent":["/**\n * @category capability\n * Deferred-numbering config descriptor. See\n * docs/superpowers/specs/2026-06-08-sealed-numbering-and-store-clock-design.md.\n */\n\n/** A registered deferred-numbering series. */\nexport interface DeferredNumberingConfig {\n /** Series name — the key passed to `vault.sequence(series)`. */\n readonly series: string\n /** Collection holding the records to number. */\n readonly collection: string\n /** Field on each record where the assigned serial is written. */\n readonly field: string\n /**\n * Minimum wall-clock age (ms) before an entry is eligible at a pass, in\n * addition to the interval commit-wait. Default 0 — the store-clock\n * interval (`storeLatest ≤ now.earliest`) is the correctness mechanism.\n */\n readonly settleWindowMs: number\n}\n\n/**\n * Options for {@link withDeferredNumbering} (#844b — was an inline literal, so\n * unnameable). Same shape as {@link DeferredNumberingConfig} except\n * `settleWindowMs` is optional; the factory defaults it to 0.\n */\nexport interface WithDeferredNumberingOptions {\n /** Series name — the key passed to `vault.sequence(series)`. */\n readonly series: string\n /** Collection holding the records to number. */\n readonly collection: string\n /** Field on each record where the assigned serial is written. */\n readonly field: string\n /** See {@link DeferredNumberingConfig.settleWindowMs}. Default 0. */\n readonly settleWindowMs?: number\n}\n\n/** Declare a deferred-numbering series. Pass the result in `createNoydb({ numbering: [...] })`. */\nexport function withDeferredNumbering(opts: WithDeferredNumberingOptions): DeferredNumberingConfig {\n return {\n series: opts.series,\n collection: opts.collection,\n field: opts.field,\n settleWindowMs: opts.settleWindowMs ?? 0,\n }\n}\n","/**\n * The `computed` via-binding (#638 Task 7) — covers ONLY `mode: 'virtual'`\n * fields. Materialized entries never reach here: they compile into\n * `mergedComputed` (`kernel/collection-config.ts`) and run through the\n * EXISTING stage-5 `evalComputedFields` write path, byte-for-byte unchanged\n * (the behavior lock).\n *\n * A virtual field is computed on READ, inside `present()` — the money-\n * `Formatted`/i18n-`Label` precedent (seam map Part 4) generalized to a\n * user-declared function. It is NEVER stored (no `encodeAtRest`/\n * `decodeAtRest` — the field never appears in `_data` or any `_sealed`\n * slot), and its posture is fixed `queryable: 'none'` — there is no stored/\n * indexed form to query against, regardless of what its sources would\n * otherwise permit (`ViaGraph`'s grain-'virtual' clamp, `kernel/via/graph.ts`,\n * is the belt; this binding's own static posture is the suspenders for a\n * depsless virtual field, which registers no graph edge at all).\n *\n * Export/read redaction for a TAINTED virtual field (sourced from a\n * classified/sealed field) is NOT this binding's job — it stays ignorant of\n * taint, exactly like `evalComputedFields` stays ignorant of it for\n * materialized fields. `kernel/via/taint-binding.ts#taintBinding` (appended\n * to the pipeline by `via/graph-wiring.ts#applyTaintOverlay`, AFTER this\n * binding) overwrites a tainted virtual field's value with the same\n * `EXPORT_REDACTION_MARKER` on every present() — the one enforcement seam\n * every via feature's taint already routes through.\n */\nimport type { ViaBinding, ViaPosture } from '../../kernel/via/index.js'\nimport { installViaBinder } from '../../kernel/via/index.js'\nimport type { ComputedDescriptor } from './descriptor.js'\n\nexport interface ComputedViaConfig {\n /** field name -> its virtual-mode descriptor. Materialized entries are never present here. */\n readonly virtualFields: ReadonlyMap<string, ComputedDescriptor>\n}\n\nconst VIRTUAL_POSTURE: ViaPosture = { encryptedAtRest: 'envelope', queryable: 'none', exportable: true, forgettable: false }\n\nexport function computedBinding(cfg: ComputedViaConfig): ViaBinding {\n const fields = cfg.virtualFields\n return {\n brand: 'computed',\n posture: VIRTUAL_POSTURE,\n covers: (field) => fields.has(field),\n present: (record) => {\n let r = record\n for (const [field, desc] of fields) {\n if (r === record) r = { ...record }\n r[field] = desc.fn(r)\n }\n return r\n },\n }\n}\n\nexport function linkComputedVia(): void {\n installViaBinder('computed', (cfg) => computedBinding(cfg as ComputedViaConfig))\n}\n","/**\n * computed() — the declaration factory for a field whose value is DERIVED\n * from other fields on the same record (#638 Task 7, spec §6). Composes\n * with `via()` (the locked grammar since phase A: `via(computed(fn, { deps,\n * mode }), money('EUR'))`), grouped by `_viaBrand` like every other via\n * feature (`kernel/via/compose.ts#mergeViaFields`).\n *\n * `mode` picks where the function runs:\n * - `'materialized'` (default) — TODAY's stage-5 write-time eager compute\n * (`with-formula/computed/index.ts#evalComputedFields`), stored like any\n * other field. Byte-for-byte the existing `computed: { field: fn }` sugar.\n * - `'virtual'` — rides the `present` read phase (the money-`Formatted`/\n * i18n-`Label` precedent, seam map Part 4): computed fresh on every\n * read, NEVER stored, `queryable: 'none'`, excluded from export unless\n * its declared `deps` permit (identical taint rule to materialized —\n * see `via/computed/binding.ts`).\n *\n * `deps` names the OTHER fields `fn` reads — feeds `ViaGraph` (Task 1/2) so\n * a source's taint (e.g. a classified field) propagates to this derived\n * field. A depsless entry is fine UNLESS the collection also declares\n * classified fields (`kernel/collection-config.ts#resolveComputedEdges`\n * refuses it — closes the #636 opaque-function leak).\n */\nimport type { ViaDescriptor } from '../../kernel/via/index.js'\nimport { linkComputedVia } from './binding.js'\n\nexport interface ComputedDescriptor extends ViaDescriptor {\n readonly _viaBrand: 'computed'\n readonly fn: (record: Record<string, unknown>) => unknown\n readonly deps?: readonly string[]\n readonly mode: 'materialized' | 'virtual'\n}\n\nexport function computed(\n fn: (record: Record<string, unknown>) => unknown,\n opts?: { readonly deps?: readonly string[]; readonly mode?: 'materialized' | 'virtual' },\n): ComputedDescriptor {\n // Self-link, exactly as `money()` and `lookup()` do (#813). Until this call\n // existed, `computed` was the only via feature whose binder was installed by a\n // DIFFERENT module — `port/with/computed-strategy.ts` — rather than by its own\n // declaration factory. That works whenever the kernel spine and the consumer's\n // `computed` import resolve to one module instance, and fails when they do not:\n // under vitest's `server.deps.inline`, a consumer got the descriptor from one\n // transformed instance while the binder registry consulted at bind time lived in\n // another, producing `VIA_NOT_LINKED` for a descriptor `isComputedDescriptor()`\n // accepted. money/i18n/lookup were immune precisely because they self-link.\n //\n // Constructing a descriptor is the binding's opt-in unit, so linking here makes\n // the guarantee local: whatever instance produced the descriptor also has the\n // binder. `installViaBinder` is idempotent + first-wins, so the eager call in\n // `port/with/computed-strategy.ts` stays harmless.\n linkComputedVia()\n return {\n _viaBrand: 'computed',\n fn,\n ...(opts?.deps !== undefined ? { deps: opts.deps } : {}),\n mode: opts?.mode ?? 'materialized',\n }\n}\n\nexport function isComputedDescriptor(x: unknown): x is ComputedDescriptor {\n return typeof x === 'object' && x !== null && (x as { _viaBrand?: unknown })._viaBrand === 'computed'\n}\n","/**\n * The `'lookup'` `ViaBinding` — wires the lookup engine (present-time label\n * dressing across all three backing tiers) into the kernel's generic Via\n * port. Mirrors `via/i18n/binding.ts`'s #553 static-link pattern; the\n * present-time label-dressing algorithm below is adapted from\n * `via-i18n/binding.ts:253-337` (the same wildcard/array/scalar handling,\n * the same `onMissing`/`substitute` policy engine), generalized to branch on\n * `backing` instead of a static-vs-dynamic descriptor-shape check. For the\n * `'static'` and `'reserved'` tiers this delegates to `cfg.lookupLabelResolver`\n * — the SAME vault-built closure the i18n binding's `dictLabelResolver` uses\n * (static table first, else the `vault.dictionary()` handle) — so a native\n * `dict()`/`lookup(static)` field resolves through the identical label data\n * as its `dictKey()`/`staticDict()` alias (the byte-equivalence lock).\n *\n * `lookup()`/`enumOf()`/`dict()` each call {@link linkLookupVia} first — the\n * same #553 pattern `money()`/`dictKey()` use.\n *\n * `buildClause` (label-predicate queries) is still undeclared — out of scope\n * for #650. `compareForOrder` (#650 Task 6, spec §5; matrix tier added Task\n * 7) resolves a `sortBy`-declared field's ordering via `cfg.snapshotFor`'s\n * sync snapshot; the hook signature is UNCHANGED (`via/index.ts:128-129` — no\n * locale param), so it closes over each descriptor's own `displayLocale`\n * (the same locale-less-hinge default `runLookupPresent`'s\n * `hasStaticDisplay` branch already uses). `resolveOrderLabel` (#650 Task\n * 7) is the PER-CALL-locale sibling `orderBy(..., {by:'label'})` needs —\n * see its own doc comment below. `describeFragment` (#650 Task 7) is the\n * first-ever consumed `ViaBinding.describeFragment` implementation — see\n * `with-shape/introspection/describe.ts`'s `buildDescription`.\n */\nimport type { ViaBinding, ViaReadCtx } from '../../kernel/via/index.js'\nimport { installViaBinder } from '../../kernel/via/index.js'\nimport type { LookupDescriptor, LookupBacking, Vocabulary, OnDelete } from './descriptor.js'\nimport { resolvePolicy, type Layer } from '../i18n/policy.js'\nimport { LocaleNotSpecifiedError, UnknownLookupKeyError, ValidationError } from '../../kernel/errors.js'\nimport { getAtPath, setAtPathInPlace } from '../../kernel/paths.js'\nimport type { MaterializedBacking } from './registry.js'\nimport { buildLookupSnapshot } from './snapshot.js'\n\n/**\n * Config a collection's lookup declarations resolve to — the binding's\n * construction input. `lookupLabelResolver`/`getLookupBacking`/`membership`/\n * `snapshotFor` are vault-built closures (never a `Collection` handle,\n * keyring, or DEK/CEK — the zero-knowledge boundary).\n */\nexport interface LookupViaConfig {\n readonly lookupFields: Record<string, LookupDescriptor>\n readonly lookupLabelResolver?: (dimension: string, key: string, locale: string, fallback?: unknown) => Promise<string | undefined>\n /**\n * The matrix (collection) tier's present-time backing-row source, keyed by the full\n * descriptor (not a bare dimension name) so the closure can resolve by `descriptor.key`,\n * not the backing row's PUT-id (#651 Task 3 — the same descriptor-gaining dispatch Task 7\n * already applied to `snapshotFor`).\n */\n readonly getLookupBacking?: (descriptor: LookupDescriptor) => (key: string) => Promise<Record<string, unknown> | undefined>\n /** Closed-vocabulary write-time membership test (#650 Task 3) — `(field, key) => known?`. */\n readonly membership?: (field: string, key: string) => boolean | Promise<boolean>\n /** Sync per-descriptor altKey index — `ingest`'s normalization source (#650 Task 3). */\n readonly getAltIndex?: (desc: LookupDescriptor) => MaterializedBacking | undefined\n /**\n * Sync materialized `key -> row` rows for a lookup descriptor (#650 Task\n * 6, spec §5; matrix-tier routing added #650 Task 7) — `compareForOrder`\n * and `resolveOrderLabel` below, and `snapshot.ts`'s `presentForJoin`\n * builder, all read this same vault-built closure. Reserved AND\n * collection (matrix) tier route here (the vault wires\n * `dimension -> LookupHandle.snapshotEntries()` / `dimension ->\n * collection.querySourceForJoin().snapshot()` respectively, keyed by\n * `descriptor.key` for the matrix case — see `registry.ts`'s\n * `buildLookupSnapshotRows`); static tier is resolved locally from\n * `descriptor.table` without calling this.\n */\n readonly snapshotFor?: (descriptor: LookupDescriptor) => ReadonlyMap<string, Record<string, unknown>> | undefined\n readonly collectionName: string\n}\n\n/** Enum tier (`backing:'static'`, no `table`) has no label source at all — never dressed. */\nfunction hasLabelSource(desc: LookupDescriptor): boolean {\n return !(desc.backing === 'static' && desc.table === undefined)\n}\n\n/**\n * Resolve one key's label. `'static'`/`'reserved'` both go through\n * `cfg.lookupLabelResolver` (mirrors `dictLabelResolver`'s own static-table-\n * first-else-reserved-handle branching — the SAME closure is reused, see\n * `kernel/vault.ts`). `'collection'` (matrix tier) reads the declared\n * `present.label` off the backing row via `cfg.getLookupBacking`; when\n * `present.by` is set, that field's value is a `{ locale -> label }` map\n * indexed by the effective locale.\n */\nasync function fetchLookupLabel(\n desc: LookupDescriptor,\n key: string,\n effLocale: string,\n fieldFallback: string | readonly string[] | undefined,\n cfg: LookupViaConfig,\n): Promise<string | undefined> {\n if (desc.backing === 'collection') {\n const getRow = cfg.getLookupBacking?.(desc)\n const row = getRow ? await getRow(key) : undefined\n const labelField = desc.present?.label\n if (!row || labelField === undefined) return undefined\n const raw = row[labelField]\n if (desc.present?.by !== undefined) {\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>)[effLocale] as string | undefined : undefined\n }\n return typeof raw === 'string' ? raw : undefined\n }\n return cfg.lookupLabelResolver?.(desc.dimension, key, effLocale, fieldFallback)\n}\n\n/** `present` — resolve `<field>Label` for every declared lookup field. Adapted from `via-i18n/binding.ts:253-337`. */\nasync function runLookupPresent(\n record: Record<string, unknown>,\n ctx: ViaReadCtx,\n cfg: LookupViaConfig,\n): Promise<Record<string, unknown>> {\n const fields = Object.entries(cfg.lookupFields).filter(([, d]) => hasLabelSource(d))\n if (fields.length === 0) return record\n\n const locale = typeof ctx.locale === 'string' ? ctx.locale : undefined\n const fallback = ctx.fallback as string | readonly string[] | undefined\n const layer = ctx.layer as Layer\n\n // `{ locale: 'raw' }` wants the untouched record — mirrors\n // `via-i18n/binding.ts`'s `locale !== 'raw'` dict-label gate exactly (no\n // synthetic `<field>Label` derivative on a raw read).\n if (locale === 'raw') return record\n\n // Static-display hybrid hinge: a `backing:'static'` field with a declared\n // `displayLocale` resolves its `<field>Label` even under a locale-less\n // read (mirrors staticDict's `hasStaticDisplay` gate).\n const hasStaticDisplay = fields.some(([, d]) => d.backing === 'static' && d.displayLocale !== undefined)\n if (!locale && !hasStaticDisplay) return record\n\n let result = record\n const withLabels = { ...result }\n\n for (const [field, desc] of fields) {\n const policy = desc.onMissing ? resolvePolicy(desc.onMissing, layer) : 'null'\n const fieldFallback = policy === 'substitute' ? (fallback ?? desc.substitute) : fallback\n const effLocale = locale ?? (desc.backing === 'static' ? desc.displayLocale : undefined)\n\n const resolveKey = async (key: string): Promise<string | null> => {\n if (!effLocale) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(field, `lookup \"${field}\": no locale active to resolve key \"${key}\".`)\n }\n return null\n }\n const label = await fetchLookupLabel(desc, key, effLocale, fieldFallback, cfg)\n if (label === undefined) {\n if (policy === 'throw') {\n throw new LocaleNotSpecifiedError(field, `lookup \"${field}\": no label for key \"${key}\" in locale \"${effLocale}\".`)\n }\n return null\n }\n return label\n }\n\n if (field.includes('[].')) {\n const parts = field.split('[].')\n const arrayKey = parts[0]!\n const leaf = parts[1]\n if (!leaf || leaf.includes('.')) continue\n const arr = (withLabels as Record<string, unknown>)[arrayKey]\n if (!Array.isArray(arr)) continue\n const labelKey = `${leaf}Label`\n ;(withLabels as Record<string, unknown>)[arrayKey] = await Promise.all(\n arr.map(async (el) => {\n if (!el || typeof el !== 'object' || Array.isArray(el)) return el\n const k = (el as Record<string, unknown>)[leaf]\n if (typeof k !== 'string') return el\n return { ...(el as Record<string, unknown>), [labelKey]: await resolveKey(k) }\n }),\n )\n continue\n }\n\n const val = result[field]\n if (Array.isArray(val)) {\n withLabels[`${field}Label`] = await Promise.all(\n val.map(async (k) => ({ key: k, label: typeof k === 'string' ? await resolveKey(k) : null })),\n )\n } else if (typeof val === 'string') {\n const label = await resolveKey(val)\n if (label !== null) withLabels[`${field}Label`] = label\n }\n }\n\n result = withLabels\n return result\n}\n\n/**\n * One field's `lookup` descriptor as it appears on a `ViaBinding.\n * describeFragment()` payload (#650 Task 7 — the first real consumer,\n * `with-shape/introspection/describe.ts`'s `buildDescription`, imports this\n * type directly; `describe.ts` is NOT under `kernel/**`, so it's free to\n * import concrete via/ types the way it already does for\n * `LookupDescriptor`/`MoneyDescriptor`/etc.). `dimension` is OMITTED (not\n * emitted as `''`) for a bare `enumOf()` descriptor — the #650 Task 2\n * `dimension:''` sentinel resolved: no dimension name means no `dimension`\n * key, not a meaningless empty string (T2 carry, #650 Task 7).\n */\nexport interface LookupDescribeFragmentEntry {\n readonly dimension?: string\n readonly backing: LookupBacking\n readonly vocabulary: Vocabulary\n readonly key: string\n readonly altKeys?: readonly string[]\n readonly present?: { readonly label: string; readonly by?: string }\n readonly sortBy?: string\n readonly onDelete: OnDelete\n /** Statically-known closed-vocabulary key set (declared `keys`, or a static table's own keys). Omitted when membership lives only in the backing collection/dictionary (open vocabulary, or closed with no declared `keys`). */\n readonly keys?: readonly string[]\n}\n\n/** The `'lookup'` binding's `describeFragment()` payload shape. */\nexport interface LookupDescribeFragment {\n readonly lookupFields: Record<string, LookupDescribeFragmentEntry>\n}\n\nfunction buildLookupDescribeFragment(cfg: LookupViaConfig): Record<string, unknown> {\n const lookupFields: Record<string, LookupDescribeFragmentEntry> = {}\n for (const [field, desc] of Object.entries(cfg.lookupFields)) {\n lookupFields[field] = {\n ...(desc.dimension !== '' ? { dimension: desc.dimension } : {}),\n backing: desc.backing,\n vocabulary: desc.vocabulary,\n key: desc.key,\n onDelete: desc.onDelete,\n ...(desc.altKeys !== undefined ? { altKeys: desc.altKeys } : {}),\n ...(desc.present !== undefined ? { present: desc.present } : {}),\n ...(desc.sortBy !== undefined ? { sortBy: desc.sortBy } : {}),\n // #657 — static tier: when no `keys` was explicitly declared but a\n // `table` was (the staticDict()-equivalent `lookup(dim, {backing:\n // 'static', table})` shape), the table's own key set IS the\n // statically-known closed-vocabulary set the DescribedField.lookup\n // docblock promises (\"declared `keys`, OR a static table's own\n // keys\"). Reserved/matrix tiers never carry `table`, so this branch\n // never fires for them — their `keys` emission is unchanged.\n ...(desc.keys !== undefined\n ? { keys: desc.keys }\n : desc.backing === 'static' && desc.table !== undefined ? { keys: Object.keys(desc.table) } : {}),\n }\n }\n return { lookupFields }\n}\n\n/**\n * `cfg.getAltIndex(desc)` (matrix tier) reads the backing collection's cache\n * via `querySourceForJoin()` (`buildLookupAltIndex`, registry.ts) — which\n * throws a `.join()`-branded message when that collection was opened\n * `{prefetch:false}` (lazy mode is unsupported for altKey normalization).\n * Normalization must never silently not happen (the banned silent-no-op\n * class, #650 Task 3 review, Important 2) — detect that specific failure\n * and surface a CLEAR, lookup-branded `ValidationError` at the point of\n * failure instead of letting the confusing join-branded one leak onto an\n * unrelated `put()`. Any OTHER error (e.g. `materializeBackingTable`'s own\n * altKey-collision `ValidationError`) propagates unchanged.\n */\nfunction getAltIndexOrThrow(field: string, desc: LookupDescriptor, cfg: LookupViaConfig): MaterializedBacking | undefined {\n try {\n return cfg.getAltIndex?.(desc)\n } catch (err) {\n if (err instanceof Error && err.message.includes('lazy-mode')) {\n throw new ValidationError(\n `lookup: altKeys on \"${field}\" require the backing collection \"${desc.dimension}\" to be ` +\n `prefetch-enabled (lazy mode unsupported); open it without {prefetch:false} or drop altKeys.`,\n )\n }\n throw err\n }\n}\n\n/**\n * `ingest` — altKey candidate values normalize to the canonical key (#650\n * Task 3, spec §3). Pure, sync, idempotent (a canonical key maps to\n * itself); no store read — consults the pre-materialized\n * `cfg.getAltIndex(desc)`. The money `canonicalizeIncomingMoney` precedent\n * (`via/index.ts:108`).\n *\n * A `[].`-wildcard multi-value path (`getAtPath` resolves >1 entries — an\n * array of nested objects, e.g. `'lines[].country'`, the same wildcard\n * convention `runLookupPresent` above already handles) normalizes EVERY\n * element's leaf value, not just a lone scalar (#652 fix — this used to bail\n * out entirely here while `runLookupEnforceWrite` below validated every\n * value unnormalized, so a legitimate altKey in an array position was\n * wrongly refused by closed-vocabulary enforcement). `setAtPathInPlace`\n * can't write into a `[].`-wildcard path, so the array is reconstructed\n * immutably instead, mirroring `runLookupPresent`'s own `field.includes\n * ('[].')` branch. A plain field whose OWN value is a bare top-level array\n * (not a `[].`-wildcard path) gets the SAME element-wise normalization\n * against `backing.altIndex` (#661 fix — `getAtPath` resolves it to one\n * opaque value, so the array itself is `values[0]`; a non-string element is\n * left untouched, mirroring the scalar branch's own `typeof !== 'string'`\n * skip — no parallel coercion invented for this shape).\n */\nfunction runLookupIngest(record: Record<string, unknown>, cfg: LookupViaConfig): Record<string, unknown> {\n const withAltKeys = Object.entries(cfg.lookupFields).filter(([, d]) => (d.altKeys?.length ?? 0) > 0)\n if (withAltKeys.length === 0) return record\n\n let result = record\n for (const [field, desc] of withAltKeys) {\n const backing = getAltIndexOrThrow(field, desc, cfg)\n if (!backing || backing.altIndex.size === 0) continue\n\n if (field.includes('[].')) {\n const [arrayKey, leaf] = field.split('[].')\n if (!leaf || leaf.includes('.')) continue\n const arr = record[arrayKey!]\n if (!Array.isArray(arr)) continue\n let changed = false\n const normalized = arr.map((item) => {\n if (!item || typeof item !== 'object' || Array.isArray(item)) return item\n const value = (item as Record<string, unknown>)[leaf]\n if (typeof value !== 'string') return item\n const canonical = backing.altIndex.get(value)\n if (canonical === undefined || canonical === value) return item\n changed = true\n return { ...(item as Record<string, unknown>), [leaf]: canonical }\n })\n if (!changed) continue\n if (result === record) result = { ...record }\n result[arrayKey!] = normalized\n continue\n }\n\n const values = getAtPath(record, field)\n if (values.length !== 1) continue\n const value = values[0]\n\n // `getAtPath`/`setAtPathInPlace` resolve `field` generically, dotted\n // paths included (e.g. 'meta.tags') — do not rewrite this branch to a\n // direct `record[field]` bracket access, which would silently stop\n // normalizing/enforcing a dotted-non-wildcard bare-array field (#661).\n if (Array.isArray(value)) {\n if (value.length === 0) continue\n let changed = false\n const normalized = value.map((el) => {\n if (typeof el !== 'string') return el\n const canonical = backing.altIndex.get(el)\n if (canonical === undefined || canonical === el) return el\n changed = true\n return canonical\n })\n if (!changed) continue\n if (result === record) result = { ...record }\n setAtPathInPlace(result, field, normalized)\n continue\n }\n\n if (typeof value !== 'string') continue\n const canonical = backing.altIndex.get(value)\n if (canonical === undefined || canonical === value) continue\n if (result === record) result = { ...record }\n setAtPathInPlace(result, field, canonical)\n }\n return result\n}\n\n/**\n * `enforceWrite` — closed-vocabulary write refusal (#650 Task 3, spec §3).\n * Runs only for `vocabulary:'closed'` fields; `'open'` (the dictKey/dict\n * default) skips the check entirely, so #649's fix is additive — existing\n * dictKey/staticDict collections are unaffected. `ctx` carries no\n * cross-collection door (`id`/`vault`/`prior`/`emit` only, unchanged) —\n * membership is a vault-built closure on `cfg`, per spec.\n */\nasync function runLookupEnforceWrite(record: Record<string, unknown>, cfg: LookupViaConfig): Promise<void> {\n for (const [field, desc] of Object.entries(cfg.lookupFields)) {\n if (desc.vocabulary !== 'closed') continue\n // Checks every value `getAtPath` returns — for a `[].`-wildcard\n // multi-value path, that's every element's leaf value.\n // `runLookupIngest` above now normalizes each of those elements first\n // (#652), so what lands here for a `[].`-wildcard field is already\n // canonical; this loop's job stays membership, not normalization.\n for (const value of getAtPath(record, field)) {\n // A plain field whose OWN value is a bare top-level array (#661) —\n // `runLookupIngest` above has already normalized its elements'\n // altKeys, so membership-check each element through the SAME\n // `cfg.membership` closure the scalar branch below uses, refusing on\n // the first unknown one. A non-string element is skipped, mirroring\n // the scalar branch's own skip.\n if (Array.isArray(value)) {\n for (const el of value) {\n if (typeof el !== 'string') continue\n const known = cfg.membership ? await cfg.membership(field, el) : true\n if (!known) throw new UnknownLookupKeyError(desc.dimension, field, el)\n }\n continue\n }\n if (typeof value !== 'string') continue\n const known = cfg.membership ? await cfg.membership(field, value) : true\n if (!known) throw new UnknownLookupKeyError(desc.dimension, field, value)\n }\n }\n}\n\n/**\n * `compareForOrder` — exact ordering for a `sortBy`-declared lookup field\n * against the sync snapshot (#650 Task 6, spec §5, conflict resolution 4;\n * matrix-tier coverage added #650 Task 7). Opt-in: undeclared `sortBy`\n * (every dictKey/staticDict alias and every lookup field declared before\n * Task 6) returns `undefined` — falls through to the generic stored-value\n * comparator, byte-identical to today. Static tier reads `descriptor.table`\n * directly; reserved AND matrix (collection) tier both read `cfg.snapshotFor`\n * (the SAME live cache `presentForJoin`'s lookup half reads — see\n * `snapshot.ts`'s file header). The hook has no locale parameter\n * (`via/index.ts:128-129`, unchanged) — closes over the descriptor's own\n * `displayLocale` (the same locale-less-hinge default `runLookupPresent`\n * already uses); a `sortBy` field whose value isn't locale-keyed\n * (`present.by` undefined) never needs one. A `by`-keyed `sortBy` field\n * with NO declared `displayLocale` degrades to comparing the raw canonical\n * keys (silent — `LookupSnapshot.compareKeys` never throws; declare-time\n * warning at `descriptor.ts`'s `lookup()` factory; use\n * `orderBy(field, dir, {by:'label'})` — `resolveOrderLabel` below — for a\n * PER-CALL locale instead).\n */\nfunction compareLookupOrder(field: string, a: unknown, b: unknown, cfg: LookupViaConfig): number | undefined {\n if (typeof a !== 'string' || typeof b !== 'string') return undefined\n const desc = cfg.lookupFields[field]\n if (!desc || desc.sortBy === undefined) return undefined\n const rows = desc.backing === 'static'\n ? (desc.table ? new Map(Object.entries(desc.table)) : undefined)\n : cfg.snapshotFor?.(desc)\n if (!rows) return undefined\n return buildLookupSnapshot(desc.dimension, rows, desc).compareKeys(a, b, desc.displayLocale ?? '')\n}\n\n/**\n * `resolveOrderLabel` — per-key, PER-CALL-locale label resolution for\n * `orderBy(field, dir, { by: 'label' })` (#650 Task 7, spec §6 / seam map\n * Part 10 surprise 6's option (b)) — the channel `compareForOrder` above\n * structurally cannot serve, since `ViaBinding.compareForOrder` carries no\n * locale parameter. Consumed by `kernel/query/builder.ts`'s\n * `buildOrderLabelMaps` as the fallback for lookup fields the legacy dict\n * registries don't bridge (matrix tier; reserved/static tier already\n * resolves via that bridge — `JoinContext.resolveDictSource` — tried\n * FIRST by the caller, see `registry.ts`'s `collectLookupDictCompat` doc\n * comment). Reuses the exact same `cfg.snapshotFor`/`buildLookupSnapshot`\n * machinery as `compareLookupOrder` above, just with the per-call `locale`\n * in place of the descriptor's own `displayLocale` — falling back to\n * `displayLocale` only when the call itself is locale-less, the same\n * hinge order `runLookupPresent` already uses.\n */\nfunction resolveLookupOrderLabel(field: string, key: string, locale: string | undefined, cfg: LookupViaConfig): string | undefined {\n const desc = cfg.lookupFields[field]\n if (!desc) return undefined\n const rows = desc.backing === 'static'\n ? (desc.table ? new Map(Object.entries(desc.table)) : undefined)\n : cfg.snapshotFor?.(desc)\n if (!rows) return undefined\n return buildLookupSnapshot(desc.dimension, rows, desc).label(key, locale ?? desc.displayLocale ?? '')\n}\n\nexport function lookupBinding(cfg: LookupViaConfig): ViaBinding {\n return {\n brand: 'lookup',\n posture: { encryptedAtRest: 'envelope', queryable: 'full', exportable: true, forgettable: false },\n reservedPrefixes: ['_dict_', '_lookup_'],\n covers: (field) => field in cfg.lookupFields,\n ingest: (record) => runLookupIngest(record, cfg),\n enforceWrite: (record) => runLookupEnforceWrite(record, cfg),\n present: async (record, ctx) => runLookupPresent(record, ctx, cfg),\n compareForOrder: (field, a, b) => compareLookupOrder(field, a, b, cfg),\n resolveOrderLabel: (field, key, locale) => resolveLookupOrderLabel(field, key, locale, cfg),\n describeFragment: () => buildLookupDescribeFragment(cfg),\n }\n}\n\nexport function linkLookupVia(): void {\n installViaBinder('lookup', (c) => lookupBinding(c as LookupViaConfig))\n}\n","/**\n * `lookup()` / `enumOf()` / `dict()` descriptors — the three declaration\n * surfaces for the `'lookup'` via binding (#650 Task 2, phase D of the Via\n * port). One `LookupDescriptor` shape; the tiers are `backing` details:\n *\n * - `lookup(dimension, opts?)` — matrix tier: first-class collection backing\n * (default `backing:'collection'`) — a reference-collection dimension\n * (e.g. `countries`), open vocabulary by default.\n * - `enumOf(keys)` — enum tier: static in-config table, CLOSED\n * vocabulary, no backing store at all (no dimension name — pure inline\n * keys). Exported as `enumOf`; the barrel (`index.ts`) re-exports it as\n * `enum` (`enum` is a reserved word, so it can't be the function's own\n * name).\n * - `dict(dimension, opts?)` — dict tier: reserved `_dict_<dimension>`\n * micro-collection backing (the `vault.dictionary(name)` engine), open\n * vocabulary by default.\n *\n * Each factory calls {@link linkLookupVia} first — the declaration IS the\n * via binding's opt-in unit (#553), same pattern as `money()`/`i18nText()`/\n * `dictKey()`.\n */\n\nimport type { OnMissingPolicy } from '../i18n/policy.js'\nimport { linkLookupVia } from './binding.js'\n\n/** `'closed'` = enum semantics (membership enforced, Task 3); `'open'` permits unknown keys. */\nexport type Vocabulary = 'open' | 'closed'\n\n/** Where a dimension's rows live: static in-config table / reserved micro-collection / first-class collection. */\nexport type LookupBacking = 'static' | 'reserved' | 'collection'\n\n/** Delete-time referential policy for the backing dimension (default `'restrict'`, enforced in Task 5). */\nexport type OnDelete = 'restrict' | 'cascade' | 'nullify'\n\n/** The one descriptor shape every tier compiles to — tiers differ only by `backing`. */\nexport interface LookupDescriptor<Keys extends string = string> {\n readonly _viaBrand: 'lookup'\n /** Dimension/dictionary/target name. Empty for a bare `enumOf()` (no backing store, no name). */\n readonly dimension: string\n /** Canonical key field on the row (default `'id'`). */\n readonly key: string\n /** Candidate keys normalized to `key` on ingest (Task 3). */\n readonly altKeys?: readonly string[]\n readonly vocabulary: Vocabulary\n /** Dressing dimension: which backing-row field supplies `<field>Label`, optionally keyed `by` a sub-field (e.g. locale). */\n readonly present?: { readonly label: string; readonly by?: string }\n /** Field to sort by against the snapshot (Task 6). */\n readonly sortBy?: string\n readonly backing: LookupBacking\n readonly onDelete: OnDelete\n /** Static/enum inline key set. */\n readonly keys?: readonly Keys[]\n /** Static tier only: in-code `key -> { locale -> label }` table. */\n readonly table?: Readonly<Record<string, Readonly<Record<string, string>>>>\n /** Static hybrid hinge (the `staticDict` alias) — locale-less `<field>Label`. */\n readonly displayLocale?: string\n readonly onMissing?: OnMissingPolicy\n readonly substitute?: readonly string[]\n /** Inline display labels (value -> label), the dict-tier sync fallback (mirrors `dictKey`'s `labels`). */\n readonly labels?: Record<string, string>\n}\n\n/**\n * `sortBy`/`present.by` coupling warning (#650 Task 7, T6 minor — task-6-\n * report.md Concern #4). A `by`-keyed `present` (locale-map) field used as\n * `sortBy` needs a declared `displayLocale` for the locale-less\n * `compareForOrder` sort hook (a plain `orderBy(field)`, no `{by:'label'}`)\n * to resolve anything — without one it silently degrades to comparing the\n * raw canonical keys (never throws — `LookupSnapshot.compareKeys`'s\n * contract). `orderBy(field, dir, {by:'label'})` doesn't need this (it\n * carries its own per-call locale via `ViaBinding.resolveOrderLabel`,\n * #650 Task 7) — only a sortBy-driven PLAIN orderBy does. Warn once at\n * declare time rather than degrade silently at query time.\n */\nfunction warnIfSortByNeedsDisplayLocale(\n dimension: string,\n opts?: { sortBy?: string; present?: { by?: string }; displayLocale?: string },\n): void {\n if (opts?.sortBy !== undefined && opts.present?.by !== undefined && opts.displayLocale === undefined) {\n console.warn(\n `[noy-db] lookup(\"${dimension}\"): sortBy \"${opts.sortBy}\" is locale-keyed (present.by is set) but no ` +\n `displayLocale is declared — a locale-less orderBy() will silently sort by the raw stored key instead ` +\n `of the resolved label. Declare displayLocale, or sort via orderBy(field, dir, { by: 'label' }), which ` +\n `resolves at the query's own per-call locale.`,\n )\n }\n}\n\n/**\n * Matrix tier — first-class collection backing (default `backing:'collection'`).\n * `dimension` names the backing collection (e.g. `'countries'`).\n *\n * `backing` may be overridden to construct any tier through this one\n * factory — e.g. `lookup(name, { backing:'static', table, displayLocale })`\n * is the table-bearing static tier `staticDict()` compiles onto. The\n * `table`/`displayLocale`/`keys`/`onMissing`/`substitute`/`labels` options\n * are a superset of the brief's literal opts list: `LookupDescriptor`\n * already carries these fields for exactly this purpose, and without them\n * `backing:'static'` would be unreachable stand-alone through `lookup()`\n * (see task-2-report.md's \"Design decisions\").\n *\n * **`altKeys` caveat (matrix tier only)**: normalizing an altKey candidate\n * to its canonical `key` requires the backing `dimension` collection to be\n * open in EAGER mode (the default; `{ prefetch: false }` — lazy mode — is\n * unsupported). A `put()` on a field with `altKeys` whose backing collection\n * is lazy throws a `ValidationError` naming the field and dimension; open\n * the backing collection without `{ prefetch: false }`, or drop `altKeys`.\n */\nexport function lookup<Keys extends string>(\n dimension: string,\n opts?: {\n key?: string\n altKeys?: readonly string[]\n vocabulary?: Vocabulary\n present?: { label: string; by?: string }\n sortBy?: string\n backing?: LookupBacking\n onDelete?: OnDelete\n keys?: readonly Keys[]\n table?: Readonly<Record<string, Readonly<Record<string, string>>>>\n displayLocale?: string\n onMissing?: OnMissingPolicy\n substitute?: readonly string[]\n labels?: Record<string, string>\n },\n): LookupDescriptor<Keys> {\n linkLookupVia()\n warnIfSortByNeedsDisplayLocale(dimension, opts)\n return {\n _viaBrand: 'lookup',\n dimension,\n key: opts?.key ?? 'id',\n vocabulary: opts?.vocabulary ?? 'open',\n backing: opts?.backing ?? 'collection',\n onDelete: opts?.onDelete ?? 'restrict',\n ...(opts?.altKeys !== undefined ? { altKeys: opts.altKeys } : {}),\n ...(opts?.present !== undefined ? { present: opts.present } : {}),\n ...(opts?.sortBy !== undefined ? { sortBy: opts.sortBy } : {}),\n ...(opts?.keys !== undefined ? { keys: opts.keys } : {}),\n ...(opts?.table !== undefined ? { table: opts.table } : {}),\n ...(opts?.displayLocale !== undefined ? { displayLocale: opts.displayLocale } : {}),\n ...(opts?.onMissing !== undefined ? { onMissing: opts.onMissing } : {}),\n ...(opts?.substitute !== undefined ? { substitute: opts.substitute } : {}),\n ...(opts?.labels !== undefined ? { labels: opts.labels } : {}),\n }\n}\n\n/**\n * Enum tier — static in-config table, CLOSED vocabulary, no backing store.\n * No dimension name (pure inline keys) — `dimension` is `''`.\n */\nexport function enumOf<const Keys extends readonly string[]>(keys: Keys): LookupDescriptor<Keys[number]> {\n linkLookupVia()\n return {\n _viaBrand: 'lookup',\n dimension: '',\n key: 'id',\n vocabulary: 'closed',\n backing: 'static',\n onDelete: 'restrict',\n keys,\n }\n}\n\n/**\n * Dict tier — reserved `_dict_<dimension>` micro-collection backing (the\n * `vault.dictionary(dimension)` engine), open vocabulary by default. The\n * native equivalent of `dictKey()`.\n *\n * Unlike `lookup()`'s matrix tier, `dict()` has no `altKeys` option — its\n * `_dict_<dimension>` backing is the always-synchronous `LookupHandle`\n * write-through cache, never a `vault.collection()` that can be opened\n * `{ prefetch: false }`, so the matrix tier's lazy-mode altKeys restriction\n * does not apply here.\n */\nexport function dict<Keys extends string>(\n dimension: string,\n opts?: {\n keys?: readonly Keys[]\n vocabulary?: Vocabulary\n present?: { label: string; by?: string }\n onDelete?: OnDelete\n onMissing?: OnMissingPolicy\n substitute?: readonly string[]\n },\n): LookupDescriptor<Keys> {\n linkLookupVia()\n return {\n _viaBrand: 'lookup',\n dimension,\n key: 'id',\n vocabulary: opts?.vocabulary ?? 'open',\n backing: 'reserved',\n onDelete: opts?.onDelete ?? 'restrict',\n ...(opts?.keys !== undefined ? { keys: opts.keys } : {}),\n ...(opts?.present !== undefined ? { present: opts.present } : {}),\n ...(opts?.onMissing !== undefined ? { onMissing: opts.onMissing } : {}),\n ...(opts?.substitute !== undefined ? { substitute: opts.substitute } : {}),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,OAAO,IAAI,CAAC;AAAA,EAC9D;AACF;AAMO,SAAS,OAA6C,MAA4C;AACvG,gBAAc;AACd,SAAO;AAAA,IACL,WAAW;AAAA,IACX,WAAW;AAAA,IACX,KAAK;AAAA,IACL,YAAY;AAAA,IACZ,SAAS;AAAA,IACT,UAAU;AAAA,IACV;AAAA,EACF;AACF;AAaO,SAAS,KACd,WACA,MAQwB;AACxB,gBAAc;AACd,SAAO;AAAA,IACL,WAAW;AAAA,IACX;AAAA,IACA,KAAK;AAAA,IACL,YAAY,MAAM,cAAc;AAAA,IAChC,SAAS;AAAA,IACT,UAAU,MAAM,YAAY;AAAA,IAC5B,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;AAAA,IACtD,GAAI,MAAM,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,IAC/D,GAAI,MAAM,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,IACrE,GAAI,MAAM,eAAe,SAAY,EAAE,YAAY,KAAK,WAAW,IAAI,CAAC;AAAA,EAC1E;AACF;","names":["value","canonical","known"]}
@@ -20,7 +20,7 @@
20
20
  *
21
21
  * ```ts
22
22
  * const db = await createNoydb({
23
- * store: jsonFile({ dir: './data' }),
23
+ * store: toFile({ dir: './data' }),
24
24
  * syncPolicy: {
25
25
  * push: { mode: 'debounce', debounceMs: 5_000 },
26
26
  * pull: { mode: 'on-focus' },
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  Noydb,
3
3
  createNoydb
4
- } from "./chunk-XOBHRD2M.js";
4
+ } from "./chunk-TWS3S62A.js";
5
5
  import "./chunk-NJ4DYYO5.js";
6
6
  import "./chunk-4JQK3L4V.js";
7
7
  import "./chunk-SHEEBRZ4.js";
@@ -50,7 +50,7 @@ import "./chunk-UADPR6F4.js";
50
50
  import "./chunk-6UBZ6I5Z.js";
51
51
  import "./chunk-C25JXSOR.js";
52
52
  import "./chunk-56IIVAEO.js";
53
- import "./chunk-VQNJ7UZL.js";
53
+ import "./chunk-MTJLOC3Y.js";
54
54
  import "./chunk-EZNTORXE.js";
55
55
  import "./chunk-KPXM4WO6.js";
56
56
  import "./chunk-WZ3NCMK6.js";
@@ -79,4 +79,4 @@ export {
79
79
  Noydb,
80
80
  createNoydb
81
81
  };
82
- //# sourceMappingURL=noydb-KXS35UJS.js.map
82
+ //# sourceMappingURL=noydb-FHZ4ZDBP.js.map
@@ -7,7 +7,7 @@ import {
7
7
  withMetrics,
8
8
  withRetry,
9
9
  wrapStore
10
- } from "../chunk-VSRSQ2CR.js";
10
+ } from "../chunk-EIPVYUEP.js";
11
11
  import "../chunk-PZ5AY32C.js";
12
12
  export {
13
13
  routeStore,
@@ -5,8 +5,8 @@ import {
5
5
  PresenceHandle,
6
6
  SyncEngine,
7
7
  SyncTransaction
8
- } from "../chunk-KBPU5M2E.js";
9
- import "../chunk-VQNJ7UZL.js";
8
+ } from "../chunk-BXHMZ2XW.js";
9
+ import "../chunk-MTJLOC3Y.js";
10
10
  import "../chunk-EZNTORXE.js";
11
11
  import "../chunk-RZPOZPZU.js";
12
12
  import "../chunk-VH6SOCXH.js";
@@ -40,8 +40,8 @@ import {
40
40
  PresenceHandle,
41
41
  SyncEngine,
42
42
  SyncTransaction
43
- } from "../chunk-KBPU5M2E.js";
44
- import "../chunk-VQNJ7UZL.js";
43
+ } from "../chunk-BXHMZ2XW.js";
44
+ import "../chunk-MTJLOC3Y.js";
45
45
  import "../chunk-EZNTORXE.js";
46
46
  import {
47
47
  SYNC_CREDENTIALS_COLLECTION,
@@ -204,7 +204,7 @@ export interface RoutedNoydbStore extends NoydbStore {
204
204
  * - `hydrate: ['invoices', 'clients']` — copies only named collections.
205
205
  *
206
206
  * Use cases:
207
- * - Shared device: `await store.override('default', memory(), { hydrate: true })`
207
+ * - Shared device: `await store.override('default', toMemory(), { hydrate: true })`
208
208
  * - Restricted network: `store.override('blobs', localFile(...))`
209
209
  */
210
210
  override(route: OverrideTarget, store: NoydbStore, opts?: OverrideOptions): void | Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy-db/hub",
3
- "version": "0.4.0-pre.7",
3
+ "version": "0.4.0-pre.8",
4
4
  "description": "Zero-knowledge, offline-first, encrypted document store — core library with AES-256-GCM, PBKDF2, multi-user keyring, and sync engine",
5
5
  "license": "MIT",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
@@ -204,14 +204,14 @@
204
204
  "node": ">=22.0.0"
205
205
  },
206
206
  "dependencies": {
207
- "@noy-db/attestation": "0.4.0-pre.7"
207
+ "@noy-db/attestation": "0.4.0-pre.8"
208
208
  },
209
209
  "devDependencies": {
210
210
  "@types/node": "^22.0.0",
211
211
  "esbuild": "^0.25.0",
212
212
  "zod": "^4.0.0",
213
213
  "zod-to-json-schema": "^3.25.2",
214
- "@noy-db/on-shamir": "0.4.0-pre.7"
214
+ "@noy-db/on-shamir": "0.4.0-pre.8"
215
215
  },
216
216
  "peerDependencies": {
217
217
  "zod-to-json-schema": "^3.25.0"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/kernel/sync-policy.ts"],"sourcesContent":["/**\n * Sync scheduling policy.\n *\n * ## What it controls\n *\n * A {@link SyncPolicy} has two halves:\n * - **push** ({@link PushPolicy}) — when dirty local writes are sent to the remote.\n * - **pull** ({@link PullPolicy}) — when the remote is polled for new data.\n *\n * ## Choosing a policy\n *\n * The right policy depends on the backend's operational characteristics:\n *\n * | Backend type | Recommended policy |\n * |---|---|\n * | Per-record (DynamoDB, S3, IDB) | {@link INDEXED_STORE_POLICY} — `on-change` push, `manual` pull |\n * | Bundle (Drive, WebDAV, Git) | {@link POD_STORE_POLICY} — `debounce` push, `interval` pull |\n *\n * Consumers can override via `createNoydb({ syncPolicy: { ... } })`:\n *\n * ```ts\n * const db = await createNoydb({\n * store: jsonFile({ dir: './data' }),\n * syncPolicy: {\n * push: { mode: 'debounce', debounceMs: 5_000 },\n * pull: { mode: 'on-focus' },\n * },\n * })\n * ```\n *\n * ## Scheduler lifecycle\n *\n * {@link SyncScheduler} owns all timers, debounce logic, and browser lifecycle\n * hooks (`visibilitychange`, `pagehide`, `beforeExit`). Call `scheduler.start()`\n * after opening a vault and `scheduler.stop()` when closing it. The scheduler\n * delegates actual push/pull work to {@link SyncSchedulerCallbacks} provided\n * by the {@link SyncEngine}.\n *\n * @module\n */\n\n// ─── Policy types ───────────────────────────────────────────────────────\n\n/**\n * When push operations are triggered automatically.\n *\n * - `'manual'` — only on explicit `sync.push()` calls.\n * - `'on-change'` — immediately after every local write (respecting `minIntervalMs`).\n * - `'debounce'` — after `debounceMs` of inactivity following a write.\n * - `'interval'` — on a fixed timer regardless of writes.\n */\nexport type PushMode = 'manual' | 'on-change' | 'debounce' | 'interval'\n\n/**\n * When pull operations are triggered automatically.\n *\n * - `'manual'` — only on explicit `sync.pull()` calls.\n * - `'interval'` — on a fixed `intervalMs` timer.\n * - `'on-focus'` — when the browser tab regains visibility.\n */\nexport type PullMode = 'manual' | 'interval' | 'on-focus'\n\n/**\n * Push half of a sync policy. Controls the trigger mode and timing guards\n * for outbound sync operations.\n */\nexport interface PushPolicy {\n /** Push trigger mode. */\n readonly mode: PushMode\n /** Debounce delay in ms. Only used when `mode: 'debounce'`. Default: 30_000. */\n readonly debounceMs?: number\n /** Interval in ms between automatic pushes. Used by `'interval'` and as floor for `'debounce'`. */\n readonly intervalMs?: number\n /**\n * Hard floor between pushes regardless of mode. Prevents burst writes\n * from hammering the remote. Default: 0 (no floor).\n */\n readonly minIntervalMs?: number\n /**\n * Force a push on page unload (`pagehide` / `visibilitychange → hidden`)\n * in browsers, `beforeExit` in Node. Default: true for non-manual modes.\n */\n readonly onUnload?: boolean\n}\n\n/**\n * Pull half of a sync policy. Controls when and how often inbound sync\n * operations are triggered.\n */\nexport interface PullPolicy {\n /** Pull trigger mode. */\n readonly mode: PullMode\n /** Interval in ms between automatic pulls. Used by `'interval'` mode. Default: 60_000. */\n readonly intervalMs?: number\n}\n\n/**\n * Combined push + pull sync scheduling policy for a vault.\n *\n * Pass via `createNoydb({ syncPolicy })` to override the default policy\n * derived from the active store type. Pre-built defaults are available\n * as `INDEXED_STORE_POLICY` and `POD_STORE_POLICY`.\n */\nexport interface SyncPolicy {\n readonly push: PushPolicy\n readonly pull: PullPolicy\n}\n\n// ─── Default policies by store category ─────────────────────────────────\n\n/** Default for per-record stores (DynamoDB, S3, file, IDB). */\nexport const INDEXED_STORE_POLICY: SyncPolicy = {\n push: { mode: 'on-change', minIntervalMs: 0, onUnload: true },\n pull: { mode: 'manual' },\n}\n\n/** Default for bundle stores (Drive, WebDAV, Git). */\nexport const POD_STORE_POLICY: SyncPolicy = {\n push: { mode: 'debounce', debounceMs: 30_000, minIntervalMs: 120_000, onUnload: true },\n pull: { mode: 'interval', intervalMs: 60_000 },\n}\n\n/** @deprecated Use `POD_STORE_POLICY`. */\nexport const BUNDLE_STORE_POLICY = POD_STORE_POLICY\n\n// ─── Sync scheduler ─────────────────────────────────────────────────────\n\n/**\n * Current operational state of the `SyncScheduler`.\n *\n * - `'idle'` — no pending or active sync operations.\n * - `'pending'` — local writes are queued, waiting for debounce/interval to fire.\n * - `'pushing'` — push in progress.\n * - `'pulling'` — pull in progress.\n * - `'error'` — last sync operation failed; `lastError` holds the cause.\n */\nexport type SyncSchedulerState = 'idle' | 'pending' | 'pushing' | 'pulling' | 'error'\n\n/**\n * Snapshot of the sync scheduler's state, returned by `SyncScheduler.status`.\n * Safe to expose in a reactive UI status indicator.\n */\nexport interface SyncSchedulerStatus {\n readonly state: SyncSchedulerState\n readonly lastPushAt: string | null\n readonly lastPullAt: string | null\n readonly lastError: Error | null\n readonly pendingWrites: number\n}\n\n/**\n * Callbacks injected into `SyncScheduler` by the SyncEngine.\n *\n * The scheduler owns timers and lifecycle hooks; it delegates actual push/pull\n * work to these callbacks to stay decoupled from the sync implementation.\n */\nexport interface SyncSchedulerCallbacks {\n push(): Promise<void>\n pull(): Promise<void>\n getDirtyCount(): number\n}\n\n/**\n * Manages sync timing according to a `SyncPolicy`.\n *\n * The scheduler owns all timers and lifecycle hooks. It delegates actual\n * push/pull work to callbacks provided by the SyncEngine.\n */\nexport class SyncScheduler {\n private readonly policy: SyncPolicy\n private readonly callbacks: SyncSchedulerCallbacks\n\n private _state: SyncSchedulerState = 'idle'\n private _lastPushAt: string | null = null\n private _lastPullAt: string | null = null\n private _lastError: Error | null = null\n private _lastPushTime = 0 // monotonic ms for minIntervalMs enforcement\n\n // Timers\n private debounceTimer: ReturnType<typeof setTimeout> | null = null\n private pushIntervalTimer: ReturnType<typeof setInterval> | null = null\n private pullIntervalTimer: ReturnType<typeof setInterval> | null = null\n\n // Bound handlers for cleanup\n private readonly boundOnVisibilityChange: (() => void) | null = null\n private readonly boundOnBeforeExit: (() => void) | null = null\n private readonly boundOnPageHide: (() => void) | null = null\n\n private started = false\n\n constructor(policy: SyncPolicy, callbacks: SyncSchedulerCallbacks) {\n this.policy = policy\n this.callbacks = callbacks\n\n // Pre-bind handlers\n if (this.shouldRegisterUnload()) {\n this.boundOnVisibilityChange = this.handleVisibilityChange.bind(this)\n this.boundOnPageHide = this.handlePageHide.bind(this)\n this.boundOnBeforeExit = this.handleBeforeExit.bind(this)\n }\n }\n\n /** Current scheduler status snapshot. */\n get status(): SyncSchedulerStatus {\n return {\n state: this._state,\n lastPushAt: this._lastPushAt,\n lastPullAt: this._lastPullAt,\n lastError: this._lastError,\n pendingWrites: this.callbacks.getDirtyCount(),\n }\n }\n\n /** Start the scheduler — registers timers, event listeners. */\n start(): void {\n if (this.started) return\n this.started = true\n\n // Push: interval mode\n if (this.policy.push.mode === 'interval' && this.policy.push.intervalMs) {\n this.pushIntervalTimer = setInterval(() => {\n void this.executePush()\n }, this.policy.push.intervalMs)\n }\n\n // Pull: interval mode\n if (this.policy.pull.mode === 'interval' && this.policy.pull.intervalMs) {\n this.pullIntervalTimer = setInterval(() => {\n void this.executePull()\n }, this.policy.pull.intervalMs)\n }\n\n // Pull: on-focus mode\n if (this.policy.pull.mode === 'on-focus' && typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', this.handleFocusPull)\n }\n\n // Unload hooks\n if (this.shouldRegisterUnload()) {\n if (typeof document !== 'undefined' && this.boundOnVisibilityChange) {\n document.addEventListener('visibilitychange', this.boundOnVisibilityChange)\n }\n if (typeof globalThis.addEventListener === 'function' && this.boundOnPageHide) {\n globalThis.addEventListener('pagehide', this.boundOnPageHide)\n }\n if (typeof process !== 'undefined' && this.boundOnBeforeExit) {\n process.on('beforeExit', this.boundOnBeforeExit)\n }\n }\n }\n\n /** Stop the scheduler — clears timers, removes event listeners. */\n stop(): void {\n if (!this.started) return\n this.started = false\n\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer)\n this.debounceTimer = null\n }\n if (this.pushIntervalTimer) {\n clearInterval(this.pushIntervalTimer)\n this.pushIntervalTimer = null\n }\n if (this.pullIntervalTimer) {\n clearInterval(this.pullIntervalTimer)\n this.pullIntervalTimer = null\n }\n\n // Focus pull\n if (this.policy.pull.mode === 'on-focus' && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', this.handleFocusPull)\n }\n\n // Unload hooks\n if (typeof document !== 'undefined' && this.boundOnVisibilityChange) {\n document.removeEventListener('visibilitychange', this.boundOnVisibilityChange)\n }\n if (typeof globalThis.removeEventListener === 'function' && this.boundOnPageHide) {\n globalThis.removeEventListener('pagehide', this.boundOnPageHide)\n }\n if (typeof process !== 'undefined' && this.boundOnBeforeExit) {\n process.removeListener('beforeExit', this.boundOnBeforeExit)\n }\n }\n\n /**\n * Notify the scheduler that a local write occurred.\n * For `on-change` mode: triggers immediate push (respecting minIntervalMs).\n * For `debounce` mode: resets the debounce timer.\n * For `manual` / `interval`: no-op.\n */\n notifyChange(): void {\n if (!this.started) return\n\n if (this.policy.push.mode === 'on-change') {\n void this.executePush()\n } else if (this.policy.push.mode === 'debounce') {\n this.resetDebounce()\n }\n }\n\n /** Force an immediate push, bypassing the scheduler. */\n async forcePush(): Promise<void> {\n await this.executePush()\n }\n\n /** Force an immediate pull, bypassing the scheduler. */\n async forcePull(): Promise<void> {\n await this.executePull()\n }\n\n // ─── Internal ─────────────────────────────────────────────────────\n\n private async executePush(): Promise<void> {\n if (this._state === 'pushing') return // already in progress\n\n // minIntervalMs enforcement\n const minInterval = this.policy.push.minIntervalMs ?? 0\n if (minInterval > 0) {\n const elapsed = Date.now() - this._lastPushTime\n if (elapsed < minInterval) {\n // Schedule for later if debounce mode\n if (this.policy.push.mode === 'debounce') {\n this.scheduleDebounce(minInterval - elapsed)\n }\n return\n }\n }\n\n // Nothing to push\n if (this.callbacks.getDirtyCount() === 0) {\n this._state = 'idle'\n return\n }\n\n this._state = 'pushing'\n try {\n await this.callbacks.push()\n this._lastPushAt = new Date().toISOString()\n this._lastPushTime = Date.now()\n this._lastError = null\n this._state = this.callbacks.getDirtyCount() > 0 ? 'pending' : 'idle'\n } catch (err) {\n this._lastError = err instanceof Error ? err : new Error(String(err))\n this._state = 'error'\n }\n }\n\n private async executePull(): Promise<void> {\n if (this._state === 'pulling') return\n\n const previousState = this._state\n this._state = 'pulling'\n try {\n await this.callbacks.pull()\n this._lastPullAt = new Date().toISOString()\n this._lastError = null\n this._state = previousState === 'pending' ? 'pending' : 'idle'\n } catch (err) {\n this._lastError = err instanceof Error ? err : new Error(String(err))\n this._state = 'error'\n }\n }\n\n private resetDebounce(): void {\n if (this.debounceTimer) clearTimeout(this.debounceTimer)\n const ms = this.policy.push.debounceMs ?? 30_000\n this._state = 'pending'\n this.scheduleDebounce(ms)\n }\n\n private scheduleDebounce(ms: number): void {\n if (this.debounceTimer) clearTimeout(this.debounceTimer)\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null\n void this.executePush()\n }, ms)\n }\n\n private shouldRegisterUnload(): boolean {\n const onUnload = this.policy.push.onUnload\n if (onUnload !== undefined) return onUnload\n return this.policy.push.mode !== 'manual'\n }\n\n // ─── Event handlers ───────────────────────────────────────────────\n\n private handleVisibilityChange(): void {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {\n this.fireUnloadPush()\n }\n }\n\n private handlePageHide(): void {\n this.fireUnloadPush()\n }\n\n private handleBeforeExit(): void {\n this.fireUnloadPush()\n }\n\n private handleFocusPull = (): void => {\n if (typeof document !== 'undefined' && document.visibilityState === 'visible') {\n void this.executePull()\n }\n }\n\n private fireUnloadPush(): void {\n if (this.callbacks.getDirtyCount() === 0) return\n // Best-effort synchronous-ish push on unload\n void this.callbacks.push().catch(() => {})\n }\n}\n"],"mappings":";AA+GO,IAAM,uBAAmC;AAAA,EAC9C,MAAM,EAAE,MAAM,aAAa,eAAe,GAAG,UAAU,KAAK;AAAA,EAC5D,MAAM,EAAE,MAAM,SAAS;AACzB;AAGO,IAAM,mBAA+B;AAAA,EAC1C,MAAM,EAAE,MAAM,YAAY,YAAY,KAAQ,eAAe,MAAS,UAAU,KAAK;AAAA,EACrF,MAAM,EAAE,MAAM,YAAY,YAAY,IAAO;AAC/C;AAGO,IAAM,sBAAsB;AA6C5B,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EACA;AAAA,EAET,SAA6B;AAAA,EAC7B,cAA6B;AAAA,EAC7B,cAA6B;AAAA,EAC7B,aAA2B;AAAA,EAC3B,gBAAgB;AAAA;AAAA;AAAA,EAGhB,gBAAsD;AAAA,EACtD,oBAA2D;AAAA,EAC3D,oBAA2D;AAAA;AAAA,EAGlD,0BAA+C;AAAA,EAC/C,oBAAyC;AAAA,EACzC,kBAAuC;AAAA,EAEhD,UAAU;AAAA,EAElB,YAAY,QAAoB,WAAmC;AACjE,SAAK,SAAS;AACd,SAAK,YAAY;AAGjB,QAAI,KAAK,qBAAqB,GAAG;AAC/B,WAAK,0BAA0B,KAAK,uBAAuB,KAAK,IAAI;AACpE,WAAK,kBAAkB,KAAK,eAAe,KAAK,IAAI;AACpD,WAAK,oBAAoB,KAAK,iBAAiB,KAAK,IAAI;AAAA,IAC1D;AAAA,EACF;AAAA;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AAgC;AACtC,UAAM,WAAW,KAAK,OAAO,KAAK;AAClC,QAAI,aAAa,OAAW,QAAO;AACnC,WAAO,KAAK,OAAO,KAAK,SAAS;AAAA,EACnC;AAAA;AAAA,EAIQ,yBAA+B;AACrC,QAAI,OAAO,aAAa,eAAe,SAAS,oBAAoB,UAAU;AAC5E,WAAK,eAAe;AAAA,IACtB;AAAA,EACF;AAAA,EAEQ,iBAAuB;AAC7B,SAAK,eAAe;AAAA,EACtB;AAAA,EAEQ,mBAAyB;AAC/B,SAAK,eAAe;AAAA,EACtB;AAAA,EAEQ,kBAAkB,MAAY;AACpC,QAAI,OAAO,aAAa,eAAe,SAAS,oBAAoB,WAAW;AAC7E,WAAK,KAAK,YAAY;AAAA,IACxB;AAAA,EACF;AAAA,EAEQ,iBAAuB;AAC7B,QAAI,KAAK,UAAU,cAAc,MAAM,EAAG;AAE1C,SAAK,KAAK,UAAU,KAAK,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAC3C;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/with-store/route-store.ts","../src/with-store/store-middleware.ts"],"sourcesContent":["/**\n * Store router / multiplexer.\n *\n * Dispatches `NoydbStore` operations to different backends based on\n * collection type, record size, record age, collection name, or vault name.\n *\n * ```ts\n * const db = await createNoydb({\n * store: routeStore({\n * default: dynamo({ table: 'myapp' }),\n * blobs: s3Store({ bucket: 'myapp-blobs' }),\n * }),\n * })\n * ```\n *\n * @module\n */\n\nimport type {\n NoydbStore,\n EncryptedEnvelope,\n VaultSnapshot,\n StoreCapabilities,\n} from '../kernel/types.js'\n\n// ─── Internal collection prefixes (duplicated to avoid circular import) ──\n\nconst BLOB_CHUNKS = '_blob_chunks'\nconst BLOB_INDEX = '_blob_index'\nconst BLOB_SLOTS = '_blob_slots_'\nconst BLOB_VERSIONS = '_blob_versions_'\n\n// ─── Options ─────────────────────────────────────────────────────────────\n\n/**\n * Size-tiered blob routing configuration.\n *\n * Routes blob chunks to different stores based on byte size. Small blobs\n * (under `threshold`) stay in the primary or `small` store; large blobs\n * go to `large`. This lets you keep DynamoDB as the default while sending\n * large binary objects to S3.\n */\nexport interface BlobStoreRoute {\n /** Store for small blobs (under threshold). Falls back to `default`. */\n readonly small?: NoydbStore\n /** Store for large blobs (over threshold). */\n readonly large: NoydbStore\n /** Size threshold in bytes. Default: `400 * 1024` (DynamoDB item limit). */\n readonly threshold?: number\n}\n\n/**\n * Blob lifecycle management policies evaluated during `compact()`.\n *\n * Controls orphan cleanup, cold-tier archival, and hard deletion of\n * blobs that are no longer referenced by any record.\n */\nexport interface BlobLifecyclePolicy {\n /** Delete orphan blobs (refCount: 0) after this many days. Default: 7. */\n readonly orphanRetentionDays?: number\n /** Move blobs not accessed in this many days to the cold blob store. */\n readonly archiveAfterDays?: number\n /** Store for archived blobs. Required if archiveAfterDays is set. */\n readonly archiveStore?: NoydbStore\n /** Hard-delete archived blobs after this many days. */\n readonly expireAfterDays?: number\n}\n\n/**\n * Age-based hot/cold tiering configuration.\n *\n * Records whose `_ts` timestamp is older than `coldAfterDays` are migrated\n * to the `cold` store during `compact()`. Reads transparently fall through\n * to the cold store when the hot store returns null, so callers don't need\n * to know which tier a record lives in.\n */\nexport interface AgeRoute {\n /** Store for records older than the cutoff. */\n readonly cold: NoydbStore\n /**\n * Days after last modification before a record is cold-eligible for the\n * ROLLING `compact(vault)` migrator. Omit for period-driven archival only\n * (`compact(vault, { before })`), where the cutoff is supplied per call.\n */\n readonly coldAfterDays?: number\n /**\n * Collections that participate in age tiering.\n * Empty array or omitted = all user collections (excluding `_` prefixed).\n */\n readonly collections?: string[]\n}\n\n/**\n * Options for `routeStore()` — the store multiplexer.\n *\n * At minimum, provide a `default` store. All other fields are optional\n * extensions for specific routing scenarios (blobs → S3, geographic sharding,\n * age-based tiering, etc.).\n */\nexport interface RouteStoreOptions {\n /** Default store for all unmatched operations. */\n readonly default: NoydbStore\n\n /**\n * Route blob chunk data to a separate store.\n * - Pass a `NoydbStore` for simple prefix routing (all chunks → that store).\n * - Pass `{ small?, large, threshold? }` for size-tiered routing.\n */\n readonly blobs?: NoydbStore | BlobStoreRoute\n\n /** Route all blob metadata (index, slots, versions) to the blobs store too. Default: false. */\n readonly routeBlobMeta?: boolean\n\n /** Route specific user collections to dedicated stores. */\n readonly routes?: Record<string, NoydbStore>\n\n /** Route by vault name (prefix patterns, e.g. `'EU-'`). */\n readonly vaultRoutes?: Record<string, NoydbStore>\n\n /**\n * Age-based tiering: records older than `coldAfterDays` are read from\n * the cold store. A background `compact()` method migrates them.\n */\n readonly age?: AgeRoute\n\n /**\n * Content-aware blob routing.\n * Route blob chunks by MIME type glob pattern. The MIME type is stored\n * in `BlobObject` and matched at read time via `storeHint`.\n */\n readonly blobRoutes?: Record<string, NoydbStore>\n\n /**\n * Blob lifecycle policies.\n * Evaluated during `compact()`.\n */\n readonly blobLifecycle?: BlobLifecyclePolicy\n\n /**\n * Quota-aware overflow.\n * When the default store's usage exceeds the threshold, new writes\n * overflow to the specified store.\n */\n readonly overflow?: NoydbStore\n\n /**\n * Quota threshold (0-1). Default: 0.8 (overflow at 80% usage).\n * Only effective when `overflow` is set.\n */\n readonly quotaThreshold?: number\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/**\n * Named route that can be overridden or suspended at runtime.\n *\n * Built-in names: `'default'`, `'blobs'`, `'cold'`.\n * Custom names: any collection name from `routes`, any vault prefix from\n * `vaultRoutes`, or any sync target label.\n */\nexport type OverrideTarget =\n | 'default'\n | 'blobs'\n | 'cold'\n | (string & {}) // named collection route, vault route, or sync target label\n\n/**\n * Options for `RoutedNoydbStore.override()`.\n *\n * Controls whether the new store is pre-populated with data from the\n * original store before the switch takes effect.\n */\nexport interface OverrideOptions {\n /**\n * Hydrate the override store from the original before activating.\n * - `true` — copy all data for all vaults.\n * - `string[]` — copy only named collections.\n * Makes `override()` async — returns a Promise.\n */\n hydrate?: boolean | string[]\n}\n\n/**\n * Options for `RoutedNoydbStore.suspend()`.\n *\n * A suspended route becomes a null store: reads return null/[], writes\n * are dropped (or buffered if `queue: true`). Useful for maintenance\n * windows or restricted-network scenarios.\n */\nexport interface SuspendOptions {\n /**\n * Buffer write operations during suspension. On `resume()`, queued\n * writes are replayed against the restored store.\n */\n queue?: boolean\n /**\n * Maximum queued operations. When exceeded, oldest entries are dropped.\n * Default: 10_000.\n */\n maxQueueSize?: number\n}\n\n/** Queued write operation recorded during suspension. */\ninterface QueuedWrite {\n method: 'put' | 'delete'\n vault: string\n collection: string\n id: string\n envelope?: EncryptedEnvelope\n expectedVersion?: number\n}\n\n/**\n * Snapshot of the current override and suspend state of a `RoutedNoydbStore`.\n * Returned by `routeStatus()` for diagnostics and health dashboards.\n */\nexport interface RouteStatus {\n /** Active overrides: route name → override store name. */\n readonly overrides: Record<string, string>\n /** Currently suspended routes. */\n readonly suspended: string[]\n /** Queued writes per suspended route (only for routes suspended with `queue: true`). */\n readonly queued: Record<string, number>\n}\n\n/**\n * Extended `NoydbStore` returned by `routeStore()`.\n *\n * Satisfies the full `NoydbStore` contract plus adds runtime control\n * methods for overriding, suspending, and inspecting routes.\n */\nexport interface RoutedNoydbStore extends NoydbStore {\n /**\n * Migrate records to the cold store. Only applies when `age.cold` is\n * configured. With `{ before }`, migrates records whose `_ts < before`\n * (period-driven archival); without, uses the rolling `coldAfterDays`.\n * Returns the number of records migrated.\n */\n compact(vault: string, opts?: { before?: string }): Promise<number>\n\n /**\n * Override a named route at runtime.\n *\n * The override persists until `clearOverride()` is called or the\n * instance is closed. In-flight operations complete on the original\n * store; new operations use the override.\n *\n * Options:\n * - `hydrate: true` — async: copies all data from the original store\n * into the override before activating the switch.\n * - `hydrate: ['invoices', 'clients']` — copies only named collections.\n *\n * Use cases:\n * - Shared device: `await store.override('default', memory(), { hydrate: true })`\n * - Restricted network: `store.override('blobs', localFile(...))`\n */\n override(route: OverrideTarget, store: NoydbStore, opts?: OverrideOptions): void | Promise<void>\n\n /** Clear a runtime override, reverting to the original store. */\n clearOverride(route: OverrideTarget): void\n\n /**\n * Suspend a route entirely. Operations to suspended stores become\n * no-ops (puts silently dropped, gets return null, lists return []).\n *\n * Options:\n * - `queue: true` — buffer write operations (put/delete) during\n * suspension. When `resume()` is called, queued writes are replayed\n * against the restored store.\n *\n * Returns a `SuspendHandle` when `queue: true`, for inspecting queue state.\n */\n suspend(route: OverrideTarget, opts?: SuspendOptions): void\n\n /**\n * Resume a previously suspended route.\n * If the route was suspended with `queue: true`, replays queued writes.\n * Returns the number of replayed operations.\n */\n resume(route: OverrideTarget): Promise<number>\n\n /** Snapshot the current override/suspend state for diagnostics. */\n routeStatus(): RouteStatus\n\n /**\n * Resolve the physical backend a vault id maps to via the geographic\n * `vaultRoutes` prefix routing (collection-independent), falling back to\n * the `default` store. Used by the federation data-residency guard\n * to read the placement backend's `capabilities.region`.\n */\n resolveBackend(vaultId: string): NoydbStore\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────\n\n/**\n * Create a store multiplexer that dispatches operations to different backends\n * based on collection type, record size, record age, vault prefix, or\n * runtime overrides.\n *\n * ```ts\n * const store = routeStore({\n * default: dynamo({ table: 'myapp' }),\n * blobs: s3({ bucket: 'myapp-blobs' }),\n * routes: { auditLog: s3({ bucket: 'myapp-audit' }) },\n * })\n * ```\n *\n * The returned store satisfies `NoydbStore` and can be passed directly to\n * `createNoydb({ store })`. It also exposes additional methods\n * (`override`, `suspend`, `resume`, `routeStatus`, `compact`) for runtime\n * control and maintenance.\n */\nexport function routeStore(opts: RouteStoreOptions): RoutedNoydbStore {\n const primary = opts.default\n\n // Resolve blob store config\n const blobsIsSimple = opts.blobs && 'get' in opts.blobs\n const simpleBlobStore = blobsIsSimple ? opts.blobs : undefined\n const tieredBlobs = !blobsIsSimple ? opts.blobs : undefined\n const blobThreshold = tieredBlobs?.threshold ?? 400 * 1024\n\n // Collect all stores for loadAll/saveAll/listVaults composition\n const allStores = new Set<NoydbStore>([primary])\n if (simpleBlobStore) allStores.add(simpleBlobStore)\n if (tieredBlobs?.large) allStores.add(tieredBlobs.large)\n if (tieredBlobs?.small) allStores.add(tieredBlobs.small)\n if (opts.age?.cold) allStores.add(opts.age.cold)\n if (opts.routes) for (const s of Object.values(opts.routes)) allStores.add(s)\n if (opts.vaultRoutes) for (const s of Object.values(opts.vaultRoutes)) allStores.add(s)\n if (opts.blobRoutes) for (const s of Object.values(opts.blobRoutes)) allStores.add(s)\n if (opts.overflow) allStores.add(opts.overflow)\n if (opts.blobLifecycle?.archiveStore) allStores.add(opts.blobLifecycle.archiveStore)\n\n // ── Runtime override / suspend state ──────────────────\n\n const overrides = new Map<string, NoydbStore>()\n const suspended = new Set<string>()\n const writeQueues = new Map<string, { writes: QueuedWrite[]; maxSize: number }>()\n\n /** Null store: silently absorbs all operations when a route is suspended. */\n const NULL_STORE: NoydbStore = {\n name: 'suspended',\n async get() { return null },\n async put() {},\n async delete() {},\n async list() { return [] },\n async loadAll() { return {} },\n async saveAll() {},\n }\n\n /**\n * Map a resolved route to its canonical name for override/suspend lookup.\n * Vault routes use the prefix, collection routes use the collection name,\n * blob route is 'blobs', cold route is 'cold', everything else is 'default'.\n */\n function routeNameFor(vault: string, collection: string): string {\n if (opts.vaultRoutes) {\n for (const prefix of Object.keys(opts.vaultRoutes)) {\n if (vault.startsWith(prefix)) return prefix\n }\n }\n if (opts.routes && !collection.startsWith('_') && opts.routes[collection]) {\n return collection\n }\n if (isBlobChunks(collection) && (simpleBlobStore || tieredBlobs)) return 'blobs'\n if (opts.routeBlobMeta && isBlobMeta(collection) && (simpleBlobStore || tieredBlobs)) return 'blobs'\n if (opts.age && !collection.startsWith('_')) {\n // We don't name age 'cold' here — cold is a fallback, not a primary route\n }\n return 'default'\n }\n\n // ── Quota-aware overflow (E8) ───────────────────────────────────────\n\n const quotaExceeded = false\n\n /** Resolve the static (non-overridden) store for a given route name. */\n function resolveOriginalStore(route: string): NoydbStore {\n if (route === 'blobs') return simpleBlobStore ?? tieredBlobs?.large ?? primary\n if (route === 'cold') return opts.age?.cold ?? primary\n if (opts.routes?.[route]) return opts.routes[route]\n if (opts.vaultRoutes?.[route]) return opts.vaultRoutes[route]\n return primary\n }\n\n /**\n * Queue a write operation if the route is suspended with queue: true.\n * Returns true if queued (caller should skip the actual write).\n */\n function maybeQueueWrite(\n routeName: string,\n method: 'put' | 'delete',\n vault: string,\n collection: string,\n id: string,\n envelope?: EncryptedEnvelope,\n expectedVersion?: number,\n ): boolean {\n if (!suspended.has(routeName)) return false\n const queue = writeQueues.get(routeName)\n if (!queue) return false // suspended but no queue — NullStore behavior\n\n // Evict oldest if at capacity\n if (queue.writes.length >= queue.maxSize) {\n queue.writes.shift()\n }\n queue.writes.push({\n method, vault, collection, id,\n ...(envelope !== undefined ? { envelope } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n })\n return true\n }\n\n // ── Routing logic ──────────────────────────────────────────────────\n\n function isBlobChunks(collection: string): boolean {\n return collection === BLOB_CHUNKS\n }\n\n function isBlobMeta(collection: string): boolean {\n return collection === BLOB_INDEX\n || collection.startsWith(BLOB_SLOTS)\n || collection.startsWith(BLOB_VERSIONS)\n }\n\n function isInternal(collection: string): boolean {\n return collection.startsWith('_')\n }\n\n /**\n * Resolve the store for a given vault + collection.\n * Resolution order: overrides/suspend → vaultRoutes → routes → blobs → default\n */\n function storeFor(vault: string, collection: string): NoydbStore {\n const rName = routeNameFor(vault, collection)\n\n // 0. Runtime override / suspend check\n if (suspended.has(rName)) return NULL_STORE\n if (overrides.has(rName)) return overrides.get(rName)!\n\n // 1. Vault-based geographic routing\n if (opts.vaultRoutes) {\n for (const [prefix, store] of Object.entries(opts.vaultRoutes)) {\n if (vault.startsWith(prefix)) return store\n }\n }\n\n // 2. Per-collection routing (user collections only)\n if (opts.routes && !isInternal(collection) && opts.routes[collection]) {\n return opts.routes[collection]\n }\n\n // 3. Blob chunk routing (simple — no size tiering at the store level)\n if (isBlobChunks(collection)) {\n if (simpleBlobStore) return simpleBlobStore\n // Size-tiered: can't determine here without the envelope.\n // Default to large store — BlobSet will use storeHint for reads.\n if (tieredBlobs) return tieredBlobs.large\n }\n\n // 4. Blob metadata routing\n if (opts.routeBlobMeta && isBlobMeta(collection)) {\n if (simpleBlobStore) return simpleBlobStore\n if (tieredBlobs) return tieredBlobs.large\n }\n\n // 5. Quota-aware overflow (E8)\n if (quotaExceeded && opts.overflow) return opts.overflow\n\n // 6. Default\n return primary\n }\n\n /**\n * For size-tiered blob routing: pick store based on envelope data size.\n */\n function blobStoreForSize(dataSize: number): NoydbStore {\n if (!tieredBlobs) return simpleBlobStore ?? primary\n if (dataSize <= blobThreshold) {\n return tieredBlobs.small ?? primary\n }\n return tieredBlobs.large\n }\n\n /**\n * Age routing: check if a record is cold based on `_ts`.\n */\n function isCold(collection: string, envelope: EncryptedEnvelope, before?: string): boolean {\n if (!opts.age) return false\n if (isInternal(collection)) return false\n if (opts.age.collections && opts.age.collections.length > 0) {\n if (!opts.age.collections.includes(collection)) return false\n }\n // explicit period cutoff wins; else the rolling age cutoff; else nothing is cold\n const cutoffIso =\n before ??\n (opts.age.coldAfterDays != null\n ? new Date(Date.now() - opts.age.coldAfterDays * 24 * 60 * 60 * 1000).toISOString()\n : undefined)\n if (cutoffIso === undefined) return false\n return envelope._ts < cutoffIso\n }\n\n // ── Store methods ──────────────────────────────────────────────────\n\n // #613: advertise cold-archival when a cold route exists. Spread the\n // primary's capabilities so CAS/auth/etc. still surface; layer the flag.\n // A router with no cold route of its own must NOT inherit `coldArchival:\n // true` from a nested cold-capable primary (whole-branch review I1) — force\n // it off explicitly so the consumer's `!== true` gate throws.\n const store: RoutedNoydbStore = {\n name: buildName(),\n ...(opts.age?.cold\n ? { capabilities: { ...primary.capabilities, coldArchival: true } as StoreCapabilities }\n : primary.capabilities\n ? { capabilities: { ...primary.capabilities, coldArchival: false } as StoreCapabilities }\n : {}),\n\n async get(vault, collection, id) {\n const s = storeFor(vault, collection)\n const result = await s.get(vault, collection, id)\n\n // Age tiering: if hot store returned null, try cold\n if (result === null && opts.age && !isInternal(collection)) {\n if (!opts.age.collections?.length || opts.age.collections.includes(collection)) {\n return opts.age.cold.get(vault, collection, id)\n }\n }\n\n return result\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n // Write-behind queue: buffer if suspended with queue option\n const rn = routeNameFor(vault, collection)\n if (maybeQueueWrite(rn, 'put', vault, collection, id, envelope, expectedVersion)) return\n\n // Size-tiered blob routing\n if (isBlobChunks(collection) && tieredBlobs) {\n const dataSize = envelope._data.length\n const s = blobStoreForSize(dataSize)\n return s.put(vault, collection, id, envelope, expectedVersion)\n }\n\n const s = storeFor(vault, collection)\n\n // Age tiering: if a cold record is being updated, it goes to hot.\n if (opts.age && !isInternal(collection)) {\n opts.age.cold.delete(vault, collection, id).catch(() => {})\n }\n\n return s.put(vault, collection, id, envelope, expectedVersion)\n },\n\n async delete(vault, collection, id) {\n // Write-behind queue: buffer if suspended with queue option\n const rn = routeNameFor(vault, collection)\n if (maybeQueueWrite(rn, 'delete', vault, collection, id)) return\n\n const s = storeFor(vault, collection)\n await s.delete(vault, collection, id)\n\n // Also delete from cold store if age-tiered\n if (opts.age && !isInternal(collection)) {\n await opts.age.cold.delete(vault, collection, id).catch(() => {})\n }\n },\n\n async list(vault, collection) {\n const s = storeFor(vault, collection)\n const ids = await s.list(vault, collection)\n\n // Age tiering: merge IDs from cold store, deduplicate\n if (opts.age && !isInternal(collection)) {\n if (!opts.age.collections?.length || opts.age.collections.includes(collection)) {\n const coldIds = await opts.age.cold.list(vault, collection).catch(() => [] as string[])\n if (coldIds.length > 0) {\n const merged = new Set(ids)\n for (const id of coldIds) merged.add(id)\n return [...merged]\n }\n }\n }\n\n return ids\n },\n\n async loadAll(vault) {\n // Query all distinct stores in parallel, merge snapshots\n const stores = getStoresForVault(vault)\n const snapshots = await Promise.all(\n stores.map(s => s.loadAll(vault).catch(() => ({}) as VaultSnapshot)),\n )\n return mergeSnapshots(snapshots)\n },\n\n async saveAll(vault, data) {\n // Partition snapshot by routing rules\n const partitioned = new Map<NoydbStore, VaultSnapshot>()\n\n for (const [collection, records] of Object.entries(data)) {\n const s = storeFor(vault, collection)\n if (!partitioned.has(s)) partitioned.set(s, {})\n partitioned.get(s)![collection] = records\n }\n\n await Promise.all(\n [...partitioned.entries()].map(([s, snap]) => s.saveAll(vault, snap)),\n )\n },\n\n async compact(vault, compactOpts) {\n if (!opts.age) return 0\n let migrated = 0\n const collections = opts.age.collections?.length\n ? opts.age.collections\n : Object.keys(await primary.loadAll(vault).catch(() => ({}) as VaultSnapshot))\n\n for (const collection of collections) {\n const ids = await primary.list(vault, collection).catch(() => [] as string[])\n for (const id of ids) {\n const envelope = await primary.get(vault, collection, id)\n if (!envelope) continue\n if (isCold(collection, envelope, compactOpts?.before)) {\n await opts.age.cold.put(vault, collection, id, envelope)\n await primary.delete(vault, collection, id)\n migrated++\n }\n }\n }\n return migrated\n },\n\n // ── Runtime override / suspend ──────────────────────\n\n override(route: OverrideTarget, overrideStore: NoydbStore, overrideOpts?: OverrideOptions): void | Promise<void> {\n if (overrideOpts?.hydrate) {\n // Async hydration: copy data from current store, then activate override\n return (async () => {\n // Hydration: caller should copy data from the original store to\n // overrideStore before calling override() with { hydrate: true }.\n // The route is activated immediately after.\n overrides.set(route, overrideStore)\n })()\n }\n overrides.set(route, overrideStore)\n },\n\n clearOverride(route: OverrideTarget): void {\n overrides.delete(route)\n },\n\n suspend(route: OverrideTarget, suspendOpts?: SuspendOptions): void {\n suspended.add(route)\n if (suspendOpts?.queue) {\n writeQueues.set(route, {\n writes: [],\n maxSize: suspendOpts.maxQueueSize ?? 10_000,\n })\n }\n },\n\n async resume(route: OverrideTarget): Promise<number> {\n suspended.delete(route)\n const queue = writeQueues.get(route)\n if (!queue || queue.writes.length === 0) {\n writeQueues.delete(route)\n return 0\n }\n\n // Replay queued writes against the now-active store\n let replayed = 0\n const target = overrides.get(route) ?? resolveOriginalStore(route)\n for (const write of queue.writes) {\n try {\n if (write.method === 'put' && write.envelope) {\n await target.put(write.vault, write.collection, write.id, write.envelope, write.expectedVersion)\n } else if (write.method === 'delete') {\n await target.delete(write.vault, write.collection, write.id)\n }\n replayed++\n } catch {\n // Best-effort replay — conflicts are expected after suspension\n }\n }\n\n writeQueues.delete(route)\n return replayed\n },\n\n routeStatus(): RouteStatus {\n const ov: Record<string, string> = {}\n for (const [k, v] of overrides) ov[k] = v.name ?? 'unnamed'\n const q: Record<string, number> = {}\n for (const [k, v] of writeQueues) q[k] = v.writes.length\n return { overrides: ov, suspended: [...suspended], queued: q }\n },\n\n resolveBackend(vaultId: string): NoydbStore {\n // Geographic routing is vault-prefix based + collection-independent;\n // the region-relevant backend is the vaultRoutes match, else default.\n if (opts.vaultRoutes) {\n for (const [prefix, s] of Object.entries(opts.vaultRoutes)) {\n if (vaultId.startsWith(prefix)) return s\n }\n }\n return primary\n },\n }\n\n // ── Optional method forwarding ─────────────────────────────────────\n\n // Forward listVaults from all stores, deduplicated\n if (anyHas('listVaults')) {\n store.listVaults = async () => {\n const results = await Promise.all(\n [...allStores]\n .filter(s => s.listVaults !== undefined)\n .map(s => s.listVaults!().catch(() => [] as string[])),\n )\n return [...new Set(results.flat())]\n }\n }\n\n // Forward ping — succeed if any store responds\n if (anyHas('ping')) {\n store.ping = async () => {\n const results = await Promise.all(\n [...allStores]\n .filter(s => s.ping !== undefined)\n .map(s => s.ping!().catch(() => false)),\n )\n return results.some(Boolean)\n }\n }\n\n return store\n\n // ── Helpers ────────────────────────────────────────────────────────\n\n function buildName(): string {\n const names = [...allStores].map(s => s.name ?? '?').join('+')\n return `route(${names})`\n }\n\n function anyHas(method: string): boolean {\n return [...allStores].some(s => (s as unknown as Record<string, unknown>)[method])\n }\n\n function getStoresForVault(vault: string): NoydbStore[] {\n const stores = new Set<NoydbStore>()\n\n // Check vault routes first\n if (opts.vaultRoutes) {\n for (const [prefix, s] of Object.entries(opts.vaultRoutes)) {\n if (vault.startsWith(prefix)) {\n stores.add(s)\n return [...stores] // vault-routed: only use that store\n }\n }\n }\n\n // Default topology: primary + blob store + cold store\n stores.add(primary)\n if (simpleBlobStore) stores.add(simpleBlobStore)\n if (tieredBlobs?.large) stores.add(tieredBlobs.large)\n if (tieredBlobs?.small && tieredBlobs.small !== primary) stores.add(tieredBlobs.small)\n if (opts.age?.cold) stores.add(opts.age.cold)\n if (opts.routes) {\n for (const s of Object.values(opts.routes)) stores.add(s)\n }\n\n return [...stores]\n }\n}\n\n// ─── Snapshot merge ──────────────────────────────────────────────────────\n\nfunction mergeSnapshots(snapshots: VaultSnapshot[]): VaultSnapshot {\n const merged: VaultSnapshot = {}\n\n for (const snap of snapshots) {\n for (const [collection, records] of Object.entries(snap)) {\n if (!merged[collection]) {\n merged[collection] = { ...records }\n continue\n }\n for (const [id, envelope] of Object.entries(records)) {\n const existing = merged[collection][id]\n // Last-write-wins by _ts\n if (!existing || envelope._ts >= existing._ts) {\n merged[collection][id] = envelope\n }\n }\n }\n }\n\n return merged\n}\n","/**\n * Store middleware — composable interceptors for NoydbStore.\n *\n * ```ts\n * const resilient = wrapStore(\n * dynamo({ table: 'myapp' }),\n * withRetry({ maxRetries: 3 }),\n * withLogging({ level: 'debug' }),\n * withCache({ ttlMs: 60_000 }),\n * )\n * ```\n *\n * Each middleware is `(next: NoydbStore) => NoydbStore`. They compose\n * left-to-right: first middleware is outermost (processes requests first,\n * responses last).\n *\n * @module\n */\n\nimport type { NoydbStore, EncryptedEnvelope } from '../kernel/types.js'\n\n// ─── Core composition ───────────────────────────────────────────────────\n\n/**\n * A store middleware function.\n *\n * Takes the next store in the chain and returns a wrapped store. Middlewares\n * compose left-to-right via `wrapStore()`: the first argument is outermost\n * (first to intercept requests, last to process responses).\n *\n * ```ts\n * const mw: StoreMiddleware = (next) => ({\n * ...next,\n * async get(vault, collection, id) {\n * console.log('get', id)\n * return next.get(vault, collection, id)\n * },\n * })\n * ```\n */\nexport type StoreMiddleware = (next: NoydbStore) => NoydbStore\n\n/**\n * Wrap a store with one or more middlewares. Middlewares compose left-to-right.\n */\nexport function wrapStore(store: NoydbStore, ...middlewares: StoreMiddleware[]): NoydbStore {\n let result = store\n // Apply right-to-left so the first middleware is the outermost wrapper\n for (let i = middlewares.length - 1; i >= 0; i--) {\n result = middlewares[i]!(result)\n }\n return result\n}\n\n// ─── withRetry ──────────────────────────────────────────────────────────\n\n/** Options for `withRetry()`. */\nexport interface RetryOptions {\n /** Maximum retry attempts. Default: 3. */\n maxRetries?: number\n /** Base backoff delay in ms. Default: 500. */\n backoffMs?: number\n /** Jitter factor (0-1). Adds random delay up to `backoffMs * jitter`. Default: 0.3. */\n jitter?: number\n /** Only retry on these error codes. Default: retry all errors. */\n retryOn?: string[]\n}\n\n/**\n * Middleware that retries failed store operations with exponential backoff\n * and optional jitter. Useful for transient network errors on DynamoDB/S3.\n *\n * ```ts\n * wrapStore(dynamo({ table: 'myapp' }), withRetry({ maxRetries: 5, retryOn: ['NETWORK_ERROR'] }))\n * ```\n */\nexport function withRetry(opts: RetryOptions = {}): StoreMiddleware {\n const maxRetries = opts.maxRetries ?? 3\n const backoffMs = opts.backoffMs ?? 500\n const jitter = opts.jitter ?? 0.3\n const retryOn = opts.retryOn ? new Set(opts.retryOn) : null\n\n function shouldRetry(err: unknown): boolean {\n if (!retryOn) return true\n if (err && typeof err === 'object' && 'code' in err) {\n return retryOn.has((err as { code: string }).code)\n }\n return true\n }\n\n async function retryable<T>(fn: () => Promise<T>): Promise<T> {\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn()\n } catch (err) {\n lastError = err\n if (attempt >= maxRetries || !shouldRetry(err)) throw err\n const delay = backoffMs * Math.pow(2, attempt) * (1 + Math.random() * jitter)\n await new Promise(r => setTimeout(r, delay))\n }\n }\n throw lastError\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `retry(${next.name})` : 'retry',\n get: (v, c, id) => retryable(() => next.get(v, c, id)),\n put: (v, c, id, env, ev) => retryable(() => next.put(v, c, id, env, ev)),\n delete: (v, c, id) => retryable(() => next.delete(v, c, id)),\n list: (v, c) => retryable(() => next.list(v, c)),\n loadAll: (v) => retryable(() => next.loadAll(v)),\n saveAll: (v, d) => retryable(() => next.saveAll(v, d)),\n })\n}\n\n// ─── withLogging ────────────────────────────────────────────────────────\n\n/** Log level for `withLogging()`. Maps to standard console method names. */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/** Options for `withLogging()`. */\nexport interface LoggingOptions {\n /** Minimum log level. Default: 'info'. */\n level?: LogLevel\n /** Custom logger. Default: console. */\n logger?: {\n debug(msg: string, ...args: unknown[]): void\n info(msg: string, ...args: unknown[]): void\n warn(msg: string, ...args: unknown[]): void\n error(msg: string, ...args: unknown[]): void\n }\n /** Log the data payload (envelope contents). Default: false (privacy). */\n logData?: boolean\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 }\n\n/**\n * Middleware that logs every store operation with its method name, arguments,\n * and elapsed duration. Privacy-safe by default: envelope payloads are not\n * logged unless `logData: true` is set.\n */\nexport function withLogging(opts: LoggingOptions = {}): StoreMiddleware {\n const minLevel = LOG_LEVELS[opts.level ?? 'info']\n const logger = opts.logger ?? console\n const logData = opts.logData ?? false\n\n function log(level: LogLevel, method: string, args: Record<string, unknown>, durationMs?: number) {\n if (LOG_LEVELS[level] < minLevel) return\n const parts = [`[noydb:${method}]`, ...Object.entries(args).map(([k, v]) => `${k}=${String(v)}`)]\n if (durationMs !== undefined) parts.push(`${durationMs}ms`)\n logger[level](parts.join(' '))\n }\n\n function timed<T>(method: string, args: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n const start = Date.now()\n return fn().then(\n (result) => {\n log('debug', method, args, Date.now() - start)\n return result\n },\n (err) => {\n log('error', method, { ...args, error: (err as Error).message }, Date.now() - start)\n throw err\n },\n )\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `log(${next.name})` : 'log',\n get: (v, c, id) => timed('get', { vault: v, collection: c, id }, () => next.get(v, c, id)),\n put: (v, c, id, env, ev) => timed('put', {\n vault: v, collection: c, id, version: env._v,\n ...(logData ? { data: env._data.slice(0, 40) + '...' } : {}),\n }, () => next.put(v, c, id, env, ev)),\n delete: (v, c, id) => timed('delete', { vault: v, collection: c, id }, () => next.delete(v, c, id)),\n list: (v, c) => timed('list', { vault: v, collection: c }, () => next.list(v, c)),\n loadAll: (v) => timed('loadAll', { vault: v }, () => next.loadAll(v)),\n saveAll: (v, d) => timed('saveAll', { vault: v }, () => next.saveAll(v, d)),\n })\n}\n\n// ─── withMetrics ────────────────────────────────────────────────────────\n\n/**\n * Data emitted to `MetricsOptions.onOperation` after every store call.\n *\n * Carries method name, vault/collection/id context, elapsed duration,\n * and success/failure status. Wire this into your metrics pipeline\n * (DataDog, Prometheus, CloudWatch) to get per-operation latency histograms.\n */\nexport interface StoreOperation {\n method: 'get' | 'put' | 'delete' | 'list' | 'loadAll' | 'saveAll'\n vault: string\n collection?: string\n id?: string\n durationMs: number\n success: boolean\n error?: Error\n}\n\n/** Options for `withMetrics()`. */\nexport interface MetricsOptions {\n /** Called after every store operation. */\n onOperation: (op: StoreOperation) => void\n}\n\n/**\n * Middleware that calls `onOperation` after every store method with timing\n * and success/failure data. Designed for low-overhead integration with\n * metrics systems — the callback is synchronous and fire-and-forget.\n */\nexport function withMetrics(opts: MetricsOptions): StoreMiddleware {\n function tracked<T>(\n method: StoreOperation['method'],\n vault: string,\n fn: () => Promise<T>,\n collection?: string,\n id?: string,\n ): Promise<T> {\n const start = Date.now()\n return fn().then(\n (result) => {\n opts.onOperation({\n method, vault,\n ...(collection !== undefined ? { collection } : {}),\n ...(id !== undefined ? { id } : {}),\n durationMs: Date.now() - start, success: true,\n })\n return result\n },\n (err) => {\n opts.onOperation({\n method, vault,\n ...(collection !== undefined ? { collection } : {}),\n ...(id !== undefined ? { id } : {}),\n durationMs: Date.now() - start, success: false, error: err as Error,\n })\n throw err\n },\n )\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `metrics(${next.name})` : 'metrics',\n get: (v, c, id) => tracked('get', v, () => next.get(v, c, id), c, id),\n put: (v, c, id, env, ev) => tracked('put', v, () => next.put(v, c, id, env, ev), c, id),\n delete: (v, c, id) => tracked('delete', v, () => next.delete(v, c, id), c, id),\n list: (v, c) => tracked('list', v, () => next.list(v, c), c),\n loadAll: (v) => tracked('loadAll', v, () => next.loadAll(v)),\n saveAll: (v, d) => tracked('saveAll', v, () => next.saveAll(v, d)),\n })\n}\n\n// ─── withCircuitBreaker ─────────────────────────────────────────────────\n\n/**\n * Options for `withCircuitBreaker()`.\n *\n * The circuit breaker moves through three states:\n * - `closed`: normal operation.\n * - `open`: store is failing; all calls return fallback values immediately.\n * - `half-open`: one probe call after `resetTimeoutMs` — success closes, failure re-opens.\n */\nexport interface CircuitBreakerOptions {\n /** Number of consecutive failures before opening the circuit. Default: 5. */\n failureThreshold?: number\n /** Time in ms before attempting to half-open the circuit. Default: 30_000. */\n resetTimeoutMs?: number\n /** Called when the circuit opens (store becomes unavailable). */\n onOpen?: () => void\n /** Called when the circuit closes (store recovers). */\n onClose?: () => void\n}\n\ntype CircuitState = 'closed' | 'open' | 'half-open'\n\n/**\n * Middleware that implements the circuit-breaker pattern.\n *\n * When the wrapped store fails `failureThreshold` consecutive times, the\n * circuit opens: subsequent calls return safe fallback values (`null`, `[]`,\n * `{}`) without hitting the store. After `resetTimeoutMs` the circuit\n * half-opens and allows one probe — success closes the circuit, failure\n * keeps it open. Pair with `withRetry` to handle transient errors before\n * they trip the circuit.\n */\nexport function withCircuitBreaker(opts: CircuitBreakerOptions = {}): StoreMiddleware {\n const threshold = opts.failureThreshold ?? 5\n const resetMs = opts.resetTimeoutMs ?? 30_000\n\n let state: CircuitState = 'closed'\n let failures = 0\n let lastFailureTime = 0\n\n function recordSuccess(): void {\n if (state === 'half-open') {\n state = 'closed'\n failures = 0\n opts.onClose?.()\n }\n failures = 0\n }\n\n function recordFailure(): void {\n failures++\n lastFailureTime = Date.now()\n if (failures >= threshold && state === 'closed') {\n state = 'open'\n opts.onOpen?.()\n }\n }\n\n function canAttempt(): boolean {\n if (state === 'closed') return true\n if (state === 'open') {\n if (Date.now() - lastFailureTime >= resetMs) {\n state = 'half-open'\n return true\n }\n return false\n }\n // half-open: allow one attempt\n return true\n }\n\n async function guarded<T>(fn: () => Promise<T>, fallback: T): Promise<T> {\n if (!canAttempt()) return fallback\n try {\n const result = await fn()\n recordSuccess()\n return result\n } catch (err) {\n recordFailure()\n throw err\n }\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `cb(${next.name})` : 'cb',\n get: (v, c, id) => guarded(() => next.get(v, c, id), null),\n put: (v, c, id, env, ev) => guarded(() => next.put(v, c, id, env, ev), undefined),\n delete: (v, c, id) => guarded(() => next.delete(v, c, id), undefined),\n list: (v, c) => guarded(() => next.list(v, c), []),\n loadAll: (v) => guarded(() => next.loadAll(v), {}),\n saveAll: (v, d) => guarded(() => next.saveAll(v, d), undefined),\n })\n}\n\n// ─── withCache (read-through) ───────────────────────────────────────────\n\n/**\n * Options for `withCache()`.\n *\n * The cache is a read-through LRU that caches individual record fetches\n * (`get`). Writes (`put`, `delete`) invalidate the relevant cache entry\n * immediately. `list`, `loadAll`, and `saveAll` bypass the cache.\n *\n * Named `StoreCacheOptions` to distinguish from `CacheOptions` in\n * `@noy-db/hub/collection`, which controls the in-memory decrypted-record LRU.\n */\nexport interface StoreCacheOptions {\n /** Maximum cached entries. Default: 500. */\n maxEntries?: number\n /** Cache TTL in ms. Default: 60_000 (1 minute). 0 = no expiry. */\n ttlMs?: number\n}\n\ninterface CacheEntry {\n envelope: EncryptedEnvelope | null\n cachedAt: number\n}\n\n/**\n * Middleware that adds a read-through LRU cache for `get()` calls.\n *\n * Reduces latency for frequently-read records (e.g. lookup tables, user\n * profiles) by serving repeat reads from memory. Because NOYDB records are\n * encrypted at rest, caching envelopes is safe — the cache holds ciphertext,\n * not plaintext. For write-heavy workloads, the cache provides little benefit\n * and should be omitted to avoid the invalidation overhead.\n */\nexport function withCache(opts: StoreCacheOptions = {}): StoreMiddleware {\n const maxEntries = opts.maxEntries ?? 500\n const ttlMs = opts.ttlMs ?? 60_000\n\n // LRU cache: Map preserves insertion order, we delete+re-insert on access\n const cache = new Map<string, CacheEntry>()\n\n function cacheKey(vault: string, collection: string, id: string): string {\n return `${vault}\\0${collection}\\0${id}`\n }\n\n function getFromCache(key: string): EncryptedEnvelope | null | undefined {\n const entry = cache.get(key)\n if (!entry) return undefined\n if (ttlMs > 0 && Date.now() - entry.cachedAt > ttlMs) {\n cache.delete(key)\n return undefined\n }\n // LRU: move to end\n cache.delete(key)\n cache.set(key, entry)\n return entry.envelope\n }\n\n function setInCache(key: string, envelope: EncryptedEnvelope | null): void {\n // Evict oldest if at capacity\n if (cache.size >= maxEntries) {\n const oldest = cache.keys().next().value\n if (oldest !== undefined) cache.delete(oldest)\n }\n cache.set(key, { envelope, cachedAt: Date.now() })\n }\n\n function invalidate(key: string): void {\n cache.delete(key)\n }\n\n return (next) => ({\n ...next,\n name: next.name ? `cache(${next.name})` : 'cache',\n\n async get(vault, collection, id) {\n const key = cacheKey(vault, collection, id)\n const cached = getFromCache(key)\n if (cached !== undefined) return cached\n const result = await next.get(vault, collection, id)\n setInCache(key, result)\n return result\n },\n\n async put(vault, collection, id, env, ev) {\n invalidate(cacheKey(vault, collection, id))\n await next.put(vault, collection, id, env, ev)\n setInCache(cacheKey(vault, collection, id), env)\n },\n\n async delete(vault, collection, id) {\n invalidate(cacheKey(vault, collection, id))\n await next.delete(vault, collection, id)\n },\n\n list: (v, c) => next.list(v, c),\n loadAll: (v) => next.loadAll(v),\n saveAll: (v, d) => next.saveAll(v, d),\n })\n}\n\n// ─── withHealthCheck ────────────────────────────────────────────────────\n\nexport interface HealthCheckOptions {\n /** Ping interval in ms. Default: 30_000. */\n checkIntervalMs?: number\n /** Suspend after N consecutive ping failures. Default: 3. */\n suspendAfterFailures?: number\n /** Resume after N consecutive ping successes. Default: 1. */\n resumeAfterSuccess?: number\n /** Called when the store is auto-suspended. */\n onSuspend?: () => void\n /** Called when the store is auto-resumed. */\n onResume?: () => void\n /**\n * Custom health check. Default: calls `store.ping()` if available,\n * otherwise attempts a `list()` on a sentinel collection.\n */\n check?: () => Promise<boolean>\n}\n\n/**\n * Auto-suspends a store when health checks fail, auto-resumes when they recover.\n *\n * When suspended, `get` returns null, `put`/`delete` are no-ops, `list` returns [].\n * This is identical to the `NullStore` behavior from `routeStore.suspend()`.\n */\nexport function withHealthCheck(opts: HealthCheckOptions = {}): StoreMiddleware {\n const intervalMs = opts.checkIntervalMs ?? 30_000\n const failThreshold = opts.suspendAfterFailures ?? 3\n const successThreshold = opts.resumeAfterSuccess ?? 1\n\n let isSuspended = false\n let consecutiveFailures = 0\n let consecutiveSuccesses = 0\n\n return (next) => {\n const checkFn = opts.check ?? (\n next.ping\n ? () => next.ping!()\n : async () => { await next.list('__health__', '__ping__'); return true }\n )\n\n async function doCheck(): Promise<void> {\n try {\n const ok = await checkFn()\n if (ok) {\n consecutiveFailures = 0\n consecutiveSuccesses++\n if (isSuspended && consecutiveSuccesses >= successThreshold) {\n isSuspended = false\n consecutiveSuccesses = 0\n opts.onResume?.()\n }\n } else {\n throw new Error('Health check returned false')\n }\n } catch {\n consecutiveSuccesses = 0\n consecutiveFailures++\n if (!isSuspended && consecutiveFailures >= failThreshold) {\n isSuspended = true\n consecutiveFailures = 0\n opts.onSuspend?.()\n }\n }\n }\n\n // Start checking\n setInterval(() => { void doCheck() }, intervalMs)\n\n const wrapped: NoydbStore = {\n ...next,\n name: next.name ? `health(${next.name})` : 'health',\n\n async get(v, c, id) { return isSuspended ? null : next.get(v, c, id) },\n async put(v, c, id, env, ev) { if (!isSuspended) await next.put(v, c, id, env, ev) },\n async delete(v, c, id) { if (!isSuspended) await next.delete(v, c, id) },\n async list(v, c) { return isSuspended ? [] : next.list(v, c) },\n async loadAll(v) { return isSuspended ? {} : next.loadAll(v) },\n async saveAll(v, d) { if (!isSuspended) await next.saveAll(v, d) },\n }\n\n return wrapped\n }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