@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
package/src/index.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { PGlite, type PGliteInterfaceExtensions } from "@electric-sql/pglite";
1
+ import { PGlite, type Results } from "@electric-sql/pglite";
2
2
  import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
3
3
  import type { PgliteDatabase } from "drizzle-orm/pglite";
4
4
  import { drizzle } from "drizzle-orm/pglite";
5
5
  import { defineRelations } from "drizzle-orm/relations";
6
6
 
7
7
  import type {
8
+ MutationAck,
8
9
  MutationDiagnostics,
9
10
  RegistryRelations,
10
11
  RegistryTables,
@@ -16,31 +17,473 @@ import type {
16
17
  SyncTableName,
17
18
  SyncTableRegistry,
18
19
  SyncTableUpdateInput,
20
+ WriteMode,
19
21
  } from "@pgxsinkit/contracts";
20
- import { getSyncRegistrySchema } from "@pgxsinkit/contracts";
21
- import { createElectricExtension, startConfiguredSync } from "@pgxsinkit/sync-engine";
22
+ import { fingerprintRegistry, getSyncRegistrySchema } from "@pgxsinkit/contracts";
22
23
 
23
- import { createMutationRuntime, type MutationBatchItem, type MutationDetail, type MutationKind } from "./mutation";
24
- import { generateLocalSchemaSql } from "./schema";
24
+ import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
25
+ import { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from "./convergence";
26
+ import { syncDebug, timeAsync } from "./debug";
27
+ import { type DataExportOptions, type DataExportResult, performDataExport } from "./export-data";
28
+ import { type DiagnosticExportOptions, type DiagnosticExportResult, performDiagnosticExport } from "./export-dump";
29
+ import { performStoreExport, type StoreExportOptions, type StoreExportResult } from "./export-store";
30
+ import { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql } from "./lazy-guard";
31
+ import { createLifecycleSlot } from "./lifecycle-slot";
32
+ import { wrapLiveQueryForMaterialization } from "./live-rows-sql";
33
+ import {
34
+ type LocalStoreVersionEvent,
35
+ clearLazyGroupActivation,
36
+ readActivatedLazyGroups,
37
+ reconcileLocalStoreVersion,
38
+ writeLazyGroupActivation,
39
+ } from "./local-store";
40
+ import {
41
+ createMutationRuntime,
42
+ type MutationBatchItem,
43
+ type MutationDetail,
44
+ type MutationKind,
45
+ type WriteUnit,
46
+ } from "./mutation";
47
+ import {
48
+ buildDataExportCloneCleanupSql,
49
+ buildDataExportEnumHeaderSql,
50
+ buildDesyncTableSql,
51
+ buildDropReadCacheSql,
52
+ buildWipeLocalStoreSql,
53
+ collectDataExportSyncedTableNames,
54
+ generateLocalSchemaSql,
55
+ } from "./schema";
56
+ import { startConfiguredSync } from "./shape-sync";
57
+ import {
58
+ classifyNonPersistentDataDir,
59
+ NonPersistentStoreError,
60
+ normaliseStorePathInput,
61
+ readTestStoreMarker,
62
+ resolveStoreDataDir,
63
+ RestoreTargetExistsError,
64
+ storeTargetExists,
65
+ type StorePathInput,
66
+ } from "./store-path";
67
+ import { createSyncEngine, type SyncEngine } from "./sync";
68
+ import { buildShapeHeaders } from "./sync-auth";
25
69
 
26
70
  export { generateLocalSchemaSql };
71
+ export { wrapLiveQueryForMaterialization } from "./live-rows-sql";
72
+ export type { BootReport } from "./boot-report";
73
+ export {
74
+ type CloneDumpPhases,
75
+ type CloneDumpResult,
76
+ type DiagnosticExportDeps,
77
+ type DiagnosticExportOptions,
78
+ type DiagnosticExportResult,
79
+ performDiagnosticExport,
80
+ runThrowawayCloneDump,
81
+ } from "./export-dump";
82
+ export {
83
+ type DataExportDeps,
84
+ DataExportDrainError,
85
+ type DataExportOptions,
86
+ type DataExportResult,
87
+ DEFAULT_DRAIN_TIMEOUT_MS,
88
+ type DrainJournalOption,
89
+ type DrainJournalOptions,
90
+ performDataExport,
91
+ } from "./export-data";
92
+ export {
93
+ type DataExportReport,
94
+ deriveStoreId,
95
+ type DiagnosticDumpReport,
96
+ type ExportReport,
97
+ type ExportReportCommon,
98
+ performDatadirDump,
99
+ performStoreExport,
100
+ type StoreBackupReport,
101
+ type StoreExportDeps,
102
+ type StoreExportOptions,
103
+ type StoreExportResult,
104
+ } from "./export-store";
105
+ export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
106
+ export {
107
+ InvalidStorePathError,
108
+ NonPersistentStoreError,
109
+ resolveStoreDataDir,
110
+ RestoreTargetExistsError,
111
+ storeIndexedDbDatabaseName,
112
+ storeTargetExists,
113
+ } from "./store-path";
114
+ export {
115
+ type ConvergenceClient,
116
+ type ConvergenceDriver,
117
+ type ConvergenceDriverOptions,
118
+ type ConvergenceTrigger,
119
+ createBrowserConvergenceTrigger,
120
+ createConvergenceDriver,
121
+ createIntervalConvergenceTrigger,
122
+ } from "./convergence";
123
+ export { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from "./debug";
124
+ export {
125
+ type AttachedSyncClient,
126
+ attachSyncClient,
127
+ type AttachSyncClientOptions,
128
+ provisionSyncWorker,
129
+ } from "./worker/attach-sync-client";
130
+ export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
131
+ export {
132
+ computeLiveDiff,
133
+ type LiveDiffState,
134
+ LiveRowsMaterializer,
135
+ rowKey,
136
+ seedLiveDiffState,
137
+ } from "./worker/live-diff";
138
+ export { createWorkerTokenCache, type WorkerTokenCache } from "./worker/token-cache";
139
+ export {
140
+ type AttachAckPayload,
141
+ type AttachPayload,
142
+ type AuthTokenSnapshot,
143
+ BRIDGE_CHANNEL,
144
+ BRIDGE_PROTOCOL_VERSION,
145
+ type BridgeCodec,
146
+ type BridgeEnvelope,
147
+ type BridgeEvent,
148
+ type BridgeMessageType,
149
+ type BridgePort,
150
+ encodeEnvelope,
151
+ type ExportArtefactWire,
152
+ identityCodec,
153
+ isBridgeEnvelope,
154
+ type LiveDiffPayload,
155
+ type LiveInitialPayload,
156
+ postBridgeMessage,
157
+ type ProvisionAckPayload,
158
+ type ProvisionPayload,
159
+ type RpcOp,
160
+ type RpcPayload,
161
+ type RpcResultPayload,
162
+ type SetOnlinePayload,
163
+ type SubscribePayload,
164
+ type TokenRequestPayload,
165
+ type TokenResponsePayload,
166
+ type WakePayload,
167
+ } from "./worker/protocol";
168
+ export {
169
+ assertLazyRefsActivated,
170
+ buildLazyGuardIndex,
171
+ findReferencedLazyKeysInSql,
172
+ type LazyGuardIndex,
173
+ LazyRelationNotActivatedError,
174
+ } from "./lazy-guard";
175
+ export {
176
+ getJournalTable,
177
+ getLocalMetaTable,
178
+ getOverlayTable,
179
+ getReadModelView,
180
+ getSyncedLocalTable,
181
+ getSyncStateView,
182
+ type JournalTable,
183
+ type LocalMetaTable,
184
+ type OverlayTable,
185
+ type ReadModelView,
186
+ type SyncStateView,
187
+ } from "./local-tables";
188
+ export type { LocalStoreVersionEvent };
27
189
 
28
- export type ClientPGlite = PGliteWithLive &
29
- PGliteInterfaceExtensions<{ electric: ReturnType<typeof createElectricExtension> }>;
190
+ // The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit
191
+ // sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032
192
+ // S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real
193
+ // return so the type follows the attached object.
194
+ export type ClientPGlite = PGliteWithLive & { electric: SyncEngine["namespace"] };
195
+
196
+ /**
197
+ * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by
198
+ * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
199
+ * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
200
+ * asset load — see the field's JSDoc for the accelerator geometry.
201
+ */
202
+ export interface PgliteBootAssets {
203
+ pgliteWasmModule?: WebAssembly.Module;
204
+ initdbWasmModule?: WebAssembly.Module;
205
+ fsBundle?: Blob;
206
+ }
207
+
208
+ /** Options for {@link createClientPGlite}. */
209
+ export interface CreateClientPGliteOptions {
210
+ /**
211
+ * Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and
212
+ * passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own
213
+ * asset load), so it never fails the create.
214
+ */
215
+ bootAssets?: Promise<PgliteBootAssets>;
216
+ /**
217
+ * @internal Test-only storage-backend override (ADR-0036). `"memory"` resolves the store to a
218
+ * scheme-selected in-memory store — the sanctioned unit-test/ephemeral lane. Never a product
219
+ * configuration: reached only through `@pgxsinkit/client/testing`, never consumer-facing.
220
+ */
221
+ backendOverride?: "memory";
222
+ /**
223
+ * A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as
224
+ * produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created
225
+ * store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)
226
+ * has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no
227
+ * freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.
228
+ */
229
+ restoreFrom?: File | Blob;
230
+ }
231
+
232
+ /**
233
+ * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
234
+ * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset
235
+ * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
236
+ * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
237
+ * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
238
+ * hooks, journal recovery and store-version reconcile, exactly as its own `storePath` path does.
239
+ *
240
+ * Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED (IndexedDB in a
241
+ * browser/worker, the filesystem on Bun/Node); a scheme-bearing path throws {@link InvalidStorePathError}.
242
+ * Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests("x"))`) so a test can
243
+ * mint a memory store without naming a backend.
244
+ *
245
+ * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
246
+ * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
247
+ * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.
248
+ *
249
+ * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
250
+ * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
251
+ */
252
+ export async function createClientPGlite(
253
+ store: StorePathInput,
254
+ options?: CreateClientPGliteOptions,
255
+ ): Promise<ClientPGlite> {
256
+ // Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),
257
+ // then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
258
+ // empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
259
+ const normalised = normaliseStorePathInput(store);
260
+ const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);
261
+ // Stamp only the storage scheme (e.g. "idb:" / "memory:"), never the full path — the path can carry an
262
+ // identity-specific store name, and the boot rail stays monotonic-and-scheme only.
263
+ const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
264
+ // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the
265
+ // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled
266
+ // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
267
+ // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
268
+ const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
269
+ return (await timeAsync(
270
+ "boot pglite.create",
271
+ () =>
272
+ // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT
273
+ // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So
274
+ // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.
275
+ // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections
276
+ // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the
277
+ // `electric` namespace is provisioned later, exactly as the registry-derived schema is.
278
+ PGlite.create(dataDir, {
279
+ ...(bootAssets ?? {}),
280
+ // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
281
+ // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
282
+ // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
283
+ // create (the store initdbs empty).
284
+ ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
285
+ extensions: {
286
+ live,
287
+ },
288
+ }),
289
+ { dataDir: dataDirScheme },
290
+ // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time
291
+ // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).
292
+ )) as unknown as ClientPGlite;
293
+ }
30
294
 
31
295
  export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
32
296
  registry: TRegistry;
33
297
  electricUrl: string;
34
298
  writeUrl: string;
35
299
  getAuthToken?: () => Promise<string | undefined>;
300
+ /**
301
+ * Static headers added to **every** read-shape and write request, alongside the per-request
302
+ * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway
303
+ * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform
304
+ * function gateway expects. Sent even when no `getAuthToken` is supplied.
305
+ */
306
+ requestHeaders?: Record<string, string>;
307
+ /**
308
+ * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over
309
+ * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never
310
+ * see these. The seam exists because the two ingress points have opposite geometry: the write
311
+ * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its
312
+ * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed
313
+ * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per
314
+ * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need
315
+ * (e.g. `apikey`) in the shared {@link requestHeaders}.
316
+ */
317
+ writeRequestHeaders?: Record<string, string>;
36
318
  syncEnabled?: boolean;
37
- dataDir?: string;
319
+ /**
320
+ * The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
321
+ * is DERIVED from the environment (IndexedDB in a browser/worker, the filesystem on Bun/Node); a
322
+ * scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
323
+ * at boot. Defaults to a built-in overlay store name when omitted. A memory-backed store is not a product
324
+ * configuration — for the test/ephemeral lane, spread `memoryStoreForTests(...)` from
325
+ * `@pgxsinkit/client/testing` instead of naming one here.
326
+ */
327
+ storePath?: string;
328
+ /**
329
+ * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
330
+ * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
331
+ * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling
332
+ * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise
333
+ * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips
334
+ * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that
335
+ * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite
336
+ * falls back to loading its own assets, so this is a pure best-effort accelerator.
337
+ */
338
+ pgliteBootAssets?: Promise<PgliteBootAssets>;
38
339
  resetSubscriptionKeys?: string[];
39
340
  prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
40
341
  prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;
41
342
  onStatusChange?: (status: SyncRuntimeStatus) => void;
42
343
  onTableInitialSync?: (tableKey: string) => void;
344
+ /**
345
+ * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
346
+ * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile
347
+ * (journal recovery still runs, as it does on every path). Use it only when the caller has already
348
+ * applied the registry schema itself. Contrast the three PGlite-provenance seams:
349
+ * - {@link storePath} (default) — the client creates the store AND runs every post-create step.
350
+ * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
351
+ * the client still runs every post-create step (schema/prepare/reconcile), exactly as `storePath` does.
352
+ * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
353
+ *
354
+ * A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
355
+ * non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics
356
+ * assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading
357
+ * `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.
358
+ *
359
+ * Mutually exclusive with {@link precreatedPglite} (supplying both throws).
360
+ */
43
361
  pgliteInstance?: ClientPGlite;
362
+ /**
363
+ * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
364
+ * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
365
+ * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version
366
+ * reconcile all run exactly as on the {@link storePath} path. This is the difference from
367
+ * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that
368
+ * option's JSDoc for the three-way distinction.
369
+ *
370
+ * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
371
+ * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.
372
+ * - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager
373
+ * create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also
374
+ * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot
375
+ * dependency.
376
+ * - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as
377
+ * {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being
378
+ * swallowed by the reject-fallback).
379
+ */
380
+ precreatedPglite?: Promise<ClientPGlite>;
381
+ /**
382
+ * Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by
383
+ * {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's
384
+ * `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the
385
+ * bytes that travelled inside it). Three restore-only rules apply, none of them optional:
386
+ *
387
+ * - **Fresh target only.** Refused with {@link RestoreTargetExistsError} if a store already exists at the
388
+ * resolved {@link storePath} — restore never overlays a live store (that would corrupt the datadir); the
389
+ * remedy is a deliberate {@link SyncClient.destroy} of the existing store first.
390
+ * - **Always boots offline.** The engine boots with sync OFF regardless of {@link syncEnabled}/{@link autoSync}
391
+ * or anything captured in the backup — no shape streams, no read fetch, no flush, no convergence passes.
392
+ * Restore wins over an explicit online option (a debug-rail warning notes the override). The app inspects
393
+ * {@link SyncClient.diagnostics}, releases/discards the quarantined rows, then a subsequent NORMAL boot of
394
+ * the (now-persisted) store brings sync online — `loadDataDir` happens exactly once, on this restore boot.
395
+ * - **Journal quarantined.** Every non-terminal recovered row (`pending`/`sending`/`failed`) is moved to
396
+ * `quarantined` — nothing recovered from a backup auto-flushes (the write path has no `mutationId` dedupe
397
+ * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
398
+ * (`discardQuarantined`) them explicitly.
399
+ *
400
+ * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
401
+ * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
402
+ * with `restoreFrom` throws).
403
+ */
404
+ restoreFrom?: File | Blob;
405
+ /**
406
+ * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
407
+ * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
408
+ * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
409
+ * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version
410
+ * reconcile) and buffered in memory, with commits gated until those phases finish — so the network
411
+ * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
412
+ * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.
413
+ *
414
+ * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the
415
+ * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong
416
+ * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,
417
+ * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for
418
+ * every warm store).
419
+ */
420
+ freshStore?: boolean;
421
+ /**
422
+ * Hard cap on send attempts before a still-failing mutation is quarantined
423
+ * (ADR-0005 congestion policy). Defaults to the library's built-in cap.
424
+ */
425
+ maxMutationAttempts?: number;
426
+ /**
427
+ * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library
428
+ * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either
429
+ * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept
430
+ * overlay + quarantined journal rows so the entity accepts new mutations again.
431
+ */
432
+ onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;
433
+ /**
434
+ * Invoked when mutations are `conflicted` — a stale write the server declined under the
435
+ * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a
436
+ * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.
437
+ */
438
+ onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;
439
+ /**
440
+ * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the
441
+ * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay
442
+ * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.
443
+ */
444
+ onReject?: (rejected: MutationDetail[]) => void | Promise<void>;
445
+ /**
446
+ * Invoked on boot when the registry fingerprint differs from the one the local store was
447
+ * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the
448
+ * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is
449
+ * postponed (and retried on a later boot) rather than dropping owed data.
450
+ */
451
+ onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;
452
+ /**
453
+ * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.
454
+ * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`
455
+ * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.
456
+ * Omit it for fully-manual convergence (the mechanism primitives stay public either way).
457
+ */
458
+ autoSync?: ConvergenceTrigger;
459
+ /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */
460
+ onConvergencePass?: (error: unknown) => void;
461
+ /**
462
+ * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).
463
+ * The runtime enters the `degraded` phase and holds the read cache at the last applied commit
464
+ * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.
465
+ */
466
+ onSyncError?: (error: Error) => void;
467
+ /**
468
+ * Boot observability (ADR-0034): invoked exactly once, at boot completion, with the finalized
469
+ * {@link BootReport}. The push counterpart of {@link SyncClient.bootReport} (the pull) for consumers that
470
+ * want the numbers without polling — dashboards, CI budget gates. Never fired before initial sync; a
471
+ * `stop()`/`destroy()` before then means it never fires.
472
+ */
473
+ onBootReport?: (report: BootReport) => void;
474
+ /**
475
+ * @internal Boot mode stamped into the {@link BootReport} (ADR-0034). `defineSyncWorker` sets `"worker"`;
476
+ * absent → `"in-process"`. Not a behavior knob — it only labels the report.
477
+ */
478
+ bootMode?: BootReport["mode"];
479
+ /**
480
+ * @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
481
+ * minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
482
+ * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.
483
+ * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}
484
+ * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
485
+ */
486
+ provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
44
487
  }
45
488
 
46
489
  export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {
@@ -51,6 +494,129 @@ export interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey
51
494
  delete: (entityKey: Record<string, string>) => Promise<void>;
52
495
  }
53
496
 
497
+ /**
498
+ * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into
499
+ * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the
500
+ * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.
501
+ */
502
+ export interface SyncTransactionTableHandle<
503
+ TRegistry extends SyncTableRegistry,
504
+ TKey extends SyncTableName<TRegistry>,
505
+ > {
506
+ create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;
507
+ update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
508
+ delete: (entityKey: Record<string, string>) => void;
509
+ /**
510
+ * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity
511
+ * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base
512
+ * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the
513
+ * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only
514
+ * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there
515
+ * is no local row to update and nothing to show optimistically.
516
+ *
517
+ * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful
518
+ * only inside a `transaction({ mode: "pessimistic" })` block (or over a statically-pessimistic table). An
519
+ * optimistic-routed blind write has nothing to converge and THROWS at enqueue.
520
+ *
521
+ * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does
522
+ * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered
523
+ * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a
524
+ * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.
525
+ */
526
+ updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;
527
+ }
528
+
529
+ /** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */
530
+ export interface SyncTransaction<TRegistry extends SyncTableRegistry> {
531
+ tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };
532
+ }
533
+
534
+ /**
535
+ * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server
536
+ * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes
537
+ * in the background, so its `acks` are empty.
538
+ */
539
+ export interface SyncTransactionResult {
540
+ acks: MutationAck[];
541
+ }
542
+
543
+ /** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */
544
+ export interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {
545
+ toSQL(): { sql: string; params: unknown[] };
546
+ }
547
+
548
+ /**
549
+ * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle
550
+ * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.
551
+ */
552
+ export type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (
553
+ client: SyncClient<TRegistry>,
554
+ ) => DrizzleQueryBuilder<TRows>;
555
+
556
+ /**
557
+ * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can
558
+ * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those
559
+ * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no
560
+ * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.
561
+ */
562
+ export interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {
563
+ use?: readonly SyncTableName<TRegistry>[];
564
+ build: GuardedQueryFn<TRegistry, TRows>;
565
+ }
566
+
567
+ /**
568
+ * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads
569
+ * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.
570
+ * Shared by the live React hooks and the non-live facade.
571
+ */
572
+ export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
573
+ /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */
574
+ sql: string;
575
+ /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */
576
+ use?: readonly SyncTableName<TRegistry>[];
577
+ }
578
+
579
+ /**
580
+ * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks
581
+ * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle
582
+ * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;
583
+ * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached
584
+ * client runs the live query in the worker and streams DIFFs across the bridge.
585
+ */
586
+ export interface SubscribeLiveRowsInput {
587
+ sql: string;
588
+ params: readonly unknown[];
589
+ /**
590
+ * The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the
591
+ * compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose
592
+ * tables share a column name compiles to duplicate output names — which PGlite's `live` extension
593
+ * refuses to materialise (`column "title" specified more than once`) and which silently collapse
594
+ * same-named columns even in a plain query. When supplied, the seam wraps the query so every output
595
+ * column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
596
+ * by alias (the `@pgxsinkit/react` hooks do). Omit for a raw or non-colliding query — the seam then
597
+ * leaves the SQL untouched and rows stay keyed by the underlying column names (backward-compatible).
598
+ */
599
+ fields?: readonly string[];
600
+ /**
601
+ * The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query.
602
+ * When {@link fields} is supplied the result columns are the aliases, so a PK column here must be named
603
+ * by its ALIAS (the aliased result column), not the underlying source column.
604
+ */
605
+ pkColumns?: readonly string[];
606
+ /**
607
+ * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can
608
+ * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the
609
+ * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.
610
+ */
611
+ use?: readonly string[];
612
+ }
613
+
614
+ /** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */
615
+ export interface LiveRowsSubscription<TRow> {
616
+ initialRows: TRow[];
617
+ unsubscribe: () => void;
618
+ }
619
+
54
620
  export interface SyncClient<TRegistry extends SyncTableRegistry> {
55
621
  drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
56
622
  pglite: ClientPGlite;
@@ -62,7 +628,24 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
62
628
  status: SyncRuntimeStatus;
63
629
  start: () => Promise<void>;
64
630
  stop: () => Promise<void>;
65
- destroy: () => Promise<void>;
631
+ /**
632
+ * Wipe the entire local store (synced cache + overlay + journal) and close the handle
633
+ * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so
634
+ * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.
635
+ * Runs under the single lifecycle slot (ADR-0035 decision 4): a concurrent export — or another
636
+ * `destroy`/`discardEphemeral`/`dropReadCache` — rejects with a {@link LifecycleBusyError} rather
637
+ * than interleaving the wipe with a running export.
638
+ */
639
+ destroy: (options?: { force?: boolean }) => Promise<void>;
640
+ /**
641
+ * Drop and rebuild the reconstructible synced read cache, preserving the overlay and
642
+ * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or
643
+ * stale read cache without losing un-flushed writes. Runs under the single lifecycle slot
644
+ * (ADR-0035 decision 4) — it drops and rebuilds the synced tables, so an export must not capture a
645
+ * half-rebuilt cache; a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
646
+ * {@link LifecycleBusyError}.
647
+ */
648
+ dropReadCache: () => Promise<void>;
66
649
  flush: (table?: SyncTableName<TRegistry>) => Promise<void>;
67
650
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
68
651
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
@@ -81,11 +664,239 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
81
664
  delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;
82
665
  batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;
83
666
  };
667
+ /**
668
+ * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic
669
+ * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a
670
+ * stale edit instead of resolving it as a new write.
671
+ */
672
+ discardConflict: <TKey extends SyncTableName<TRegistry>>(
673
+ table: TKey,
674
+ entityKey: Record<string, string>,
675
+ ) => Promise<void>;
676
+ /**
677
+ * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic
678
+ * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write
679
+ * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the
680
+ * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer
681
+ * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay
682
+ * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.
683
+ */
684
+ discardQuarantined: <TKey extends SyncTableName<TRegistry>>(
685
+ table: TKey,
686
+ entityKey: Record<string, string>,
687
+ ) => Promise<void>;
84
688
  diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;
689
+ /**
690
+ * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and
691
+ * worker-attached client (on the latter the statement runs in the worker). The statement runs raw
692
+ * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it
693
+ * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
694
+ * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
695
+ * store, not to read app state or mutate it.
696
+ */
697
+ rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
698
+ /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
699
+ rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
700
+ /**
701
+ * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).
702
+ * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every
703
+ * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any
704
+ * lazy relation the SQL still references but that is not active, so the result is never silently
705
+ * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds
706
+ * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.
707
+ */
708
+ query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;
709
+ /** {@link query} returning the first row, or null when empty. */
710
+ queryRow: <TRows extends readonly unknown[]>(
711
+ build: GuardedQueryFn<TRegistry, TRows>,
712
+ ) => Promise<TRows[number] | null>;
713
+ /**
714
+ * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL
715
+ * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those
716
+ * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use
717
+ * {@link query} instead (no `use` needed).
718
+ */
719
+ queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;
720
+ /** {@link queryRaw} returning the first row, or null when empty. */
721
+ queryRawRow: <TRows extends readonly unknown[]>(
722
+ spec: GuardedRawQuerySpec<TRegistry, TRows>,
723
+ ) => Promise<TRows[number] | null>;
724
+ /**
725
+ * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held
726
+ * out of the eager boot, resolving once their initial sync completes. Idempotent — eager or
727
+ * already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`
728
+ * read, or as the manual escape hatch the tripwire points to.
729
+ */
730
+ ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
731
+ /**
732
+ * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`
733
+ * relation; true for eager relations once boot completes (and always when sync is disabled).
734
+ */
735
+ isSynced: (key: SyncTableName<TRegistry>) => boolean;
736
+ /**
737
+ * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its
738
+ * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot
739
+ * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it
740
+ * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes
741
+ * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim
742
+ * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`
743
+ * relation, idle-eviction is otherwise automatic at session end.
744
+ */
745
+ desync: (key: SyncTableName<TRegistry>) => Promise<void>;
746
+ /**
747
+ * Drop an **ephemeral** relation's local rows and revert it to dormant (ADR-0021) — the narrow,
748
+ * scoped twin of {@link desync}. It runs the identical group-teardown machinery (stop the group stream,
749
+ * clear the persisted lazy activation, reset the persisted subscription, clean-truncate every member),
750
+ * but under a STRICTER gate: EVERY member of the relation's consistency group must be `retention:
751
+ * "ephemeral"` — it refuses (naming the offender) if any member is persistent. Where a `desync` from one
752
+ * tab reverts the shared group for every attached tab (the SharedWorker footgun), `discardEphemeral` is
753
+ * safe under multi-tab because an ephemeral window is per-delivery-session and inherently single-consumer
754
+ * — nothing durable, and no other tab, depends on it. Refuses an `eager` relation (always-on, would
755
+ * immediately re-sync) and a group that owes the server unsettled writes, exactly as `desync` does. The
756
+ * finalize primitive for a secure-delivery window: drop the local rows at session end without touching a
757
+ * durable relation. Note the drop is local-lifecycle only: a later re-subscription re-activates the lazy
758
+ * group and re-streams whatever the SERVER still serves — post-finalize non-redelivery is the server
759
+ * gate's guarantee (e.g. a consumed server-owned cursor), not this method's. Runs under the single
760
+ * lifecycle slot (ADR-0035 decision 4): a concurrent export (or `destroy`/`dropReadCache`) rejects with a
761
+ * {@link LifecycleBusyError} rather than interleaving the cache truncate with a running export.
762
+ */
763
+ discardEphemeral: (key: SyncTableName<TRegistry>) => Promise<void>;
764
+ /**
765
+ * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads
766
+ * (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation
767
+ * auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the
768
+ * query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could
769
+ * not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`
770
+ * are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or
771
+ * `ensureSynced` first.
772
+ */
773
+ prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;
774
+ /**
775
+ * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every
776
+ * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.
777
+ *
778
+ * - `mode: "pessimistic"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint
779
+ * and this call resolves only once the server has decided. The result's `acks` carry each member's
780
+ * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for
781
+ * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A
782
+ * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with
783
+ * no local base row and no overlay, for a write target excluded from the actor's read shape.
784
+ * - `mode: "optimistic"` — an atomic batch enqueue that flushes in the background (empty `acks`).
785
+ */
786
+ transaction: (
787
+ options: { mode: WriteMode },
788
+ run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,
789
+ ) => Promise<SyncTransactionResult>;
790
+ /**
791
+ * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's
792
+ * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)
793
+ * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The
794
+ * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the
795
+ * same readiness as a synchronous snapshot.
796
+ */
797
+ groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;
798
+ /**
799
+ * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
800
+ * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
801
+ * directly), so they run unchanged against both the in-process client (which implements it over
802
+ * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the
803
+ * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.
804
+ */
805
+ subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(
806
+ input: SubscribeLiveRowsInput,
807
+ onRows: (rows: TRow[]) => void,
808
+ ) => Promise<LiveRowsSubscription<TRow>>;
809
+ /**
810
+ * Boot observability (ADR-0034): the engine's most recent COMPLETED boot report, or `null` before the
811
+ * first boot finalizes (and after a `stop()`/`destroy()` that preceded initial sync). Pull — so a
812
+ * late-attaching tab can read a boot that predates it; in worker mode it round-trips to the worker's
813
+ * stored report. The push counterpart is the `onBootReport` client option.
814
+ */
815
+ bootReport: () => Promise<BootReport | null>;
816
+ /**
817
+ * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
818
+ * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
819
+ * `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine
820
+ * suspension, no tab disruption), so it never blocks and is the only lossless export an offline device
821
+ * with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under
822
+ * the single lifecycle slot: a second export (or, later, `destroy`/`discardEphemeral`) attempted while
823
+ * one is in flight rejects immediately with a {@link LifecycleBusyError} — retry once it settles.
824
+ * Resolves to the artefact `File` plus an {@link ExportReport} (phase timings + a diagnostics snapshot).
825
+ */
826
+ exportStore: (options?: StoreExportOptions) => Promise<StoreExportResult>;
827
+ /**
828
+ * Take a **diagnostic dump** (ADR-0035): human-readable SQL of EVERYTHING the store holds — synced tables,
829
+ * the `_overlay`/`_mutations` journal (unflushed writes included — the evidence a diagnostic exists for),
830
+ * the `pgxsinkit` metadata schema, the read-model views, and the reconcile functions/triggers — via
831
+ * `pg_dump`. To keep `pg_dump`'s `DEALLOCATE ALL` away from the live engine, the dump runs against a
832
+ * memory-backed THROWAWAY clone booted from a live datadir dump (ADR-0035 addendum): the running store is
833
+ * never suspended and no tab is disrupted. Awaits engine-ready rather than rejecting during boot, then
834
+ * runs under the single lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects
835
+ * immediately with a {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a
836
+ * {@link DiagnosticDumpReport} (phase timings + a diagnostics snapshot). Active ephemeral (`pg_temp`)
837
+ * clusters are absent by construction (ADR-0035 decision 5 — `pg_dump` ignores temp objects).
838
+ */
839
+ exportDiagnostics: (options?: DiagnosticExportOptions) => Promise<DiagnosticExportResult>;
840
+ /**
841
+ * Take a **data export** (ADR-0035): the PORTABLE artefact — the synced tables and the enum types they
842
+ * depend on, schema + data, nothing of pgxsinkit's machinery — as SQL loadable into a vanilla Postgres. It
843
+ * is a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner` (one `-t` per
844
+ * physical synced table; ephemeral/read-projection entries excluded by construction), run against the same
845
+ * memory-backed THROWAWAY clone the diagnostic dump uses — so the live engine is never touched.
846
+ *
847
+ * Unlike the other two exports it GUARDS the journal (decision 3): a strict export requires a DRAINED
848
+ * journal — all mutation counts zero, including `acked` writes whose synced echo has not landed (they live
849
+ * only in the Overlay). The drain flushes drainable rows and awaits convergence up to
850
+ * `drainJournal.timeoutMs` (default `15_000`); non-drainable states (`failed`/`quarantined`/`conflicted`)
851
+ * fail FAST with a {@link DataExportDrainError} carrying the diagnostics. `drainJournal: false` is the
852
+ * escape hatch — export synced state as-is (unflushed writes absent; `report.escapeHatch` records it). An
853
+ * offline device with a clean journal exports strictly and instantly; one with a dirty journal cannot
854
+ * produce a strict export (its lossless option is `exportStore`).
855
+ *
856
+ * Awaits engine-ready rather than rejecting during boot, then runs the whole drain+dump under the single
857
+ * lifecycle slot — a concurrent export (or `destroy`/`discardEphemeral`) rejects with a
858
+ * {@link LifecycleBusyError}. Resolves to the SQL `File` (`application/sql`) plus a {@link DataExportReport}
859
+ * (drain + clone-pipeline phase timings, the applied `-t` table list, and the escape-hatch flag).
860
+ */
861
+ exportData: (options?: DataExportOptions) => Promise<DataExportResult>;
85
862
  }
86
863
 
87
864
  export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };
88
865
 
866
+ /**
867
+ * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
868
+ * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
869
+ * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
870
+ * of this contract. `rowMode: "array"` is what `@electric-sql/pglite-repl` asks for on every exec.
871
+ */
872
+ export interface RawQueryOptions {
873
+ rowMode?: "object" | "array";
874
+ }
875
+
876
+ /** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */
877
+ export interface ReplInspectionSurface {
878
+ query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
879
+ exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
880
+ }
881
+
882
+ /**
883
+ * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
884
+ * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter
885
+ * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is
886
+ * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).
887
+ * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
888
+ */
889
+ export function replAdapter(
890
+ client: Pick<SyncClient<SyncTableRegistry>, "rawQuery" | "rawExec">,
891
+ ): ReplInspectionSurface {
892
+ return {
893
+ // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: "array" }` and renders
894
+ // each row with `row.map`, so dropping the options here breaks every REPL statement.
895
+ query: (sql, params, options) => client.rawQuery(sql, params, options),
896
+ exec: (sql, options) => client.rawExec(sql, options),
897
+ };
898
+ }
899
+
89
900
  export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
90
901
  options: CreateSyncClientOptions<TRegistry>,
91
902
  ): Promise<SyncClient<TRegistry>> {
@@ -99,75 +910,665 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
99
910
  resolveReady = resolve;
100
911
  });
101
912
 
913
+ if (options.pgliteInstance && options.precreatedPglite) {
914
+ throw new Error(
915
+ "createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).",
916
+ );
917
+ }
918
+
919
+ // Restore (ADR-0035 decision 6) owns the store's CREATION — the backup tarball is a `loadDataDir` seed on
920
+ // the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already
921
+ // exists and is provisioned). Fail loudly rather than silently ignore one.
922
+ const restoreBoot = options.restoreFrom != null;
923
+ if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
924
+ throw new Error(
925
+ "createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).",
926
+ );
927
+ }
928
+
929
+ // Restore ALWAYS boots offline (ADR-0035 decision 6), regardless of `syncEnabled`/`autoSync` or anything
930
+ // captured in the backup: no shape streams, no read fetch, no flush, no convergence passes. The app deals
931
+ // with the quarantined journal, then a subsequent NORMAL boot brings sync online. Restore wins over an
932
+ // explicit online option — warn on the debug rail so the override is visible rather than silent.
933
+ if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {
934
+ syncDebug("boot restore forces offline — ignoring the online sync option for this restore boot", {
935
+ syncEnabled: options.syncEnabled === true,
936
+ autoSync: options.autoSync != null,
937
+ });
938
+ }
939
+ const syncEnabled = restoreBoot ? false : (options.syncEnabled ?? true);
940
+ // ADR-0032 S4 overlap flag, computed once up front so the boot report and the prefetch gate agree.
941
+ const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
942
+
943
+ // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
944
+ // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
945
+ const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
946
+ mode: options.bootMode ?? "in-process",
947
+ freshStore: options.freshStore === true,
948
+ overlapPrefetch,
949
+ registryFingerprint: fingerprintRegistry(options.registry),
950
+ });
951
+ // The single engine lifecycle slot (ADR-0035 decision 4). The three exports plus the destructive
952
+ // lifecycle ops — `destroy()`, `discardEphemeral()`, and `dropReadCache()` — all serialise through it,
953
+ // so a wipe/rebuild can never interleave a running export (nor vice versa): the slot rejects the second
954
+ // entrant with a typed LifecycleBusyError in either direction.
955
+ const lifecycleSlot = createLifecycleSlot();
956
+
957
+ let finalizedBootReport: BootReport | null = null;
958
+ const finalizeBootReport = () => {
959
+ if (finalizedBootReport) return;
960
+ finalizedBootReport = bootReportBuilder.finalize();
961
+ options.onBootReport?.(finalizedBootReport);
962
+ };
963
+
964
+ // The testing marker (ADR-0036 decision 3), read once off the options object: `"memory"` selects the
965
+ // memory backend for a client-owned create AND acknowledges the BYO seam; `"acknowledged"` only unlocks
966
+ // the BYO refusal. Absent for every production consumer — the marker rides in only via
967
+ // `@pgxsinkit/client/testing`, never named in a public type.
968
+ const testStoreMarker = readTestStoreMarker(options);
969
+ const backendOverride = testStoreMarker === "memory" ? ("memory" as const) : undefined;
970
+
971
+ // Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
972
+ // `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.
973
+ const createClientOptions: CreateClientPGliteOptions = {
974
+ ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
975
+ ...(backendOverride ? { backendOverride } : {}),
976
+ // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
977
+ // mutually exclusive with the BYO instance seams (checked above), so it only ever rides a client-owned
978
+ // create — never the adopt paths, which leave `restoreFrom` unread.
979
+ ...(restoreBoot ? { restoreFrom: options.restoreFrom } : {}),
980
+ };
981
+ const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
982
+
983
+ // Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
984
+ // brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
985
+ // half-write) an existing datadir; the memory test lane is fresh by construction, so this is a no-op there.
986
+ if (restoreBoot) {
987
+ if (await storeTargetExists(fallbackStorePath, backendOverride)) {
988
+ throw new RestoreTargetExistsError(fallbackStorePath);
989
+ }
990
+ }
991
+ // Time a client-owned `createClientPGlite` into `phases.pgliteCreateMs`; an ADOPTED store (spare or
992
+ // caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
993
+ const timedCreate = async (): Promise<ClientPGlite> => {
994
+ const startedAt = performance.now();
995
+ const created = await createClientPGlite(fallbackStorePath, createClientOptions);
996
+ bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
997
+ return created;
998
+ };
999
+
1000
+ // Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
1001
+ // acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the
1002
+ // `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are
1003
+ // an undefined dataDir (PGlite's in-memory default) and an explicit memory store. Checked AFTER a
1004
+ // successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the
1005
+ // `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).
1006
+ const refuseIfNonPersistent = (instance: ClientPGlite): void => {
1007
+ if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
1008
+ const observed = classifyNonPersistentDataDir((instance as { dataDir?: string }).dataDir);
1009
+ if (observed !== null) throw new NonPersistentStoreError(observed);
1010
+ };
1011
+
102
1012
  let pglite: ClientPGlite;
1013
+ // Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates
1014
+ // whether the provision stamp is honoured (ADR-0034).
1015
+ let adoptedPrecreated = false;
103
1016
  if (options.pgliteInstance) {
1017
+ // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
1018
+ // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc. No create here → `pgliteCreateMs` null.
1019
+ refuseIfNonPersistent(options.pgliteInstance);
104
1020
  pglite = options.pgliteInstance;
105
- // Assume schema is already applied by caller
1021
+ } else if (options.precreatedPglite) {
1022
+ // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every
1023
+ // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
1024
+ // `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN
1025
+ // branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,
1026
+ // outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create
1027
+ // that never produced a store).
1028
+ const outcome = await options.precreatedPglite.then(
1029
+ (instance) => ({ ok: true as const, instance }),
1030
+ (error: unknown) => ({ ok: false as const, error }),
1031
+ );
1032
+ if (outcome.ok) {
1033
+ refuseIfNonPersistent(outcome.instance);
1034
+ pglite = outcome.instance;
1035
+ adoptedPrecreated = true;
1036
+ } else {
1037
+ syncDebug("boot precreated pglite rejected — falling back to storePath create", {
1038
+ error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
1039
+ });
1040
+ pglite = await timedCreate();
1041
+ }
106
1042
  } else {
107
- pglite = (await PGlite.create(options.dataDir ?? "idb://pgxsinkit-overlay-v1", {
108
- extensions: {
109
- electric: createElectricExtension(),
110
- live,
111
- },
112
- })) as ClientPGlite;
1043
+ pglite = await timedCreate();
1044
+ }
1045
+
1046
+ // Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
1047
+ // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`
1048
+ // null (the create was paid at provision time, off this boot's clock).
1049
+ if (adoptedPrecreated && options.provisionStamp) {
1050
+ const stamp = await options.provisionStamp.catch(() => null);
1051
+ if (stamp) {
1052
+ bootReportBuilder.setProvision({
1053
+ initdbMs: stamp.initdbMs,
1054
+ provisionedMsBeforeBoot: Math.max(0, bootReportBuilder.bootStartPerf - stamp.provisionReadyAt),
1055
+ });
1056
+ }
1057
+ }
1058
+
1059
+ // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths
1060
+ // (pgliteInstance, precreatedPglite, storePath) — ADR-0032 S1. The engine is no longer a create-time
1061
+ // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no
1062
+ // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former
1063
+ // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached
1064
+ // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when
1065
+ // the extension provided it at create time. `engine.close` (the former extension close hook — abort every
1066
+ // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment
1067
+ // `pglite.close()` used to trigger it.
1068
+ const engine: SyncEngine = await createSyncEngine(pglite);
1069
+ (pglite as { electric: SyncEngine["namespace"] }).electric = engine.namespace;
1070
+
1071
+ // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to
1072
+ // the right steady-state phase (`ready` if already caught up, else `syncing`).
1073
+ let initialSyncCompleted = false;
1074
+ // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a
1075
+ // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare
1076
+ // `onSyncActivity` must not clear it.
1077
+ let degradedReason: "stream" | "commit" | null = null;
1078
+
1079
+ // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────
1080
+ // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape
1081
+ // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which
1082
+ // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then
1083
+ // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the
1084
+ // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact
1085
+ // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).
1086
+ // (`overlapPrefetch` is computed once up front — see the boot-report builder above.)
1087
+ let openDbGate: () => void = () => {};
1088
+ const dbReady = overlapPrefetch
1089
+ ? new Promise<void>((resolve) => {
1090
+ openDbGate = resolve;
1091
+ })
1092
+ : null;
1093
+
1094
+ // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —
1095
+ // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.
1096
+ const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({
1097
+ syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),
1098
+ registry: options.registry,
1099
+ promotedGroups,
1100
+ ...(dbReady ? { dbReady } : {}),
1101
+ // Boot observability (ADR-0034): the collector opens a per-boot-group accumulator (rows/requests/fetch/
1102
+ // apply wall) for the eager + promoted groups; lazy on-demand starts get none, so they never enter the report.
1103
+ bootCollector: bootReportBuilder,
1104
+ // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.
1105
+ onLazyActivated: (groupKey) => {
1106
+ void writeLazyGroupActivation(pglite, options.registry, groupKey);
1107
+ },
1108
+ // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session
1109
+ // never wedges on JWT expiry. Read and write share one token lifecycle.
1110
+ ...(options.getAuthToken || options.requestHeaders
1111
+ ? {
1112
+ shapeHeaders: buildShapeHeaders({
1113
+ ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
1114
+ ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
1115
+ }),
1116
+ }
1117
+ : {}),
1118
+ ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),
1119
+ // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and
1120
+ // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).
1121
+ onGroupReady: (groupKey) => {
1122
+ status.groups = { ...(status.groups ?? {}), [groupKey]: true };
1123
+ options.onStatusChange?.(status);
1124
+ },
1125
+ onInitialSync: () => {
1126
+ initialSyncCompleted = true;
1127
+ status.phase = "ready";
1128
+ options.onStatusChange?.(status);
1129
+ // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp
1130
+ // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).
1131
+ syncDebug("boot client ready");
1132
+ // Boot observability (ADR-0034): finalize the report at exactly this moment — the `boot client ready`
1133
+ // rail line — and fire the one-shot `onBootReport` push. Idempotent, so the sync-disabled path's own
1134
+ // finalize below never double-fires it.
1135
+ finalizeBootReport();
1136
+ resolveReady();
1137
+ },
1138
+ onSyncError: (error) => {
1139
+ // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than
1140
+ // letting the read cache silently diverge from the server. Sticky (see below).
1141
+ status.phase = "degraded";
1142
+ degradedReason = "commit";
1143
+ status.lastError = error.message;
1144
+ options.onStatusChange?.(status);
1145
+ options.onSyncError?.(error);
1146
+ },
1147
+ // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting
1148
+ // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a
1149
+ // commit-failure degraded. Cleared on the next successful batch below.
1150
+ onReadStreamError: (error) => {
1151
+ // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is
1152
+ // the more serious signal — a stream blip must not overwrite it).
1153
+ if (status.phase === "auth-needed") return;
1154
+ if (status.phase === "degraded" && degradedReason === "commit") return;
1155
+ // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most
1156
+ // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one
1157
+ // way then another reports the current cause (observability).
1158
+ status.phase = "degraded";
1159
+ degradedReason = "stream";
1160
+ status.lastError = error.message;
1161
+ options.onStatusChange?.(status);
1162
+ },
1163
+ // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered
1164
+ // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,
1165
+ // so only `onSyncError` clearing (a clean commit) would lift it.
1166
+ onSyncActivity: () => {
1167
+ if (status.phase === "auth-needed" || (status.phase === "degraded" && degradedReason === "stream")) {
1168
+ degradedReason = null;
1169
+ status.phase = initialSyncCompleted ? "ready" : "syncing";
1170
+ options.onStatusChange?.(status);
1171
+ }
1172
+ },
1173
+ // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the
1174
+ // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token
1175
+ // provider exists — without one there is no auth lifecycle to track.
1176
+ ...(options.getAuthToken
1177
+ ? {
1178
+ onAuthError: () => {
1179
+ if (status.phase !== "auth-needed") {
1180
+ status.phase = "auth-needed";
1181
+ options.onStatusChange?.(status);
1182
+ }
1183
+ },
1184
+ }
1185
+ : {}),
1186
+ });
1187
+
1188
+ // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,
1189
+ // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to
1190
+ // reset, so both DB reads the sequential path makes first are skipped here.
1191
+ let earlySync: ReturnType<typeof startConfiguredSync> | null = null;
1192
+ let earlySyncStartedAt = 0;
1193
+ if (overlapPrefetch) {
1194
+ status.isRunning = true;
1195
+ status.phase = "syncing";
1196
+ options.onStatusChange?.(status);
1197
+ earlySyncStartedAt = performance.now();
1198
+ earlySync = startConfiguredSync(
1199
+ pglite as unknown as Parameters<typeof startConfiguredSync>[0],
1200
+ buildStartOptions(new Set()),
1201
+ );
1202
+ }
113
1203
 
1204
+ if (!options.pgliteInstance) {
114
1205
  if (options.prepareLocalDbBeforeSchema) {
115
- await options.prepareLocalDbBeforeSchema(pglite);
1206
+ const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
1207
+ await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
116
1208
  }
117
1209
 
118
1210
  const schemaSql = generateLocalSchemaSql(options.registry);
119
- await pglite.exec(schemaSql);
1211
+ await bootReportBuilder.phase("schemaExec", "boot local schema", () => pglite.exec(schemaSql));
120
1212
 
121
1213
  if (options.prepareLocalDb) {
122
- await options.prepareLocalDb(pglite);
1214
+ const prepareLocalDb = options.prepareLocalDb;
1215
+ await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDb(pglite));
123
1216
  }
124
1217
  }
125
1218
 
1219
+ // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):
1220
+ // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone
1221
+ // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.
1222
+ const writePathHeaders =
1223
+ options.requestHeaders || options.writeRequestHeaders
1224
+ ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }
1225
+ : undefined;
1226
+
1227
+ const mutationRuntime = createMutationRuntime({
1228
+ db: pglite,
1229
+ registry: options.registry,
1230
+ writeUrl: options.writeUrl,
1231
+ ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
1232
+ ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
1233
+ ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
1234
+ ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),
1235
+ ...(options.onConflict ? { onConflict: options.onConflict } : {}),
1236
+ ...(options.onReject ? { onReject: options.onReject } : {}),
1237
+ });
1238
+
1239
+ // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then
1240
+ // reconcile the local store against the current registry fingerprint before sync starts
1241
+ // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).
1242
+ await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.recoverSending());
1243
+
1244
+ // Restore-boot quarantine (ADR-0035 decision 6): the moment a store is booted FROM a backup, every
1245
+ // non-terminal recovered journal row (`pending`/`sending`/`failed`) is parked in `quarantined` so nothing
1246
+ // recovered auto-flushes — the write path has no `mutationId` dedupe ledger, making replay unsafe on
1247
+ // last-write-wins tables (silent stale reverts) and colliding on a recreated PK. Runs ONLY on the restore
1248
+ // boot (loadDataDir happens exactly once); a subsequent normal boot of the persisted store never re-runs
1249
+ // it. Placed AFTER `recoverSending` (which lifts any `sending` back to `pending`) so a single pass over
1250
+ // pending/sending/failed catches the lot. The app then inspects `diagnostics()` and releases/discards them.
1251
+ if (restoreBoot) {
1252
+ await mutationRuntime.quarantineRecovered();
1253
+ }
1254
+
1255
+ let versionEvent: LocalStoreVersionEvent | null = null;
1256
+
1257
+ // Registry-fingerprint mismatch on restore (ADR-0035 decision 6): an old backup restored against a NEWER
1258
+ // registry needs NO special handling — the existing local-schema-evolution path (ADR-0006) owns it, and
1259
+ // restore composes with it for free. On this restore boot the quarantine above ran FIRST, so every
1260
+ // recovered row now counts toward `owedMutations` (pending+sending+failed+quarantined) inside
1261
+ // `rebuildReadCacheOrDefer`: a stale fingerprint therefore DEFERS the read-cache rebuild rather than
1262
+ // dropping the quarantined writes, exactly as it would for any store that owes work. The rebuild completes
1263
+ // on a later boot once the app has released/discarded the quarantine and drained the journal.
1264
+ if (!options.pgliteInstance) {
1265
+ versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
1266
+ reconcileLocalStoreVersion({
1267
+ db: pglite,
1268
+ registry: options.registry,
1269
+ runtime: mutationRuntime,
1270
+ ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),
1271
+ }),
1272
+ );
1273
+ }
1274
+
126
1275
  const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
1276
+ // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.
1277
+ const lazyGuardIndex = buildLazyGuardIndex(options.registry);
127
1278
 
128
- const syncEnabled = options.syncEnabled ?? true;
129
1279
  let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;
1280
+ let convergenceDriver: ConvergenceDriver | null = null;
130
1281
 
131
1282
  status.isRunning = true;
132
1283
 
1284
+ // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile
1285
+ // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op
1286
+ // on the sequential path (`openDbGate` is the empty default there).
1287
+ openDbGate();
1288
+
133
1289
  if (syncEnabled) {
134
- await resetSubscriptionsIfRequested(pglite, options.resetSubscriptionKeys);
1290
+ if (earlySync) {
1291
+ // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle
1292
+ // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and
1293
+ // `onInitialSync` still gates `ready` on a fully-consistent first paint). The construction was kicked
1294
+ // off before schema exec, so time it here (concurrent-segment wall) into `phases.syncStartMs`.
1295
+ sync = await earlySync;
1296
+ bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
1297
+ bootReportBuilder.markSyncStartDone();
1298
+ } else {
1299
+ // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt
1300
+ // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).
1301
+ // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the
1302
+ // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a
1303
+ // fresh re-stream (ADR-0006).
1304
+ const resetKeys =
1305
+ versionEvent?.status === "rebuilt"
1306
+ ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
1307
+ : options.resetSubscriptionKeys;
1308
+ await resetSubscriptionsIfRequested(pglite, resetKeys);
135
1309
 
136
- status.phase = "syncing";
137
- options.onStatusChange?.(status);
1310
+ status.phase = "syncing";
1311
+ options.onStatusChange?.(status);
138
1312
 
139
- const syncAuthToken = options.getAuthToken ? await options.getAuthToken() : undefined;
1313
+ // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
1314
+ // (ADR-0021 §2); the sync engine does no DB read of its own.
1315
+ const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
140
1316
 
141
- sync = await startConfiguredSync(pglite as unknown as Parameters<typeof startConfiguredSync>[0], {
142
- syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),
143
- ...(syncAuthToken ? { shapeHeaders: { Authorization: `Bearer ${syncAuthToken}` } } : {}),
144
- ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),
145
- onInitialSync: () => {
146
- status.phase = "ready";
147
- options.onStatusChange?.(status);
148
- resolveReady();
149
- },
150
- });
1317
+ sync = await bootReportBuilder.phase("syncStart", "boot sync start", () =>
1318
+ startConfiguredSync(
1319
+ pglite as unknown as Parameters<typeof startConfiguredSync>[0],
1320
+ buildStartOptions(promotedGroups),
1321
+ ),
1322
+ );
1323
+ bootReportBuilder.markSyncStartDone();
1324
+ }
151
1325
  } else {
152
1326
  status.phase = "ready";
153
1327
  options.onStatusChange?.(status);
1328
+ // Sync disabled: there is no `onInitialSync` gate, but boot IS complete — finalize the report at the
1329
+ // same moment `ready` resolves (ADR-0034). Idempotent with the sync path's finalize.
1330
+ finalizeBootReport();
154
1331
  resolveReady();
155
1332
  }
156
1333
 
157
- const mutationRuntime = createMutationRuntime({
158
- db: pglite,
159
- registry: options.registry,
160
- writeUrl: options.writeUrl,
161
- ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
162
- });
1334
+ // Restore boots offline (ADR-0035 decision 6): never stand up the convergence driver on a restore boot,
1335
+ // so an `autoSync` trigger the caller passed (even an online one) drives NO flush/reconcile passes — the
1336
+ // recovered journal is quarantined and must stay put until the app releases it and a normal boot goes
1337
+ // online. On every other boot the driver behaves exactly as before.
1338
+ if (options.autoSync && !restoreBoot) {
1339
+ convergenceDriver = createConvergenceDriver({
1340
+ client: {
1341
+ flush: () => mutationRuntime.flush(),
1342
+ reconcile: () => mutationRuntime.reconcile(),
1343
+ },
1344
+ trigger: options.autoSync,
1345
+ ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),
1346
+ });
163
1347
 
164
- await mutationRuntime.recoverSending();
1348
+ // Start driving convergence once the initial sync is ready, so a pass never races the
1349
+ // first shape load. stop()/destroy() halt it.
1350
+ void ready.then(() => convergenceDriver?.start());
1351
+ }
165
1352
 
1353
+ // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the
1354
+ // write flushes immediately rather than waiting for the trigger's next interval tick. This is what
1355
+ // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the
1356
+ // caller drives `flush`/`reconcile` itself.
1357
+ const requestConvergence = () => convergenceDriver?.requestPass();
166
1358
  const mutate: SyncClient<TRegistry>["mutate"] = {
167
- create: (table, input) => mutationRuntime.create(table, input),
168
- update: (table, entityKey, patch) => mutationRuntime.update(table, entityKey, patch),
169
- delete: (table, entityKey) => mutationRuntime.delete(table, entityKey),
170
- batch: (items) => mutationRuntime.batch(items),
1359
+ create: async (table, input) => {
1360
+ await mutationRuntime.create(table, input);
1361
+ requestConvergence();
1362
+ },
1363
+ update: async (table, entityKey, patch) => {
1364
+ await mutationRuntime.update(table, entityKey, patch);
1365
+ requestConvergence();
1366
+ },
1367
+ delete: async (table, entityKey) => {
1368
+ await mutationRuntime.delete(table, entityKey);
1369
+ requestConvergence();
1370
+ },
1371
+ batch: async (items) => {
1372
+ await mutationRuntime.batch(items);
1373
+ requestConvergence();
1374
+ },
1375
+ };
1376
+
1377
+ // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────
1378
+ const ensureSynced: SyncClient<TRegistry>["ensureSynced"] = async (keys) => {
1379
+ const activeSync = sync;
1380
+ if (activeSync == null || keys.length === 0) return;
1381
+ const groupKeys = new Set<string>();
1382
+ for (const key of keys) {
1383
+ const groupKey = activeSync.groupKeyForTable(key);
1384
+ if (groupKey != null) groupKeys.add(groupKey);
1385
+ }
1386
+ await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));
1387
+ };
1388
+
1389
+ const isSynced: SyncClient<TRegistry>["isSynced"] = (key) => {
1390
+ const activeSync = sync;
1391
+ // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is "dormant".
1392
+ if (activeSync == null) return true;
1393
+ return activeSync.isTableStarted(key);
1394
+ };
1395
+
1396
+ // ADR-0021 §2/§4: the tables of `entry`'s consistency GROUP — a group is one subscription / one
1397
+ // transaction frontier, so reverting one member to dormant reverts them all (a table with no
1398
+ // `consistencyGroup` is its own singleton group).
1399
+ const groupTableKeysFor = (key: SyncTableName<TRegistry>, entry: SyncTableEntry): SyncTableName<TRegistry>[] => {
1400
+ const targetGroup = entry.consistencyGroup;
1401
+ return (
1402
+ targetGroup == null
1403
+ ? [key]
1404
+ : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(
1405
+ (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,
1406
+ )
1407
+ ) as SyncTableName<TRegistry>[];
1408
+ };
1409
+
1410
+ // The shared group-teardown body of {@link desync} and {@link discardEphemeral} (ADR-0021 §2/§4). Both
1411
+ // revert a lazy relation's whole consistency group to dormant: refuse if any writable member owes
1412
+ // unsettled writes, stop the group stream, clear the persisted lazy activation, delete the persisted
1413
+ // Electric subscription (so re-activation re-streams from scratch), then clean-truncate every member's
1414
+ // local cluster. `label` names the calling primitive in the owed-writes refusal so each keeps its own
1415
+ // diagnostic (desync stays byte-identical). Callers apply their own lazy/retention gates BEFORE this.
1416
+ const tearDownLazyGroup = async (key: SyncTableName<TRegistry>, entry: SyncTableEntry, label: string) => {
1417
+ const groupTableKeys = groupTableKeysFor(key, entry);
1418
+
1419
+ // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the
1420
+ // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.
1421
+ let owed = 0;
1422
+ for (const member of groupTableKeys) {
1423
+ if (options.registry[member]!.mode === "readonly") continue;
1424
+ const stats = await mutationRuntime.readMutationStats(member);
1425
+ owed +=
1426
+ stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
1427
+ }
1428
+ if (owed > 0) {
1429
+ throw new Error(
1430
+ `${label}('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,
1431
+ );
1432
+ }
1433
+
1434
+ const activeSync = sync;
1435
+ // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the
1436
+ // registry derivation when sync is disabled.
1437
+ const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;
1438
+ // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and
1439
+ // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot
1440
+ // holds the relation dormant again.
1441
+ if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);
1442
+ if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);
1443
+ // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the
1444
+ // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we
1445
+ // truncate below — leaving the relation permanently missing its pre-desync data.
1446
+ if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);
1447
+ // Clean-truncate every member's local cluster.
1448
+ for (const member of groupTableKeys) {
1449
+ await pglite.exec(buildDesyncTableSql(options.registry, member as string));
1450
+ }
1451
+ };
1452
+
1453
+ const desync: SyncClient<TRegistry>["desync"] = async (key) => {
1454
+ const entry = options.registry[key];
1455
+ if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);
1456
+ if (entry.subscription !== "lazy") {
1457
+ throw new Error(
1458
+ `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,
1459
+ );
1460
+ }
1461
+ await tearDownLazyGroup(key, entry, "desync");
1462
+ };
1463
+
1464
+ const discardEphemeral: SyncClient<TRegistry>["discardEphemeral"] = (key) =>
1465
+ // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4): discardEphemeral
1466
+ // clean-truncates an ephemeral group's local cache, so an export must never interleave it (nor it an
1467
+ // export) — the slot's typed LifecycleBusyError fires in both directions. The existing lazy/ephemeral
1468
+ // gates below stay EXACTLY as they were, now inside the slot run. (`desync` is deliberately NOT slotted:
1469
+ // only the ADR-0035-named destructive ops — destroy/discardEphemeral/dropReadCache — serialise here.)
1470
+ lifecycleSlot.run("discardEphemeral", async () => {
1471
+ const entry = options.registry[key];
1472
+ if (entry == null) throw new Error(`discardEphemeral: unknown table ${String(key)}`);
1473
+ // Keep the lazy gate desync has: eager+ephemeral is NOT forbidden by the type system (retention and
1474
+ // subscription are independent scalars on the entry — see contracts config.ts / registry.ts), and an
1475
+ // eager relation would immediately re-stream, so the same refusal applies here.
1476
+ if (entry.subscription !== "lazy") {
1477
+ throw new Error(
1478
+ `discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded — an eager relation is always-on and would immediately re-sync.`,
1479
+ );
1480
+ }
1481
+ // STRICTER gate than desync: every member of the consistency group must be ephemeral. Retention is read
1482
+ // as `entry.retention ?? "persistent"` (absent → persistent, matching validateRegistryLifecycleGroups and
1483
+ // the schema generator); a read PROJECTION surfaces its declared retention on the same `retention` field
1484
+ // (withRetention/asEphemeral/defineReadProjection all set it), so this one read covers tables and
1485
+ // projections alike. Refuse (naming the offender) if any member is persistent — discardEphemeral is the
1486
+ // multi-tab-safe primitive for per-delivery-session windows, and truncating a persistent member's cache
1487
+ // would drop durable local data; use desync for a persistent lazy relation.
1488
+ for (const member of groupTableKeysFor(key, entry)) {
1489
+ if ((options.registry[member]!.retention ?? "persistent") !== "ephemeral") {
1490
+ throw new Error(
1491
+ `discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent — ` +
1492
+ `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`,
1493
+ );
1494
+ }
1495
+ }
1496
+ await tearDownLazyGroup(key, entry, "discardEphemeral");
1497
+ });
1498
+
1499
+ const transaction: SyncClient<TRegistry>["transaction"] = async ({ mode }, run) => {
1500
+ // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.
1501
+ const collected: MutationBatchItem<TRegistry>[] = [];
1502
+ const txTables = Object.fromEntries(
1503
+ Object.keys(options.registry).map((tableKey) => [
1504
+ tableKey,
1505
+ {
1506
+ create: (input: unknown) => {
1507
+ collected.push({ table: tableKey, kind: "create", input } as MutationBatchItem<TRegistry>);
1508
+ },
1509
+ update: (entityKey: Record<string, string>, patch: unknown) => {
1510
+ collected.push({ table: tableKey, kind: "update", entityKey, patch } as MutationBatchItem<TRegistry>);
1511
+ },
1512
+ updateBlind: (entityKey: Record<string, string>, patch: unknown) => {
1513
+ collected.push({
1514
+ table: tableKey,
1515
+ kind: "update",
1516
+ entityKey,
1517
+ patch,
1518
+ blind: true,
1519
+ } as MutationBatchItem<TRegistry>);
1520
+ },
1521
+ delete: (entityKey: Record<string, string>) => {
1522
+ collected.push({ table: tableKey, kind: "delete", entityKey } as MutationBatchItem<TRegistry>);
1523
+ },
1524
+ },
1525
+ ]),
1526
+ ) as SyncTransaction<TRegistry>["tables"];
1527
+
1528
+ await run({ tables: txTables });
1529
+
1530
+ if (collected.length === 0) {
1531
+ return { acks: [] };
1532
+ }
1533
+
1534
+ const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };
1535
+ await mutationRuntime.batch(collected, unit);
1536
+
1537
+ if (mode === "optimistic") {
1538
+ // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).
1539
+ void mutationRuntime.flush();
1540
+ return { acks: [] };
1541
+ }
1542
+
1543
+ // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.
1544
+ return await mutationRuntime.flushUnit(unit.id);
1545
+ };
1546
+
1547
+ const prepareQuery: SyncClient<TRegistry>["prepareQuery"] = async ({ sql, use }) => {
1548
+ // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.
1549
+ // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,
1550
+ // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent
1551
+ // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).
1552
+ const toActivate = new Set<string>(use ?? []);
1553
+ for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);
1554
+ await ensureSynced([...toActivate] as SyncTableName<TRegistry>[]);
1555
+ // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),
1556
+ // throw rather than let the query read empty/stale. In the normal path everything scanned was just
1557
+ // activated, so this passes.
1558
+ assertLazyRefsActivated({
1559
+ sql,
1560
+ index: lazyGuardIndex,
1561
+ isActive: (key) => isSynced(key as SyncTableName<TRegistry>),
1562
+ });
1563
+ };
1564
+
1565
+ const runGuardedQuery = async <TRows extends readonly unknown[]>(
1566
+ build: GuardedQueryFn<TRegistry, TRows>,
1567
+ use?: readonly SyncTableName<TRegistry>[],
1568
+ ): Promise<TRows> => {
1569
+ const builder = build(client);
1570
+ await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });
1571
+ return builder;
171
1572
  };
172
1573
 
173
1574
  const client: SyncClient<TRegistry> = {
@@ -194,31 +1595,204 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
194
1595
  await ready;
195
1596
  },
196
1597
  stop: async () => {
1598
+ // Await any in-flight convergence pass before closing PGlite, so a pass never queries a
1599
+ // closed handle.
1600
+ await convergenceDriver?.stop();
197
1601
  sync?.unsubscribe();
198
1602
  status.isRunning = false;
199
1603
  options.onStatusChange?.(status);
1604
+ // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact
1605
+ // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
1606
+ // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
1607
+ await engine.close();
200
1608
  await pglite.close();
201
1609
  },
202
- destroy: async () => {
203
- sync?.unsubscribe();
204
- status.isRunning = false;
205
- options.onStatusChange?.(status);
206
- await pglite.close();
207
- },
1610
+ destroy: (destroyOptions) =>
1611
+ // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can
1612
+ // never interleave a running export (nor an export interleave this wipe) — the slot's typed
1613
+ // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
1614
+ // inside the slot run.
1615
+ lifecycleSlot.run("destroy", async () => {
1616
+ if (!destroyOptions?.force) {
1617
+ const stats = await mutationRuntime.readMutationStats();
1618
+ const owed =
1619
+ stats.pendingCount +
1620
+ stats.sendingCount +
1621
+ stats.failedCount +
1622
+ stats.quarantinedCount +
1623
+ stats.conflictedCount;
1624
+
1625
+ if (owed > 0) {
1626
+ throw new Error(
1627
+ `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,
1628
+ );
1629
+ }
1630
+ }
1631
+
1632
+ // Drain any in-flight convergence pass before wiping, so a pass never writes into a store
1633
+ // being torn down underneath it.
1634
+ await convergenceDriver?.stop();
1635
+ sync?.unsubscribe();
1636
+ status.isRunning = false;
1637
+ options.onStatusChange?.(status);
1638
+ await pglite.exec(buildWipeLocalStoreSql(options.registry));
1639
+ // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
1640
+ // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
1641
+ await engine.close();
1642
+ await pglite.close();
1643
+ }),
1644
+ dropReadCache: () =>
1645
+ // Under the SAME lifecycle slot as the exports (ADR-0035 decision 4). WHY dropReadCache is slotted and
1646
+ // not just destroy/discardEphemeral: it DROPS and rebuilds the synced read-cache tables, so an export
1647
+ // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
1648
+ // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
1649
+ lifecycleSlot.run("dropReadCache", async () => {
1650
+ await pglite.exec(buildDropReadCacheSql(options.registry));
1651
+ await pglite.exec(generateLocalSchemaSql(options.registry));
1652
+ // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch
1653
+ // rather than the bookkeeping believing they are already caught up (ADR-0006).
1654
+ await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
1655
+ }),
208
1656
  flush: (table) => mutationRuntime.flush(table),
209
1657
  reconcile: (table) => mutationRuntime.reconcile(table),
210
1658
  retryFailed: (table) => mutationRuntime.retryFailed(table),
211
1659
  recoverSending: (table) => mutationRuntime.recoverSending(table),
212
1660
  readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),
213
1661
  mutate,
1662
+ discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),
1663
+ discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),
214
1664
  diagnostics: async (table) => ({
215
1665
  mutation: await mutationRuntime.readMutationStats(table),
216
1666
  }),
1667
+ // Inspection surface (see the interface doc): straight through to the underlying store, no journal /
1668
+ // overlay involvement. The worker facade runs the identical call inside the worker's own client.
1669
+ rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
1670
+ rawExec: (sql, options) => pglite.exec(sql, options),
1671
+ query: (build) => runGuardedQuery(build),
1672
+ queryRow: async (build) => {
1673
+ const rows = await runGuardedQuery(build);
1674
+ return rows[0] ?? null;
1675
+ },
1676
+ queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),
1677
+ queryRawRow: async (spec) => {
1678
+ const rows = await runGuardedQuery(spec.build, spec.use);
1679
+ return rows[0] ?? null;
1680
+ },
1681
+ ensureSynced,
1682
+ isSynced,
1683
+ desync,
1684
+ discardEphemeral,
1685
+ prepareQuery,
1686
+ transaction,
1687
+ groupReady: async (table) => {
1688
+ const activeSync = sync;
1689
+ // Sync disabled → local-only: every relation is trivially "ready" (nothing to await).
1690
+ if (activeSync == null) return;
1691
+ const groupKey = activeSync.groupKeyForTable(table as string);
1692
+ if (groupKey == null) return;
1693
+ await activeSync.groupReady(groupKey);
1694
+ },
1695
+ // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React
1696
+ // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),
1697
+ // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs
1698
+ // incrementally against its own materialized state; the column set only matters for the worker bridge.
1699
+ subscribeLiveRows: async ({ sql, params, fields }, onRows) => {
1700
+ // Render the query safe to materialise: a JOIN with same-named columns fails `live.query`'s
1701
+ // temp-view creation (`column "title" specified more than once`) unless every output column has a
1702
+ // unique alias. No `fields` → SQL unchanged (backward-compatible name-keyed rows).
1703
+ const materialSql = wrapLiveQueryForMaterialization(sql, fields);
1704
+ const registered = await pglite.live.query<Record<string, unknown>>(materialSql, params as unknown[]);
1705
+ const listener = (results: { rows: Record<string, unknown>[] }) => {
1706
+ onRows(results.rows as never);
1707
+ };
1708
+ registered.subscribe(listener);
1709
+ return {
1710
+ initialRows: registered.initialResults.rows as never,
1711
+ unsubscribe: () => {
1712
+ void registered.unsubscribe(listener);
1713
+ },
1714
+ };
1715
+ },
1716
+ // Boot observability (ADR-0034): the finalized report (null before initial sync completes / after an
1717
+ // early stop). Resolves from the builder-owned ref this client holds — no round trip in-process.
1718
+ bootReport: async () => finalizedBootReport,
1719
+ exportStore: async (exportOptions) => {
1720
+ // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
1721
+ // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
1722
+ await ready;
1723
+ // Name the backup from the configured plain store PATH (ADR-0036), never the PGlite instance's
1724
+ // resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name
1725
+ // as something to imitate. The store id is the path's last segment (see `deriveStoreId`).
1726
+ return lifecycleSlot.run("exportStore", () =>
1727
+ performStoreExport(
1728
+ {
1729
+ pglite,
1730
+ readMutationStats: () => mutationRuntime.readMutationStats(),
1731
+ ...(options.storePath != null ? { storePath: options.storePath } : {}),
1732
+ },
1733
+ exportOptions,
1734
+ ),
1735
+ );
1736
+ },
1737
+ exportDiagnostics: async (exportOptions) => {
1738
+ // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot
1739
+ // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is
1740
+ // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pglite`, then
1741
+ // clones it in memory — the live engine every reference here holds is never closed (the addendum's
1742
+ // whole reason for the throwaway clone over the abandoned suspend/reopen seam).
1743
+ await ready;
1744
+ return lifecycleSlot.run("exportDiagnostics", () =>
1745
+ performDiagnosticExport(
1746
+ {
1747
+ pglite,
1748
+ readMutationStats: () => mutationRuntime.readMutationStats(),
1749
+ ...(options.storePath != null ? { storePath: options.storePath } : {}),
1750
+ },
1751
+ exportOptions,
1752
+ ),
1753
+ );
1754
+ },
1755
+ exportData: async (exportOptions) => {
1756
+ // Same lifecycle discipline (ADR-0035): await engine-ready first (wait out a boot rather than reject),
1757
+ // THEN take the single slot. The DRAIN runs inside the slot (the caller-side placement decision 3
1758
+ // makes): flush needs the running engine and is not lifecycle-exclusive, but the artefact must be
1759
+ // taken right after the drain, so export owns the store's lifecycle for the whole drain+dump. The
1760
+ // `-t` allowlist + enum header are resolved from the registry through the SAME projection the DDL
1761
+ // generator uses — never re-derived by string convention.
1762
+ await ready;
1763
+ return lifecycleSlot.run("exportData", () =>
1764
+ performDataExport(
1765
+ {
1766
+ pglite,
1767
+ readMutationStats: () => mutationRuntime.readMutationStats(),
1768
+ flush: () => mutationRuntime.flush(),
1769
+ syncedTableNames: collectDataExportSyncedTableNames(options.registry),
1770
+ enumHeaderSql: buildDataExportEnumHeaderSql(options.registry),
1771
+ cloneCleanupSql: buildDataExportCloneCleanupSql(options.registry),
1772
+ ...(options.storePath != null ? { storePath: options.storePath } : {}),
1773
+ },
1774
+ exportOptions,
1775
+ ),
1776
+ );
1777
+ },
217
1778
  };
218
1779
 
219
1780
  return client;
220
1781
  }
221
1782
 
1783
+ /**
1784
+ * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009
1785
+ * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;
1786
+ * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables
1787
+ * collapse onto one group key.
1788
+ */
1789
+ function allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
1790
+ const keys = Object.values(registry)
1791
+ .filter((entry) => typeof entry.shape?.shapeKey === "string" && entry.shape.shapeKey.length > 0)
1792
+ .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);
1793
+ return [...new Set(keys)];
1794
+ }
1795
+
222
1796
  async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {
223
1797
  if (!keys || keys.length === 0) {
224
1798
  return;
@@ -260,6 +1834,23 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
260
1834
  ) as RegistryViews<TRegistry>;
261
1835
  }
262
1836
 
1837
+ /**
1838
+ * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance
1839
+ * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL
1840
+ * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is
1841
+ * constructed over a stub client that is never invoked (`construct` stores the client without calling it).
1842
+ * The same builders `createSyncClient` uses, so a query built on either client compiles identically.
1843
+ */
1844
+ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
1845
+ registry: TRegistry,
1846
+ ): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {
1847
+ const stubClient = {} as ClientPGlite;
1848
+ return {
1849
+ drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),
1850
+ views: buildViews(registry),
1851
+ };
1852
+ }
1853
+
263
1854
  function buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(
264
1855
  registry: TRegistry,
265
1856
  electricUrl: string,
@@ -280,6 +1871,16 @@ function buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {
280
1871
  primaryKey: entry.primaryKey,
281
1872
  ...(entry.shape !== undefined ? { shape: entry.shape } : {}),
282
1873
  clientProjection,
1874
+ // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the
1875
+ // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /
1876
+ // `classifyTableApplyStrategy` on the model, never carried through this config surface.
1877
+ // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables
1878
+ // onto one MultiShapeStream; absent → singleton group.
1879
+ ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),
1880
+ // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager
1881
+ // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).
1882
+ ...(entry.subscription ? { subscription: entry.subscription } : {}),
1883
+ ...(entry.retention ? { retention: entry.retention } : {}),
283
1884
  };
284
1885
  }
285
1886