@pgxsinkit/client 0.1.36 → 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 (64) hide show
  1. package/dist/boot-report.d.ts +134 -0
  2. package/dist/boot-report.d.ts.map +1 -0
  3. package/dist/export-data.d.ts +100 -0
  4. package/dist/export-data.d.ts.map +1 -0
  5. package/dist/export-dump.d.ts +92 -0
  6. package/dist/export-dump.d.ts.map +1 -0
  7. package/dist/export-store.d.ts +214 -0
  8. package/dist/export-store.d.ts.map +1 -0
  9. package/dist/index.d.ts +206 -13
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +886 -69
  12. package/dist/index.js.map +21 -14
  13. package/dist/lazy-guard.d.ts +4 -3
  14. package/dist/lazy-guard.d.ts.map +1 -1
  15. package/dist/lifecycle-slot.d.ts +31 -0
  16. package/dist/lifecycle-slot.d.ts.map +1 -0
  17. package/dist/live-rows-sql.d.ts +21 -0
  18. package/dist/live-rows-sql.d.ts.map +1 -0
  19. package/dist/mutation-state.d.ts +9 -2
  20. package/dist/mutation-state.d.ts.map +1 -1
  21. package/dist/mutation.d.ts +12 -0
  22. package/dist/mutation.d.ts.map +1 -1
  23. package/dist/schema.d.ts +33 -0
  24. package/dist/schema.d.ts.map +1 -1
  25. package/dist/shape-sync.d.ts +10 -0
  26. package/dist/shape-sync.d.ts.map +1 -1
  27. package/dist/store-path.d.ts +132 -0
  28. package/dist/store-path.d.ts.map +1 -0
  29. package/dist/sync/index.d.ts +1 -1
  30. package/dist/sync/index.d.ts.map +1 -1
  31. package/dist/sync/types.d.ts +8 -0
  32. package/dist/sync/types.d.ts.map +1 -1
  33. package/dist/testing.d.ts +27 -0
  34. package/dist/testing.d.ts.map +1 -0
  35. package/dist/testing.js +17 -0
  36. package/dist/testing.js.map +11 -0
  37. package/dist/worker/attach-sync-client.d.ts +23 -2
  38. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  39. package/dist/worker/define-sync-worker.d.ts +5 -4
  40. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  41. package/dist/worker/protocol.d.ts +89 -8
  42. package/dist/worker/protocol.d.ts.map +1 -1
  43. package/package.json +9 -4
  44. package/skills/core/SKILL.md +14 -1
  45. package/skills/operating/SKILL.md +75 -15
  46. package/src/boot-report.ts +287 -0
  47. package/src/export-data.ts +300 -0
  48. package/src/export-dump.ts +239 -0
  49. package/src/export-store.ts +309 -0
  50. package/src/index.ts +623 -82
  51. package/src/lazy-guard.ts +23 -9
  52. package/src/lifecycle-slot.ts +66 -0
  53. package/src/live-rows-sql.ts +45 -0
  54. package/src/mutation-state.ts +11 -2
  55. package/src/mutation.ts +42 -0
  56. package/src/schema.ts +120 -1
  57. package/src/shape-sync.ts +21 -0
  58. package/src/store-path.ts +249 -0
  59. package/src/sync/index.ts +11 -0
  60. package/src/sync/types.ts +9 -0
  61. package/src/testing.ts +53 -0
  62. package/src/worker/attach-sync-client.ts +101 -6
  63. package/src/worker/define-sync-worker.ts +196 -30
  64. package/src/worker/protocol.ts +110 -10
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  // @bun
2
+ var __require = import.meta.require;
3
+
2
4
  // packages/client/src/index.ts
3
- import { PGlite as PGlite2 } from "@electric-sql/pglite";
5
+ import { PGlite as PGlite3 } from "@electric-sql/pglite";
4
6
  import { live } from "@electric-sql/pglite/live";
5
7
 
6
8
  // node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/entity.js
@@ -7941,6 +7943,129 @@ async function timeAsync(event, fn, data) {
7941
7943
  }
7942
7944
  }
7943
7945
 
7946
+ // packages/client/src/boot-report.ts
7947
+ var nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
7948
+ function createGroupAccumulator(groupKey, tables, bootStartPerf) {
7949
+ const startedAtMs = nowMs() - bootStartPerf;
7950
+ let requests = 0;
7951
+ let rows = 0;
7952
+ let fetchMs = 0;
7953
+ let applyMs = 0;
7954
+ let readyAtMs = null;
7955
+ let readyReached = false;
7956
+ let frozen = false;
7957
+ let lastMark = nowMs();
7958
+ return {
7959
+ onBatchDelivered: (changeCount) => {
7960
+ if (readyReached)
7961
+ frozen = true;
7962
+ if (frozen)
7963
+ return;
7964
+ const now2 = nowMs();
7965
+ fetchMs += Math.max(0, now2 - lastMark);
7966
+ lastMark = now2;
7967
+ requests += 1;
7968
+ rows += changeCount;
7969
+ },
7970
+ onApply: (ms) => {
7971
+ if (frozen)
7972
+ return;
7973
+ applyMs += ms;
7974
+ lastMark = nowMs();
7975
+ },
7976
+ markReady: () => {
7977
+ if (readyAtMs != null)
7978
+ return;
7979
+ readyAtMs = nowMs() - bootStartPerf;
7980
+ readyReached = true;
7981
+ },
7982
+ snapshot: () => ({
7983
+ groupKey,
7984
+ tables,
7985
+ startedAtMs,
7986
+ readyAtMs: readyAtMs ?? nowMs() - bootStartPerf,
7987
+ requests,
7988
+ rows,
7989
+ fetchMs,
7990
+ applyMs
7991
+ })
7992
+ };
7993
+ }
7994
+ function createBootReportBuilder(init) {
7995
+ const startedAt = Date.now();
7996
+ const bootStartPerf = nowMs();
7997
+ const durations = new Map;
7998
+ let prepareMs = null;
7999
+ let pgliteCreateMs = null;
8000
+ let provision = null;
8001
+ let syncStartDoneOffset = null;
8002
+ const groups = [];
8003
+ let built = null;
8004
+ const duration = (key) => durations.get(key) ?? 0;
8005
+ return {
8006
+ bootStartPerf,
8007
+ phase: async (key, event, fn, data) => {
8008
+ const startedAtPerf = nowMs();
8009
+ syncDebug(`${event} start`, data);
8010
+ try {
8011
+ return await fn();
8012
+ } finally {
8013
+ const ms = nowMs() - startedAtPerf;
8014
+ syncDebug(`${event} done`, { ms: Math.round(ms) });
8015
+ if (key === "prepare")
8016
+ prepareMs = (prepareMs ?? 0) + ms;
8017
+ else
8018
+ durations.set(key, ms);
8019
+ }
8020
+ },
8021
+ setPgliteCreateMs: (ms) => {
8022
+ pgliteCreateMs = ms;
8023
+ },
8024
+ setProvision: (value) => {
8025
+ provision = value;
8026
+ },
8027
+ setSyncStartMs: (ms) => {
8028
+ durations.set("syncStart", ms);
8029
+ },
8030
+ markSyncStartDone: () => {
8031
+ syncStartDoneOffset = nowMs() - bootStartPerf;
8032
+ },
8033
+ beginGroup: (groupKey, tables) => {
8034
+ const accumulator = createGroupAccumulator(groupKey, tables, bootStartPerf);
8035
+ groups.push(accumulator);
8036
+ return accumulator;
8037
+ },
8038
+ finalize: () => {
8039
+ if (built)
8040
+ return built;
8041
+ const totalMs = nowMs() - bootStartPerf;
8042
+ const syncStartBase = syncStartDoneOffset ?? totalMs;
8043
+ built = {
8044
+ reportVersion: 1,
8045
+ mode: init.mode,
8046
+ freshStore: init.freshStore,
8047
+ overlapPrefetch: init.overlapPrefetch,
8048
+ registryFingerprint: init.registryFingerprint,
8049
+ startedAt,
8050
+ totalMs,
8051
+ provision,
8052
+ phases: {
8053
+ pgliteCreateMs,
8054
+ schemaExecMs: duration("schemaExec"),
8055
+ journalRecoveryMs: duration("journalRecovery"),
8056
+ storeVersionReconcileMs: duration("storeVersionReconcile"),
8057
+ syncStartMs: duration("syncStart"),
8058
+ catchupMs: Math.max(0, totalMs - syncStartBase),
8059
+ ...prepareMs != null ? { prepareMs } : {}
8060
+ },
8061
+ groups: groups.map((group) => group.snapshot())
8062
+ };
8063
+ return built;
8064
+ },
8065
+ report: () => built
8066
+ };
8067
+ }
8068
+
7944
8069
  // packages/client/src/convergence.ts
7945
8070
  function createConvergenceDriver(options) {
7946
8071
  let unsubscribe = null;
@@ -8037,6 +8162,308 @@ function createIntervalConvergenceTrigger(intervalMs) {
8037
8162
  };
8038
8163
  }
8039
8164
 
8165
+ // packages/client/src/export-dump.ts
8166
+ import { PGlite as PGlite2 } from "@electric-sql/pglite";
8167
+
8168
+ // packages/client/src/export-store.ts
8169
+ var nowMs2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
8170
+ function deriveStoreId(storePath) {
8171
+ if (!storePath)
8172
+ return "pgxsinkit-store";
8173
+ const lastSegment = storePath.split("/").filter(Boolean).pop() ?? storePath;
8174
+ const safe = lastSegment.replace(/[^A-Za-z0-9._-]/g, "-").replace(/^-+|-+$/g, "");
8175
+ return safe.length > 0 ? safe : "pgxsinkit-store";
8176
+ }
8177
+ var compactTimestamp = () => new Date().toISOString().replace(/[:.]/g, "-");
8178
+ async function performDatadirDump(pglite, compression, startPerf) {
8179
+ const checkpointStartedAtMs = nowMs2() - startPerf;
8180
+ const checkpointStartPerf = nowMs2();
8181
+ await pglite.exec("CHECKPOINT");
8182
+ const checkpointMs = nowMs2() - checkpointStartPerf;
8183
+ const dumpStartedAtMs = nowMs2() - startPerf;
8184
+ const dumpStartPerf = nowMs2();
8185
+ const dumped = await pglite.dumpDataDir(compression);
8186
+ const dumpMs = nowMs2() - dumpStartPerf;
8187
+ return { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs };
8188
+ }
8189
+ async function performStoreExport(deps, options = {}) {
8190
+ const startedAt = Date.now();
8191
+ const startPerf = nowMs2();
8192
+ const compression = options.compression ?? "auto";
8193
+ const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(deps.pglite, compression, startPerf);
8194
+ const dumpedName = dumped instanceof File ? dumped.name : "";
8195
+ const gzipped = dumpedName.endsWith(".gz") || dumped.type.includes("gzip");
8196
+ const appliedCompression = gzipped ? "gzip" : "none";
8197
+ const extension = gzipped ? ".pgdata.tar.gz" : ".pgdata.tar";
8198
+ const mimeType = gzipped ? "application/x-gzip" : "application/x-tar";
8199
+ const storeId = deriveStoreId(deps.storePath);
8200
+ const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}${extension}`;
8201
+ const bytes = new Uint8Array(await dumped.arrayBuffer());
8202
+ const file = new File([bytes], fileName, { type: mimeType });
8203
+ const diagnostics = await deps.readMutationStats();
8204
+ const report = {
8205
+ reportVersion: 1,
8206
+ kind: "store-backup",
8207
+ scope: "whole-store",
8208
+ compression: appliedCompression,
8209
+ startedAt,
8210
+ totalMs: nowMs2() - startPerf,
8211
+ byteLength: file.size,
8212
+ phases: { checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs },
8213
+ diagnostics
8214
+ };
8215
+ return { file, report };
8216
+ }
8217
+
8218
+ // packages/client/src/store-path.ts
8219
+ class InvalidStorePathError extends Error {
8220
+ constructor(message) {
8221
+ super(`[pgxsinkit] ${message}`);
8222
+ this.name = "InvalidStorePathError";
8223
+ }
8224
+ }
8225
+
8226
+ class NonPersistentStoreError extends Error {
8227
+ constructor(observed) {
8228
+ const reason = observed === "in-memory-default" ? "its dataDir is undefined \u2014 PGlite's default is an in-memory store (`new PGlite()`)" : "its dataDir is a memory-backed store";
8229
+ super(`[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` + "(persistent retention, the optimistic Mutation journal) assume a persisted store \u2014 a memory store " + "would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a " + "plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with " + '`memoryStoreForTests` / `testStoreAcknowledgment` from "@pgxsinkit/client/testing" (ADR-0036).');
8230
+ this.name = "NonPersistentStoreError";
8231
+ }
8232
+ }
8233
+
8234
+ class RestoreTargetExistsError extends Error {
8235
+ constructor(storePath) {
8236
+ super(`[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` + "Restore only ever boots a brand-new store (it never overlays an existing one \u2014 that would corrupt the " + "datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh " + "path (ADR-0035 decision 6).");
8237
+ this.name = "RestoreTargetExistsError";
8238
+ }
8239
+ }
8240
+ var TEST_STORE_BACKEND = Symbol.for("pgxsinkit.internal.testStoreBackend");
8241
+ function readTestStoreMarker(options) {
8242
+ if (options == null || typeof options !== "object")
8243
+ return;
8244
+ const marker = options[TEST_STORE_BACKEND];
8245
+ return marker === "memory" || marker === "acknowledged" ? marker : undefined;
8246
+ }
8247
+ function normaliseStorePathInput(input) {
8248
+ if (typeof input === "string")
8249
+ return { storePath: input };
8250
+ return {
8251
+ storePath: input.storePath,
8252
+ ...readTestStoreMarker(input) === "memory" ? { backendOverride: "memory" } : {}
8253
+ };
8254
+ }
8255
+ function detectStoreEnv() {
8256
+ return { hasIndexedDb: typeof globalThis.indexedDB !== "undefined" };
8257
+ }
8258
+ function resolveStoreDataDir(storePath, backendOverride, env = detectStoreEnv()) {
8259
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
8260
+ throw new InvalidStorePathError('invalid storePath: expected a non-empty plain store name (e.g. "my-app-store"); received an empty or whitespace-only value (ADR-0036).');
8261
+ }
8262
+ if (storePath.includes("://")) {
8263
+ throw new InvalidStorePathError(`invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` + 'Pass just the name (e.g. "my-app-store") \u2014 the storage backend (IndexedDB in a browser, the ' + "filesystem on Bun/Node) is derived for you; drop the scheme prefix (ADR-0036).");
8264
+ }
8265
+ if (backendOverride === "memory")
8266
+ return `memory://${storePath}`;
8267
+ return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;
8268
+ }
8269
+ function storeIndexedDbDatabaseName(storePath) {
8270
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
8271
+ throw new InvalidStorePathError("invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).");
8272
+ }
8273
+ if (storePath.includes("://")) {
8274
+ throw new InvalidStorePathError(`invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`);
8275
+ }
8276
+ return `/pglite/${storePath}`;
8277
+ }
8278
+ function classifyNonPersistentDataDir(dataDir) {
8279
+ if (dataDir == null)
8280
+ return "in-memory-default";
8281
+ if (dataDir.startsWith("memory://"))
8282
+ return "memory-scheme";
8283
+ return null;
8284
+ }
8285
+ async function storeTargetExists(storePath, backendOverride, env = detectStoreEnv()) {
8286
+ const dataDir = resolveStoreDataDir(storePath, backendOverride, env);
8287
+ if (dataDir.startsWith("memory://"))
8288
+ return false;
8289
+ if (dataDir.startsWith("file://")) {
8290
+ const path = dataDir.slice("file://".length);
8291
+ const { existsSync } = await import("fs");
8292
+ return existsSync(path);
8293
+ }
8294
+ const idb = globalThis.indexedDB;
8295
+ if (idb?.databases == null)
8296
+ return false;
8297
+ const target = storeIndexedDbDatabaseName(storePath);
8298
+ const databases = await idb.databases();
8299
+ return databases.some((db) => db.name === target);
8300
+ }
8301
+
8302
+ // packages/client/src/export-dump.ts
8303
+ var cloneCounter = 0;
8304
+ var nextCloneStorePath = () => `pgxsinkit-export-clone-${++cloneCounter}-${Math.random().toString(36).slice(2, 10)}`;
8305
+ async function runThrowawayCloneDump(pglite, startPerf, options = {}) {
8306
+ const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(pglite, "none", startPerf);
8307
+ const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
8308
+ const cloneBootStartedAtMs = nowMs2() - startPerf;
8309
+ const cloneBootStartPerf = nowMs2();
8310
+ const throwaway = await PGlite2.create({ dataDir: cloneDataDir, loadDataDir: dumped });
8311
+ const cloneBootMs = nowMs2() - cloneBootStartPerf;
8312
+ let sqlBytes;
8313
+ let pgDumpStartedAtMs;
8314
+ let pgDumpMs;
8315
+ try {
8316
+ if (options.prepareClone) {
8317
+ await options.prepareClone(throwaway);
8318
+ }
8319
+ pgDumpStartedAtMs = nowMs2() - startPerf;
8320
+ const pgDumpStartPerf = nowMs2();
8321
+ const { pgDump } = await import("@electric-sql/pglite-tools/pg_dump");
8322
+ const dumpFile = await pgDump({
8323
+ pg: throwaway,
8324
+ ...options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {},
8325
+ fileName: "pgxsinkit-export.sql"
8326
+ });
8327
+ pgDumpMs = nowMs2() - pgDumpStartPerf;
8328
+ sqlBytes = new Uint8Array(await dumpFile.arrayBuffer());
8329
+ } finally {
8330
+ await throwaway.close();
8331
+ }
8332
+ return {
8333
+ sqlBytes,
8334
+ phases: {
8335
+ checkpointStartedAtMs,
8336
+ checkpointMs,
8337
+ dumpStartedAtMs,
8338
+ dumpMs,
8339
+ cloneBootStartedAtMs,
8340
+ cloneBootMs,
8341
+ pgDumpStartedAtMs,
8342
+ pgDumpMs
8343
+ }
8344
+ };
8345
+ }
8346
+ async function performDiagnosticExport(deps, options = {}) {
8347
+ const startedAt = Date.now();
8348
+ const startPerf = nowMs2();
8349
+ const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf);
8350
+ const storeId = deriveStoreId(deps.storePath);
8351
+ const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;
8352
+ const file = new File([sqlBytes], fileName, { type: "application/sql" });
8353
+ const diagnostics = await deps.readMutationStats();
8354
+ const report = {
8355
+ reportVersion: 1,
8356
+ kind: "diagnostic-dump",
8357
+ scope: "everything",
8358
+ startedAt,
8359
+ totalMs: nowMs2() - startPerf,
8360
+ byteLength: file.size,
8361
+ phases,
8362
+ diagnostics
8363
+ };
8364
+ return { file, report };
8365
+ }
8366
+
8367
+ // packages/client/src/export-data.ts
8368
+ var DEFAULT_DRAIN_TIMEOUT_MS = 15000;
8369
+ var DRAIN_POLL_INTERVAL_MS = 50;
8370
+
8371
+ class DataExportDrainError extends Error {
8372
+ reason;
8373
+ diagnostics;
8374
+ constructor(reason, diagnostics) {
8375
+ const detail = reason === "non-drainable-state" ? `non-drainable journal rows are present (failed=${diagnostics.failedCount}, ` + `quarantined=${diagnostics.quarantinedCount}, conflicted=${diagnostics.conflictedCount}) \u2014 these never ` + "drain on their own" : `the journal did not drain within the timeout (pending=${diagnostics.pendingCount}, ` + `sending=${diagnostics.sendingCount}, acked=${diagnostics.ackedCount}) \u2014 most likely acked writes whose ` + "synced echo has not landed";
8376
+ super(`[pgxsinkit] exportData refused: ${detail}. A strict data export needs a DRAINED journal (ADR-0035); ` + "resolve the rows, retry once they converge, use `drainJournal: false` to export synced state as-is, or " + "take a lossless `exportStore` backup instead.");
8377
+ this.name = "DataExportDrainError";
8378
+ this.reason = reason;
8379
+ this.diagnostics = diagnostics;
8380
+ }
8381
+ }
8382
+ var hasNonDrainableRows = (diagnostics) => diagnostics.failedCount > 0 || diagnostics.quarantinedCount > 0 || diagnostics.conflictedCount > 0;
8383
+ var isFullyDrained = (diagnostics) => diagnostics.pendingCount === 0 && diagnostics.sendingCount === 0 && diagnostics.ackedCount === 0 && !hasNonDrainableRows(diagnostics);
8384
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8385
+ async function drainJournalForExport(deps, timeoutMs) {
8386
+ const drainStartPerf = nowMs2();
8387
+ let diagnostics = await deps.readMutationStats();
8388
+ if (hasNonDrainableRows(diagnostics)) {
8389
+ throw new DataExportDrainError("non-drainable-state", diagnostics);
8390
+ }
8391
+ if (isFullyDrained(diagnostics)) {
8392
+ return { diagnostics, drainMs: nowMs2() - drainStartPerf };
8393
+ }
8394
+ for (;; ) {
8395
+ await deps.flush().catch(() => {
8396
+ return;
8397
+ });
8398
+ diagnostics = await deps.readMutationStats();
8399
+ if (hasNonDrainableRows(diagnostics)) {
8400
+ throw new DataExportDrainError("non-drainable-state", diagnostics);
8401
+ }
8402
+ if (isFullyDrained(diagnostics)) {
8403
+ return { diagnostics, drainMs: nowMs2() - drainStartPerf };
8404
+ }
8405
+ if (nowMs2() - drainStartPerf >= timeoutMs) {
8406
+ throw new DataExportDrainError("timeout", diagnostics);
8407
+ }
8408
+ await sleep(DRAIN_POLL_INTERVAL_MS);
8409
+ }
8410
+ }
8411
+ function buildArtefactCommentHeader(tableNames, escapeHatch) {
8412
+ const tableList = tableNames.length > 0 ? tableNames.join(", ") : "(none)";
8413
+ return [
8414
+ "-- pgxsinkit data export (ADR-0035): the synced tables + their enum types, schema + data,",
8415
+ "-- nothing of pgxsinkit's overlay/journal/metadata machinery \u2014 loadable into a vanilla Postgres.",
8416
+ "-- Produced by a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner`",
8417
+ "-- run against a throwaway in-memory clone of the local store.",
8418
+ `-- Tables: ${tableList}`,
8419
+ escapeHatch ? "-- Journal drain: SKIPPED (drainJournal: false) \u2014 reflects synced state as-is; unflushed local writes are absent." : "-- Journal drain: enforced \u2014 the Mutation journal was fully drained before the dump.",
8420
+ ""
8421
+ ].join(`
8422
+ `);
8423
+ }
8424
+ async function performDataExport(deps, options = {}) {
8425
+ const startedAt = Date.now();
8426
+ const startPerf = nowMs2();
8427
+ const drainOption = options.drainJournal ?? { timeoutMs: DEFAULT_DRAIN_TIMEOUT_MS };
8428
+ const escapeHatch = drainOption === false;
8429
+ const drainStartedAtMs = nowMs2() - startPerf;
8430
+ const drainMs = escapeHatch ? 0 : (await drainJournalForExport(deps, drainOption.timeoutMs)).drainMs;
8431
+ const pgDumpArgs = ["--no-owner", ...deps.syncedTableNames.flatMap((name2) => ["-t", name2])];
8432
+ const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf, {
8433
+ pgDumpArgs,
8434
+ ...deps.cloneCleanupSql.length > 0 ? { prepareClone: async (clone) => void await clone.exec(deps.cloneCleanupSql) } : {}
8435
+ });
8436
+ const header = buildArtefactCommentHeader(deps.syncedTableNames, escapeHatch) + deps.enumHeaderSql;
8437
+ const storeId = deriveStoreId(deps.storePath);
8438
+ const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-data.sql`;
8439
+ const file = new File([header, sqlBytes], fileName, { type: "application/sql" });
8440
+ const diagnostics = await deps.readMutationStats();
8441
+ const report = {
8442
+ reportVersion: 1,
8443
+ kind: "data-export",
8444
+ scope: "synced-tables",
8445
+ tables: deps.syncedTableNames,
8446
+ escapeHatch,
8447
+ startedAt,
8448
+ totalMs: nowMs2() - startPerf,
8449
+ byteLength: file.size,
8450
+ phases: {
8451
+ drainStartedAtMs,
8452
+ drainMs,
8453
+ checkpointStartedAtMs: phases.checkpointStartedAtMs,
8454
+ checkpointMs: phases.checkpointMs,
8455
+ dumpStartedAtMs: phases.dumpStartedAtMs,
8456
+ dumpMs: phases.dumpMs,
8457
+ cloneBootStartedAtMs: phases.cloneBootStartedAtMs,
8458
+ cloneBootMs: phases.cloneBootMs,
8459
+ pgDumpStartedAtMs: phases.pgDumpStartedAtMs,
8460
+ pgDumpMs: phases.pgDumpMs
8461
+ },
8462
+ diagnostics
8463
+ };
8464
+ return { file, report };
8465
+ }
8466
+
8040
8467
  // packages/client/src/lazy-guard.ts
8041
8468
  function buildLazyGuardIndex(registry2) {
8042
8469
  const lazyKeys = new Set;
@@ -8046,11 +8473,16 @@ function buildLazyGuardIndex(registry2) {
8046
8473
  continue;
8047
8474
  lazyKeys.add(key);
8048
8475
  const tokens = [];
8049
- const table = getTableConfig(entry.table);
8050
- tokens.push(quotedRef(table.name, table.schema));
8051
- if (entry.view != null) {
8052
- const view = getViewConfig(entry.view);
8053
- tokens.push(quotedRef(view.name, view.schema));
8476
+ if (entry.readProjection) {
8477
+ const localTable = getTableConfig(entry.localTable);
8478
+ tokens.push(quotedRef(localTable.name, localTable.schema));
8479
+ } else {
8480
+ const table = getTableConfig(entry.table);
8481
+ tokens.push(quotedRef(table.name, table.schema));
8482
+ if (entry.view != null) {
8483
+ const view = getViewConfig(entry.view);
8484
+ tokens.push(quotedRef(view.name, view.schema));
8485
+ }
8054
8486
  }
8055
8487
  lazyTokens.set(key, tokens);
8056
8488
  }
@@ -8094,6 +8526,45 @@ class LazyRelationNotActivatedError extends Error {
8094
8526
  }
8095
8527
  }
8096
8528
 
8529
+ // packages/client/src/lifecycle-slot.ts
8530
+ class LifecycleBusyError extends Error {
8531
+ runningLabel;
8532
+ attemptedLabel;
8533
+ constructor(attemptedLabel, runningLabel) {
8534
+ super(`[pgxsinkit] lifecycle busy: "${attemptedLabel}" refused while "${runningLabel}" is running (ADR-0035; retry once it settles).`);
8535
+ this.name = "LifecycleBusyError";
8536
+ this.attemptedLabel = attemptedLabel;
8537
+ this.runningLabel = runningLabel;
8538
+ }
8539
+ }
8540
+ function createLifecycleSlot() {
8541
+ let running = null;
8542
+ return {
8543
+ run: async (label, fn) => {
8544
+ if (running !== null)
8545
+ throw new LifecycleBusyError(label, running);
8546
+ running = label;
8547
+ try {
8548
+ return await fn();
8549
+ } finally {
8550
+ running = null;
8551
+ }
8552
+ },
8553
+ isBusy: () => running !== null,
8554
+ runningLabel: () => running
8555
+ };
8556
+ }
8557
+
8558
+ // packages/client/src/live-rows-sql.ts
8559
+ var LIVE_QUERY_TABLE_ALIAS = "__pgx_live";
8560
+ function wrapLiveQueryForMaterialization(sql2, fields) {
8561
+ if (fields == null || fields.length === 0) {
8562
+ return sql2;
8563
+ }
8564
+ const aliasList = fields.map((field) => quoteIdentifier(field)).join(", ");
8565
+ return `SELECT * FROM (${sql2}) ${quoteIdentifier(LIVE_QUERY_TABLE_ALIAS)} (${aliasList})`;
8566
+ }
8567
+
8097
8568
  // packages/client/src/sync/copy.ts
8098
8569
  var DELIMITER = "\t";
8099
8570
  var NULL_MARKER = "\\N";
@@ -8987,8 +9458,11 @@ function readBaseColumnTypeSql(column, localSchema) {
8987
9458
  return sqlType;
8988
9459
  }
8989
9460
  function collectEnumDefinitions(registry2, localSchema) {
9461
+ return collectEnumDefinitionsFromEntries(Object.values(registry2), localSchema);
9462
+ }
9463
+ function collectEnumDefinitionsFromEntries(entries, localSchema) {
8990
9464
  const enumDefinitionsByName = new Map;
8991
- for (const entry of Object.values(registry2)) {
9465
+ for (const entry of entries) {
8992
9466
  const columns = getProjectedColumns(entry).map(({ column }) => column);
8993
9467
  for (const column of columns) {
8994
9468
  const enumDefinition = readEnumColumnDefinition(column, localSchema);
@@ -9007,6 +9481,55 @@ function collectEnumDefinitions(registry2, localSchema) {
9007
9481
  }
9008
9482
  return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));
9009
9483
  }
9484
+ function ownsPersistentSyncedTable(entry) {
9485
+ return !entry.readProjection && entry.retention !== "ephemeral";
9486
+ }
9487
+ function collectDataExportSyncedTableNames(registry2) {
9488
+ const localSchema = getSyncRegistrySchema(registry2);
9489
+ const names = [];
9490
+ for (const [tableKey, entry] of Object.entries(registry2)) {
9491
+ if (!ownsPersistentSyncedTable(entry)) {
9492
+ continue;
9493
+ }
9494
+ names.push(getClientProjection(entry, tableKey, localSchema).syncedTable);
9495
+ }
9496
+ return names;
9497
+ }
9498
+ function buildDataExportCloneCleanupSql(registry2) {
9499
+ const localSchema = getSyncRegistrySchema(registry2);
9500
+ const statements = [];
9501
+ for (const [tableKey, entry] of Object.entries(registry2)) {
9502
+ if (!ownsPersistentSyncedTable(entry) || entry.mode === "readonly") {
9503
+ continue;
9504
+ }
9505
+ const projection2 = getClientProjection(entry, tableKey, localSchema);
9506
+ statements.push(`DROP TRIGGER IF EXISTS ${projection2.reconcileTrigger} ON ${projection2.syncedTable};`);
9507
+ statements.push(`DROP FUNCTION IF EXISTS ${projection2.reconcileFunction}();`);
9508
+ }
9509
+ return statements.join(`
9510
+ `);
9511
+ }
9512
+ function buildDataExportEnumHeaderSql(registry2) {
9513
+ const localSchema = getSyncRegistrySchema(registry2);
9514
+ const exportedEntries = Object.values(registry2).filter(ownsPersistentSyncedTable);
9515
+ const enumDefinitions = collectEnumDefinitionsFromEntries(exportedEntries, localSchema);
9516
+ if (enumDefinitions.length === 0) {
9517
+ return "";
9518
+ }
9519
+ const statements = [
9520
+ "-- Enum types referenced by the exported tables. `pg_dump -t` does not emit the enum types",
9521
+ "-- its tables depend on, so pgxsinkit generates them here from the sync registry (ADR-0035)."
9522
+ ];
9523
+ if (localSchema !== "public") {
9524
+ statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);
9525
+ }
9526
+ for (const enumDefinition of enumDefinitions) {
9527
+ statements.push(buildCreateEnumTypeSql(enumDefinition));
9528
+ }
9529
+ return `${statements.join(`
9530
+ `)}
9531
+ `;
9532
+ }
9010
9533
  function buildCreateEnumTypeSql(enumDefinition) {
9011
9534
  const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);
9012
9535
  const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlLiteral(value)).join(", ");
@@ -9464,7 +9987,7 @@ async function rebuildReadCacheOrDefer(args, previousFingerprint) {
9464
9987
 
9465
9988
  // packages/client/src/mutation-state.ts
9466
9989
  var MUTATION_TRANSITIONS = {
9467
- pending: ["sending"],
9990
+ pending: ["sending", "quarantined"],
9468
9991
  sending: ["acked", "failed", "quarantined", "conflicted", "rejected", "pending"],
9469
9992
  failed: ["pending", "quarantined"],
9470
9993
  quarantined: [],
@@ -10144,6 +10667,24 @@ function createMutationRuntime(options) {
10144
10667
  await options.db.query(query.sql, query.params);
10145
10668
  }
10146
10669
  },
10670
+ quarantineRecovered: async (table) => {
10671
+ assertValidMutationTransition("pending", "quarantined");
10672
+ assertValidMutationTransition("sending", "quarantined");
10673
+ assertValidMutationTransition("failed", "quarantined");
10674
+ const contexts = filterContexts(tableContexts, table);
10675
+ const nowUs = nowMicroseconds();
10676
+ for (const context of contexts) {
10677
+ const journal = context.tables.journal;
10678
+ const query = queryBuilder.update(journal).set({
10679
+ status: "quarantined",
10680
+ updatedAtUs: nowUs,
10681
+ nextRetryAtUs: null,
10682
+ lastError: "Quarantined on restore: recovered from a store backup, not replayed (ADR-0035).",
10683
+ conflictReason: null
10684
+ }).where(inArray(journal.status, ["pending", "sending", "failed"])).toSQL();
10685
+ await options.db.query(query.sql, query.params);
10686
+ }
10687
+ },
10147
10688
  readMutationStats: async (table) => {
10148
10689
  const contexts = filterContexts(tableContexts, table);
10149
10690
  const totals = {
@@ -11175,10 +11716,12 @@ async function startConfiguredSync(pg, input) {
11175
11716
  if (group.startPromise) {
11176
11717
  return group.startPromise;
11177
11718
  }
11719
+ const bootStamp = countsTowardBoot && input.bootCollector ? input.bootCollector.beginGroup(group.groupKey, group.specs.length) : undefined;
11178
11720
  group.startPromise = startGroupSync(pg, {
11179
11721
  groupKey: group.groupKey,
11180
11722
  specs: group.specs,
11181
11723
  registry: input.registry,
11724
+ ...bootStamp ? { bootStamp } : {},
11182
11725
  ...countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {},
11183
11726
  ...input.shapeHeaders ? { headers: input.shapeHeaders } : {},
11184
11727
  ...input.onSyncError ? { onSyncError: input.onSyncError } : {},
@@ -11189,6 +11732,7 @@ async function startConfiguredSync(pg, input) {
11189
11732
  for (const spec of group.specs) {
11190
11733
  input.onTableInitialSync?.(spec.key);
11191
11734
  }
11735
+ bootStamp?.markReady();
11192
11736
  markGroupReady(group.groupKey);
11193
11737
  if (countsTowardBoot) {
11194
11738
  pendingBootGroups -= 1;
@@ -11275,6 +11819,7 @@ async function startGroupSync(pg, input) {
11275
11819
  registry: input.registry,
11276
11820
  shapes,
11277
11821
  ...input.dbReady ? { dbReady: input.dbReady } : {},
11822
+ ...input.bootStamp ? { bootStamp: input.bootStamp } : {},
11278
11823
  ...input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {},
11279
11824
  ...input.onSyncError ? { onSyncError: input.onSyncError } : {},
11280
11825
  ...input.onSyncActivity ? { onSyncActivity: input.onSyncActivity } : {}
@@ -11744,6 +12289,7 @@ async function createSyncEngine(pg, options) {
11744
12289
  onSyncError,
11745
12290
  onSyncActivity,
11746
12291
  dbReady,
12292
+ bootStamp,
11747
12293
  maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,
11748
12294
  commitRetryDelayMs = computeRetryDelayMs
11749
12295
  }) => {
@@ -12159,6 +12705,7 @@ async function createSyncEngine(pg, options) {
12159
12705
  if (changeCount > 0) {
12160
12706
  syncDebug("sync received change batch from Electric", { changes: changeCount });
12161
12707
  }
12708
+ bootStamp?.onBatchDelivered(changeCount);
12162
12709
  const commitStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
12163
12710
  let batchMaxLsn = BigInt(-1);
12164
12711
  messages.forEach((message) => {
@@ -12207,7 +12754,9 @@ async function createSyncEngine(pg, options) {
12207
12754
  }
12208
12755
  });
12209
12756
  if (dbGateOpen) {
12757
+ const applyStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
12210
12758
  await enqueueCommit();
12759
+ bootStamp?.onApply((typeof performance !== "undefined" ? performance.now() : Date.now()) - applyStartedAt);
12211
12760
  if (changeCount > 0) {
12212
12761
  if (batchMaxLsn <= committedLsn) {
12213
12762
  const elapsed = (typeof performance !== "undefined" ? performance.now() : Date.now()) - commitStartedAt;
@@ -12231,7 +12780,9 @@ async function createSyncEngine(pg, options) {
12231
12780
  await initMetadataTables();
12232
12781
  dbGateOpen = true;
12233
12782
  syncDebug("boot commits opened");
12783
+ const drainStartedAt = typeof performance !== "undefined" ? performance.now() : Date.now();
12234
12784
  await enqueueCommit();
12785
+ bootStamp?.onApply((typeof performance !== "undefined" ? performance.now() : Date.now()) - drainStartedAt);
12235
12786
  });
12236
12787
  }
12237
12788
  streams.push({
@@ -12420,10 +12971,11 @@ function encodeEnvelope(codec, type, payload, id) {
12420
12971
  function isBridgeEnvelope(data) {
12421
12972
  return typeof data === "object" && data !== null && data.ch === BRIDGE_CHANNEL && data.v === BRIDGE_PROTOCOL_VERSION;
12422
12973
  }
12423
- function postBridgeMessage(port, codec, type, payload, id) {
12424
- const { envelope, transfer } = encodeEnvelope(codec, type, payload, id);
12425
- if (transfer && transfer.length > 0) {
12426
- port.postMessage(envelope, transfer);
12974
+ function postBridgeMessage(port, codec, type, payload, id, transfer) {
12975
+ const { envelope, transfer: codecTransfer } = encodeEnvelope(codec, type, payload, id);
12976
+ const allTransfer = [...codecTransfer ?? [], ...transfer ?? []];
12977
+ if (allTransfer.length > 0) {
12978
+ port.postMessage(envelope, allTransfer);
12427
12979
  } else {
12428
12980
  port.postMessage(envelope);
12429
12981
  }
@@ -12501,6 +13053,9 @@ async function attachSyncClient(options) {
12501
13053
  case "sync-error":
12502
13054
  options.onSyncError?.(new Error(event.message));
12503
13055
  break;
13056
+ case "boot-report":
13057
+ options.onBootReport?.(event.report);
13058
+ break;
12504
13059
  case "debug": {
12505
13060
  if (globalThis.__pgxsinkitDebug === true) {
12506
13061
  const line3 = `[pgxsinkit\xB7w ${event.stamp.toFixed(0)}ms] ${event.line}`;
@@ -12598,10 +13153,18 @@ async function attachSyncClient(options) {
12598
13153
  attachAckReject = reject;
12599
13154
  });
12600
13155
  const initialToken = options.getToken ? await options.getToken() : null;
13156
+ const memoryOverride = readTestStoreMarker(options) === "memory";
13157
+ const restoreWire = options.restoreFrom ? {
13158
+ buffer: await options.restoreFrom.arrayBuffer(),
13159
+ fileName: options.restoreFrom instanceof File ? options.restoreFrom.name : "restore.pgdata.tar",
13160
+ mimeType: options.restoreFrom.type || "application/octet-stream"
13161
+ } : undefined;
12601
13162
  const attachPayload = {
12602
13163
  token: initialToken,
12603
13164
  ...options.storeId ? { storeId: options.storeId } : {},
12604
- ...options.dataDir ? { dataDir: options.dataDir } : {},
13165
+ ...options.storePath ? { storePath: options.storePath } : {},
13166
+ ...memoryOverride ? { testStoreBackend: "memory" } : {},
13167
+ ...restoreWire ? { restore: restoreWire } : {},
12605
13168
  ...options.syncEnabled != null || options.role != null || options.freshStore != null ? {
12606
13169
  config: {
12607
13170
  ...options.syncEnabled != null ? { syncEnabled: options.syncEnabled } : {},
@@ -12610,7 +13173,7 @@ async function attachSyncClient(options) {
12610
13173
  }
12611
13174
  } : {}
12612
13175
  };
12613
- postBridgeMessage(port, codec, "attach", attachPayload);
13176
+ postBridgeMessage(port, codec, "attach", attachPayload, undefined, restoreWire ? [restoreWire.buffer] : undefined);
12614
13177
  try {
12615
13178
  await attachAck;
12616
13179
  } catch (error) {
@@ -12633,6 +13196,7 @@ async function attachSyncClient(options) {
12633
13196
  queryId,
12634
13197
  sql: input.sql,
12635
13198
  params: [...input.params],
13199
+ ...input.fields ? { fields: [...input.fields] } : {},
12636
13200
  ...input.pkColumns ? { pkColumns: [...input.pkColumns] } : {},
12637
13201
  ...input.use ? { use: [...input.use] } : {}
12638
13202
  }, id);
@@ -12712,7 +13276,8 @@ async function attachSyncClient(options) {
12712
13276
  queryRawRow: notSupported("client.queryRawRow"),
12713
13277
  ensureSynced: notSupported("client.ensureSynced"),
12714
13278
  isSynced: notSupported("client.isSynced"),
12715
- desync: notSupported("client.desync"),
13279
+ desync: (key) => rpc("desync", [key]),
13280
+ discardEphemeral: (key) => rpc("discardEphemeral", [key]),
12716
13281
  prepareQuery: async () => {
12717
13282
  return;
12718
13283
  },
@@ -12757,6 +13322,28 @@ async function attachSyncClient(options) {
12757
13322
  });
12758
13323
  },
12759
13324
  subscribeLiveRows,
13325
+ bootReport: () => rpc("bootReport", []),
13326
+ exportStore: async (exportOptions) => {
13327
+ const wire = await rpc("exportStore", [exportOptions]);
13328
+ return {
13329
+ file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
13330
+ report: wire.report
13331
+ };
13332
+ },
13333
+ exportDiagnostics: async (exportOptions) => {
13334
+ const wire = await rpc("exportDiagnostics", [exportOptions]);
13335
+ return {
13336
+ file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
13337
+ report: wire.report
13338
+ };
13339
+ },
13340
+ exportData: async (exportOptions) => {
13341
+ const wire = await rpc("exportData", [exportOptions]);
13342
+ return {
13343
+ file: new File([wire.buffer], wire.fileName, { type: wire.mimeType }),
13344
+ report: wire.report
13345
+ };
13346
+ },
12760
13347
  notifyAuthChanged: () => {
12761
13348
  pushToken();
12762
13349
  },
@@ -12769,6 +13356,7 @@ async function attachSyncClient(options) {
12769
13356
  function provisionSyncWorker(options) {
12770
13357
  const codec = options.codec ?? identityCodec;
12771
13358
  const port = resolvePort(options);
13359
+ const memoryOverride = readTestStoreMarker(options) === "memory";
12772
13360
  return new Promise((resolve, reject) => {
12773
13361
  const listener = (message) => {
12774
13362
  if (!isBridgeEnvelope(message.data))
@@ -12786,7 +13374,8 @@ function provisionSyncWorker(options) {
12786
13374
  port.start?.();
12787
13375
  postBridgeMessage(port, codec, "provision", {
12788
13376
  ...options.storeId ? { storeId: options.storeId } : {},
12789
- ...options.dataDir ? { dataDir: options.dataDir } : {}
13377
+ ...options.storePath ? { storePath: options.storePath } : {},
13378
+ ...memoryOverride ? { testStoreBackend: "memory" } : {}
12790
13379
  });
12791
13380
  });
12792
13381
  }
@@ -12868,7 +13457,8 @@ function defineSyncWorker(options) {
12868
13457
  const codec = options.codec ?? identityCodec;
12869
13458
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30000;
12870
13459
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15000;
12871
- const createPglite = options.createPglite ?? ((dataDir) => createClientPGlite(dataDir));
13460
+ const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));
13461
+ const workerTestMarker = readTestStoreMarker(options);
12872
13462
  const ports = new Set;
12873
13463
  const liveSubs = new Map;
12874
13464
  let provisioned = null;
@@ -12900,6 +13490,35 @@ function defineSyncWorker(options) {
12900
13490
  postBridgeMessage(port, codec, type, payload);
12901
13491
  };
12902
13492
  const broadcastEvent = (event) => broadcast("event", event);
13493
+ const RAIL_BUFFER_MAX = 500;
13494
+ const railBuffer = [];
13495
+ let railReplayed = false;
13496
+ setSyncDebugSink((line3, stamp, data) => {
13497
+ if (railBuffer.length >= RAIL_BUFFER_MAX)
13498
+ railBuffer.shift();
13499
+ railBuffer.push({ stamp, line: line3, ...data ? { data } : {} });
13500
+ broadcastEvent({ kind: "debug", stamp, line: line3, ...data ? { data } : {} });
13501
+ });
13502
+ const nowStamp = () => typeof performance !== "undefined" ? performance.now() : Date.now();
13503
+ const replayRailBufferTo = (port) => {
13504
+ if (railReplayed)
13505
+ return;
13506
+ railReplayed = true;
13507
+ const buffered = [...railBuffer];
13508
+ postBridgeMessage(port, codec, "event", {
13509
+ kind: "debug",
13510
+ stamp: nowStamp(),
13511
+ line: `[replay] replaying ${buffered.length} buffered rail line(s)`
13512
+ });
13513
+ for (const entry of buffered) {
13514
+ postBridgeMessage(port, codec, "event", {
13515
+ kind: "debug",
13516
+ stamp: entry.stamp,
13517
+ line: `[replay] ${entry.line}`,
13518
+ ...entry.data ? { data: entry.data } : {}
13519
+ });
13520
+ }
13521
+ };
12903
13522
  const emitStatus = (status) => {
12904
13523
  broadcastEvent({ kind: "status", status });
12905
13524
  for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {
@@ -12922,22 +13541,31 @@ function defineSyncWorker(options) {
12922
13541
  return bootPromise;
12923
13542
  tokenCache.push(attach.token);
12924
13543
  bootedRole = attach.config?.role;
12925
- setSyncDebugSink((line3, stamp, data) => {
12926
- broadcastEvent({ kind: "debug", stamp, line: line3, ...data ? { data } : {} });
12927
- });
12928
13544
  const registry2 = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
12929
- const dataDir = attach.dataDir ?? attach.storeId ?? options.dataDir ?? "idb://pgxsinkit-overlay-v1";
12930
- const precreatedPglite = provisioned && provisioned.dataDir === dataDir ? provisioned.pglite : options.precreatedPglite;
12931
- if (precreatedPglite === provisioned?.pglite) {
12932
- syncDebug("worker adopting provisioned store", { dataDir });
13545
+ const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
13546
+ const backendOverride = attach.testStoreBackend;
13547
+ const testMarker = backendOverride === "memory" ? "memory" : workerTestMarker;
13548
+ const restoreFrom = attach.restore ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType }) : undefined;
13549
+ const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;
13550
+ const precreatedPglite = adoptingProvisioned ? provisioned.pglite : restoreFrom ? undefined : options.precreatedPglite;
13551
+ const provisionStamp = adoptingProvisioned ? provisioned.stamp : undefined;
13552
+ if (adoptingProvisioned) {
13553
+ syncDebug("worker adopting provisioned store", { storePath });
13554
+ }
13555
+ if (restoreFrom) {
13556
+ syncDebug("worker restoring store from backup", { storePath, byteLength: attach.restore.buffer.byteLength });
12933
13557
  }
12934
13558
  bootPromise = createSyncClient({
12935
13559
  registry: registry2,
12936
13560
  electricUrl: options.electricUrl,
12937
13561
  writeUrl: options.writeUrl,
12938
- dataDir,
13562
+ storePath,
13563
+ ...testMarker ? { [TEST_STORE_BACKEND]: testMarker } : {},
13564
+ ...restoreFrom ? { restoreFrom } : {},
13565
+ bootMode: "worker",
13566
+ ...provisionStamp ? { provisionStamp } : {},
12939
13567
  ...precreatedPglite ? { precreatedPglite } : {},
12940
- ...options.pgliteInstance ? { pgliteInstance: options.pgliteInstance } : {},
13568
+ ...options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {},
12941
13569
  ...attach.config?.freshStore === true ? { freshStore: true } : {},
12942
13570
  getAuthToken: getWorkerAuthToken,
12943
13571
  autoSync: gatedTrigger,
@@ -12950,7 +13578,8 @@ function defineSyncWorker(options) {
12950
13578
  onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
12951
13579
  onReject: (details) => broadcastEvent({ kind: "reject", details }),
12952
13580
  onSchemaChange: (event) => broadcastEvent({ kind: "schema-change", event }),
12953
- onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message })
13581
+ onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message }),
13582
+ onBootReport: (report) => broadcastEvent({ kind: "boot-report", report })
12954
13583
  });
12955
13584
  return bootPromise;
12956
13585
  };
@@ -12995,6 +13624,10 @@ function defineSyncWorker(options) {
12995
13624
  return active.discardConflict(args[0], args[1]);
12996
13625
  case "discardQuarantined":
12997
13626
  return active.discardQuarantined(args[0], args[1]);
13627
+ case "desync":
13628
+ return active.desync(args[0]);
13629
+ case "discardEphemeral":
13630
+ return active.discardEphemeral(args[0]);
12998
13631
  case "readMutationDetails":
12999
13632
  return active.readMutationDetails(args[0]);
13000
13633
  case "diagnostics":
@@ -13003,6 +13636,23 @@ function defineSyncWorker(options) {
13003
13636
  return active.rawQuery(args[0], args[1], args[2]);
13004
13637
  case "rawExec":
13005
13638
  return active.rawExec(args[0], args[1]);
13639
+ case "bootReport":
13640
+ return active.bootReport();
13641
+ case "exportStore": {
13642
+ const { file, report } = await active.exportStore(args[0]);
13643
+ const buffer = await file.arrayBuffer();
13644
+ return { buffer, fileName: file.name, mimeType: file.type, report };
13645
+ }
13646
+ case "exportDiagnostics": {
13647
+ const { file, report } = await active.exportDiagnostics(args[0]);
13648
+ const buffer = await file.arrayBuffer();
13649
+ return { buffer, fileName: file.name, mimeType: file.type, report };
13650
+ }
13651
+ case "exportData": {
13652
+ const { file, report } = await active.exportData(args[0]);
13653
+ const buffer = await file.arrayBuffer();
13654
+ return { buffer, fileName: file.name, mimeType: file.type, report };
13655
+ }
13006
13656
  default: {
13007
13657
  const exhaustive = op;
13008
13658
  throw new Error(`unknown rpc op ${String(exhaustive)}`);
@@ -13013,10 +13663,11 @@ function defineSyncWorker(options) {
13013
13663
  const active = client ?? await bootPromise;
13014
13664
  if (!active)
13015
13665
  throw new Error("subscribe before attach");
13016
- const { queryId, sql: sql2, params, pkColumns, use } = payload;
13666
+ const { queryId, sql: sql2, params, pkColumns, use, fields } = payload;
13017
13667
  await active.prepareQuery({ sql: sql2, ...use ? { use } : {} });
13018
13668
  const live = active.pglite.live;
13019
- const registered = pkColumns && pkColumns.length === 1 ? await live.incrementalQuery(sql2, params, pkColumns[0]) : await live.query(sql2, params);
13669
+ const materialSql = wrapLiveQueryForMaterialization(sql2, fields);
13670
+ const registered = pkColumns && pkColumns.length === 1 ? await live.incrementalQuery(materialSql, params, pkColumns[0]) : await live.query(materialSql, params);
13020
13671
  const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
13021
13672
  postBridgeMessage(port, codec, "live-initial", { queryId, rows: registered.initialResults.rows }, id);
13022
13673
  const listener = (results) => {
@@ -13037,7 +13688,8 @@ function defineSyncWorker(options) {
13037
13688
  switch (envelope.type) {
13038
13689
  case "provision": {
13039
13690
  const provision = payload;
13040
- const dataDir = provision.dataDir ?? provision.storeId ?? options.dataDir ?? "idb://pgxsinkit-overlay-v1";
13691
+ const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
13692
+ const backendOverride = provision.testStoreBackend;
13041
13693
  if (bootPromise != null || provisioned != null) {
13042
13694
  postBridgeMessage(port, codec, "provision-ack", {
13043
13695
  ok: true,
@@ -13045,12 +13697,20 @@ function defineSyncWorker(options) {
13045
13697
  });
13046
13698
  break;
13047
13699
  }
13048
- const pglite = createPglite(dataDir);
13049
- provisioned = { dataDir, pglite };
13700
+ const provisionStartedAt = nowStamp();
13701
+ const pglite = createPglite(storePath, backendOverride);
13702
+ const stamp = pglite.then(() => {
13703
+ const readyAt = nowStamp();
13704
+ return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
13705
+ });
13706
+ provisioned = { storePath, pglite, stamp };
13050
13707
  pglite.catch(() => {
13051
13708
  return;
13052
13709
  });
13053
- syncDebug("worker store provisioned", { dataDir });
13710
+ stamp.catch(() => {
13711
+ return;
13712
+ });
13713
+ syncDebug("worker store provisioned", { storePath });
13054
13714
  pglite.then(() => postBridgeMessage(port, codec, "provision-ack", {
13055
13715
  ok: true,
13056
13716
  ...provision.storeId ? { storeId: provision.storeId } : {}
@@ -13071,7 +13731,17 @@ function defineSyncWorker(options) {
13071
13731
  }
13072
13732
  case "attach": {
13073
13733
  const attach = payload;
13734
+ replayRailBufferTo(port);
13074
13735
  const alreadyBooted = bootPromise !== null;
13736
+ if (alreadyBooted && attach.restore != null) {
13737
+ postBridgeMessage(port, codec, "attach-ack", {
13738
+ alreadyBooted,
13739
+ error: {
13740
+ message: "[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead."
13741
+ }
13742
+ });
13743
+ break;
13744
+ }
13075
13745
  if (alreadyBooted) {
13076
13746
  tokenCache.pushIfFresher(attach.token);
13077
13747
  const requested = attach.config?.role;
@@ -13122,7 +13792,8 @@ function defineSyncWorker(options) {
13122
13792
  if (!active)
13123
13793
  throw new Error("rpc before attach");
13124
13794
  const value = await dispatchRpc(active, op, args);
13125
- postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id);
13795
+ const transfer = op === "exportStore" || op === "exportDiagnostics" || op === "exportData" ? [value.buffer] : undefined;
13796
+ postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id, transfer);
13126
13797
  } catch (error) {
13127
13798
  postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
13128
13799
  }
@@ -13220,13 +13891,16 @@ function bindGlobalScope(connect) {
13220
13891
  }
13221
13892
  }
13222
13893
  // packages/client/src/index.ts
13223
- async function createClientPGlite(dataDir, options) {
13894
+ async function createClientPGlite(store, options) {
13895
+ const normalised = normaliseStorePathInput(store);
13896
+ const dataDir = resolveStoreDataDir(normalised.storePath, options?.backendOverride ?? normalised.backendOverride);
13224
13897
  const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
13225
13898
  const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => {
13226
13899
  return;
13227
13900
  }) : undefined;
13228
- return await timeAsync("boot pglite.create", () => PGlite2.create(dataDir, {
13901
+ return await timeAsync("boot pglite.create", () => PGlite3.create(dataDir, {
13229
13902
  ...bootAssets ?? {},
13903
+ ...options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {},
13230
13904
  extensions: {
13231
13905
  live
13232
13906
  }
@@ -13250,27 +13924,91 @@ async function createSyncClient(options) {
13250
13924
  if (options.pgliteInstance && options.precreatedPglite) {
13251
13925
  throw new Error("createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` \u2014 they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).");
13252
13926
  }
13253
- const createBootAssets = options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : undefined;
13254
- const fallbackDataDir = options.dataDir ?? "idb://pgxsinkit-overlay-v1";
13927
+ const restoreBoot = options.restoreFrom != null;
13928
+ if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
13929
+ throw new Error("createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` \u2014 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).");
13930
+ }
13931
+ if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {
13932
+ syncDebug("boot restore forces offline \u2014 ignoring the online sync option for this restore boot", {
13933
+ syncEnabled: options.syncEnabled === true,
13934
+ autoSync: options.autoSync != null
13935
+ });
13936
+ }
13937
+ const syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
13938
+ const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
13939
+ const bootReportBuilder = createBootReportBuilder({
13940
+ mode: options.bootMode ?? "in-process",
13941
+ freshStore: options.freshStore === true,
13942
+ overlapPrefetch,
13943
+ registryFingerprint: fingerprintRegistry(options.registry)
13944
+ });
13945
+ const lifecycleSlot = createLifecycleSlot();
13946
+ let finalizedBootReport = null;
13947
+ const finalizeBootReport = () => {
13948
+ if (finalizedBootReport)
13949
+ return;
13950
+ finalizedBootReport = bootReportBuilder.finalize();
13951
+ options.onBootReport?.(finalizedBootReport);
13952
+ };
13953
+ const testStoreMarker = readTestStoreMarker(options);
13954
+ const backendOverride = testStoreMarker === "memory" ? "memory" : undefined;
13955
+ const createClientOptions = {
13956
+ ...options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {},
13957
+ ...backendOverride ? { backendOverride } : {},
13958
+ ...restoreBoot ? { restoreFrom: options.restoreFrom } : {}
13959
+ };
13960
+ const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
13961
+ if (restoreBoot) {
13962
+ if (await storeTargetExists(fallbackStorePath, backendOverride)) {
13963
+ throw new RestoreTargetExistsError(fallbackStorePath);
13964
+ }
13965
+ }
13966
+ const timedCreate = async () => {
13967
+ const startedAt = performance.now();
13968
+ const created = await createClientPGlite(fallbackStorePath, createClientOptions);
13969
+ bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
13970
+ return created;
13971
+ };
13972
+ const refuseIfNonPersistent = (instance) => {
13973
+ if (testStoreMarker !== undefined)
13974
+ return;
13975
+ const observed = classifyNonPersistentDataDir(instance.dataDir);
13976
+ if (observed !== null)
13977
+ throw new NonPersistentStoreError(observed);
13978
+ };
13255
13979
  let pglite;
13980
+ let adoptedPrecreated = false;
13256
13981
  if (options.pgliteInstance) {
13982
+ refuseIfNonPersistent(options.pgliteInstance);
13257
13983
  pglite = options.pgliteInstance;
13258
13984
  } else if (options.precreatedPglite) {
13259
- pglite = await options.precreatedPglite.catch((error) => {
13260
- syncDebug("boot precreated pglite rejected \u2014 falling back to dataDir create", {
13261
- error: error instanceof Error ? error.message : String(error)
13985
+ const outcome = await options.precreatedPglite.then((instance) => ({ ok: true, instance }), (error) => ({ ok: false, error }));
13986
+ if (outcome.ok) {
13987
+ refuseIfNonPersistent(outcome.instance);
13988
+ pglite = outcome.instance;
13989
+ adoptedPrecreated = true;
13990
+ } else {
13991
+ syncDebug("boot precreated pglite rejected \u2014 falling back to storePath create", {
13992
+ error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error)
13262
13993
  });
13263
- return createClientPGlite(fallbackDataDir, createBootAssets);
13264
- });
13994
+ pglite = await timedCreate();
13995
+ }
13265
13996
  } else {
13266
- pglite = await createClientPGlite(fallbackDataDir, createBootAssets);
13997
+ pglite = await timedCreate();
13998
+ }
13999
+ if (adoptedPrecreated && options.provisionStamp) {
14000
+ const stamp = await options.provisionStamp.catch(() => null);
14001
+ if (stamp) {
14002
+ bootReportBuilder.setProvision({
14003
+ initdbMs: stamp.initdbMs,
14004
+ provisionedMsBeforeBoot: Math.max(0, bootReportBuilder.bootStartPerf - stamp.provisionReadyAt)
14005
+ });
14006
+ }
13267
14007
  }
13268
14008
  const engine = await createSyncEngine(pglite);
13269
14009
  pglite.electric = engine.namespace;
13270
- const syncEnabled = options.syncEnabled ?? true;
13271
14010
  let initialSyncCompleted = false;
13272
14011
  let degradedReason = null;
13273
- const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
13274
14012
  let openDbGate = () => {};
13275
14013
  const dbReady = overlapPrefetch ? new Promise((resolve) => {
13276
14014
  openDbGate = resolve;
@@ -13280,6 +14018,7 @@ async function createSyncClient(options) {
13280
14018
  registry: options.registry,
13281
14019
  promotedGroups,
13282
14020
  ...dbReady ? { dbReady } : {},
14021
+ bootCollector: bootReportBuilder,
13283
14022
  onLazyActivated: (groupKey) => {
13284
14023
  writeLazyGroupActivation(pglite, options.registry, groupKey);
13285
14024
  },
@@ -13299,6 +14038,7 @@ async function createSyncClient(options) {
13299
14038
  status.phase = "ready";
13300
14039
  options.onStatusChange?.(status);
13301
14040
  syncDebug("boot client ready");
14041
+ finalizeBootReport();
13302
14042
  resolveReady();
13303
14043
  },
13304
14044
  onSyncError: (error) => {
@@ -13335,22 +14075,24 @@ async function createSyncClient(options) {
13335
14075
  } : {}
13336
14076
  });
13337
14077
  let earlySync = null;
14078
+ let earlySyncStartedAt = 0;
13338
14079
  if (overlapPrefetch) {
13339
14080
  status.isRunning = true;
13340
14081
  status.phase = "syncing";
13341
14082
  options.onStatusChange?.(status);
14083
+ earlySyncStartedAt = performance.now();
13342
14084
  earlySync = startConfiguredSync(pglite, buildStartOptions(new Set));
13343
14085
  }
13344
14086
  if (!options.pgliteInstance) {
13345
14087
  if (options.prepareLocalDbBeforeSchema) {
13346
14088
  const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
13347
- await timeAsync("boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
14089
+ await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
13348
14090
  }
13349
14091
  const schemaSql = generateLocalSchemaSql(options.registry);
13350
- await timeAsync("boot local schema", () => pglite.exec(schemaSql));
14092
+ await bootReportBuilder.phase("schemaExec", "boot local schema", () => pglite.exec(schemaSql));
13351
14093
  if (options.prepareLocalDb) {
13352
14094
  const prepareLocalDb = options.prepareLocalDb;
13353
- await timeAsync("boot prepare(local-db)", () => prepareLocalDb(pglite));
14095
+ await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDb(pglite));
13354
14096
  }
13355
14097
  }
13356
14098
  const writePathHeaders = options.requestHeaders || options.writeRequestHeaders ? { ...options.requestHeaders ?? {}, ...options.writeRequestHeaders ?? {} } : undefined;
@@ -13365,10 +14107,13 @@ async function createSyncClient(options) {
13365
14107
  ...options.onConflict ? { onConflict: options.onConflict } : {},
13366
14108
  ...options.onReject ? { onReject: options.onReject } : {}
13367
14109
  });
13368
- await timeAsync("boot journal recovery", () => mutationRuntime.recoverSending());
14110
+ await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.recoverSending());
14111
+ if (restoreBoot) {
14112
+ await mutationRuntime.quarantineRecovered();
14113
+ }
13369
14114
  let versionEvent = null;
13370
14115
  if (!options.pgliteInstance) {
13371
- versionEvent = await timeAsync("boot store-version reconcile", () => reconcileLocalStoreVersion({
14116
+ versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () => reconcileLocalStoreVersion({
13372
14117
  db: pglite,
13373
14118
  registry: options.registry,
13374
14119
  runtime: mutationRuntime,
@@ -13384,20 +14129,24 @@ async function createSyncClient(options) {
13384
14129
  if (syncEnabled) {
13385
14130
  if (earlySync) {
13386
14131
  sync = await earlySync;
14132
+ bootReportBuilder.setSyncStartMs(performance.now() - earlySyncStartedAt);
14133
+ bootReportBuilder.markSyncStartDone();
13387
14134
  } else {
13388
14135
  const resetKeys = versionEvent?.status === "rebuilt" ? [...options.resetSubscriptionKeys ?? [], ...allGroupSubscriptionKeys(options.registry)] : options.resetSubscriptionKeys;
13389
14136
  await resetSubscriptionsIfRequested(pglite, resetKeys);
13390
14137
  status.phase = "syncing";
13391
14138
  options.onStatusChange?.(status);
13392
14139
  const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
13393
- sync = await timeAsync("boot sync start", () => startConfiguredSync(pglite, buildStartOptions(promotedGroups)));
14140
+ sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startConfiguredSync(pglite, buildStartOptions(promotedGroups)));
14141
+ bootReportBuilder.markSyncStartDone();
13394
14142
  }
13395
14143
  } else {
13396
14144
  status.phase = "ready";
13397
14145
  options.onStatusChange?.(status);
14146
+ finalizeBootReport();
13398
14147
  resolveReady();
13399
14148
  }
13400
- if (options.autoSync) {
14149
+ if (options.autoSync && !restoreBoot) {
13401
14150
  convergenceDriver = createConvergenceDriver({
13402
14151
  client: {
13403
14152
  flush: () => mutationRuntime.flush(),
@@ -13445,15 +14194,12 @@ async function createSyncClient(options) {
13445
14194
  return true;
13446
14195
  return activeSync.isTableStarted(key);
13447
14196
  };
13448
- const desync = async (key) => {
13449
- const entry = options.registry[key];
13450
- if (entry == null)
13451
- throw new Error(`desync: unknown table ${String(key)}`);
13452
- if (entry.subscription !== "lazy") {
13453
- throw new Error(`desync('${String(key)}') refused: only a lazy relation can be desynced \u2014 an eager relation is always-on and would immediately re-sync.`);
13454
- }
14197
+ const groupTableKeysFor = (key, entry) => {
13455
14198
  const targetGroup = entry.consistencyGroup;
13456
- const groupTableKeys = targetGroup == null ? [key] : Object.keys(options.registry).filter((candidate) => options.registry[candidate].consistencyGroup === targetGroup);
14199
+ return targetGroup == null ? [key] : Object.keys(options.registry).filter((candidate) => options.registry[candidate].consistencyGroup === targetGroup);
14200
+ };
14201
+ const tearDownLazyGroup = async (key, entry, label) => {
14202
+ const groupTableKeys = groupTableKeysFor(key, entry);
13457
14203
  let owed = 0;
13458
14204
  for (const member of groupTableKeys) {
13459
14205
  if (options.registry[member].mode === "readonly")
@@ -13462,7 +14208,7 @@ async function createSyncClient(options) {
13462
14208
  owed += stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
13463
14209
  }
13464
14210
  if (owed > 0) {
13465
- throw new Error(`desync('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`);
14211
+ throw new Error(`${label}('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`);
13466
14212
  }
13467
14213
  const activeSync = sync;
13468
14214
  const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;
@@ -13476,6 +14222,29 @@ async function createSyncClient(options) {
13476
14222
  await pglite.exec(buildDesyncTableSql(options.registry, member));
13477
14223
  }
13478
14224
  };
14225
+ const desync = async (key) => {
14226
+ const entry = options.registry[key];
14227
+ if (entry == null)
14228
+ throw new Error(`desync: unknown table ${String(key)}`);
14229
+ if (entry.subscription !== "lazy") {
14230
+ throw new Error(`desync('${String(key)}') refused: only a lazy relation can be desynced \u2014 an eager relation is always-on and would immediately re-sync.`);
14231
+ }
14232
+ await tearDownLazyGroup(key, entry, "desync");
14233
+ };
14234
+ const discardEphemeral = (key) => lifecycleSlot.run("discardEphemeral", async () => {
14235
+ const entry = options.registry[key];
14236
+ if (entry == null)
14237
+ throw new Error(`discardEphemeral: unknown table ${String(key)}`);
14238
+ if (entry.subscription !== "lazy") {
14239
+ throw new Error(`discardEphemeral('${String(key)}') refused: only a lazy relation can be discarded \u2014 an eager relation is always-on and would immediately re-sync.`);
14240
+ }
14241
+ for (const member of groupTableKeysFor(key, entry)) {
14242
+ if ((options.registry[member].retention ?? "persistent") !== "ephemeral") {
14243
+ throw new Error(`discardEphemeral('${String(key)}') refused: group member '${String(member)}' is persistent \u2014 ` + `discardEphemeral only drops an ephemeral relation's local rows. Use desync for a persistent lazy relation.`);
14244
+ }
14245
+ }
14246
+ await tearDownLazyGroup(key, entry, "discardEphemeral");
14247
+ });
13479
14248
  const transaction = async ({ mode }, run) => {
13480
14249
  const collected = [];
13481
14250
  const txTables = Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
@@ -13556,7 +14325,7 @@ async function createSyncClient(options) {
13556
14325
  await engine.close();
13557
14326
  await pglite.close();
13558
14327
  },
13559
- destroy: async (destroyOptions) => {
14328
+ destroy: (destroyOptions) => lifecycleSlot.run("destroy", async () => {
13560
14329
  if (!destroyOptions?.force) {
13561
14330
  const stats = await mutationRuntime.readMutationStats();
13562
14331
  const owed = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;
@@ -13571,12 +14340,12 @@ async function createSyncClient(options) {
13571
14340
  await pglite.exec(buildWipeLocalStoreSql(options.registry));
13572
14341
  await engine.close();
13573
14342
  await pglite.close();
13574
- },
13575
- dropReadCache: async () => {
14343
+ }),
14344
+ dropReadCache: () => lifecycleSlot.run("dropReadCache", async () => {
13576
14345
  await pglite.exec(buildDropReadCacheSql(options.registry));
13577
14346
  await pglite.exec(generateLocalSchemaSql(options.registry));
13578
14347
  await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
13579
- },
14348
+ }),
13580
14349
  flush: (table) => mutationRuntime.flush(table),
13581
14350
  reconcile: (table) => mutationRuntime.reconcile(table),
13582
14351
  retryFailed: (table) => mutationRuntime.retryFailed(table),
@@ -13603,6 +14372,7 @@ async function createSyncClient(options) {
13603
14372
  ensureSynced,
13604
14373
  isSynced,
13605
14374
  desync,
14375
+ discardEphemeral,
13606
14376
  prepareQuery,
13607
14377
  transaction,
13608
14378
  groupReady: async (table) => {
@@ -13614,8 +14384,9 @@ async function createSyncClient(options) {
13614
14384
  return;
13615
14385
  await activeSync.groupReady(groupKey);
13616
14386
  },
13617
- subscribeLiveRows: async ({ sql: sql2, params }, onRows) => {
13618
- const registered = await pglite.live.query(sql2, params);
14387
+ subscribeLiveRows: async ({ sql: sql2, params, fields }, onRows) => {
14388
+ const materialSql = wrapLiveQueryForMaterialization(sql2, fields);
14389
+ const registered = await pglite.live.query(materialSql, params);
13619
14390
  const listener = (results) => {
13620
14391
  onRows(results.rows);
13621
14392
  };
@@ -13626,6 +14397,35 @@ async function createSyncClient(options) {
13626
14397
  registered.unsubscribe(listener);
13627
14398
  }
13628
14399
  };
14400
+ },
14401
+ bootReport: async () => finalizedBootReport,
14402
+ exportStore: async (exportOptions) => {
14403
+ await ready;
14404
+ return lifecycleSlot.run("exportStore", () => performStoreExport({
14405
+ pglite,
14406
+ readMutationStats: () => mutationRuntime.readMutationStats(),
14407
+ ...options.storePath != null ? { storePath: options.storePath } : {}
14408
+ }, exportOptions));
14409
+ },
14410
+ exportDiagnostics: async (exportOptions) => {
14411
+ await ready;
14412
+ return lifecycleSlot.run("exportDiagnostics", () => performDiagnosticExport({
14413
+ pglite,
14414
+ readMutationStats: () => mutationRuntime.readMutationStats(),
14415
+ ...options.storePath != null ? { storePath: options.storePath } : {}
14416
+ }, exportOptions));
14417
+ },
14418
+ exportData: async (exportOptions) => {
14419
+ await ready;
14420
+ return lifecycleSlot.run("exportData", () => performDataExport({
14421
+ pglite,
14422
+ readMutationStats: () => mutationRuntime.readMutationStats(),
14423
+ flush: () => mutationRuntime.flush(),
14424
+ syncedTableNames: collectDataExportSyncedTableNames(options.registry),
14425
+ enumHeaderSql: buildDataExportEnumHeaderSql(options.registry),
14426
+ cloneCleanupSql: buildDataExportCloneCleanupSql(options.registry),
14427
+ ...options.storePath != null ? { storePath: options.storePath } : {}
14428
+ }, exportOptions));
13629
14429
  }
13630
14430
  };
13631
14431
  return client;
@@ -13690,14 +14490,23 @@ function getClientProjection2(entry, tableKey) {
13690
14490
  return entry.clientProjection;
13691
14491
  }
13692
14492
  export {
14493
+ wrapLiveQueryForMaterialization,
13693
14494
  timeAsync,
13694
14495
  syncDebug,
14496
+ storeTargetExists,
14497
+ storeIndexedDbDatabaseName,
13695
14498
  setSyncDebugSink,
13696
14499
  seedLiveDiffState,
14500
+ runThrowawayCloneDump,
13697
14501
  rowKey,
14502
+ resolveStoreDataDir,
13698
14503
  replAdapter,
13699
14504
  provisionSyncWorker,
13700
14505
  postBridgeMessage,
14506
+ performStoreExport,
14507
+ performDiagnosticExport,
14508
+ performDatadirDump,
14509
+ performDataExport,
13701
14510
  isBridgeEnvelope,
13702
14511
  instrumentShapeFetch,
13703
14512
  identityCodec,
@@ -13710,9 +14519,11 @@ export {
13710
14519
  generateLocalSchemaSql,
13711
14520
  findReferencedLazyKeysInSql,
13712
14521
  encodeEnvelope,
14522
+ deriveStoreId,
13713
14523
  defineSyncWorker,
13714
14524
  createWorkerTokenCache,
13715
14525
  createSyncClient,
14526
+ createLifecycleSlot,
13716
14527
  createIntervalConvergenceTrigger,
13717
14528
  createConvergenceDriver,
13718
14529
  createClientPGlite,
@@ -13722,10 +14533,16 @@ export {
13722
14533
  buildLazyGuardIndex,
13723
14534
  attachSyncClient,
13724
14535
  assertLazyRefsActivated,
14536
+ RestoreTargetExistsError,
14537
+ NonPersistentStoreError,
13725
14538
  LiveRowsMaterializer,
14539
+ LifecycleBusyError,
13726
14540
  LazyRelationNotActivatedError,
14541
+ InvalidStorePathError,
14542
+ DataExportDrainError,
14543
+ DEFAULT_DRAIN_TIMEOUT_MS,
13727
14544
  BRIDGE_PROTOCOL_VERSION,
13728
14545
  BRIDGE_CHANNEL
13729
14546
  };
13730
14547
 
13731
- //# debugId=22D1673F4572222464756E2164756E21
14548
+ //# debugId=ED0C4066D1B14CF464756E2164756E21