@pgxsinkit/client 0.1.53 → 0.2.1

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.
Files changed (85) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/export-store.d.ts +1 -1
  9. package/dist/export-store.d.ts.map +1 -1
  10. package/dist/index.d.ts +286 -51
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4795 -1519
  13. package/dist/index.js.map +34 -24
  14. package/dist/live-rows-sql.d.ts +1 -1
  15. package/dist/local-store.d.ts +16 -31
  16. package/dist/local-store.d.ts.map +1 -1
  17. package/dist/local-tables.d.ts +4 -4
  18. package/dist/mutation.d.ts +18 -15
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/opfs-effects.d.ts +51 -0
  21. package/dist/opfs-effects.d.ts.map +1 -0
  22. package/dist/placement-probe.d.ts +75 -0
  23. package/dist/placement-probe.d.ts.map +1 -0
  24. package/dist/schema.d.ts +11 -16
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/store-boot.d.ts +77 -0
  27. package/dist/store-boot.d.ts.map +1 -0
  28. package/dist/store-lifecycle.d.ts +153 -0
  29. package/dist/store-lifecycle.d.ts.map +1 -0
  30. package/dist/store-meta.d.ts +190 -0
  31. package/dist/store-meta.d.ts.map +1 -0
  32. package/dist/store-path.d.ts +77 -7
  33. package/dist/store-path.d.ts.map +1 -1
  34. package/dist/sync/apply.d.ts.map +1 -1
  35. package/dist/sync/shape-inbox.d.ts +1 -1
  36. package/dist/sync/types.d.ts +3 -3
  37. package/dist/testing.js.map +3 -3
  38. package/dist/worker/attach-sync-client.d.ts +300 -16
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +164 -23
  41. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  42. package/dist/worker/election-coordinator.d.ts +95 -0
  43. package/dist/worker/election-coordinator.d.ts.map +1 -0
  44. package/dist/worker/engine-control.d.ts +266 -0
  45. package/dist/worker/engine-control.d.ts.map +1 -0
  46. package/dist/worker/engine-router.d.ts +75 -0
  47. package/dist/worker/engine-router.d.ts.map +1 -0
  48. package/dist/worker/live-query-manager.d.ts.map +1 -1
  49. package/dist/worker/protocol.d.ts +47 -31
  50. package/dist/worker/protocol.d.ts.map +1 -1
  51. package/dist/worker/sw-placement.d.ts +37 -0
  52. package/dist/worker/sw-placement.d.ts.map +1 -0
  53. package/package.json +4 -3
  54. package/skills/core/SKILL.md +15 -12
  55. package/skills/operating/SKILL.md +142 -46
  56. package/src/adoption.ts +275 -0
  57. package/src/boot-report.ts +70 -17
  58. package/src/convergence.ts +2 -1
  59. package/src/export-store.ts +1 -1
  60. package/src/index.ts +1157 -115
  61. package/src/live-rows-sql.ts +1 -1
  62. package/src/local-store.ts +18 -40
  63. package/src/local-tables.ts +2 -2
  64. package/src/mutation.ts +115 -53
  65. package/src/mutations-api.ts +3 -3
  66. package/src/opfs-effects.ts +160 -0
  67. package/src/placement-probe.ts +168 -0
  68. package/src/schema.ts +17 -22
  69. package/src/store-boot.ts +343 -0
  70. package/src/store-lifecycle.ts +227 -0
  71. package/src/store-meta.ts +459 -0
  72. package/src/store-path.ts +197 -22
  73. package/src/sync/apply.ts +63 -63
  74. package/src/sync/index.ts +2 -2
  75. package/src/sync/shape-inbox.ts +1 -1
  76. package/src/sync/types.ts +3 -3
  77. package/src/testing.ts +2 -2
  78. package/src/worker/attach-sync-client.ts +1753 -102
  79. package/src/worker/define-sync-worker.ts +1034 -71
  80. package/src/worker/election-coordinator.ts +462 -0
  81. package/src/worker/engine-control.ts +379 -0
  82. package/src/worker/engine-router.ts +355 -0
  83. package/src/worker/live-query-manager.ts +4 -1
  84. package/src/worker/protocol.ts +46 -16
  85. package/src/worker/sw-placement.ts +64 -0
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/store-path.ts", "../src/testing.ts"],
4
4
  "sourcesContent": [
5
- "// Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker\n// attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a\n// PGlite storage URL. The storage backend is DERIVED from the environment here, never chosen by the\n// consumer: IndexedDB in a browser (or a worker), the filesystem on Bun/Node. A memory-backed store is\n// not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic\n// Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing\n// acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal\n// {@link TEST_STORE_BACKEND} symbol.\n//\n// This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` URLs (the\n// export machinery's throwaway clone, a later slice, is the one other internal `memory://` site). A\n// resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something\n// a consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old\n// contract loudly at the boundary rather than silently re-interpreting it.\n\n/**\n * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or\n * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the\n * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and\n * shows the corrected form, without echoing a resolvable URL a consumer might imitate.\n */\nexport class InvalidStorePathError extends Error {\n constructor(message: string) {\n super(`[pgxsinkit] ${message}`);\n this.name = \"InvalidStorePathError\";\n }\n}\n\n/**\n * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /\n * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its\n * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins\n * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a\n * consumer is never left guessing which store to hand us instead.\n */\nexport class NonPersistentStoreError extends Error {\n constructor(observed: \"in-memory-default\" | \"memory-scheme\") {\n const reason =\n observed === \"in-memory-default\"\n ? \"its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)\"\n : \"its dataDir is a memory-backed store\";\n super(\n `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +\n \"(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store \" +\n \"would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a \" +\n \"plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with \" +\n '`memoryStoreForTests` / `testStoreAcknowledgment` from \"@pgxsinkit/client/testing\" (ADR-0036).',\n );\n this.name = \"NonPersistentStoreError\";\n }\n}\n\n/**\n * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY\n * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never\n * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type\n * (not a bare `Error`) so a caller can `instanceof`-branch \"target already there\" from a genuine boot failure.\n * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —\n * dropping a user's local store must be their explicit act).\n */\nexport class RestoreTargetExistsError extends Error {\n constructor(storePath: string) {\n super(\n `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +\n \"Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the \" +\n \"datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh \" +\n \"path (ADR-0035 decision 6).\",\n );\n this.name = \"RestoreTargetExistsError\";\n }\n}\n\n/**\n * The module-internal marker a testing helper stamps onto the options object so option handling can select\n * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)\n * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,\n * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the\n * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the\n * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately\n * absent from the main entry's exports and from every public type, so a production consumer cannot name it.\n */\nexport const TEST_STORE_BACKEND: unique symbol = Symbol.for(\"pgxsinkit.internal.testStoreBackend\");\n\n/**\n * What a testing helper's marker asks of option handling: `\"memory\"` mints a scheme-selected memory store\n * (and, being ours-under-the-covers, also unlocks the BYO refusal); `\"acknowledged\"` only unlocks the BYO\n * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an\n * import whose name says what it is.\n */\nexport type TestStoreMarker = \"memory\" | \"acknowledged\";\n\n/** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */\nexport type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };\n\n/** Read the internal testing marker off an options object, or `undefined` when none was stamped. */\nexport function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {\n if (options == null || typeof options !== \"object\") return undefined;\n const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];\n return marker === \"memory\" || marker === \"acknowledged\" ? marker : undefined;\n}\n\n/**\n * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain\n * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a\n * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing\n * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests(\"x\"))` without a consumer ever\n * naming a backend.\n */\nexport type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);\n\n/** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */\nexport function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: \"memory\" } {\n if (typeof input === \"string\") return { storePath: input };\n return {\n storePath: input.storePath,\n ...(readTestStoreMarker(input) === \"memory\" ? { backendOverride: \"memory\" as const } : {}),\n };\n}\n\n/**\n * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in\n * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's\n * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but\n * Bun/Node do not — so it distinguishes \"run in the browser\" (idb) from \"run on the server\" (filesystem)\n * without a DOM-lib dependency.\n */\nexport interface StoreEnv {\n hasIndexedDb: boolean;\n}\n\n/** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */\nfunction detectStoreEnv(): StoreEnv {\n return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== \"undefined\" };\n}\n\n/**\n * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point\n * (ADR-0036 decision 2). Browser/worker (`indexedDB` present) → `idb://<storePath>`; Bun/Node → `file://<storePath>`\n * (relative paths resolve against the working directory, exactly as PGlite's filesystem backend does — pass\n * an absolute path if that matters). The `backendOverride` is internal-only: `\"memory\"` selects a\n * scheme-selected `memory://<storePath>` store for the sanctioned test/ephemeral lanes.\n *\n * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath\n * contract fails loudly at the boundary, never silently re-interpreted (no-legacy rule). The returned URL is\n * internal plumbing; do not surface it to consumers as something to imitate.\n *\n * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected\n * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`\n * instance silently omits relation files created after initdb, so a restored clone raises \"relation does not\n * exist\". Callers that need a memory store must route through this function, never construct `MemoryFS`.\n */\nexport function resolveStoreDataDir(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n 'invalid storePath: expected a non-empty plain store name (e.g. \"my-app-store\"); received an empty or whitespace-only value (ADR-0036).',\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +\n 'Pass just the name (e.g. \"my-app-store\") — the storage backend (IndexedDB in a browser, the ' +\n \"filesystem on Bun/Node) is derived for you; drop the scheme prefix (ADR-0036).\",\n );\n }\n if (backendOverride === \"memory\") return `memory://${storePath}`;\n return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;\n}\n\n/**\n * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for\n * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite\n * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`\n * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a\n * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather\n * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as\n * {@link resolveStoreDataDir} does, so the two stay in lockstep.\n */\nexport function storeIndexedDbDatabaseName(storePath: string): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n \"invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).\",\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,\n );\n }\n return `/pglite/${storePath}`;\n}\n\n/**\n * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending\n * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a\n * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,\n * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the\n * two accidental non-persistent shapes, it is not a storage-backend whitelist).\n */\nexport function classifyNonPersistentDataDir(\n dataDir: string | undefined,\n): \"in-memory-default\" | \"memory-scheme\" | null {\n if (dataDir == null) return \"in-memory-default\";\n if (dataDir.startsWith(\"memory://\")) return \"memory-scheme\";\n return null;\n}\n\n/**\n * Does the backend store a plain {@link storePath} resolves to ALREADY exist? The fresh-target gate for a\n * restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:\n *\n * - **memory** (`backendOverride === \"memory\"`) — a scheme-selected memory store is fresh by construction:\n * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`\n * (the sanctioned test/ephemeral lane never blocks a restore).\n * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported\n * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the\n * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,\n * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.\n * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name\n * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older\n * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let\n * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a\n * PGlite-level boot failure. We never fake a positive.\n */\nexport async function storeTargetExists(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): Promise<boolean> {\n const dataDir = resolveStoreDataDir(storePath, backendOverride, env);\n if (dataDir.startsWith(\"memory://\")) return false;\n if (dataDir.startsWith(\"file://\")) {\n // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and\n // cwd-relative paths identically to PGlite's own filesystem backend.\n const path = dataDir.slice(\"file://\".length);\n const { existsSync } = await import(\"node:fs\");\n return existsSync(path);\n }\n // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in\n // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.\n const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;\n if (idb?.databases == null) return false;\n const target = storeIndexedDbDatabaseName(storePath);\n const databases = await idb.databases();\n return databases.some((db) => db.name === target);\n}\n",
6
- "// `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).\n//\n// pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a\n// memory store: `createSyncClient`/`createClientPGlite` take a plain `storePath` whose backend is derived\n// (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory\n// stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export\n// machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so\n// reaching a memory store is always a visible, deliberate act. App bundles never import it, so the whole\n// module (and any mention of memory) tree-shakes away.\n//\n// The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}\n// marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:\n//\n// createSyncClient({ ...memoryStoreForTests(\"my-test\"), registry, electricUrl, writeUrl })\n// createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, writeUrl })\n\nimport { TEST_STORE_BACKEND } from \"./store-path\";\n\n/**\n * The public shape of {@link memoryStoreForTests}'s output: just a `storePath`. The internal backend marker\n * rides alongside at runtime but is deliberately absent from this type, so no production type mentions memory.\n */\nexport interface MemoryStoreForTests {\n storePath: string;\n}\n\n/**\n * Mint client store options that resolve to a scheme-selected in-memory store — the unit-test / ephemeral\n * lane (ADR-0036 decision 3). Spread the result into `createSyncClient` (or `defineSyncWorker` where its\n * options accept `storePath`): the client reads the internal marker and selects the memory backend.\n *\n * DURABILITY CAVEAT: a memory store is session-scoped, so pgxsinkit's persistent-retention guarantee and the\n * optimistic Mutation journal's durability window are BOTH void on it — everything is lost when the instance\n * closes. Use it only for tests and throwaway/ephemeral flows, never for anything a user expects to persist.\n */\nexport function memoryStoreForTests(storePath: string): MemoryStoreForTests {\n // The marker is a symbol-keyed property, so it survives an object spread but is invisible to the public\n // type and to `Object.keys`. Cast because the return TYPE deliberately hides it (ADR-0036 decision 3).\n return { storePath, [TEST_STORE_BACKEND]: \"memory\" } as MemoryStoreForTests;\n}\n\n/**\n * Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal\n * (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent\n * PGlite via `pgliteInstance` / `precreatedPglite`. Spread it alongside that option.\n *\n * Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent\n * store voids the retention + journal durability guarantees.\n */\nexport function testStoreAcknowledgment(): Record<never, never> {\n // An empty public shape carrying only the internal marker — nothing for a consumer to configure.\n return { [TEST_STORE_BACKEND]: \"acknowledged\" } as Record<never, never>;\n}\n"
5
+ "// Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker\n// attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a\n// PGlite storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by\n// the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the\n// filesystem on Bun/Node. A memory-backed store is\n// not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic\n// Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing\n// acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal\n// {@link TEST_STORE_BACKEND} symbol.\n//\n// This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` / `opfs://`\n// URLs (the export machinery's throwaway clone is the one other internal `memory://` site). A\n// resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something a\n// consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old contract\n// loudly at the boundary rather than silently re-interpreting it.\n//\n// Under ADR-0049 (capability-driven engine placement) it also owns the browser-side STORE IDENTITY encoding\n// and the disjoint OPFS namespaces the placement probe, the commitment marker, and the store meta record all\n// key on. `storeIdentityComponent` is the one injective encoding for every browser-side identity surface\n// (OPFS namespace entries, leader lock, meta record key, communication-centre SharedWorker name; D11), and the\n// `pgxsinkit/stores|commitments|probe` namespace builders are the one place those names live (D6).\n\n/**\n * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or\n * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the\n * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and\n * shows the corrected form, without echoing a resolvable URL a consumer might imitate.\n */\nexport class InvalidStorePathError extends Error {\n constructor(message: string) {\n super(`[pgxsinkit] ${message}`);\n this.name = \"InvalidStorePathError\";\n }\n}\n\n/**\n * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /\n * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its\n * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins\n * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a\n * consumer is never left guessing which store to hand us instead.\n */\nexport class NonPersistentStoreError extends Error {\n constructor(observed: \"in-memory-default\" | \"memory-scheme\") {\n const reason =\n observed === \"in-memory-default\"\n ? \"its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)\"\n : \"its dataDir is a memory-backed store\";\n super(\n `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +\n \"(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store \" +\n \"would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a \" +\n \"plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with \" +\n '`memoryStoreForTests` / `testStoreAcknowledgment` from \"@pgxsinkit/client/testing\" (ADR-0036).',\n );\n this.name = \"NonPersistentStoreError\";\n }\n}\n\n/**\n * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY\n * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never\n * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type\n * (not a bare `Error`) so a caller can `instanceof`-branch \"target already there\" from a genuine boot failure.\n * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —\n * dropping a user's local store must be their explicit act).\n */\nexport class RestoreTargetExistsError extends Error {\n constructor(storePath: string) {\n super(\n `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +\n \"Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the \" +\n \"datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh \" +\n \"path (ADR-0035 decision 6).\",\n );\n this.name = \"RestoreTargetExistsError\";\n }\n}\n\n/**\n * The module-internal marker a testing helper stamps onto the options object so option handling can select\n * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)\n * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,\n * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the\n * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the\n * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately\n * absent from the main entry's exports and from every public type, so a production consumer cannot name it.\n */\nexport const TEST_STORE_BACKEND: unique symbol = Symbol.for(\"pgxsinkit.internal.testStoreBackend\");\n\n/**\n * What a testing helper's marker asks of option handling: `\"memory\"` mints a scheme-selected memory store\n * (and, being ours-under-the-covers, also unlocks the BYO refusal); `\"acknowledged\"` only unlocks the BYO\n * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an\n * import whose name says what it is.\n */\nexport type TestStoreMarker = \"memory\" | \"acknowledged\";\n\n/** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */\nexport type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };\n\n/** Read the internal testing marker off an options object, or `undefined` when none was stamped. */\nexport function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {\n if (options == null || typeof options !== \"object\") return undefined;\n const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];\n return marker === \"memory\" || marker === \"acknowledged\" ? marker : undefined;\n}\n\n/**\n * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain\n * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a\n * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing\n * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests(\"x\"))` without a consumer ever\n * naming a backend.\n */\nexport type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);\n\n/** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */\nexport function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: \"memory\" } {\n if (typeof input === \"string\") return { storePath: input };\n return {\n storePath: input.storePath,\n ...(readTestStoreMarker(input) === \"memory\" ? { backendOverride: \"memory\" as const } : {}),\n };\n}\n\n/**\n * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in\n * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's\n * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but\n * Bun/Node do not — so it distinguishes \"run in the browser\" (idb) from \"run on the server\" (filesystem)\n * without a DOM-lib dependency.\n */\nexport interface StoreEnv {\n hasIndexedDb: boolean;\n /**\n * ADR-0049 (D1): the PLACEMENT PROBE's injected result — whether a REAL `createSyncAccessHandle` open\n * succeeded in the executing scope (the bench phase-0 mechanism, performed by the async boot path — never\n * method-presence sniffing). Optional so every existing `StoreEnv` construction stays valid; `undefined`\n * means \"no OPFS sync access\" (false). {@link detectStoreEnv} ALWAYS reports `false` for it: there is no\n * synchronous ambient detection for handle grants, and method-presence sniffing is forbidden — only the\n * boot path's real probe open can flip it true.\n */\n hasOpfsSyncAccess?: boolean;\n}\n\n/** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */\nfunction detectStoreEnv(): StoreEnv {\n // `hasOpfsSyncAccess` is deliberately absent (false): the placement probe (an async handle open) is the\n // only honest source, and this synchronous ambient detector must never guess it (ADR-0049 D1).\n return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== \"undefined\" };\n}\n\n/**\n * The shared plain-`storePath` boundary guard (ADR-0036 decision 1). A storePath is a PLAIN name, never a\n * storage URL: empty/whitespace-only or scheme-bearing (`://`) values fail loudly with\n * {@link InvalidStorePathError}. Factored so {@link resolveStoreDataDir} and {@link storeIdentityComponent}\n * share ONE message set (no drift between the two identity-surface entry points).\n */\nfunction assertPlainStorePath(storePath: string): void {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n 'invalid storePath: expected a non-empty plain store name (e.g. \"my-app-store\"); received an empty or whitespace-only value (ADR-0036).',\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +\n 'Pass just the name (e.g. \"my-app-store\") — the storage backend (capability-selected opfs-repacked ' +\n \"with IndexedDB fallback in a browser, or the filesystem on Bun/Node) is derived for you; drop the \" +\n \"scheme prefix (ADR-0036/ADR-0049).\",\n );\n }\n}\n\n/**\n * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point\n * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves\n * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;\n * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`\n * is internal-only: `\"memory\"` selects a scheme-selected `memory://<storePath>` test/ephemeral store.\n *\n * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath\n * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is\n * internal plumbing; do not surface it to consumers as something to imitate.\n *\n * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected\n * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`\n * instance silently omits relation files created after initdb, so a restored clone raises \"relation does not\n * exist\". Callers that need a memory store must route through this function, never construct `MemoryFS`.\n *\n * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in\n * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:\n * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →\n * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — PGlite does NOT accept it as a `dataDir`;\n * {@link createClientPGlite} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace\n * builders below. Like every URL resolved here, it never leaks to consumers.\n */\nexport function resolveStoreDataDir(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): string {\n assertPlainStorePath(storePath);\n if (backendOverride === \"memory\") return `memory://${storePath}`;\n if (env.hasOpfsSyncAccess) return `opfs://${storePath}`;\n return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;\n}\n\n/**\n * The per-component ENCODED length cap for {@link storeIdentityComponent}. A filesystem-safe bound for a\n * single OPFS name component; the fixed container/namespace names (`pgxsinkit`, `stores`, `commitments`,\n * `probe`) are SEPARATE path components and add nothing to this budget. Encoding is what is capped, not the\n * raw input — a short multi-byte name can expand past the bound.\n */\nconst STORE_IDENTITY_ENCODED_CAP = 128;\n\n/**\n * The ONE injective encoding for every browser-side identity surface (ADR-0049 D11, invariant 10): OPFS\n * namespace entries ({@link opfsStoreDirectoryPath} / {@link opfsCommitmentSentinelPath}), the leader lock\n * name, the store meta record key, and the communication-centre SharedWorker name all derive from this single\n * canonical component. Percent-encoding (`encodeURIComponent`) — injective, never lossy sanitising, so two\n * distinct store paths can never collapse to one identity (e.g. `\"foo/bar\"` → `foo%2Fbar` vs the literal\n * `\"foo%2Fbar\"` → `foo%252Fbar`).\n *\n * Domain (invariant 10):\n * - Same boundary guards as {@link resolveStoreDataDir}: empty/whitespace-only or scheme-bearing (`://`)\n * paths throw {@link InvalidStorePathError} (shared {@link assertPlainStorePath}).\n * - A lone UTF-16 surrogate makes `encodeURIComponent` raise a `URIError`; that is wrapped into\n * {@link InvalidStorePathError} so callers branch one error type at the boundary.\n * - `.` and `..` pass through `encodeURIComponent` UNCHANGED, but the File System Standard reserves them as\n * invalid file names, so both are rejected.\n * - The ENCODED length is capped at {@link STORE_IDENTITY_ENCODED_CAP} (a per-component filesystem-safe\n * bound); overflow is rejected.\n */\nexport function storeIdentityComponent(storePath: string): string {\n assertPlainStorePath(storePath);\n let identity: string;\n try {\n identity = encodeURIComponent(storePath);\n } catch (error) {\n // The only `encodeURIComponent` failure is a lone UTF-16 surrogate (`URIError`); rewrap it so the domain\n // presents ONE error type at the boundary (never a bare `URIError`).\n if (error instanceof URIError) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: it contains a lone UTF-16 surrogate, which has no ` +\n \"valid encoding as a store identity (ADR-0049).\",\n );\n }\n throw error;\n }\n if (identity === \".\" || identity === \"..\") {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: \".\" and \"..\" are reserved file names (File System ` +\n \"Standard) and cannot be a store identity (ADR-0049).\",\n );\n }\n if (identity.length > STORE_IDENTITY_ENCODED_CAP) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: its encoded store identity is ${identity.length} ` +\n `characters, over the ${STORE_IDENTITY_ENCODED_CAP}-character per-component cap (ADR-0049). Note the ` +\n \"cap is on the ENCODED form — a short multi-byte name can expand past it.\",\n );\n }\n return identity;\n}\n\n/**\n * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,\n * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `\"foo\"`'s\n * commitment sentinel vs a store literally named `\"foo.committed\"`). This module is the ONLY place that knows\n * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the sole owner of the `/pglite/`\n * prefix.\n */\nexport const OPFS_TOOLKIT_CONTAINER = \"pgxsinkit\";\n\n/**\n * OPFS path (segment array) of a store's four-file VFS directory: `pgxsinkit/stores/<identity>` (ADR-0049 D6).\n * Returned as SEGMENTS, not a joined string, because consumers traverse OPFS via a `getDirectoryHandle` chain.\n */\nexport function opfsStoreDirectoryPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"stores\", storeIdentityComponent(storePath)];\n}\n\n/**\n * OPFS path (segment array) of a store's commitment marker sentinel: `pgxsinkit/commitments/<identity>`\n * (ADR-0049 D6). Disjoint from {@link opfsStoreDirectoryPath} — the store directory holds exactly the four\n * VFS-owned files, and a suffix-sibling sentinel would collide across valid identities. Segments, not a joined\n * string, for the same `getDirectoryHandle`-chain reason.\n */\nexport function opfsCommitmentSentinelPath(storePath: string): readonly [string, string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"commitments\", storeIdentityComponent(storePath)];\n}\n\n/**\n * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No\n * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.\n */\nexport function opfsProbeDirectoryPath(): readonly [string, string] {\n return [OPFS_TOOLKIT_CONTAINER, \"probe\"];\n}\n\n/**\n * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for\n * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite\n * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`\n * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a\n * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather\n * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as\n * {@link resolveStoreDataDir} does, so the two stay in lockstep.\n */\nexport function storeIndexedDbDatabaseName(storePath: string): string {\n if (typeof storePath !== \"string\" || storePath.trim().length === 0) {\n throw new InvalidStorePathError(\n \"invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).\",\n );\n }\n if (storePath.includes(\"://\")) {\n throw new InvalidStorePathError(\n `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,\n );\n }\n return `/pglite/${storePath}`;\n}\n\n/**\n * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending\n * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a\n * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,\n * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the\n * two accidental non-persistent shapes, it is not a storage-backend whitelist).\n */\nexport function classifyNonPersistentDataDir(\n dataDir: string | undefined,\n): \"in-memory-default\" | \"memory-scheme\" | null {\n if (dataDir == null) return \"in-memory-default\";\n if (dataDir.startsWith(\"memory://\")) return \"memory-scheme\";\n return null;\n}\n\n/**\n * The minimal structural shape of an OPFS `FileSystemDirectoryHandle` this module traverses — just the\n * never-creating `getDirectoryHandle` hop. Declared locally so the module carries no DOM lib dependency\n * (matching how the rest of it reads capabilities structurally off `globalThis`).\n */\ninterface OpfsDirectoryHandle {\n getDirectoryHandle(name: string, options: { create: false }): Promise<OpfsDirectoryHandle>;\n}\n\n/**\n * Does either backend a browser boot could own for a plain {@link storePath} ALREADY exist? The fresh-target\n * gate for a restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:\n *\n * - **memory** (`backendOverride === \"memory\"`) — a scheme-selected memory store is fresh by construction:\n * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`\n * (the sanctioned test/ephemeral lane never blocks a restore).\n * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported\n * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the\n * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,\n * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.\n * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at\n * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via\n * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is\n * ONLY the fresh-target gate; it is emphatically NOT commitment authority — a store directory without a\n * commitment marker is an uncommitted CANDIDATE, and deciding that is the store meta record's phase machine\n * (plan step 2), never this function. `navigator.storage`/`getDirectory` absent → best-effort `false`\n * (mirrors the idb `databases()` stance — never fabricate a positive). A `NotFoundError` anywhere in the\n * chain → `false`; any OTHER error propagates (a genuine failure the restore caller must see).\n * A missing OPFS directory does not finish a granted browser check: IDB is also probed, because a predecessor\n * or fixed-placement store may still own the same public path.\n * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name\n * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older\n * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let\n * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a\n * PGlite-level boot failure. We never fake a positive.\n */\nexport async function storeTargetExists(\n storePath: string,\n backendOverride?: \"memory\",\n env: StoreEnv = detectStoreEnv(),\n): Promise<boolean> {\n const dataDir = resolveStoreDataDir(storePath, backendOverride, env);\n if (dataDir.startsWith(\"memory://\")) return false;\n if (dataDir.startsWith(\"file://\")) {\n // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and\n // cwd-relative paths identically to PGlite's own filesystem backend.\n const path = dataDir.slice(\"file://\".length);\n const { existsSync } = await import(\"node:fs\");\n return existsSync(path);\n }\n if (dataDir.startsWith(\"opfs://\")) {\n // Structural typing off `globalThis` — no DOM lib dependency (like the rest of the module).\n const storage = (\n globalThis as {\n navigator?: {\n storage?: { getDirectory?: () => Promise<OpfsDirectoryHandle> };\n };\n }\n ).navigator?.storage;\n // API absent → best-effort false (never a fabricated positive), same stance as idb `databases()`.\n if (storage?.getDirectory != null) {\n const segments = opfsStoreDirectoryPath(storePath);\n try {\n let handle = await storage.getDirectory();\n for (const segment of segments) {\n // Never-creating existence walk: `{ create: false }` at every hop — this is a gate, not a mkdir.\n handle = await handle.getDirectoryHandle(segment, { create: false });\n }\n return true;\n } catch (error) {\n // A missing entry anywhere in the chain proves OPFS absence; anything else is a real failure to surface.\n if ((error as { name?: string }).name !== \"NotFoundError\") throw error;\n }\n }\n // A granted browser must also reject an IDB predecessor at this path; fall through to the shared IDB probe.\n }\n // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in\n // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.\n const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;\n if (idb?.databases == null) return false;\n const target = storeIndexedDbDatabaseName(storePath);\n const databases = await idb.databases();\n return databases.some((db) => db.name === target);\n}\n",
6
+ "// `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).\n//\n// pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a\n// memory store: `createSyncClient`/`createClientPGlite` take a plain `storePath` whose backend is derived\n// (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory\n// stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export\n// machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so\n// reaching a memory store is always a visible, deliberate act. App bundles never import it, so the whole\n// module (and any mention of memory) tree-shakes away.\n//\n// The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}\n// marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:\n//\n// createSyncClient({ ...memoryStoreForTests(\"my-test\"), registry, electricUrl, batchWriteUrl })\n// createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, batchWriteUrl })\n\nimport { TEST_STORE_BACKEND } from \"./store-path\";\n\n/**\n * The public shape of {@link memoryStoreForTests}'s output: just a `storePath`. The internal backend marker\n * rides alongside at runtime but is deliberately absent from this type, so no production type mentions memory.\n */\nexport interface MemoryStoreForTests {\n storePath: string;\n}\n\n/**\n * Mint client store options that resolve to a scheme-selected in-memory store — the unit-test / ephemeral\n * lane (ADR-0036 decision 3). Spread the result into `createSyncClient` (or `defineSyncWorker` where its\n * options accept `storePath`): the client reads the internal marker and selects the memory backend.\n *\n * DURABILITY CAVEAT: a memory store is session-scoped, so pgxsinkit's persistent-retention guarantee and the\n * optimistic Mutation journal's durability window are BOTH void on it — everything is lost when the instance\n * closes. Use it only for tests and throwaway/ephemeral flows, never for anything a user expects to persist.\n */\nexport function memoryStoreForTests(storePath: string): MemoryStoreForTests {\n // The marker is a symbol-keyed property, so it survives an object spread but is invisible to the public\n // type and to `Object.keys`. Cast because the return TYPE deliberately hides it (ADR-0036 decision 3).\n return { storePath, [TEST_STORE_BACKEND]: \"memory\" } as MemoryStoreForTests;\n}\n\n/**\n * Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal\n * (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent\n * PGlite via `pgliteInstance` / `precreatedPglite`. Spread it alongside that option.\n *\n * Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent\n * store voids the retention + journal durability guarantees.\n */\nexport function testStoreAcknowledgment(): Record<never, never> {\n // An empty public shape carrying only the internal marker — nothing for a consumer to configure.\n return { [TEST_STORE_BACKEND]: \"acknowledged\" } as Record<never, never>;\n}\n"
7
7
  ],
8
- "mappings": ";;AAiFO,IAAM,qBAAoC,OAAO,IAAI,qCAAqC;;;AC9C1F,SAAS,mBAAmB,CAAC,WAAwC;AAAA,EAG1E,OAAO,EAAE,YAAY,qBAAqB,SAAS;AAAA;AAW9C,SAAS,uBAAuB,GAAyB;AAAA,EAE9D,OAAO,GAAG,qBAAqB,eAAe;AAAA;",
8
+ "mappings": ";;AAwFO,IAAM,qBAAoC,OAAO,IAAI,qCAAqC;;;ACrD1F,SAAS,mBAAmB,CAAC,WAAwC;AAAA,EAG1E,OAAO,EAAE,YAAY,qBAAqB,SAAS;AAAA;AAW9C,SAAS,uBAAuB,GAAyB;AAAA,EAE9D,OAAO,GAAG,qBAAqB,eAAe;AAAA;",
9
9
  "debugId": "7077823A374194F864756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -1,23 +1,189 @@
1
- import type { SyncRuntimeStatus, SyncTableRegistry } from "@pgxsinkit/contracts";
1
+ import type { SyncRuntimeStatus, SyncStorageDeclaration, SyncTableRegistry } from "@pgxsinkit/contracts";
2
2
  import type { BootReport } from "../boot-report";
3
3
  import { type MutationDetail, type SyncClient } from "../index";
4
4
  import type { LocalStoreVersionEvent } from "../local-store";
5
+ import { type OpfsEffectsDeps } from "../opfs-effects";
6
+ import { type DestructionEffects } from "../store-lifecycle";
7
+ import { type StoreMetaDeps } from "../store-meta";
8
+ import { type PlacementQueryResult } from "./define-sync-worker";
9
+ import { type CoordinatorDeps } from "./election-coordinator";
10
+ import { type ExecutionLimitConfig } from "./engine-control";
5
11
  import { type AuthTokenSnapshot, type BridgeCodec, type BridgePort, type BridgeTransferable } from "./protocol";
6
12
  /** A `Worker`/`SharedWorker`-shaped handle: a dedicated `Worker` IS the port; a `SharedWorker` carries `.port`. */
7
13
  interface WorkerLike {
8
14
  port?: BridgePort;
9
15
  postMessage?: (message: unknown, transfer?: BridgeTransferable[]) => void;
10
- addEventListener?: (type: "message", listener: (event: {
11
- data: unknown;
16
+ addEventListener?: (type: "message" | "error", listener: (event: {
17
+ data?: unknown;
18
+ message?: unknown;
12
19
  }) => void) => void;
13
- removeEventListener?: (type: "message", listener: (event: {
14
- data: unknown;
20
+ removeEventListener?: (type: "message" | "error", listener: (event: {
21
+ data?: unknown;
22
+ message?: unknown;
15
23
  }) => void) => void;
24
+ terminate?: () => void;
25
+ }
26
+ /**
27
+ * The elected engine worker handle the election coordinator drives (ADR-0049 D5, step 8): `terminate()` (a
28
+ * deliberate teardown / respawn), `onError` (a reported worker death → immediate respawn), and
29
+ * `deliverControlPort` (post the engine end of the announce control channel — `{ [CONTROL_PORT_DELIVERY_KEY]:
30
+ * true }` with the port transferred — so the elected worker's step-9 control plane starts on it). The consumer
31
+ * supplies a factory that constructs their own `defineSyncWorker` entry as a dedicated `Worker`; wrap it with
32
+ * {@link wrapEngineWorker}.
33
+ */
34
+ export interface ElectedEngineWorker {
35
+ terminate(): void;
36
+ onError(listener: (message: string) => void): void;
37
+ deliverControlPort(port: unknown): void;
38
+ }
39
+ /**
40
+ * Wrap a dedicated `Worker` (a consumer's `defineSyncWorker` engine entry) into the {@link ElectedEngineWorker}
41
+ * the coordinator drives (ADR-0049 step 10b). `deliverControlPort` posts `{ [CONTROL_PORT_DELIVERY_KEY]: true }`
42
+ * on the worker's implicit port with the control-channel end TRANSFERRED — exactly the delivery message the
43
+ * step-9 engine control plane listens for. `onError` subscribes to the worker's `error` event; `terminate`
44
+ * forwards to `worker.terminate()`.
45
+ */
46
+ /**
47
+ * The default {@link AttachSyncClientOptions.awaitOwnershipRelease} — a documented NO-OP (ADR-0049 step 11b
48
+ * follow-up 1). The OPFS-repacked VFS enforces single-owner access with EXCLUSIVE OPFS sync-access handles
49
+ * (`StoreOwnedError`), not a Web Lock, so there is no ownership lock to await from here without importing the
50
+ * VFS. The bounded wait for the dead worker's agent to release the handle lives entirely in the SUCCESSOR'S OPEN
51
+ * PATH: the respawned engine's `createOpfsRepacked` open retries on the owned-store contention error until it
52
+ * clears (the `openWithBoundedRetries` wrapper) — the fault-matrix "successor open retries on contention" row.
53
+ * So the coordinator can respawn immediately after a deliberate terminate; its VFS open is the real gate.
54
+ */
55
+ export declare function resolvedOwnershipRelease(): Promise<void>;
56
+ export declare function wrapEngineWorker(worker: WorkerLike): ElectedEngineWorker;
57
+ /**
58
+ * `destroy()` on an attached facade REFUSES when other tabs still hold the store (ADR-0049 D8, plan fault row
59
+ * "`destroy()` with peers attached → refused with a typed error — close peers first"). The SharedWorker — the
60
+ * only role that knows the attached-tab count — answers a peer-count query; more than one attached tab (this
61
+ * one plus at least one other) raises this. `peers` is the total attached-tab count, this tab included.
62
+ */
63
+ export declare class StoreDestroyRefusedError extends Error {
64
+ readonly peers: number;
65
+ constructor(peers: number);
66
+ }
67
+ /**
68
+ * Attach WIRING failure (ADR-0049 D1/D5): the SharedWorker requires election (a router-only, handle-denied home)
69
+ * but the elected engine worker CANNOT be constructed — neither a `createEngineWorker` override was supplied NOR is
70
+ * the SharedWorker's own script URL derivable (a plain scope that cannot report `self.location.href`, or a
71
+ * non-module entry). Capability absence FALLS BACK (idbfs); a wiring failure ERRORS — the capability was present and
72
+ * the configuration was wrong, and silently downgrading storage would hide the defect. `[pgxsinkit]`-prefixed like
73
+ * the repo's other typed errors so a consumer can `instanceof`-branch it.
74
+ */
75
+ export declare class ElectedEngineUnconstructibleError extends Error {
76
+ constructor(detail: string);
77
+ }
78
+ /**
79
+ * Build the REAL {@link DestructionEffects} for a store — the OPFS commitment sentinel + store directory
80
+ * (`opfs-effects.ts`), the meta record (`store-meta.ts`), and the PGlite idb database. The destruction machine is
81
+ * backend-agnostic (`store-lifecycle.ts`): `deleteBackendStore` delete-if-presents BOTH the OPFS directory and
82
+ * the idb database, so it works whichever backend the store used. Injectable IO (`opfs`/`meta`) so the wiring is
83
+ * unit-testable with fakes.
84
+ */
85
+ export declare function createStoreDestructionEffects(storePath: string, deps?: {
86
+ opfs?: OpfsEffectsDeps;
87
+ meta?: StoreMetaDeps;
88
+ }): DestructionEffects;
89
+ /**
90
+ * Destroy every local artifact of a store BY PATH (ADR-0050 stage 2; the public face of the ADR-0049 D8
91
+ * destruction machinery): the OPFS store directory, the commitment sentinel, the meta record, AND the idb
92
+ * database — backend-agnostic (delete-if-present on both backends), with the bounded VFS-ownership-lag retry.
93
+ *
94
+ * **Precondition: the store is NOT running.** This is the companion to {@link SyncClient.destroy} (the
95
+ * supervised destroy of an ATTACHED store — peer-checked, teardown-acknowledged): reach for
96
+ * `destroyStoreArtifacts` for a store nobody is attached to — an obsolete path a preference change left
97
+ * behind, a wipe of known store paths. Called on a path a live engine still holds, the backend delete throws
98
+ * an ownership error after the bounded retry — loud, and safely RE-RUNNABLE: the destruction sequence is
99
+ * idempotent and phase-recorded (a store whose meta record says `deleting` is refused for boot), so a re-run
100
+ * completes it. No liveness probe is attempted here — it could not be race-free, and the ownership error
101
+ * already fails hard; callers keep failed paths on their own retry list (e.g. the board's Obsolete stores).
102
+ */
103
+ export declare function destroyStoreArtifacts(storePath: string, opts?: StoreDestructionRetryOptions): Promise<void>;
104
+ /** Options for {@link quiesceStoreWorker} (ADR-0050). */
105
+ export interface StoreWorkerQuiesceOptions {
106
+ /** The ADR-0050 storage declaration to post on the port. Omit (or `{}`) to state NO opinion — always
107
+ * compatible with whatever declaration the live worker already bound, so it can never be refused. Passing a
108
+ * concrete declaration risks a `StorageDeclarationRefusedError` if it disagrees with the bound one. */
109
+ storage?: SyncStorageDeclaration;
110
+ /** Bound on the whole handshake (declaration → placement reply → teardown ack). Default 6000ms. On timeout
111
+ * the returned promise REJECTS — the caller keeps the path on its retry list; it is NOT proof of teardown. */
112
+ timeoutMs?: number;
113
+ /** Injectable timers (tests); defaults to real `setTimeout`/`clearTimeout`. */
114
+ timers?: AttachClientTimers;
115
+ }
116
+ /** The outcome of {@link quiesceStoreWorker}. */
117
+ export interface StoreWorkerQuiesceOutcome {
118
+ /** The store's engine home as reported by its placement reply. */
119
+ engineHome: PlacementQueryResult["engineHome"];
120
+ /** True iff an SW-direct engine was torn down here (its host closed, releasing the backend connection).
121
+ * `false` for an `elected-worker` home — there is no in-SharedWorker engine to close from this router-only
122
+ * connection; the elected dedicated engine dies with its owning tab (the browser terminates it on document
123
+ * teardown), releasing its store, so no active teardown is needed before a path-addressed destroy. */
124
+ toreDown: boolean;
125
+ }
126
+ /**
127
+ * Quiesce the SharedWorker HOSTING a store, by path, so its backend connection is released BEFORE a
128
+ * {@link destroyStoreArtifacts} on the same path (ADR-0050). The gap it closes: the board's workers are
129
+ * `extendedLifetime`, so a store's SharedWorker OUTLIVES the document that spawned it — and the idbfs backend
130
+ * holds its IndexedDB connection open for the engine's whole life. So after a reload, an idbfs store's worker
131
+ * is still alive and still holding the connection; `deleteDatabase` blocks and `destroyStoreArtifacts` fails,
132
+ * boot after boot, until the browser eventually reaps the worker. OPFS releases its handles when idle, so it
133
+ * never had this problem — this is the idbfs (SW-direct) fix.
134
+ *
135
+ * `worker` is a factory (or instance), exactly like {@link attachSyncClient}'s `worker` — the caller constructs
136
+ * `new SharedWorker(url, { name: storePath })`, so the library stays DOM-free. Connecting by that name reaches
137
+ * the LIVE worker (if any) or spawns a fresh one; either way the sequence is: post the declaration, query
138
+ * placement, and — for a `shared-worker` home — send `engine-teardown` and await its reserved ack, which the
139
+ * host posts only after `closeHost()` has stopped the engine and released the backend connection (it then
140
+ * closes its own scope). An `elected-worker` home resolves immediately with `toreDown: false` (see the field).
141
+ *
142
+ * Idempotent and safe on an already-dead store: a fresh spawn boots no engine, and its teardown closes an empty
143
+ * host. Compose it as `await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)` — a
144
+ * quiesce failure (timeout) must NOT abort the destroy, whose own ownership-lag handling reports honestly and
145
+ * leaves the path re-runnable.
146
+ */
147
+ export declare function quiesceStoreWorker(worker: (() => WorkerLike) | WorkerLike, opts?: StoreWorkerQuiesceOptions): Promise<StoreWorkerQuiesceOutcome>;
148
+ /** The bounded ownership-retry options for {@link runStoreDestruction} (the VFS-lock-lag guard, D8/fault row). */
149
+ export interface StoreDestructionRetryOptions {
150
+ /** Max retries of `deleteBackendStore` on an ownership-lock-lag error before giving up (default 5). */
151
+ maxOwnershipRetries?: number;
152
+ /** Classify an error as VFS-ownership-lock lag (retryable). Default: OPFS `NoModificationAllowedError`-class. */
153
+ isOwnershipError?: (error: unknown) => boolean;
154
+ /** Between-retries delay; defaults to a real timer. Injected in tests. */
155
+ delay?: (ms: number) => Promise<void>;
156
+ /** The between-retries delay (ms); default 50. */
157
+ retryDelayMs?: number;
158
+ }
159
+ /**
160
+ * Run the destructive lifecycle (ADR-0049 D8) with a BOUNDED ownership-lock-lag retry around the backend-store
161
+ * delete. The engine was just detached, so its VFS ownership lock may not have cleared yet — the fault row
162
+ * "VFS ownership-lock release lag → successor retries until clear, bounded" applies to destroy too. The other
163
+ * steps (set `deleting`, delete sentinel, delete the meta record) are idempotent and not retried here. Shared by
164
+ * the attached-facade supervisor (this module) and the in-process `destroy()` (index.ts).
165
+ */
166
+ export declare function runStoreDestruction(effects: DestructionEffects, opts?: StoreDestructionRetryOptions): Promise<void>;
167
+ /**
168
+ * The `setTimeout`/`clearTimeout` pair the handoff-queue deadline and the bridge-silence reconnect schedule on
169
+ * (ADR-0049 step 7) — injectable for deterministic tests, exactly the discipline `engine-router.ts` follows so
170
+ * the whole placement seam is unit-testable with no real timers.
171
+ */
172
+ export interface AttachClientTimers {
173
+ setTimeout(fn: () => void, ms: number): unknown;
174
+ clearTimeout(handle: unknown): void;
16
175
  }
17
176
  export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
18
177
  registry: TRegistry;
19
- /** A native `Worker` or `SharedWorker` (or anything port-shaped). Provide this OR {@link port}. */
20
- worker?: WorkerLike;
178
+ /**
179
+ * The worker input — PRIMARILY a FACTORY `() => SharedWorker` (ADR-0049 D5). A `SharedWorker` object cannot be
180
+ * reconstructed from itself, so the factory is what makes SharedWorker-death recovery (the keepalive
181
+ * reconstruction, and the {@link bridgeSilenceMs} bridge-silence reconnect) a GUARANTEE rather than an option:
182
+ * both re-invoke it for a fresh SharedWorker. A bare instance (a native `Worker`/`SharedWorker`, or anything
183
+ * port-shaped) is ALSO accepted for tests and exotic hosts — reconstruction is then structurally unavailable
184
+ * (diagnostics say so). Provide this OR {@link port}.
185
+ */
186
+ worker?: (() => WorkerLike) | WorkerLike;
21
187
  /** A raw transport port (a `MessageChannel` port in tests, a `SharedWorker.port` in a browser). */
22
188
  port?: BridgePort;
23
189
  /**
@@ -51,11 +217,27 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
51
217
  * Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.
52
218
  * A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred
53
219
  * `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.
54
- * Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the
55
- * attach with a typed error (you cannot restore into a running store). The restored engine boots offline and
56
- * its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.
220
+ * Restore rides the one handshake that reaches the ENGINE HOME: a restore-bearing attach awaits the
221
+ * placement reply, then carries the artifact on the SW-port handshake when the in-scope host is the engine
222
+ * (SW-direct / declared-idbfs) or on the first per-tab PIPE handshake when the engine is elected — the
223
+ * router-only SharedWorker is payload-blind, so a restore posted there would be dropped and destroyed.
224
+ * Passing it when the engine has ALREADY booted rejects the attach with a typed error
225
+ * (`RestoreIntoRunningStoreError` by name — you cannot restore into a running store). The restored engine
226
+ * boots offline and its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on
227
+ * `createSyncClient`.
57
228
  */
58
229
  restoreFrom?: File | Blob;
230
+ /**
231
+ * The tab's WIRE storage declaration for this store (ADR-0050) — posted as the declaration message on the
232
+ * worker port BEFORE the placement query (so `backend: "idbfs"` can skip the probe), and carried on the
233
+ * provision/attach payloads so the engine binds it (durability included). Omit (or `{}`) for "no opinion":
234
+ * a registry-attached static declaration, else the capability defaults, decide. A registry-attached
235
+ * declaration is AUTHORITATIVE — an explicit field here that disagrees with it (or with the declaration
236
+ * another tab already bound) is a typed refusal (`StorageDeclarationRefusedError`), never silently
237
+ * overridden: a store's declaration is immutable, and a preference change mints a fresh store under a
238
+ * fresh path instead.
239
+ */
240
+ storage?: SyncStorageDeclaration;
59
241
  codec?: BridgeCodec;
60
242
  onStatusChange?: (status: SyncRuntimeStatus) => void;
61
243
  onConflict?: (details: MutationDetail[]) => void;
@@ -69,6 +251,90 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
69
251
  * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.
70
252
  */
71
253
  onBootReport?: (report: BootReport) => void;
254
+ /**
255
+ * The bridge-silence deadline (ms) for non-leader reconnection (ADR-0049 D5). DISABLED when undefined (the
256
+ * default); the election coordinator (step 8) sets it. When set: a pending op left with NO bridge traffic
257
+ * since it was posted, past this deadline, triggers ONE reconnect attempt via the {@link worker} FACTORY (if the
258
+ * input is a factory) — construct a fresh SharedWorker, resolve its port, re-attach, flush the queue,
259
+ * re-subscribe. With a bare-instance input reconstruction is structurally unavailable, so no reconnect is armed.
260
+ * Scheduled on {@link timers}.
261
+ */
262
+ bridgeSilenceMs?: number;
263
+ /**
264
+ * The bounded handoff queue (ADR-0049 invariant 9). While the handoff window is open — after a relocation
265
+ * notice, before the replacement pipe's handshake completes — new data-path ops are QUEUED, not posted.
266
+ * `cap` overflow or `deadlineMs` expiry fails queued ops with `EngineRelocatedError("not-dispatched")` (they
267
+ * never left the tab, so they are safe to retry). Defaults: `cap` 256, `deadlineMs` 15000. The deadline is
268
+ * scheduled on {@link timers}.
269
+ */
270
+ handoffQueue?: {
271
+ cap?: number;
272
+ deadlineMs?: number;
273
+ };
274
+ /**
275
+ * Injectable timers for the handoff-queue deadline and the bridge-silence reconnect (ADR-0049 step 7) — the
276
+ * same deterministic-test seam `engine-router.ts` exposes. Defaults to `globalThis.setTimeout`/`clearTimeout`.
277
+ */
278
+ timers?: AttachClientTimers;
279
+ /**
280
+ * The elected engine worker OVERRIDE (ADR-0049 D5). In `elected-worker` placement (a router-only SharedWorker)
281
+ * the tab's election coordinator spawns the real engine as a dedicated `Worker`. NORMALLY NO WIRING IS NEEDED:
282
+ * the worker entry is dual-scope (one file serves both homes), the SharedWorker reports its own script URL in the
283
+ * placement reply, and the winning tab constructs the engine as `new Worker(swScriptUrl, { type: "module" })`
284
+ * itself. Supply this override ONLY for entries that cannot be reconstructed from their URL as a module worker
285
+ * (classic-script workers, `blob:`/`data:` URLs, CSP constraints); wrap the constructed worker with
286
+ * {@link wrapEngineWorker}. When election is required but NEITHER a derivable URL NOR this override is available,
287
+ * attach fails with the typed {@link ElectedEngineUnconstructibleError} — never a silent no-engine attach.
288
+ */
289
+ createEngineWorker?: () => ElectedEngineWorker;
290
+ /**
291
+ * The opt-in engine-construction EXECUTION LIMIT (ADR-0049 D5) as this tab carries it — every tab attaching to a
292
+ * store MUST carry the SAME value the worker was constructed with (`ExecutionLimitMismatchError` on a mismatch).
293
+ * DISABLED by default (`undefined` / absent `maxDispatchMs`) — no finite worst-case query duration exists, so
294
+ * enabling the limit (which converts slow to terminated by policy) is a deliberate consumer choice. When
295
+ * `maxDispatchMs` is set AND this tab is on an elected per-tab pipe, a dispatched RPC still outstanding past the
296
+ * limit is reported to the router as an `overdue-dispatch` (the router then probes the engine's control channel;
297
+ * a WASM-blocked engine cannot answer → the leader retires + respawns it). ELECTED PLACEMENT ONLY — on SW-direct
298
+ * the option is rejected as unsupported during attach rather than silently ignored.
299
+ */
300
+ executionLimit?: ExecutionLimitConfig;
301
+ /**
302
+ * The leader-keepalive ping cadence (ms) the election coordinator uses (ADR-0049 step 8). Default 20000. The
303
+ * keepalive is the ONE standing timer that detects SharedWorker death (unanswered pings) → reconstruct via the
304
+ * {@link worker} factory + re-announce the still-live engine. Lower it to detect SW death faster.
305
+ */
306
+ keepaliveIntervalMs?: number;
307
+ /** Consecutive unanswered keepalive pings before SharedWorker reconstruction (ADR-0049 step 8). Default 2. */
308
+ keepaliveMissThreshold?: number;
309
+ /**
310
+ * Await the VFS ownership release after a deliberate engine termination (ADR-0049 step 8). Defaults to the
311
+ * documented no-op {@link resolvedOwnershipRelease} — the HONEST MINIMUM (step 11b follow-up 1): the
312
+ * OPFS-repacked VFS enforces ownership with EXCLUSIVE OPFS sync-access handles (`StoreOwnedError` /
313
+ * `STORE_OWNED`), NOT a Web Lock, so there is no lock name to `navigator.locks.request(..., { ifAvailable })`
314
+ * against here. The bounded wait therefore lives in the SUCCESSOR'S OPEN PATH: the respawned elected engine
315
+ * worker's own `createOpfsRepacked` open throws the owned-store contention error and is retried with backoff
316
+ * (the `openWithBoundedRetries` wrapper in `createClientPGlite`) until the dead worker's agent releases the
317
+ * handle — exactly the fault-matrix row "VFS ownership-lock release lag → successor open retries on contention
318
+ * until clear, bounded, then boot failure". Supply a custom async wait only to inject a real probe (tests do).
319
+ */
320
+ awaitOwnershipRelease?: () => Promise<void>;
321
+ /**
322
+ * @internal test seam (ADR-0049 step 10b): override the election coordinator's IO — the Web Locks surface and
323
+ * the page-lifecycle subscription. Production reads `navigator.locks` structurally and subscribes to real
324
+ * `pagehide`/`pageshow`. Injected so the election wiring is unit-testable with a fake locks (no real
325
+ * `navigator.locks` under Bun).
326
+ */
327
+ electionIo?: {
328
+ locks?: CoordinatorDeps["locks"];
329
+ pageLifecycle?: CoordinatorDeps["pageLifecycle"];
330
+ };
331
+ /**
332
+ * @internal test seam (ADR-0049 step 10b): override the destruction effects the ATTACHED `destroy()` runs
333
+ * after it detaches. Production builds real OPFS + meta-record + idb effects from the store path
334
+ * ({@link createStoreDestructionEffects}); injected so the supervised-destroy path is unit-testable with fake
335
+ * effects (effect-order assertions, ownership-lock-lag retry).
336
+ */
337
+ createDestructionEffects?: (storePath: string) => DestructionEffects;
72
338
  }
73
339
  /**
74
340
  * The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
@@ -87,13 +353,31 @@ export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient
87
353
  setOnline: (online: boolean) => void;
88
354
  };
89
355
  export declare function attachSyncClient<const TRegistry extends SyncTableRegistry>(options: AttachSyncClientOptions<TRegistry>): Promise<AttachedSyncClient<TRegistry>>;
356
+ /** {@link provisionSyncWorker} options — attach's transport/store/factory seams, plus the provision expiry. */
357
+ export type ProvisionSyncWorkerOptions<TRegistry extends SyncTableRegistry> = Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "storePath" | "storage" | "codec" | "createEngineWorker" | "electionIo" | "awaitOwnershipRelease" | "timers"> & {
358
+ /**
359
+ * How long (ms) the elected-mode provision claim (and its shared-coordinator ref) is held before an abandoned
360
+ * warmed provision auto-retires (ADR-0049 step 8, "abandoned warmed provision → claim expiry"). Default 60000.
361
+ * A later {@link attachSyncClient} on the same store ADOPTS the grant within this window (adding its own claim,
362
+ * so the engine outlives the expiry). Inert on SW-direct.
363
+ */
364
+ provisionExpiryMs?: number;
365
+ };
90
366
  /**
91
- * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen
92
- * against a freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the
93
- * raw store idle until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the
94
- * provision (its initdb settled); rejects only if the worker reports the create failed — the caller treats
95
- * either outcome as best-effort, since attach falls back to a fresh create regardless.
367
+ * Pre-spawn a worker's store WITHOUT attaching (ADR-0032 decision 5). Sent at the board's login screen against a
368
+ * freshly-named spare `SharedWorker`: the worker runs PGlite `create`/initdb only and holds the raw store idle
369
+ * until the real {@link attachSyncClient} claim adopts it. Resolves when the worker acks the provision (its initdb
370
+ * settled); rejects only if the worker reports the create failed — the caller treats either outcome as best-effort,
371
+ * since attach falls back to a fresh create regardless.
372
+ *
373
+ * Routed through the SAME placement-query-first flow as {@link attachSyncClient} (ADR-0049 step 8): a SW-direct
374
+ * (or declared-idbfs) SharedWorker takes the `provision` bridge envelope on the SW port; a
375
+ * router-only (`electionRequired`) SharedWorker DROPS bridge envelopes, so provision drives the election
376
+ * coordinator's PROVISION CLAIM (expiry-bounded) and delivers the `provision` over the elected engine's per-tab
377
+ * PIPE. The coordinator is REGISTERED per store so a later attach on the same tab ADOPTS the grant — no second
378
+ * lock, no second engine, no double initdb (invariant 2). Elected mode REQUIRES a {@link createEngineWorker}
379
+ * factory (mirroring attach); its absence is a clear rejection, never a hang.
96
380
  */
97
- export declare function provisionSyncWorker<TRegistry extends SyncTableRegistry>(options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "storePath" | "codec">): Promise<void>;
381
+ export declare function provisionSyncWorker<const TRegistry extends SyncTableRegistry>(options: ProvisionSyncWorkerOptions<TRegistry>): Promise<void>;
98
382
  export {};
99
383
  //# sourceMappingURL=attach-sync-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"attach-sync-client.d.ts","sourceRoot":"","sources":["../../src/worker/attach-sync-client.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAEV,iBAAiB,EAEjB,iBAAiB,EAElB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAIjD,OAAO,EAQL,KAAK,cAAc,EAEnB,KAAK,UAAU,EAGhB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAG7D,OAAO,EAGL,KAAK,iBAAiB,EACtB,KAAK,WAAW,EAEhB,KAAK,UAAU,EACf,KAAK,kBAAkB,EAcxB,MAAM,YAAY,CAAC;AAEpB,mHAAmH;AACnH,UAAU,UAAU;IAClB,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,kBAAkB,EAAE,KAAK,IAAI,CAAC;IAC1E,gBAAgB,CAAC,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,KAAK,IAAI,CAAC;IAC3F,mBAAmB,CAAC,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,KAAK,IAAI,CAAC;CAC/F;AAED,MAAM,WAAW,uBAAuB,CAAC,SAAS,SAAS,iBAAiB;IAC1E,QAAQ,EAAE,SAAS,CA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