@pgxsinkit/client 0.1.36 → 0.1.41

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 (64) hide show
  1. package/dist/boot-report.d.ts +134 -0
  2. package/dist/boot-report.d.ts.map +1 -0
  3. package/dist/export-data.d.ts +100 -0
  4. package/dist/export-data.d.ts.map +1 -0
  5. package/dist/export-dump.d.ts +92 -0
  6. package/dist/export-dump.d.ts.map +1 -0
  7. package/dist/export-store.d.ts +214 -0
  8. package/dist/export-store.d.ts.map +1 -0
  9. package/dist/index.d.ts +206 -13
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1373 -8308
  12. package/dist/index.js.map +25 -131
  13. package/dist/lazy-guard.d.ts +4 -3
  14. package/dist/lazy-guard.d.ts.map +1 -1
  15. package/dist/lifecycle-slot.d.ts +31 -0
  16. package/dist/lifecycle-slot.d.ts.map +1 -0
  17. package/dist/live-rows-sql.d.ts +21 -0
  18. package/dist/live-rows-sql.d.ts.map +1 -0
  19. package/dist/mutation-state.d.ts +9 -2
  20. package/dist/mutation-state.d.ts.map +1 -1
  21. package/dist/mutation.d.ts +12 -0
  22. package/dist/mutation.d.ts.map +1 -1
  23. package/dist/schema.d.ts +33 -0
  24. package/dist/schema.d.ts.map +1 -1
  25. package/dist/shape-sync.d.ts +10 -0
  26. package/dist/shape-sync.d.ts.map +1 -1
  27. package/dist/store-path.d.ts +132 -0
  28. package/dist/store-path.d.ts.map +1 -0
  29. package/dist/sync/index.d.ts +1 -1
  30. package/dist/sync/index.d.ts.map +1 -1
  31. package/dist/sync/types.d.ts +8 -0
  32. package/dist/sync/types.d.ts.map +1 -1
  33. package/dist/testing.d.ts +27 -0
  34. package/dist/testing.d.ts.map +1 -0
  35. package/dist/testing.js +17 -0
  36. package/dist/testing.js.map +11 -0
  37. package/dist/worker/attach-sync-client.d.ts +23 -2
  38. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  39. package/dist/worker/define-sync-worker.d.ts +5 -4
  40. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  41. package/dist/worker/protocol.d.ts +89 -8
  42. package/dist/worker/protocol.d.ts.map +1 -1
  43. package/package.json +9 -4
  44. package/skills/core/SKILL.md +14 -1
  45. package/skills/operating/SKILL.md +75 -15
  46. package/src/boot-report.ts +287 -0
  47. package/src/export-data.ts +300 -0
  48. package/src/export-dump.ts +239 -0
  49. package/src/export-store.ts +309 -0
  50. package/src/index.ts +623 -82
  51. package/src/lazy-guard.ts +23 -9
  52. package/src/lifecycle-slot.ts +66 -0
  53. package/src/live-rows-sql.ts +45 -0
  54. package/src/mutation-state.ts +11 -2
  55. package/src/mutation.ts +42 -0
  56. package/src/schema.ts +120 -1
  57. package/src/shape-sync.ts +21 -0
  58. package/src/store-path.ts +249 -0
  59. package/src/sync/index.ts +11 -0
  60. package/src/sync/types.ts +9 -0
  61. package/src/testing.ts +53 -0
  62. package/src/worker/attach-sync-client.ts +101 -6
  63. package/src/worker/define-sync-worker.ts +196 -30
  64. package/src/worker/protocol.ts +110 -10
@@ -0,0 +1,249 @@
1
+ // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker
2
+ // attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a
3
+ // PGlite storage URL. The storage backend is DERIVED from the environment here, never chosen by the
4
+ // consumer: IndexedDB in a browser (or a worker), the filesystem on Bun/Node. A memory-backed store is
5
+ // not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic
6
+ // Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing
7
+ // acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal
8
+ // {@link TEST_STORE_BACKEND} symbol.
9
+ //
10
+ // This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` URLs (the
11
+ // export machinery's throwaway clone, a later slice, is the one other internal `memory://` site). A
12
+ // resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something
13
+ // a consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old
14
+ // contract loudly at the boundary rather than silently re-interpreting it.
15
+
16
+ /**
17
+ * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or
18
+ * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the
19
+ * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and
20
+ * shows the corrected form, without echoing a resolvable URL a consumer might imitate.
21
+ */
22
+ export class InvalidStorePathError extends Error {
23
+ constructor(message: string) {
24
+ super(`[pgxsinkit] ${message}`);
25
+ this.name = "InvalidStorePathError";
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /
31
+ * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its
32
+ * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins
33
+ * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a
34
+ * consumer is never left guessing which store to hand us instead.
35
+ */
36
+ export class NonPersistentStoreError extends Error {
37
+ constructor(observed: "in-memory-default" | "memory-scheme") {
38
+ const reason =
39
+ observed === "in-memory-default"
40
+ ? "its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)"
41
+ : "its dataDir is a memory-backed store";
42
+ super(
43
+ `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +
44
+ "(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store " +
45
+ "would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a " +
46
+ "plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with " +
47
+ '`memoryStoreForTests` / `testStoreAcknowledgment` from "@pgxsinkit/client/testing" (ADR-0036).',
48
+ );
49
+ this.name = "NonPersistentStoreError";
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY
55
+ * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never
56
+ * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type
57
+ * (not a bare `Error`) so a caller can `instanceof`-branch "target already there" from a genuine boot failure.
58
+ * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —
59
+ * dropping a user's local store must be their explicit act).
60
+ */
61
+ export class RestoreTargetExistsError extends Error {
62
+ constructor(storePath: string) {
63
+ super(
64
+ `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +
65
+ "Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the " +
66
+ "datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh " +
67
+ "path (ADR-0035 decision 6).",
68
+ );
69
+ this.name = "RestoreTargetExistsError";
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The module-internal marker a testing helper stamps onto the options object so option handling can select
75
+ * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)
76
+ * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,
77
+ * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the
78
+ * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the
79
+ * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately
80
+ * absent from the main entry's exports and from every public type, so a production consumer cannot name it.
81
+ */
82
+ export const TEST_STORE_BACKEND: unique symbol = Symbol.for("pgxsinkit.internal.testStoreBackend");
83
+
84
+ /**
85
+ * What a testing helper's marker asks of option handling: `"memory"` mints a scheme-selected memory store
86
+ * (and, being ours-under-the-covers, also unlocks the BYO refusal); `"acknowledged"` only unlocks the BYO
87
+ * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an
88
+ * import whose name says what it is.
89
+ */
90
+ export type TestStoreMarker = "memory" | "acknowledged";
91
+
92
+ /** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */
93
+ export type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };
94
+
95
+ /** Read the internal testing marker off an options object, or `undefined` when none was stamped. */
96
+ export function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {
97
+ if (options == null || typeof options !== "object") return undefined;
98
+ const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];
99
+ return marker === "memory" || marker === "acknowledged" ? marker : undefined;
100
+ }
101
+
102
+ /**
103
+ * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain
104
+ * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a
105
+ * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing
106
+ * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests("x"))` without a consumer ever
107
+ * naming a backend.
108
+ */
109
+ export type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);
110
+
111
+ /** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */
112
+ export function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: "memory" } {
113
+ if (typeof input === "string") return { storePath: input };
114
+ return {
115
+ storePath: input.storePath,
116
+ ...(readTestStoreMarker(input) === "memory" ? { backendOverride: "memory" as const } : {}),
117
+ };
118
+ }
119
+
120
+ /**
121
+ * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in
122
+ * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's
123
+ * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but
124
+ * Bun/Node do not — so it distinguishes "run in the browser" (idb) from "run on the server" (filesystem)
125
+ * without a DOM-lib dependency.
126
+ */
127
+ export interface StoreEnv {
128
+ hasIndexedDb: boolean;
129
+ }
130
+
131
+ /** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */
132
+ function detectStoreEnv(): StoreEnv {
133
+ return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== "undefined" };
134
+ }
135
+
136
+ /**
137
+ * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point
138
+ * (ADR-0036 decision 2). Browser/worker (`indexedDB` present) → `idb://<storePath>`; Bun/Node → `file://<storePath>`
139
+ * (relative paths resolve against the working directory, exactly as PGlite's filesystem backend does — pass
140
+ * an absolute path if that matters). The `backendOverride` is internal-only: `"memory"` selects a
141
+ * scheme-selected `memory://<storePath>` store for the sanctioned test/ephemeral lanes.
142
+ *
143
+ * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath
144
+ * contract fails loudly at the boundary, never silently re-interpreted (no-legacy rule). The returned URL is
145
+ * internal plumbing; do not surface it to consumers as something to imitate.
146
+ *
147
+ * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
148
+ * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
149
+ * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
150
+ * exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
151
+ */
152
+ export function resolveStoreDataDir(
153
+ storePath: string,
154
+ backendOverride?: "memory",
155
+ env: StoreEnv = detectStoreEnv(),
156
+ ): string {
157
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
158
+ throw new InvalidStorePathError(
159
+ 'invalid storePath: expected a non-empty plain store name (e.g. "my-app-store"); received an empty or whitespace-only value (ADR-0036).',
160
+ );
161
+ }
162
+ if (storePath.includes("://")) {
163
+ throw new InvalidStorePathError(
164
+ `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +
165
+ 'Pass just the name (e.g. "my-app-store") — the storage backend (IndexedDB in a browser, the ' +
166
+ "filesystem on Bun/Node) is derived for you; drop the scheme prefix (ADR-0036).",
167
+ );
168
+ }
169
+ if (backendOverride === "memory") return `memory://${storePath}`;
170
+ return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;
171
+ }
172
+
173
+ /**
174
+ * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for
175
+ * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite
176
+ * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`
177
+ * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a
178
+ * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather
179
+ * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as
180
+ * {@link resolveStoreDataDir} does, so the two stay in lockstep.
181
+ */
182
+ export function storeIndexedDbDatabaseName(storePath: string): string {
183
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
184
+ throw new InvalidStorePathError(
185
+ "invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).",
186
+ );
187
+ }
188
+ if (storePath.includes("://")) {
189
+ throw new InvalidStorePathError(
190
+ `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,
191
+ );
192
+ }
193
+ return `/pglite/${storePath}`;
194
+ }
195
+
196
+ /**
197
+ * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending
198
+ * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a
199
+ * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,
200
+ * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the
201
+ * two accidental non-persistent shapes, it is not a storage-backend whitelist).
202
+ */
203
+ export function classifyNonPersistentDataDir(
204
+ dataDir: string | undefined,
205
+ ): "in-memory-default" | "memory-scheme" | null {
206
+ if (dataDir == null) return "in-memory-default";
207
+ if (dataDir.startsWith("memory://")) return "memory-scheme";
208
+ return null;
209
+ }
210
+
211
+ /**
212
+ * Does the backend store a plain {@link storePath} resolves to ALREADY exist? The fresh-target gate for a
213
+ * restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:
214
+ *
215
+ * - **memory** (`backendOverride === "memory"`) — a scheme-selected memory store is fresh by construction:
216
+ * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`
217
+ * (the sanctioned test/ephemeral lane never blocks a restore).
218
+ * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported
219
+ * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the
220
+ * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,
221
+ * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.
222
+ * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name
223
+ * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older
224
+ * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let
225
+ * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a
226
+ * PGlite-level boot failure. We never fake a positive.
227
+ */
228
+ export async function storeTargetExists(
229
+ storePath: string,
230
+ backendOverride?: "memory",
231
+ env: StoreEnv = detectStoreEnv(),
232
+ ): Promise<boolean> {
233
+ const dataDir = resolveStoreDataDir(storePath, backendOverride, env);
234
+ if (dataDir.startsWith("memory://")) return false;
235
+ if (dataDir.startsWith("file://")) {
236
+ // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and
237
+ // cwd-relative paths identically to PGlite's own filesystem backend.
238
+ const path = dataDir.slice("file://".length);
239
+ const { existsSync } = await import("node:fs");
240
+ return existsSync(path);
241
+ }
242
+ // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in
243
+ // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.
244
+ const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;
245
+ if (idb?.databases == null) return false;
246
+ const target = storeIndexedDbDatabaseName(storePath);
247
+ const databases = await idb.databases();
248
+ return databases.some((db) => db.name === target);
249
+ }
package/src/sync/index.ts CHANGED
@@ -169,6 +169,7 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
169
169
  onSyncError,
170
170
  onSyncActivity,
171
171
  dbReady,
172
+ bootStamp,
172
173
  maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,
173
174
  commitRetryDelayMs = computeRetryDelayMs,
174
175
  }: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {
@@ -845,6 +846,9 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
845
846
  if (changeCount > 0) {
846
847
  syncDebug("sync received change batch from Electric", { changes: changeCount });
847
848
  }
849
+ // Boot observability (ADR-0034): one delivery = one shape-stream response. Records the fetch (network)
850
+ // gap since the last settle plus this batch's request + change-row counts. No-op post-ready (frozen).
851
+ bootStamp?.onBatchDelivered(changeCount);
848
852
  const commitStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
849
853
 
850
854
  // The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;
@@ -925,7 +929,10 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
925
929
  // is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that
926
930
  // bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).
927
931
  if (dbGateOpen) {
932
+ const applyStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
928
933
  await enqueueCommit();
934
+ // Boot observability (ADR-0034): the apply (commit-into-PGlite) wall for this delivery.
935
+ bootStamp?.onApply((typeof performance !== "undefined" ? performance.now() : Date.now()) - applyStartedAt);
929
936
  if (changeCount > 0) {
930
937
  // Truthful rail (ADR-0031): the "applied" line only fires when this batch's completed changes
931
938
  // actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the
@@ -962,7 +969,11 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
962
969
  await initMetadataTables();
963
970
  dbGateOpen = true;
964
971
  syncDebug("boot commits opened");
972
+ // Boot observability (ADR-0034): on the overlap path the buffered catch-up drains here (not in a
973
+ // subscribe callback), so stamp the drain's apply wall into the group's accumulator.
974
+ const drainStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
965
975
  await enqueueCommit();
976
+ bootStamp?.onApply((typeof performance !== "undefined" ? performance.now() : Date.now()) - drainStartedAt);
966
977
  });
967
978
  }
968
979
 
package/src/sync/types.ts CHANGED
@@ -5,6 +5,8 @@ import type { PgliteDatabase } from "drizzle-orm/pglite";
5
5
 
6
6
  import type { SyncTableRegistry } from "@pgxsinkit/contracts";
7
7
 
8
+ import type { GroupBootStamp } from "../boot-report";
9
+
8
10
  // Re-exported so in-repo tests (e.g. tests/unit/sync-engine.test.ts) can name these Electric types
9
11
  // via this engine module — they resolve here, inside @pgxsinkit/client's dependency scope, without
10
12
  // the root workspace needing a direct dependency on the Electric client packages.
@@ -87,6 +89,13 @@ export interface SyncShapesToTablesOptions {
87
89
  * immediate retry instead of sleeping the real backoff.
88
90
  */
89
91
  commitRetryDelayMs?: ((attempt: number) => number) | undefined;
92
+ /**
93
+ * Boot observability (ADR-0034): a per-group accumulator, stamped as this group's stream chain delivers
94
+ * batches (`onBatchDelivered`), applies commits into PGlite (`onApply`), and reaches initial sync
95
+ * (`markReady`). Present only for eager + promoted BOOT groups; absent for on-demand lazy starts and any
96
+ * boot without report instrumentation.
97
+ */
98
+ bootStamp?: GroupBootStamp | undefined;
90
99
  }
91
100
 
92
101
  export interface SyncShapesToTablesResult {
package/src/testing.ts ADDED
@@ -0,0 +1,53 @@
1
+ // `@pgxsinkit/client/testing` — the ONLY sanctioned door to a memory-backed store (ADR-0036 decision 3).
2
+ //
3
+ // pgxsinkit's durability semantics assume a persisted store, so the production API surface cannot express a
4
+ // memory store: `createSyncClient`/`createClientPGlite` take a plain `storePath` whose backend is derived
5
+ // (IndexedDB / filesystem), and the BYO seam refuses a provably non-persistent instance. Genuine memory
6
+ // stores are needed in exactly two of OUR places — the unit-test lane (speed + isolation) and the export
7
+ // machinery's throwaway clone — and this subpath serves the first: an import whose NAME says what it is, so
8
+ // reaching a memory store is always a visible, deliberate act. App bundles never import it, so the whole
9
+ // module (and any mention of memory) tree-shakes away.
10
+ //
11
+ // The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}
12
+ // marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
13
+ //
14
+ // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, writeUrl })
15
+ // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, writeUrl })
16
+
17
+ import { TEST_STORE_BACKEND } from "./store-path";
18
+
19
+ /**
20
+ * The public shape of {@link memoryStoreForTests}'s output: just a `storePath`. The internal backend marker
21
+ * rides alongside at runtime but is deliberately absent from this type, so no production type mentions memory.
22
+ */
23
+ export interface MemoryStoreForTests {
24
+ storePath: string;
25
+ }
26
+
27
+ /**
28
+ * Mint client store options that resolve to a scheme-selected in-memory store — the unit-test / ephemeral
29
+ * lane (ADR-0036 decision 3). Spread the result into `createSyncClient` (or `defineSyncWorker` where its
30
+ * options accept `storePath`): the client reads the internal marker and selects the memory backend.
31
+ *
32
+ * DURABILITY CAVEAT: a memory store is session-scoped, so pgxsinkit's persistent-retention guarantee and the
33
+ * optimistic Mutation journal's durability window are BOTH void on it — everything is lost when the instance
34
+ * closes. Use it only for tests and throwaway/ephemeral flows, never for anything a user expects to persist.
35
+ */
36
+ export function memoryStoreForTests(storePath: string): MemoryStoreForTests {
37
+ // The marker is a symbol-keyed property, so it survives an object spread but is invisible to the public
38
+ // type and to `Object.keys`. Cast because the return TYPE deliberately hides it (ADR-0036 decision 3).
39
+ return { storePath, [TEST_STORE_BACKEND]: "memory" } as MemoryStoreForTests;
40
+ }
41
+
42
+ /**
43
+ * Mint an options fragment that ACKNOWLEDGES a caller-owned test store, bypassing the BYO refusal
44
+ * (ADR-0036 decision 4) WITHOUT selecting a backend — for when the test supplies its own non-persistent
45
+ * PGlite via `pgliteInstance` / `precreatedPglite`. Spread it alongside that option.
46
+ *
47
+ * Same DURABILITY CAVEAT as {@link memoryStoreForTests}: only for tests / throwaway flows; a non-persistent
48
+ * store voids the retention + journal durability guarantees.
49
+ */
50
+ export function testStoreAcknowledgment(): Record<never, never> {
51
+ // An empty public shape carrying only the internal marker — nothing for a consumer to configure.
52
+ return { [TEST_STORE_BACKEND]: "acknowledged" } as Record<never, never>;
53
+ }
@@ -19,6 +19,10 @@ import type {
19
19
  WriteMode,
20
20
  } from "@pgxsinkit/contracts";
21
21
 
22
+ import type { BootReport } from "../boot-report";
23
+ import type { DataExportOptions, DataExportResult } from "../export-data";
24
+ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-dump";
25
+ import type { StoreExportOptions, StoreExportResult } from "../export-store";
22
26
  import {
23
27
  buildRegistryReadHandles,
24
28
  type LiveRowsSubscription,
@@ -30,6 +34,7 @@ import {
30
34
  type SyncTransactionResult,
31
35
  } from "../index";
32
36
  import type { LocalStoreVersionEvent } from "../local-store";
37
+ import { readTestStoreMarker } from "../store-path";
33
38
  import { LiveRowsMaterializer } from "./live-diff";
34
39
  import {
35
40
  type AttachAckPayload,
@@ -39,12 +44,14 @@ import {
39
44
  type BridgeEvent,
40
45
  type BridgePort,
41
46
  type BridgeTransferable,
47
+ type ExportArtefactWire,
42
48
  identityCodec,
43
49
  isBridgeEnvelope,
44
50
  type LiveDiffPayload,
45
51
  type LiveInitialPayload,
46
52
  postBridgeMessage,
47
53
  type ProvisionAckPayload,
54
+ type RestoreArtefactWire,
48
55
  type RpcOp,
49
56
  type RpcResultPayload,
50
57
  type TokenRequestPayload,
@@ -72,7 +79,12 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
72
79
  getToken?: () => Promise<AuthTokenSnapshot | null>;
73
80
  /** The bound store id (resolved tab-side before attach — SharedWorker naming, ADR-0032 decision 5). */
74
81
  storeId?: string;
75
- dataDir?: string;
82
+ /**
83
+ * The plain store PATH (ADR-0036) the worker opens if it must create its own store — a name, not a
84
+ * storage URL. Spread `memoryStoreForTests(...)` from `@pgxsinkit/client/testing` here for a memory store
85
+ * in tests (it also carries the internal marker forwarded to the worker as the memory-backend override).
86
+ */
87
+ storePath?: string;
76
88
  syncEnabled?: boolean;
77
89
  /**
78
90
  * Which baked registry the worker boots (ADR-0032 S3) — forwarded in the attach `config.role`. A worker
@@ -86,6 +98,15 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
86
98
  * the worker's `createSyncClient` then overlaps the shape catch-up with its local boot phases.
87
99
  */
88
100
  freshStore?: boolean;
101
+ /**
102
+ * Restore the worker's store from a backup on attach (ADR-0035 decision 6) — the worker-mode `restoreFrom`.
103
+ * A `File`/`Blob` as produced by {@link SyncClient.exportStore}; the facade decomposes it into a transferred
104
+ * `ArrayBuffer` + name/mime ({@link RestoreArtefactWire}) and the worker recomposes it for `createSyncClient`.
105
+ * Restore rides the FIRST (boot) attach: passing it when the worker's engine has ALREADY booted rejects the
106
+ * attach with a typed error (you cannot restore into a running store). The restored engine boots offline and
107
+ * its recovered journal is quarantined, exactly as in-process — see `restoreFrom` on `createSyncClient`.
108
+ */
109
+ restoreFrom?: File | Blob;
89
110
  codec?: BridgeCodec;
90
111
  onStatusChange?: (status: SyncRuntimeStatus) => void;
91
112
  onConflict?: (details: MutationDetail[]) => void;
@@ -93,6 +114,12 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
93
114
  onReject?: (details: MutationDetail[]) => void;
94
115
  onSchemaChange?: (event: LocalStoreVersionEvent) => void;
95
116
  onSyncError?: (error: Error) => void;
117
+ /**
118
+ * Boot observability (ADR-0034): invoked once with the worker engine's finalized {@link BootReport} if the
119
+ * engine's boot finalizes WHILE this tab is attached (the one-shot `boot-report` broadcast). A tab that
120
+ * attaches AFTER the boot never receives the push — it reads the report via {@link SyncClient.bootReport}.
121
+ */
122
+ onBootReport?: (report: BootReport) => void;
96
123
  }
97
124
 
98
125
  /**
@@ -196,6 +223,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
196
223
  case "sync-error":
197
224
  options.onSyncError?.(new Error(event.message));
198
225
  break;
226
+ case "boot-report":
227
+ // Boot observability (ADR-0034): the one-shot push for a tab attached at finalize. A late tab never
228
+ // gets this event and pulls the report via `client.bootReport()` instead.
229
+ options.onBootReport?.(event.report);
230
+ break;
199
231
  case "debug": {
200
232
  // Re-print the worker's rail line gated on THIS tab's own flag, origin-tagged with the worker's
201
233
  // monotonic stamp (ADR-0032 decision 7) — a SharedWorker's own console is otherwise invisible.
@@ -300,10 +332,25 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
300
332
  attachAckReject = reject;
301
333
  });
302
334
  const initialToken = options.getToken ? await options.getToken() : null;
335
+ // The testing memory-backend override travels as an explicit wire field, not the symbol marker — a symbol
336
+ // does not survive `postMessage` structured clone (ADR-0036). Read it off the spread helper's options here.
337
+ const memoryOverride = readTestStoreMarker(options) === "memory";
338
+ // Restore (ADR-0035 decision 6): a `File`/`Blob` cannot cross as a transferable, so decompose it into a
339
+ // zero-copy `ArrayBuffer` + name/mime (the `ExportArtefactWire` pattern in reverse) and list the buffer on
340
+ // the attach `postMessage`'s transfer list. Read the bytes BEFORE building the payload (async).
341
+ const restoreWire: RestoreArtefactWire | undefined = options.restoreFrom
342
+ ? {
343
+ buffer: await options.restoreFrom.arrayBuffer(),
344
+ fileName: options.restoreFrom instanceof File ? options.restoreFrom.name : "restore.pgdata.tar",
345
+ mimeType: options.restoreFrom.type || "application/octet-stream",
346
+ }
347
+ : undefined;
303
348
  const attachPayload: AttachPayload = {
304
349
  token: initialToken,
305
350
  ...(options.storeId ? { storeId: options.storeId } : {}),
306
- ...(options.dataDir ? { dataDir: options.dataDir } : {}),
351
+ ...(options.storePath ? { storePath: options.storePath } : {}),
352
+ ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
353
+ ...(restoreWire ? { restore: restoreWire } : {}),
307
354
  ...(options.syncEnabled != null || options.role != null || options.freshStore != null
308
355
  ? {
309
356
  config: {
@@ -314,7 +361,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
314
361
  }
315
362
  : {}),
316
363
  };
317
- postBridgeMessage(port, codec, "attach", attachPayload);
364
+ postBridgeMessage(port, codec, "attach", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);
318
365
  try {
319
366
  await attachAck;
320
367
  } catch (error) {
@@ -348,6 +395,7 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
348
395
  queryId,
349
396
  sql: input.sql,
350
397
  params: [...input.params],
398
+ ...(input.fields ? { fields: [...input.fields] } : {}),
351
399
  ...(input.pkColumns ? { pkColumns: [...input.pkColumns] } : {}),
352
400
  ...(input.use ? { use: [...input.use] } : {}),
353
401
  },
@@ -446,7 +494,14 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
446
494
  queryRawRow: notSupported("client.queryRawRow"),
447
495
  ensureSynced: notSupported("client.ensureSynced"),
448
496
  isSynced: notSupported("client.isSynced"),
449
- desync: notSupported("client.desync"),
497
+ // In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for
498
+ // EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower
499
+ // `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).
500
+ desync: (key) => rpc<void>("desync", [key]),
501
+ // Scoped, multi-tab-safe finalize (ADR-0021): drops an ephemeral relation's local rows and reverts it to
502
+ // dormant. Safe under a shared engine because an ephemeral window is per-delivery-session and inherently
503
+ // single-consumer; the RPC runs the worker's real `discardEphemeral` (refuses persistent members).
504
+ discardEphemeral: (key) => rpc<void>("discardEphemeral", [key]),
450
505
  // The worker activates lazy relations inside its `subscribe` handler (via the `use` hint), so the tab's
451
506
  // `prepareQuery` is a no-op — the live-rows subscription is already guarded worker-side (ADR-0021).
452
507
  prepareQuery: async () => undefined,
@@ -495,6 +550,42 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
495
550
  });
496
551
  },
497
552
  subscribeLiveRows,
553
+ // Boot observability (ADR-0034): pull the worker engine's stored boot report over the bridge — returns
554
+ // the same report regardless of when this tab attached (a late tab reads a boot that predates it).
555
+ bootReport: () => rpc<BootReport | null>("bootReport", []),
556
+ // Store backup (ADR-0035): the worker runs the live export on its owned client (its lifecycle slot
557
+ // serialises it against every tab). The dump crosses back as a transferred `ArrayBuffer`; rebuild the
558
+ // `File` tab-side from the wire form — NOT in the notSupported set (unlike the local `pglite` reads).
559
+ exportStore: async (exportOptions?: StoreExportOptions): Promise<StoreExportResult> => {
560
+ const wire = await rpc<ExportArtefactWire>("exportStore", [exportOptions]);
561
+ return {
562
+ file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
563
+ // The wire carries the discriminated union; `exportStore` always round-trips a store-backup report.
564
+ report: wire.report as StoreExportResult["report"],
565
+ };
566
+ },
567
+ // Diagnostic dump (ADR-0035): the worker runs the throwaway-clone dump on its owned client (same
568
+ // lifecycle slot as every tab). The SQL crosses back as the same transferred `ArrayBuffer`; rebuild the
569
+ // `File` tab-side. NOT in the notSupported set (unlike the local `pglite` reads).
570
+ exportDiagnostics: async (exportOptions?: DiagnosticExportOptions): Promise<DiagnosticExportResult> => {
571
+ const wire = await rpc<ExportArtefactWire>("exportDiagnostics", [exportOptions]);
572
+ return {
573
+ file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
574
+ // The wire carries the discriminated union; `exportDiagnostics` always round-trips a diagnostic-dump report.
575
+ report: wire.report as DiagnosticExportResult["report"],
576
+ };
577
+ },
578
+ // Data export (ADR-0035): the worker runs the drain-guarded `pg_dump -t` export on its owned client (same
579
+ // lifecycle slot as every tab). The portable SQL crosses back as the same transferred `ArrayBuffer`;
580
+ // rebuild the `File` tab-side. A `DataExportDrainError` surfaces as the rejected RPC (deserialised tab-side).
581
+ exportData: async (exportOptions?: DataExportOptions): Promise<DataExportResult> => {
582
+ const wire = await rpc<ExportArtefactWire>("exportData", [exportOptions]);
583
+ return {
584
+ file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
585
+ // The wire carries the discriminated union; `exportData` always round-trips a data-export report.
586
+ report: wire.report as DataExportResult["report"],
587
+ };
588
+ },
498
589
  notifyAuthChanged: () => {
499
590
  void pushToken();
500
591
  },
@@ -514,10 +605,13 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
514
605
  * either outcome as best-effort, since attach falls back to a fresh create regardless.
515
606
  */
516
607
  export function provisionSyncWorker<TRegistry extends SyncTableRegistry>(
517
- options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "dataDir" | "codec">,
608
+ options: Pick<AttachSyncClientOptions<TRegistry>, "worker" | "port" | "storeId" | "storePath" | "codec">,
518
609
  ): Promise<void> {
519
610
  const codec = options.codec ?? identityCodec;
520
611
  const port = resolvePort(options);
612
+ // The testing memory-backend override travels as an explicit wire field (a symbol does not survive
613
+ // structured clone, ADR-0036) — read it off the spread helper's options and forward it to the worker.
614
+ const memoryOverride = readTestStoreMarker(options) === "memory";
521
615
  return new Promise<void>((resolve, reject) => {
522
616
  const listener = (message: { data: unknown }) => {
523
617
  if (!isBridgeEnvelope(message.data)) return;
@@ -531,7 +625,8 @@ export function provisionSyncWorker<TRegistry extends SyncTableRegistry>(
531
625
  port.start?.();
532
626
  postBridgeMessage(port, codec, "provision", {
533
627
  ...(options.storeId ? { storeId: options.storeId } : {}),
534
- ...(options.dataDir ? { dataDir: options.dataDir } : {}),
628
+ ...(options.storePath ? { storePath: options.storePath } : {}),
629
+ ...(memoryOverride ? { testStoreBackend: "memory" as const } : {}),
535
630
  });
536
631
  });
537
632
  }