@pgxsinkit/client 0.3.0 → 0.5.0

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 (107) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +10 -3
  5. package/dist/boot-report.d.ts +6 -6
  6. package/dist/circuits/envelope-to-change.d.ts +9 -5
  7. package/dist/circuits/envelope-to-change.d.ts.map +1 -1
  8. package/dist/circuits/group-sync.d.ts +2 -2
  9. package/dist/circuits/group-sync.d.ts.map +1 -1
  10. package/dist/circuits/stream-source.d.ts +6 -0
  11. package/dist/circuits/stream-source.d.ts.map +1 -1
  12. package/dist/circuits/sync-engine.d.ts +2 -2
  13. package/dist/circuits/sync-engine.d.ts.map +1 -1
  14. package/dist/event-lane.d.ts +32 -1
  15. package/dist/event-lane.d.ts.map +1 -1
  16. package/dist/export-data.d.ts +3 -3
  17. package/dist/export-dump.d.ts +9 -9
  18. package/dist/export-dump.d.ts.map +1 -1
  19. package/dist/export-store.d.ts +13 -13
  20. package/dist/index.d.ts +191 -95
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +989 -432
  23. package/dist/index.js.map +39 -36
  24. package/dist/local-store.d.ts +1 -1
  25. package/dist/local-store.d.ts.map +1 -1
  26. package/dist/local-tables.d.ts +58 -0
  27. package/dist/local-tables.d.ts.map +1 -1
  28. package/dist/mutation.d.ts +2 -2
  29. package/dist/mutation.d.ts.map +1 -1
  30. package/dist/mutations-api.d.ts.map +1 -1
  31. package/dist/opfs-effects.d.ts +30 -2
  32. package/dist/opfs-effects.d.ts.map +1 -1
  33. package/dist/schema.d.ts +12 -1
  34. package/dist/schema.d.ts.map +1 -1
  35. package/dist/store-boot.d.ts +30 -2
  36. package/dist/store-boot.d.ts.map +1 -1
  37. package/dist/store-build.d.ts +19 -0
  38. package/dist/store-build.d.ts.map +1 -0
  39. package/dist/store-engine.d.ts +22 -0
  40. package/dist/store-engine.d.ts.map +1 -0
  41. package/dist/store-meta.d.ts +29 -3
  42. package/dist/store-meta.d.ts.map +1 -1
  43. package/dist/store-ownership-lock.d.ts +33 -0
  44. package/dist/store-ownership-lock.d.ts.map +1 -0
  45. package/dist/store-path.d.ts +40 -28
  46. package/dist/store-path.d.ts.map +1 -1
  47. package/dist/sync/apply.d.ts +5 -5
  48. package/dist/sync/apply.d.ts.map +1 -1
  49. package/dist/sync/copy.d.ts +82 -6
  50. package/dist/sync/copy.d.ts.map +1 -1
  51. package/dist/sync/drizzle-executor.d.ts +4 -4
  52. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  53. package/dist/sync/subscription-state.d.ts +5 -5
  54. package/dist/sync/subscription-state.d.ts.map +1 -1
  55. package/dist/testing.d.ts +1 -1
  56. package/dist/testing.js +2 -1
  57. package/dist/testing.js.map +4 -4
  58. package/dist/worker/attach-sync-client.d.ts +24 -13
  59. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  60. package/dist/worker/define-sync-worker.d.ts +35 -18
  61. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  62. package/dist/worker/live-query-manager.d.ts +3 -3
  63. package/dist/worker/live-query-manager.d.ts.map +1 -1
  64. package/dist/worker/live-query-params-guard.d.ts +5 -5
  65. package/dist/worker/protocol.d.ts +26 -7
  66. package/dist/worker/protocol.d.ts.map +1 -1
  67. package/package.json +11 -8
  68. package/skills/core/SKILL.md +80 -15
  69. package/skills/operating/SKILL.md +129 -129
  70. package/skills/operating/references/postgres-builds.md +48 -0
  71. package/src/boot-report.ts +9 -9
  72. package/src/circuits/envelope-to-change.ts +121 -12
  73. package/src/circuits/group-sync.ts +2 -2
  74. package/src/circuits/stream-source.ts +35 -9
  75. package/src/circuits/sync-engine.ts +6 -4
  76. package/src/event-lane.ts +132 -14
  77. package/src/export-data.ts +4 -4
  78. package/src/export-dump.ts +21 -26
  79. package/src/export-store.ts +17 -17
  80. package/src/index.ts +520 -284
  81. package/src/live-rows-sql.ts +1 -1
  82. package/src/local-store.ts +2 -2
  83. package/src/local-tables.ts +70 -6
  84. package/src/mutation.ts +9 -8
  85. package/src/mutations-api.ts +2 -2
  86. package/src/opfs-effects.ts +74 -10
  87. package/src/schema.ts +124 -18
  88. package/src/store-boot.ts +71 -7
  89. package/src/store-build.ts +37 -0
  90. package/src/store-engine.ts +94 -0
  91. package/src/store-lifecycle.ts +1 -1
  92. package/src/store-meta.ts +155 -4
  93. package/src/store-ownership-lock.ts +109 -0
  94. package/src/store-path.ts +56 -40
  95. package/src/sync/apply.ts +32 -46
  96. package/src/sync/copy.ts +108 -13
  97. package/src/sync/drizzle-executor.ts +13 -14
  98. package/src/sync/metadata-tables.ts +1 -1
  99. package/src/sync/subscription-state.ts +7 -7
  100. package/src/testing.ts +3 -3
  101. package/src/worker/attach-sync-client.ts +142 -56
  102. package/src/worker/define-sync-worker.ts +204 -75
  103. package/src/worker/engine-router.ts +1 -1
  104. package/src/worker/live-query-fingerprint.ts +4 -4
  105. package/src/worker/live-query-manager.ts +12 -12
  106. package/src/worker/live-query-params-guard.ts +10 -10
  107. package/src/worker/protocol.ts +38 -7
package/dist/index.js CHANGED
@@ -1,20 +1,15 @@
1
1
  // @bun
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
15
12
  };
16
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
- var __require = import.meta.require;
18
13
 
19
14
  // packages/client/src/debug.ts
20
15
  function setSyncDebugSink(sink) {
@@ -65,9 +60,9 @@ function createGroupAccumulator(groupKey, tables, bootStartPerf) {
65
60
  frozen = true;
66
61
  if (frozen)
67
62
  return;
68
- const now2 = nowMs();
69
- fetchMs += Math.max(0, now2 - lastMark);
70
- lastMark = now2;
63
+ const now = nowMs();
64
+ fetchMs += Math.max(0, now - lastMark);
65
+ lastMark = now;
71
66
  requests += 1;
72
67
  rows += changeCount;
73
68
  },
@@ -100,7 +95,7 @@ function createBootReportBuilder(init) {
100
95
  const bootStartPerf = nowMs();
101
96
  const durations = new Map;
102
97
  let prepareMs = null;
103
- let pgliteCreateMs = null;
98
+ let pgwasmCreateMs = null;
104
99
  let provision = null;
105
100
  let warmBoot = {
106
101
  schemaSkipped: false,
@@ -135,7 +130,7 @@ function createBootReportBuilder(init) {
135
130
  }
136
131
  },
137
132
  setPgliteCreateMs: (ms) => {
138
- pgliteCreateMs = ms;
133
+ pgwasmCreateMs = ms;
139
134
  },
140
135
  setProvision: (value) => {
141
136
  provision = value;
@@ -201,7 +196,7 @@ function createBootReportBuilder(init) {
201
196
  provision,
202
197
  warmBoot,
203
198
  phases: {
204
- pgliteCreateMs,
199
+ pgwasmCreateMs,
205
200
  schemaExecMs: duration("schemaExec"),
206
201
  journalRecoveryMs: duration("journalRecovery"),
207
202
  storeVersionReconcileMs: duration("storeVersionReconcile"),
@@ -267,12 +262,14 @@ function outboxStatements(localSchema) {
267
262
  "enqueued_at_us BIGINT NOT NULL",
268
263
  "attempt_count INTEGER NOT NULL DEFAULT 0",
269
264
  "next_retry_at_us BIGINT",
270
- "last_reason TEXT"
265
+ "last_reason TEXT",
266
+ "acked_at_us BIGINT"
271
267
  ].join(`,
272
268
  `)}
273
269
  );`,
274
270
  renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_stream_seq_idx`, ["stream", "seq"]),
275
- renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_retry_seq_idx`, ["next_retry_at_us", "seq"])
271
+ renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_retry_seq_idx`, ["next_retry_at_us", "seq"]),
272
+ renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_acked_seq_idx`, ["acked_at_us", "seq"])
276
273
  ];
277
274
  }
278
275
  function buildLocalMetaBootstrapSql(registry) {
@@ -284,12 +281,14 @@ function buildEntryClusterStatements(entry, tableKey, localSchema) {
284
281
  const objectSchema = ephemeral ? "public" : localSchema;
285
282
  const temp = ephemeral ? "TEMP " : "";
286
283
  const projection = getClientProjection(entry, tableKey, objectSchema);
287
- const columns = getProjectedColumns(entry).map(({ column }) => column);
284
+ const projectedColumns = getProjectedColumns(entry);
285
+ const columns = projectedColumns.map(({ column }) => column);
288
286
  const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
289
287
  const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
290
288
  statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (
291
289
  ${baseColumnsSql}
292
290
  );`);
291
+ statements.push(...buildLocalIndexStatements(entry, projection.syncedTable, projectedColumns));
293
292
  if (entry.mode === "readonly") {
294
293
  return statements;
295
294
  }
@@ -483,7 +482,6 @@ function buildReadModelViewSql(entry, projection, columnNames) {
483
482
  if (!projection.overlayTable) {
484
483
  throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);
485
484
  }
486
- const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);
487
485
  const syncedLocalUpdatedExpression = columnNames.includes("updated_at_us") ? "t.updated_at_us" : "CAST(0 AS BIGINT)";
488
486
  return [
489
487
  "SELECT",
@@ -500,14 +498,42 @@ function buildReadModelViewSql(entry, projection, columnNames) {
500
498
  ` 'synced' AS overlay_kind,`,
501
499
  ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,
502
500
  `FROM ${projection.syncedTable} AS t`,
503
- "WHERE NOT EXISTS (",
504
- " SELECT 1",
505
- ` FROM ${projection.overlayTable} AS o`,
506
- ` WHERE ${pkMatch}`,
507
- ")"
501
+ ...buildOverlayNonMembershipTest(entry.primaryKey.columns, projection.overlayTable)
508
502
  ].join(`
509
503
  `);
510
504
  }
505
+ function buildLocalIndexStatements(entry, syncedTable, projectedColumns) {
506
+ const localIndexes = entry.clientProjection?.localIndexes ?? [];
507
+ if (localIndexes.length === 0) {
508
+ return [];
509
+ }
510
+ const columnNameByKey = new Map;
511
+ for (const { propertyKey, columnName } of projectedColumns) {
512
+ columnNameByKey.set(propertyKey, columnName);
513
+ columnNameByKey.set(columnName, columnName);
514
+ }
515
+ return localIndexes.map((index) => {
516
+ const columnExpressions = index.columns.map((column) => {
517
+ const columnName = columnNameByKey.get(column);
518
+ if (!columnName) {
519
+ throw new Error(`local index ${index.name} on ${syncedTable} names column ${column}, which is not a projected column`);
520
+ }
521
+ return maybeQuoteIdentifier(columnName);
522
+ });
523
+ return renderCreateIndexStatement(syncedTable, maybeQuoteIdentifier(index.name), columnExpressions, {
524
+ ...index.unique === true ? { unique: true } : {}
525
+ });
526
+ });
527
+ }
528
+ function buildOverlayNonMembershipTest(primaryKeyColumns, overlayTable) {
529
+ const key = primaryKeyColumns.length === 1 ? `t.${primaryKeyColumns[0]}` : `(${primaryKeyColumns.map((column) => `t.${column}`).join(", ")})`;
530
+ return [
531
+ `WHERE ${key} NOT IN (`,
532
+ ` SELECT ${primaryKeyColumns.map((column) => `o.${column}`).join(", ")}`,
533
+ ` FROM ${overlayTable} AS o`,
534
+ ")"
535
+ ];
536
+ }
511
537
  function buildTableColumnSql(columns, primaryKeyColumns, localSchema) {
512
538
  return [
513
539
  ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),
@@ -727,9 +753,6 @@ function readArrayDimensions(column) {
727
753
  const arrayColumn = column;
728
754
  return arrayColumn.dimensions ?? 0;
729
755
  }
730
- function buildPrimaryKeyMatch(primaryKeyColumns) {
731
- return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(" AND ");
732
- }
733
756
  function getClientProjection(entry, tableKey, localSchema) {
734
757
  const projection = baseProjection(entry, tableKey);
735
758
  const syncedTableName = projection.syncedTable ?? tableKey;
@@ -870,7 +893,8 @@ import {
870
893
  import {
871
894
  deriveSyncColumnTypes,
872
895
  getLocalSyncedTablePrimaryKeyColumns,
873
- getSyncRegistrySchema as getSyncRegistrySchema2
896
+ getSyncRegistrySchema as getSyncRegistrySchema2,
897
+ jsonUdtName
874
898
  } from "@pgxsinkit/contracts";
875
899
  function buildJournalFixedColumns() {
876
900
  return {
@@ -930,7 +954,8 @@ function buildOutboxColumns() {
930
954
  enqueuedAtUs: bigintText("enqueued_at_us").notNull(),
931
955
  attemptCount: integer("attempt_count").notNull().default(0),
932
956
  nextRetryAtUs: bigintText("next_retry_at_us"),
933
- lastReason: text("last_reason")
957
+ lastReason: text("last_reason"),
958
+ ackedAtUs: bigintText("acked_at_us")
934
959
  };
935
960
  }
936
961
  function makeTable(localSchema, name, columns, ephemeral = false) {
@@ -1070,6 +1095,16 @@ function getReadModelView(registry, tableKey) {
1070
1095
  slot.readModel = view;
1071
1096
  return view;
1072
1097
  }
1098
+ function scalarJsonColumnNames(columnTypes) {
1099
+ const names = [];
1100
+ for (const column of columnTypes) {
1101
+ const udt = jsonUdtName(column);
1102
+ if (udt === "json" || udt === "jsonb") {
1103
+ names.push(column.name);
1104
+ }
1105
+ }
1106
+ return names;
1107
+ }
1073
1108
  function resolveApplyTarget(registry, tableKey) {
1074
1109
  const entry = requireEntry(registry, tableKey);
1075
1110
  const table = getSyncedLocalTable(registry, tableKey);
@@ -1080,13 +1115,21 @@ function resolveApplyTarget(registry, tableKey) {
1080
1115
  columnByName[column.name] = column;
1081
1116
  propertyKeyByName[column.name] = propertyKey;
1082
1117
  }
1118
+ const localPrimaryKey = getLocalSyncedTablePrimaryKeyColumns(entry).map((declared) => columns[declared] ? columns[declared].name : declared);
1119
+ const localPrimaryKeySet = new Set(localPrimaryKey);
1120
+ const serverColumns = getColumns(entry.table);
1121
+ const serverPrimaryKey = entry.primaryKey.columns.map((declared) => serverColumns[declared] ? serverColumns[declared].name : declared);
1122
+ const columnTypes = deriveSyncColumnTypes(entry);
1083
1123
  return {
1084
1124
  table,
1085
1125
  columnByName,
1086
1126
  propertyKeyByName,
1087
- primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry).map((declared) => columns[declared] ? columns[declared].name : declared),
1127
+ primaryKey: localPrimaryKey,
1128
+ serverPrimaryKey,
1129
+ droppedKeyColumns: serverPrimaryKey.filter((name) => !localPrimaryKeySet.has(name)),
1088
1130
  applyMode: entry.applyMode,
1089
- columnTypes: deriveSyncColumnTypes(entry),
1131
+ columnTypes,
1132
+ jsonColumns: scalarJsonColumnNames(columnTypes),
1090
1133
  insertRenderCache: new Map
1091
1134
  };
1092
1135
  }
@@ -1164,11 +1207,11 @@ var init_local_tables = __esm(() => {
1164
1207
  });
1165
1208
 
1166
1209
  // packages/client/src/sync/drizzle-executor.ts
1167
- import { drizzle } from "drizzle-orm/pglite";
1210
+ import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
1168
1211
  function drizzleOverPg(pg) {
1169
1212
  let db = handles.get(pg);
1170
1213
  if (!db) {
1171
- db = drizzle({ client: pg });
1214
+ db = drizzle(pg);
1172
1215
  handles.set(pg, db);
1173
1216
  }
1174
1217
  return db;
@@ -1452,6 +1495,8 @@ var init_subscription_client = __esm(() => {
1452
1495
  });
1453
1496
 
1454
1497
  // packages/client/src/sync/copy.ts
1498
+ import { getTableConfig as getTableConfig3 } from "drizzle-orm/pg-core";
1499
+ import { quoteIdentifier as quoteIdentifier3 } from "@pgxsinkit/contracts";
1455
1500
  function escapeCopyText(value) {
1456
1501
  return value.replace(COPY_TEXT_ESCAPE_RE, (c) => COPY_TEXT_ESCAPES[c] ?? c);
1457
1502
  }
@@ -1471,11 +1516,11 @@ function numberToText(value) {
1471
1516
  return "-Infinity";
1472
1517
  return String(value);
1473
1518
  }
1474
- function quoteArrayElement(text3) {
1475
- const needsQuote = text3.length === 0 || text3.toLowerCase() === "null" || ARRAY_NEEDS_QUOTE_RE.test(text3);
1519
+ function quoteArrayElement(text) {
1520
+ const needsQuote = text.length === 0 || text.toLowerCase() === "null" || ARRAY_NEEDS_QUOTE_RE.test(text);
1476
1521
  if (!needsQuote)
1477
- return text3;
1478
- return '"' + text3.replace(/(["\\])/g, "\\$1") + '"';
1522
+ return text;
1523
+ return '"' + text.replace(/(["\\])/g, "\\$1") + '"';
1479
1524
  }
1480
1525
  function arrayToText(arr) {
1481
1526
  const elements = arr.map((el) => {
@@ -1537,8 +1582,20 @@ function serializeCopyValue(value, udtName) {
1537
1582
  function generateCopyData(rows, columns, columnTypes) {
1538
1583
  return rows.map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER)).join(ROW_SEPARATOR);
1539
1584
  }
1585
+ function buildCopyFromBlobStatement({
1586
+ table,
1587
+ columns,
1588
+ rows,
1589
+ udtNames
1590
+ }) {
1591
+ const { name: tableName, schema } = getTableConfig3(table);
1592
+ const copyTarget = schema ? `${quoteIdentifier3(schema)}.${quoteIdentifier3(tableName)}` : quoteIdentifier3(tableName);
1593
+ const columnList = columns.map((column) => quoteIdentifier3(column)).join(", ");
1594
+ const sql = `COPY ${copyTarget} (${columnList}) FROM '/dev/blob' WITH (FORMAT text)`;
1595
+ return { sql, params: [], blob: COPY_TEXT_ENCODER.encode(generateCopyData(rows, columns, udtNames)) };
1596
+ }
1540
1597
  var DELIMITER = "\t", NULL_MARKER = "\\N", ROW_SEPARATOR = `
1541
- `, COPY_TEXT_ESCAPES, COPY_TEXT_ESCAPE_RE, ARRAY_NEEDS_QUOTE_RE, JSON_UDT_NAMES, JSON_ARRAY_UDT_NAMES;
1598
+ `, COPY_TEXT_ESCAPES, COPY_TEXT_ESCAPE_RE, ARRAY_NEEDS_QUOTE_RE, JSON_UDT_NAMES, JSON_ARRAY_UDT_NAMES, COPY_TEXT_ENCODER;
1542
1599
  var init_copy = __esm(() => {
1543
1600
  COPY_TEXT_ESCAPES = {
1544
1601
  "\\": "\\\\",
@@ -1553,12 +1610,13 @@ var init_copy = __esm(() => {
1553
1610
  ARRAY_NEEDS_QUOTE_RE = /[{}",\\ \t\n\r\v\f]/;
1554
1611
  JSON_UDT_NAMES = new Set(["json", "jsonb"]);
1555
1612
  JSON_ARRAY_UDT_NAMES = new Set(["_json", "_jsonb"]);
1613
+ COPY_TEXT_ENCODER = new TextEncoder;
1556
1614
  });
1557
1615
 
1558
1616
  // packages/client/src/sync/apply.ts
1559
1617
  import { and, eq as eq2, fillPlaceholders, sql } from "drizzle-orm";
1560
- import { getTableConfig as getTableConfig3 } from "drizzle-orm/pg-core";
1561
- import { quoteIdentifier as quoteIdentifier3 } from "@pgxsinkit/contracts";
1618
+ import { getTableConfig as getTableConfig4 } from "drizzle-orm/pg-core";
1619
+ import { jsonUdtName as jsonUdtName2, quoteIdentifier as quoteIdentifier4 } from "@pgxsinkit/contracts";
1562
1620
  function toDriverRow(target, data) {
1563
1621
  const out = {};
1564
1622
  for (const name of Object.keys(data)) {
@@ -1588,7 +1646,7 @@ function insertInto(db, target, colNames) {
1588
1646
  return hasGeneratedIdentityColumn(target, colNames) ? builder.overridingSystemValue() : builder;
1589
1647
  }
1590
1648
  function castTypeFor(column, tableSchema) {
1591
- const base = column.isEnum ? tableSchema ? `${quoteIdentifier3(tableSchema)}.${quoteIdentifier3(column.sqlType)}` : quoteIdentifier3(column.sqlType) : column.sqlType;
1649
+ const base = column.isEnum ? tableSchema ? `${quoteIdentifier4(tableSchema)}.${quoteIdentifier4(column.sqlType)}` : quoteIdentifier4(column.sqlType) : column.sqlType;
1592
1650
  return `${base}${column.isArray ? "[]" : ""}`;
1593
1651
  }
1594
1652
  function renderInsert(db, target, colNames, rowCount) {
@@ -1734,12 +1792,12 @@ function assertUniformColumnSet(target, columns, rows, applier) {
1734
1792
  continue;
1735
1793
  const missing = columns.filter((column) => !(column in row));
1736
1794
  const extra = keys.filter((key) => !expected.has(key));
1737
- throw new Error(`[pgxsinkit] ${applier}: batch for ${getTableConfig3(target.table).name} ` + `mixes column sets \u2014 every row must carry the same columns as the first ` + `(${columns.join(", ")})${missing.length > 0 ? `; missing ${missing.join(", ")}` : ""}` + `${extra.length > 0 ? `; unexpected ${extra.join(", ")}` : ""}`);
1795
+ throw new Error(`[pgxsinkit] ${applier}: batch for ${getTableConfig4(target.table).name} ` + `mixes column sets \u2014 every row must carry the same columns as the first ` + `(${columns.join(", ")})${missing.length > 0 ? `; missing ${missing.join(", ")}` : ""}` + `${extra.length > 0 ? `; unexpected ${extra.join(", ")}` : ""}`);
1738
1796
  }
1739
1797
  }
1740
1798
  async function applyUpsertsToTable({ pg, target, messages, debug }) {
1741
- const primaryKey2 = target.primaryKey;
1742
- if (primaryKey2.length === 0)
1799
+ const primaryKey = target.primaryKey;
1800
+ if (primaryKey.length === 0)
1743
1801
  throw new Error("applyUpsertsToTable requires a primary key");
1744
1802
  const data = messages.map((message) => message.value);
1745
1803
  const firstRow = data[0];
@@ -1765,7 +1823,7 @@ async function applyUpsertsToTable({ pg, target, messages, debug }) {
1765
1823
  }
1766
1824
  function jsonRecordsetColumns(target, firstRow) {
1767
1825
  const present = (name) => Object.prototype.hasOwnProperty.call(firstRow, name);
1768
- const { schema } = getTableConfig3(target.table);
1826
+ const { schema } = getTableConfig4(target.table);
1769
1827
  return target.columnTypes.filter((column) => present(column.name)).map((column) => ({ name: column.name, castType: castTypeFor(column, schema) }));
1770
1828
  }
1771
1829
  function jsonConflictClause(target, columns) {
@@ -1789,7 +1847,7 @@ async function applyMessagesToTableWithJsonImpl({ pg, target, messages, debug },
1789
1847
  const columns = jsonRecordsetColumns(target, firstRow);
1790
1848
  assertUniformColumnSet(target, columns.map((column) => column.name), data, "applyMessagesToTableWithJson");
1791
1849
  const targetTable = target.table;
1792
- const recordDef = columns.map((column) => `${quoteIdentifier3(column.name)} ${column.castType}`).join(", ");
1850
+ const recordDef = columns.map((column) => `${quoteIdentifier4(column.name)} ${column.castType}`).join(", ");
1793
1851
  const conflictClause = conflict ? sql` ${conflict}` : sql``;
1794
1852
  const db = drizzleOverPg(pg);
1795
1853
  const max = 1e4;
@@ -1814,9 +1872,9 @@ async function applyUpsertsToTableWithJson(options) {
1814
1872
  function copyColumnUdts(target) {
1815
1873
  const map = {};
1816
1874
  for (const column of target.columnTypes) {
1817
- const base = column.sqlType.replace(/\(.*\)/g, "").trim().toLowerCase();
1818
- if (base === "json" || base === "jsonb") {
1819
- map[column.name] = column.isArray ? `_${base}` : base;
1875
+ const udt = jsonUdtName2(column);
1876
+ if (udt !== undefined) {
1877
+ map[column.name] = udt;
1820
1878
  }
1821
1879
  }
1822
1880
  return map;
@@ -1831,24 +1889,19 @@ async function applyMessagesToTableWithCopy({ pg, target, messages, debug }) {
1831
1889
  }
1832
1890
  const columns = Object.keys(firstRow);
1833
1891
  assertUniformColumnSet(target, columns, data, "applyMessagesToTableWithCopy");
1834
- const columnUdts = copyColumnUdts(target);
1835
- const copyData = generateCopyData(data, columns, columnUdts);
1836
- const copyBlob = new Blob([copyData], { type: "text/plain" });
1837
- const { name: tableName, schema } = getTableConfig3(target.table);
1838
- const copyTarget = schema ? `${quoteIdentifier3(schema)}.${quoteIdentifier3(tableName)}` : quoteIdentifier3(tableName);
1839
- await pg.query(`
1840
- COPY ${copyTarget} (${columns.map((column) => quoteIdentifier3(column)).join(", ")})
1841
- FROM '/dev/blob'
1842
- WITH (FORMAT text)
1843
- `, [], {
1844
- blob: copyBlob
1892
+ const statement = buildCopyFromBlobStatement({
1893
+ table: target.table,
1894
+ columns,
1895
+ rows: data,
1896
+ udtNames: copyColumnUdts(target)
1845
1897
  });
1898
+ await pg.query(statement.sql, [], { blob: new Blob([statement.blob], { type: "text/plain" }) });
1846
1899
  if (debug)
1847
1900
  console.log(`Inserted ${messages.length} rows using COPY`);
1848
1901
  }
1849
1902
  function recordsetColumnCasts(target, columnNames) {
1850
1903
  const byName = new Map(target.columnTypes.map((column) => [column.name, column]));
1851
- const { schema } = getTableConfig3(target.table);
1904
+ const { schema } = getTableConfig4(target.table);
1852
1905
  return columnNames.map((name) => {
1853
1906
  const column = byName.get(name);
1854
1907
  if (!column) {
@@ -1858,18 +1911,18 @@ function recordsetColumnCasts(target, columnNames) {
1858
1911
  });
1859
1912
  }
1860
1913
  async function applyBulkDeletesToTable({ pg, target, messages, debug }) {
1861
- const primaryKey2 = target.primaryKey;
1862
- if (primaryKey2.length === 0)
1914
+ const primaryKey = target.primaryKey;
1915
+ if (primaryKey.length === 0)
1863
1916
  throw new Error("applyBulkDeletesToTable requires a primary key");
1864
1917
  if (messages.length === 0)
1865
1918
  return;
1866
1919
  const rows = messages.map((message) => {
1867
1920
  const data = message.value;
1868
- return Object.fromEntries(primaryKey2.map((column) => [column, data[column]]));
1921
+ return Object.fromEntries(primaryKey.map((column) => [column, data[column]]));
1869
1922
  });
1870
- const casts = recordsetColumnCasts(target, primaryKey2);
1871
- const recordDef = casts.map((column) => `${quoteIdentifier3(column.name)} ${column.castType}`).join(", ");
1872
- const whereJoin = primaryKey2.map((column) => `t.${quoteIdentifier3(column)} = x.${quoteIdentifier3(column)}`).join(" AND ");
1923
+ const casts = recordsetColumnCasts(target, primaryKey);
1924
+ const recordDef = casts.map((column) => `${quoteIdentifier4(column.name)} ${column.castType}`).join(", ");
1925
+ const whereJoin = primaryKey.map((column) => `t.${quoteIdentifier4(column)} = x.${quoteIdentifier4(column)}`).join(" AND ");
1873
1926
  const targetTable = target.table;
1874
1927
  const db = drizzleOverPg(pg);
1875
1928
  for (let i = 0;i < rows.length; i += JSON_RECORDSET_BATCH) {
@@ -1923,6 +1976,28 @@ function foldKey(ops, folded) {
1923
1976
  }
1924
1977
 
1925
1978
  // packages/client/src/circuits/envelope-to-change.ts
1979
+ function unescapeKeyComponent(part) {
1980
+ if (!part.includes("\\"))
1981
+ return part;
1982
+ let out = "";
1983
+ for (let i = 0;i < part.length; i += 1) {
1984
+ const ch = part[i];
1985
+ if (ch !== "\\") {
1986
+ out += ch;
1987
+ continue;
1988
+ }
1989
+ if (part[i + 1] === "\\") {
1990
+ out += "\\";
1991
+ i += 1;
1992
+ } else if (part.startsWith("x1f", i + 1)) {
1993
+ out += PK_SEPARATOR;
1994
+ i += 3;
1995
+ } else {
1996
+ throw new Error(`[pgxsinkit] stream key component ${JSON.stringify(part)} carries an unknown escape sequence`);
1997
+ }
1998
+ }
1999
+ return out;
2000
+ }
1926
2001
  function coercePrimaryKeyValue(sqlType, raw) {
1927
2002
  switch (sqlType) {
1928
2003
  case "integer":
@@ -1937,17 +2012,43 @@ function coercePrimaryKeyValue(sqlType, raw) {
1937
2012
  }
1938
2013
  }
1939
2014
  function primaryKeyFromStreamKey(target, key) {
1940
- const parts = target.primaryKey.length === 1 ? [key] : key.split(PK_SEPARATOR);
1941
- if (parts.length !== target.primaryKey.length) {
1942
- throw new Error(`[pgxsinkit] stream key "${key}" splits into ${parts.length} part(s) but the target has a ` + `${target.primaryKey.length}-column primary key (${target.primaryKey.join(", ")})`);
2015
+ const serverKey = target.serverPrimaryKey;
2016
+ const parts = serverKey.length === 1 ? [key] : key.split(PK_SEPARATOR).map(unescapeKeyComponent);
2017
+ if (parts.length !== serverKey.length) {
2018
+ throw new Error(`[pgxsinkit] stream key "${key}" splits into ${parts.length} part(s) but the server identity is a ` + `${serverKey.length}-column primary key (${serverKey.join(", ")})`);
1943
2019
  }
2020
+ const localKey = new Set(target.primaryKey);
1944
2021
  const row = {};
1945
- target.primaryKey.forEach((column, index2) => {
2022
+ serverKey.forEach((column, index) => {
2023
+ if (!localKey.has(column))
2024
+ return;
1946
2025
  const sqlType = target.columnTypes.find((type) => type.name === column)?.sqlType ?? "text";
1947
- row[column] = coercePrimaryKeyValue(sqlType, parts[index2]);
2026
+ row[column] = coercePrimaryKeyValue(sqlType, parts[index]);
1948
2027
  });
2028
+ for (const column of target.primaryKey) {
2029
+ if (!(column in row)) {
2030
+ throw new Error(`[pgxsinkit] local primary-key column "${column}" is not part of the server key ` + `(${serverKey.join(", ")}) \u2014 the stream key cannot address the local row`);
2031
+ }
2032
+ }
1949
2033
  return row;
1950
2034
  }
2035
+ function decodeJsonColumns(target, value) {
2036
+ let decoded;
2037
+ for (const column of target.jsonColumns) {
2038
+ const cell = value[column];
2039
+ if (typeof cell !== "string")
2040
+ continue;
2041
+ let parsed;
2042
+ try {
2043
+ parsed = JSON.parse(cell);
2044
+ } catch (error) {
2045
+ throw new Error(`[pgxsinkit] json column "${column}" carried a value that is not JSON text: ${JSON.stringify(cell.slice(0, 120))}`, { cause: error });
2046
+ }
2047
+ decoded ??= { ...value };
2048
+ decoded[column] = parsed;
2049
+ }
2050
+ return decoded ?? value;
2051
+ }
1951
2052
  function envelopeToChange(target, envelope) {
1952
2053
  const operation = envelope.headers.operation;
1953
2054
  if (operation === "delete") {
@@ -1960,7 +2061,14 @@ function envelopeToChange(target, envelope) {
1960
2061
  if (envelope.value === undefined) {
1961
2062
  throw new Error(`[pgxsinkit] ${operation} envelope for key "${envelope.key}" carries no row body \u2014 only a ` + `delete may omit one`);
1962
2063
  }
1963
- return { key: envelope.key, value: envelope.value, headers: { operation: "upsert" } };
2064
+ let value = envelope.value;
2065
+ if (target.droppedKeyColumns.length > 0) {
2066
+ value = { ...value };
2067
+ for (const column of target.droppedKeyColumns) {
2068
+ delete value[column];
2069
+ }
2070
+ }
2071
+ return { key: envelope.key, value: decodeJsonColumns(target, value), headers: { operation: "upsert" } };
1964
2072
  }
1965
2073
  var PK_SEPARATOR = "\x1F";
1966
2074
 
@@ -1991,21 +2099,28 @@ async function readShapeStream(options, onBatch, onEnd) {
1991
2099
  ...options.signal ? { signal: options.signal } : {},
1992
2100
  ...options.fetch ? { fetch: options.fetch } : {}
1993
2101
  });
2102
+ const live = options.live ?? true;
2103
+ let closedByCaller = false;
2104
+ let endReported = false;
2105
+ const reportEnd = (error) => {
2106
+ if (endReported || closedByCaller)
2107
+ return;
2108
+ endReported = true;
2109
+ onEnd?.(error);
2110
+ };
1994
2111
  const unsubscribe = response.subscribeJson(async (batch) => {
1995
2112
  await onBatch({
1996
2113
  envelopes: batch.items,
1997
2114
  offset: String(batch.offset),
1998
2115
  upToDate: batch.upToDate
1999
2116
  });
2117
+ if (batch.streamClosed === true || !live && batch.upToDate)
2118
+ reportEnd(null);
2000
2119
  });
2001
- let closedByCaller = false;
2002
2120
  response.closed.then(() => {
2003
- if (!closedByCaller)
2004
- onEnd?.(null);
2005
- }, (error) => {
2006
- if (!closedByCaller)
2007
- onEnd?.(error instanceof Error ? error : new Error(String(error)));
2008
- });
2121
+ if (options.signal?.aborted)
2122
+ reportEnd(null);
2123
+ }, (error) => reportEnd(error instanceof Error ? error : new Error(String(error))));
2009
2124
  return {
2010
2125
  close: () => {
2011
2126
  closedByCaller = true;
@@ -2522,12 +2637,12 @@ function groupKeyOf(spec) {
2522
2637
  }
2523
2638
  function scopedClear(target, scopeColumns, scope) {
2524
2639
  const conditions = [];
2525
- for (const [index2, name] of scopeColumns.entries()) {
2640
+ for (const [index, name] of scopeColumns.entries()) {
2526
2641
  const column = target.columnByName[name];
2527
2642
  if (column === undefined) {
2528
2643
  throw new Error(`[pgxsinkit] shape scope column "${name}" is not a column of local table ` + `"${getTableName(target.table)}" \u2014 the registry's scope declaration and its local projection ` + `have diverged.`);
2529
2644
  }
2530
- const value = scope[index2];
2645
+ const value = scope[index];
2531
2646
  conditions.push(value === null || value === undefined ? isNull(column) : eq3(column, value));
2532
2647
  }
2533
2648
  return async (db) => {
@@ -3089,7 +3204,6 @@ function describeErrorChain(error, maxDepth = 5) {
3089
3204
 
3090
3205
  // packages/client/src/event-lane.ts
3091
3206
  import { and as and3, asc, eq as eq4, inArray, isNull as isNull2, lte, notInArray, or, sql as sql4 } from "drizzle-orm";
3092
- import { drizzle as drizzle2 } from "drizzle-orm/pglite";
3093
3207
  import {
3094
3208
  batchEventAckSchema,
3095
3209
  batchEventErrorSchema,
@@ -3100,6 +3214,7 @@ import {
3100
3214
  MAX_EVENT_REQUEST_BYTES,
3101
3215
  MAX_EVENTS_PER_BATCH
3102
3216
  } from "@pgxsinkit/contracts";
3217
+ import { drizzle as drizzle2 } from "@pgxsinkit/pgwasm/drizzle";
3103
3218
  function invalidBatchEventUrl() {
3104
3219
  return new Error(`[pgxsinkit] batchEventUrl must be "${CANONICAL_EVENT_PATH}" or an absolute deployment URL ending in "${CANONICAL_EVENT_PATH}"`);
3105
3220
  }
@@ -3142,7 +3257,7 @@ function buildRequestHeaders(bearerToken, requestHeaders) {
3142
3257
  function classifyEventBatchFailure(httpStatus) {
3143
3258
  return httpStatus != null && AUTH_STATUSES.has(httpStatus) ? "auth" : "retryable";
3144
3259
  }
3145
- function parseRetryAfterMs(headerValue, nowMs2) {
3260
+ function parseRetryAfterMs(headerValue, nowMs) {
3146
3261
  if (headerValue == null) {
3147
3262
  return null;
3148
3263
  }
@@ -3157,7 +3272,7 @@ function parseRetryAfterMs(headerValue, nowMs2) {
3157
3272
  if (Number.isNaN(parsedDate)) {
3158
3273
  return null;
3159
3274
  }
3160
- return Math.max(0, parsedDate - nowMs2);
3275
+ return Math.max(0, parsedDate - nowMs);
3161
3276
  }
3162
3277
  function computeEventBackoffMs(attempt, options, random) {
3163
3278
  const baseMs = options.baseMs ?? DEFAULT_EVENT_BACKOFF_BASE_MS;
@@ -3201,14 +3316,15 @@ function validateEventLaneOptions(options) {
3201
3316
  };
3202
3317
  requireCount("events.batchSize", options.batchSize);
3203
3318
  requireMs("events.intervalMs", options.intervalMs, 1);
3319
+ requireMs("events.ackedRetentionMs", options.ackedRetentionMs, 0);
3204
3320
  const globalBackoff = requireBackoff("events.backoff", options.backoff, defaults);
3205
- for (const [stream2, streamOptions] of Object.entries(options.streams ?? {})) {
3321
+ for (const [stream, streamOptions] of Object.entries(options.streams ?? {})) {
3206
3322
  if (streamOptions == null || typeof streamOptions !== "object") {
3207
- problems.push(`\`events.streams.${stream2}\` must be an object of per-stream flush overrides`);
3323
+ problems.push(`\`events.streams.${stream}\` must be an object of per-stream flush overrides`);
3208
3324
  continue;
3209
3325
  }
3210
- requireCount(`events.streams.${stream2}.batchSize`, streamOptions.batchSize);
3211
- requireBackoff(`events.streams.${stream2}.backoff`, streamOptions.backoff, globalBackoff);
3326
+ requireCount(`events.streams.${stream}.batchSize`, streamOptions.batchSize);
3327
+ requireBackoff(`events.streams.${stream}.backoff`, streamOptions.backoff, globalBackoff);
3212
3328
  }
3213
3329
  if (problems.length > 0) {
3214
3330
  throw new Error(`pgxsinkit: invalid Event-lane tuning on the sync client (the \`events\` option) \u2014 ${problems.join("; ")}.`);
@@ -3227,10 +3343,12 @@ function createEventLaneRuntime(options) {
3227
3343
  const random = options.random ?? Math.random;
3228
3344
  const laneOptions = options.events ?? {};
3229
3345
  const batchSize = Math.max(1, Math.min(laneOptions.batchSize ?? DEFAULT_EVENT_BATCH_SIZE, MAX_EVENTS_PER_BATCH));
3346
+ const ackedRetentionMs = laneOptions.ackedRetentionMs ?? 0;
3347
+ const retainsAcked = ackedRetentionMs > 0;
3230
3348
  const nowUs = () => (BigInt(clockMs()) * 1000n).toString();
3231
- const backoffFor = (stream2) => ({
3349
+ const backoffFor = (stream) => ({
3232
3350
  ...laneOptions.backoff ?? {},
3233
- ...(stream2 != null ? laneOptions.streams?.[stream2]?.backoff : undefined) ?? {}
3351
+ ...(stream != null ? laneOptions.streams?.[stream]?.backoff : undefined) ?? {}
3234
3352
  });
3235
3353
  const disposeController = new AbortController;
3236
3354
  const statusListeners = new Set;
@@ -3246,7 +3364,7 @@ function createEventLaneRuntime(options) {
3246
3364
  }
3247
3365
  };
3248
3366
  const isOutboxEmpty = async () => {
3249
- const query = queryBuilder().select({ one: sql4`1`.as("one") }).from(outbox).limit(1).toSQL();
3367
+ const query = queryBuilder().select({ one: sql4`1`.as("one") }).from(outbox).where(isNull2(outbox.ackedAtUs)).limit(1).toSQL();
3250
3368
  const result = await options.db.query(query.sql, query.params);
3251
3369
  return result.rows.length === 0;
3252
3370
  };
@@ -3255,7 +3373,14 @@ function createEventLaneRuntime(options) {
3255
3373
  publishEmpty(empty);
3256
3374
  return empty;
3257
3375
  };
3258
- const initialProbe = refreshDrainSignal().catch((error) => {
3376
+ const sweepAckedLedger = async () => {
3377
+ const cutoffUs = (BigInt(nowUs()) - BigInt(Math.round(ackedRetentionMs)) * 1000n).toString();
3378
+ const query = queryBuilder().delete(outbox).where(lte(outbox.ackedAtUs, cutoffUs)).toSQL();
3379
+ await options.db.query(query.sql, query.params);
3380
+ };
3381
+ const initialProbe = sweepAckedLedger().catch((error) => {
3382
+ syncDebug("event lane: initial acked-ledger sweep failed", { error });
3383
+ }).then(() => refreshDrainSignal()).catch((error) => {
3259
3384
  syncDebug("event lane: initial drain-signal probe failed", { error });
3260
3385
  return false;
3261
3386
  });
@@ -3271,38 +3396,38 @@ function createEventLaneRuntime(options) {
3271
3396
  listener(report);
3272
3397
  }
3273
3398
  };
3274
- const resolveStreamEntry = (stream2) => {
3399
+ const resolveStreamEntry = (stream) => {
3275
3400
  if (!hasStreams) {
3276
3401
  throw new EventStreamsNotRegisteredError;
3277
3402
  }
3278
- const entry = streams?.[stream2];
3403
+ const entry = streams?.[stream];
3279
3404
  if (!entry) {
3280
- throw new UnknownEventStreamError(stream2, streamNames);
3405
+ throw new UnknownEventStreamError(stream, streamNames);
3281
3406
  }
3282
3407
  return entry;
3283
3408
  };
3284
- const appendEvent = async (stream2, payload) => {
3285
- const entry = resolveStreamEntry(stream2);
3409
+ const appendEvent = async (stream, payload) => {
3410
+ const entry = resolveStreamEntry(stream);
3286
3411
  if (!isZodSchema(entry.payload)) {
3287
- throw new EventPayloadInvalidError(stream2, "its registration does not carry a usable zod schema");
3412
+ throw new EventPayloadInvalidError(stream, "its registration does not carry a usable zod schema");
3288
3413
  }
3289
3414
  const parsed = entry.payload.safeParse(payload);
3290
3415
  if (!parsed.success) {
3291
- throw new EventPayloadInvalidError(stream2, parsed.error.message);
3416
+ throw new EventPayloadInvalidError(stream, parsed.error.message);
3292
3417
  }
3293
3418
  const payloadJson = JSON.stringify(payload);
3294
3419
  if (payloadJson === undefined) {
3295
- throw new EventPayloadInvalidError(stream2, "the payload is not JSON-serializable");
3420
+ throw new EventPayloadInvalidError(stream, "the payload is not JSON-serializable");
3296
3421
  }
3297
3422
  const byteLength = byteLengthOf(payloadJson);
3298
3423
  if (byteLength > MAX_EVENT_PAYLOAD_BYTES) {
3299
- throw new EventPayloadTooLargeError(stream2, byteLength);
3424
+ throw new EventPayloadTooLargeError(stream, byteLength);
3300
3425
  }
3301
3426
  const eventId = globalThis.crypto.randomUUID();
3302
3427
  const occurredAtUs = nowUs();
3303
3428
  const insert = queryBuilder().insert(outbox).values({
3304
3429
  eventId,
3305
- stream: stream2,
3430
+ stream,
3306
3431
  occurredAtUs,
3307
3432
  payload: sql4`${payloadJson}::jsonb`,
3308
3433
  enqueuedAtUs: occurredAtUs
@@ -3312,8 +3437,8 @@ function createEventLaneRuntime(options) {
3312
3437
  publishEmpty(false);
3313
3438
  return { eventId, occurredAtUs, seq };
3314
3439
  };
3315
- const streamCaps = Object.entries(laneOptions.streams ?? {}).flatMap(([stream2, streamOptions]) => streamOptions?.batchSize != null ? [[stream2, streamOptions.batchSize]] : []);
3316
- const eligibleNow = () => or(isNull2(outbox.nextRetryAtUs), lte(outbox.nextRetryAtUs, nowUs()));
3440
+ const streamCaps = Object.entries(laneOptions.streams ?? {}).flatMap(([stream, streamOptions]) => streamOptions?.batchSize != null ? [[stream, streamOptions.batchSize]] : []);
3441
+ const eligibleNow = () => and3(isNull2(outbox.ackedAtUs), or(isNull2(outbox.nextRetryAtUs), lte(outbox.nextRetryAtUs, nowUs())));
3317
3442
  const readEligibleRows = async (limit) => {
3318
3443
  const project = (source) => ({
3319
3444
  seq: sql4`${source.seq}::text`.as("seq"),
@@ -3325,7 +3450,7 @@ function createEventLaneRuntime(options) {
3325
3450
  });
3326
3451
  const query = streamCaps.length === 0 ? queryBuilder().select(project(outbox)).from(outbox).where(eligibleNow()).orderBy(asc(outbox.seq)).limit(limit) : (() => {
3327
3452
  const ranked = rankedEligible();
3328
- return queryBuilder().select(project(ranked)).from(ranked).where(or(notInArray(ranked.stream, streamCaps.map(([stream2]) => stream2)), ...streamCaps.map(([stream2, cap]) => and3(eq4(ranked.stream, stream2), lte(ranked.streamRank, cap))))).orderBy(asc(ranked.seq)).limit(limit);
3453
+ return queryBuilder().select(project(ranked)).from(ranked).where(or(notInArray(ranked.stream, streamCaps.map(([stream]) => stream)), ...streamCaps.map(([stream, cap]) => and3(eq4(ranked.stream, stream), lte(ranked.streamRank, cap))))).orderBy(asc(ranked.seq)).limit(limit);
3329
3454
  })();
3330
3455
  const compiled = query.toSQL();
3331
3456
  const result = await options.db.query(compiled.sql, compiled.params);
@@ -3382,6 +3507,13 @@ function createEventLaneRuntime(options) {
3382
3507
  const query = queryBuilder().delete(outbox).where(inArray(outbox.eventId, [...eventIds])).toSQL();
3383
3508
  await options.db.query(query.sql, query.params);
3384
3509
  };
3510
+ const stampAcked = async (eventIds) => {
3511
+ if (eventIds.length === 0) {
3512
+ return;
3513
+ }
3514
+ const query = queryBuilder().update(outbox).set({ ackedAtUs: nowUs() }).where(inArray(outbox.eventId, [...eventIds])).toSQL();
3515
+ await options.db.query(query.sql, query.params);
3516
+ };
3385
3517
  const deferEvent = async (row, reason) => {
3386
3518
  const attempt = row.attemptCount + 1;
3387
3519
  const delayMs = computeEventBackoffMs(attempt, backoffFor(row.stream), random);
@@ -3430,8 +3562,8 @@ function createEventLaneRuntime(options) {
3430
3562
  response = await send(await options.getAuthToken());
3431
3563
  }
3432
3564
  if (!response.ok) {
3433
- const text3 = await response.text();
3434
- throw new EventRequestError(parseBatchEventErrorMessage(text3) ?? (text3.length > 0 ? text3 : `Event ingestion responded with ${response.status}`), response.status, parseRetryAfterMs(response.headers.get("Retry-After"), clockMs()));
3565
+ const text = await response.text();
3566
+ throw new EventRequestError(parseBatchEventErrorMessage(text) ?? (text.length > 0 ? text : `Event ingestion responded with ${response.status}`), response.status, parseRetryAfterMs(response.headers.get("Retry-After"), clockMs()));
3435
3567
  }
3436
3568
  const parsed = batchEventAckSchema.safeParse(await response.json());
3437
3569
  if (!parsed.success) {
@@ -3443,6 +3575,7 @@ function createEventLaneRuntime(options) {
3443
3575
  const terminal = [];
3444
3576
  const deferred = [];
3445
3577
  const deletable = [];
3578
+ const stampable = [];
3446
3579
  for (const ack of acks) {
3447
3580
  const row = batch.rowsByEventId.get(ack.eventId);
3448
3581
  if (!row) {
@@ -3460,19 +3593,27 @@ function createEventLaneRuntime(options) {
3460
3593
  deferred.push(verdict);
3461
3594
  continue;
3462
3595
  }
3463
- deletable.push(ack.eventId);
3464
- if (ack.status !== "acked") {
3465
- terminal.push(verdict);
3596
+ if (ack.status === "acked") {
3597
+ (retainsAcked ? stampable : deletable).push(ack.eventId);
3598
+ continue;
3466
3599
  }
3600
+ deletable.push(ack.eventId);
3601
+ terminal.push(verdict);
3467
3602
  }
3468
3603
  await deleteEvents(deletable);
3469
- return { terminal, deferred, settledCount: deletable.length + deferred.length };
3604
+ await stampAcked(stampable);
3605
+ return { terminal, deferred, settledCount: deletable.length + stampable.length + deferred.length };
3470
3606
  };
3471
3607
  let flushChain = Promise.resolve();
3472
3608
  const runFlush = async () => {
3473
3609
  if (!hasStreams) {
3474
3610
  return;
3475
3611
  }
3612
+ if (retainsAcked) {
3613
+ await sweepAckedLedger().catch((error) => {
3614
+ syncDebug("event lane: acked-ledger sweep failed", { error });
3615
+ });
3616
+ }
3476
3617
  if (batchAttempt > 0 && clockMs() < batchRetryAtMs) {
3477
3618
  syncDebug("event lane: flush skipped (batch-level backoff)", {
3478
3619
  retryInMs: batchRetryAtMs - clockMs(),
@@ -3655,27 +3796,27 @@ var init_event_lane = __esm(() => {
3655
3796
  };
3656
3797
  UnknownEventStreamError = class UnknownEventStreamError extends Error {
3657
3798
  stream;
3658
- constructor(stream2, known) {
3659
- super(`pgxsinkit: unknown Event stream "${stream2}" \u2014 this registry registers [${known.join(", ")}]. ` + "Register it with `defineEventStream` or fix the name.");
3799
+ constructor(stream, known) {
3800
+ super(`pgxsinkit: unknown Event stream "${stream}" \u2014 this registry registers [${known.join(", ")}]. ` + "Register it with `defineEventStream` or fix the name.");
3660
3801
  this.name = "UnknownEventStreamError";
3661
- this.stream = stream2;
3802
+ this.stream = stream;
3662
3803
  }
3663
3804
  };
3664
3805
  EventPayloadInvalidError = class EventPayloadInvalidError extends Error {
3665
3806
  stream;
3666
- constructor(stream2, detail) {
3667
- super(`pgxsinkit: event payload for Event stream "${stream2}" failed its registered schema \u2014 ${detail}`);
3807
+ constructor(stream, detail) {
3808
+ super(`pgxsinkit: event payload for Event stream "${stream}" failed its registered schema \u2014 ${detail}`);
3668
3809
  this.name = "EventPayloadInvalidError";
3669
- this.stream = stream2;
3810
+ this.stream = stream;
3670
3811
  }
3671
3812
  };
3672
3813
  EventPayloadTooLargeError = class EventPayloadTooLargeError extends Error {
3673
3814
  stream;
3674
3815
  byteLength;
3675
- constructor(stream2, byteLength) {
3676
- super(`pgxsinkit: event payload for Event stream "${stream2}" is ${byteLength} bytes, over the ` + `${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit. Events are facts, not documents \u2014 carry a reference, not the document.`);
3816
+ constructor(stream, byteLength) {
3817
+ super(`pgxsinkit: event payload for Event stream "${stream}" is ${byteLength} bytes, over the ` + `${MAX_EVENT_PAYLOAD_BYTES}-byte per-event limit. Events are facts, not documents \u2014 carry a reference, not the document.`);
3677
3818
  this.name = "EventPayloadTooLargeError";
3678
- this.stream = stream2;
3819
+ this.stream = stream;
3679
3820
  this.byteLength = byteLength;
3680
3821
  }
3681
3822
  };
@@ -3744,6 +3885,7 @@ async function performStoreExport(deps, options = {}) {
3744
3885
  var nowMs2 = () => typeof performance !== "undefined" ? performance.now() : Date.now(), compactTimestamp = () => new Date().toISOString().replace(/[:.]/g, "-");
3745
3886
 
3746
3887
  // packages/client/src/store-path.ts
3888
+ import { idbDatabaseName } from "@pgxsinkit/pgwasm-c";
3747
3889
  function readTestStoreMarker(options) {
3748
3890
  if (options == null || typeof options !== "object")
3749
3891
  return;
@@ -3802,6 +3944,9 @@ function opfsStoreDirectoryPath(storePath) {
3802
3944
  function opfsCommitmentSentinelPath(storePath) {
3803
3945
  return [OPFS_TOOLKIT_CONTAINER, "commitments", storeIdentityComponent(storePath)];
3804
3946
  }
3947
+ function storeOwnershipLockName(storePath) {
3948
+ return `${OPFS_TOOLKIT_CONTAINER}:store-owner:${storeIdentityComponent(storePath)}`;
3949
+ }
3805
3950
  function opfsProbeDirectoryPath() {
3806
3951
  return [OPFS_TOOLKIT_CONTAINER, "probe"];
3807
3952
  }
@@ -3812,13 +3957,13 @@ function storeIndexedDbDatabaseName(storePath) {
3812
3957
  if (storePath.includes("://")) {
3813
3958
  throw new InvalidStorePathError(`invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`);
3814
3959
  }
3815
- return `/pglite/${storePath}`;
3960
+ return idbDatabaseName(storePath);
3816
3961
  }
3817
- function classifyNonPersistentDataDir(dataDir) {
3818
- if (dataDir == null)
3819
- return "in-memory-default";
3820
- if (dataDir.startsWith("memory://"))
3821
- return "memory-scheme";
3962
+ function classifyNonPersistentStorage(storage) {
3963
+ if (storage.kind === "memory")
3964
+ return "memory";
3965
+ if (storage.kind === "vfs" && storage.persistent === false)
3966
+ return "non-persistent-vfs";
3822
3967
  return null;
3823
3968
  }
3824
3969
  async function storeTargetExists(storePath, backendOverride, env = detectStoreEnv()) {
@@ -3863,8 +4008,8 @@ var init_store_path = __esm(() => {
3863
4008
  };
3864
4009
  NonPersistentStoreError = class NonPersistentStoreError extends Error {
3865
4010
  constructor(observed) {
3866
- 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";
3867
- 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).');
4011
+ const reason = observed === "memory" ? "its storage is in memory (pgwasm's default without a `dataDir`, or `memory://`)" : "its storage is a filesystem that explicitly reports itself non-persistent";
4012
+ super(`[pgxsinkit] refusing a non-persistent store: ${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).');
3868
4013
  this.name = "NonPersistentStoreError";
3869
4014
  }
3870
4015
  };
@@ -3878,13 +4023,19 @@ var init_store_path = __esm(() => {
3878
4023
  });
3879
4024
 
3880
4025
  // packages/client/src/export-dump.ts
3881
- import { PGlite } from "@electric-sql/pglite";
4026
+ import { createPgwasm } from "@pgxsinkit/pgwasm";
4027
+ import { cBuild } from "@pgxsinkit/pgwasm-c";
3882
4028
  async function runThrowawayCloneDump(pglite, startPerf, options = {}) {
3883
4029
  const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(pglite, "none", startPerf);
3884
4030
  const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
3885
4031
  const cloneBootStartedAtMs = nowMs2() - startPerf;
3886
4032
  const cloneBootStartPerf = nowMs2();
3887
- const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped, relaxedDurability: true });
4033
+ const throwaway = await createPgwasm({
4034
+ build: cBuild,
4035
+ dataDir: cloneDataDir,
4036
+ loadDataDir: dumped,
4037
+ relaxedDurability: true
4038
+ });
3888
4039
  const cloneBootMs = nowMs2() - cloneBootStartPerf;
3889
4040
  let sqlBytes;
3890
4041
  let pgDumpStartedAtMs;
@@ -3895,7 +4046,7 @@ async function runThrowawayCloneDump(pglite, startPerf, options = {}) {
3895
4046
  }
3896
4047
  pgDumpStartedAtMs = nowMs2() - startPerf;
3897
4048
  const pgDumpStartPerf = nowMs2();
3898
- const { pgDump } = await import("@electric-sql/pglite-tools/pg_dump");
4049
+ const { pgDump } = await import("@pgxsinkit/pgwasm-pg-dump");
3899
4050
  const dumpFile = await pgDump({
3900
4051
  pg: throwaway,
3901
4052
  ...options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {},
@@ -3993,7 +4144,7 @@ async function performDataExport(deps, options = {}) {
3993
4144
  const drainStartedAtMs = nowMs2() - startPerf;
3994
4145
  const drainMs = escapeHatch ? 0 : (await drainJournalForExport(deps, drainOption.timeoutMs)).drainMs;
3995
4146
  const pgDumpArgs = ["--no-owner", ...deps.syncedTableNames.flatMap((name) => ["-t", name])];
3996
- const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf, {
4147
+ const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pgwasm, startPerf, {
3997
4148
  pgDumpArgs,
3998
4149
  ...deps.cloneCleanupSql.length > 0 ? { prepareClone: async (clone) => void await clone.exec(deps.cloneCleanupSql) } : {}
3999
4150
  });
@@ -4044,14 +4195,14 @@ var init_export_data = __esm(() => {
4044
4195
  });
4045
4196
 
4046
4197
  // packages/client/src/lazy-guard.ts
4047
- import { getTableConfig as getTableConfig4, getViewConfig as getViewConfig2 } from "drizzle-orm/pg-core";
4198
+ import { getTableConfig as getTableConfig5, getViewConfig as getViewConfig2 } from "drizzle-orm/pg-core";
4048
4199
  function tokensForEntry(entry) {
4049
4200
  const tokens = [];
4050
4201
  if (entry.readProjection) {
4051
- const localTable = getTableConfig4(entry.localTable);
4202
+ const localTable = getTableConfig5(entry.localTable);
4052
4203
  tokens.push(quotedRef(localTable.name, localTable.schema));
4053
4204
  } else {
4054
- const table = getTableConfig4(entry.table);
4205
+ const table = getTableConfig5(entry.table);
4055
4206
  tokens.push(quotedRef(table.name, table.schema));
4056
4207
  if (entry.view != null) {
4057
4208
  const view = getViewConfig2(entry.view);
@@ -4079,28 +4230,28 @@ function buildLazyGuardIndex(registry) {
4079
4230
  function quotedRef(name, schema) {
4080
4231
  return schema != null && schema.length > 0 ? `"${schema}"."${name}"` : `"${name}"`;
4081
4232
  }
4082
- function findReferencedLazyKeysInSql(sql5, index2) {
4233
+ function findReferencedLazyKeysInSql(sql, index) {
4083
4234
  const found = new Set;
4084
- for (const [key, tokens] of index2.lazyTokens) {
4085
- if (tokens.some((token) => sqlReferencesToken(sql5, token)))
4235
+ for (const [key, tokens] of index.lazyTokens) {
4236
+ if (tokens.some((token) => sqlReferencesToken(sql, token)))
4086
4237
  found.add(key);
4087
4238
  }
4088
4239
  return found;
4089
4240
  }
4090
- function findReferencedSyncedKeysInSql(sql5, index2) {
4241
+ function findReferencedSyncedKeysInSql(sql, index) {
4091
4242
  const found = new Set;
4092
- for (const [key, tokens] of index2.allTokens) {
4093
- if (tokens.some((token) => sqlReferencesToken(sql5, token)))
4243
+ for (const [key, tokens] of index.allTokens) {
4244
+ if (tokens.some((token) => sqlReferencesToken(sql, token)))
4094
4245
  found.add(key);
4095
4246
  }
4096
4247
  return found;
4097
4248
  }
4098
- function sqlReferencesToken(sql5, token) {
4249
+ function sqlReferencesToken(sql, token) {
4099
4250
  for (let from = 0;; ) {
4100
- const at = sql5.indexOf(token, from);
4251
+ const at = sql.indexOf(token, from);
4101
4252
  if (at === -1)
4102
4253
  return false;
4103
- if (!/\bas\s+$/i.test(sql5.slice(Math.max(0, at - 16), at)))
4254
+ if (!/\bas\s+$/i.test(sql.slice(Math.max(0, at - 16), at)))
4104
4255
  return true;
4105
4256
  from = at + token.length;
4106
4257
  }
@@ -4157,20 +4308,20 @@ var init_lifecycle_slot = __esm(() => {
4157
4308
  });
4158
4309
 
4159
4310
  // packages/client/src/live-rows-sql.ts
4160
- import { quoteIdentifier as quoteIdentifier4 } from "@pgxsinkit/contracts";
4161
- function wrapLiveQueryForMaterialization(sql5, fields) {
4311
+ import { quoteIdentifier as quoteIdentifier5 } from "@pgxsinkit/contracts";
4312
+ function wrapLiveQueryForMaterialization(sql, fields) {
4162
4313
  if (fields == null || fields.length === 0) {
4163
- return sql5;
4314
+ return sql;
4164
4315
  }
4165
- const aliasList = fields.map((field) => quoteIdentifier4(field)).join(", ");
4166
- return `SELECT * FROM (${sql5}) ${quoteIdentifier4(LIVE_QUERY_TABLE_ALIAS)} (${aliasList})`;
4316
+ const aliasList = fields.map((field) => quoteIdentifier5(field)).join(", ");
4317
+ return `SELECT * FROM (${sql}) ${quoteIdentifier5(LIVE_QUERY_TABLE_ALIAS)} (${aliasList})`;
4167
4318
  }
4168
4319
  var LIVE_QUERY_TABLE_ALIAS = "__pgx_live";
4169
4320
  var init_live_rows_sql = () => {};
4170
4321
 
4171
4322
  // packages/client/src/local-store.ts
4172
4323
  import { and as and4, eq as eq5, like, notExists, sql as sql5 } from "drizzle-orm";
4173
- import { drizzle as drizzle3 } from "drizzle-orm/pglite";
4324
+ import { drizzle as drizzle3 } from "@pgxsinkit/pgwasm/drizzle";
4174
4325
  async function readStoredRegistryFingerprint(db, registry) {
4175
4326
  const meta = getLocalMetaTable(registry);
4176
4327
  const query = metaQueryBuilder.select({ value: meta.value }).from(meta).where(eq5(meta.key, REGISTRY_FINGERPRINT_KEY)).limit(1).toSQL();
@@ -4260,14 +4411,14 @@ async function rebuildReadCacheOrDefer(args, previousFingerprint) {
4260
4411
  const stats = await runtime.readMutationStats();
4261
4412
  const owedMutations = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount;
4262
4413
  if (owedMutations > 0) {
4263
- const event2 = {
4414
+ const event = {
4264
4415
  status: "deferred",
4265
4416
  previousFingerprint,
4266
4417
  nextFingerprint: current,
4267
4418
  owedMutations
4268
4419
  };
4269
- await onSchemaChange?.(event2);
4270
- return event2;
4420
+ await onSchemaChange?.(event);
4421
+ return event;
4271
4422
  }
4272
4423
  await db.exec(buildWipeLocalStoreSql(registry));
4273
4424
  await db.exec(generateLocalSchemaSql(registry));
@@ -4341,11 +4492,11 @@ import {
4341
4492
  } from "drizzle-orm";
4342
4493
  import {
4343
4494
  alias,
4344
- getTableConfig as getTableConfig5,
4495
+ getTableConfig as getTableConfig6,
4345
4496
  getViewConfig as getViewConfig3,
4346
4497
  PgDialect
4347
4498
  } from "drizzle-orm/pg-core";
4348
- import { drizzle as drizzle4 } from "drizzle-orm/pglite";
4499
+ import { drizzle as drizzle4 } from "@pgxsinkit/pgwasm/drizzle";
4349
4500
  import {
4350
4501
  batchMutationErrorSchema,
4351
4502
  buildOverlayResolutionBarrier as buildOverlayResolutionBarrier2,
@@ -4354,7 +4505,7 @@ import {
4354
4505
  getSyncRegistrySchema as getSyncRegistrySchema3,
4355
4506
  isManagedFieldGuarded,
4356
4507
  maybeQuoteIdentifier as maybeQuoteIdentifier2,
4357
- quoteIdentifier as quoteIdentifier5,
4508
+ quoteIdentifier as quoteIdentifier6,
4358
4509
  resolveServerVersionColumnName
4359
4510
  } from "@pgxsinkit/contracts";
4360
4511
  function stripReadModelOverlayFields(value) {
@@ -4555,7 +4706,7 @@ function createMutationRuntime(options) {
4555
4706
  const pessimisticUnitIds = new Set;
4556
4707
  const needsAuthClaims = items.some((item) => item.kind === "create" && getTableContext(item.table).managedAuthClaimCreateFields.length > 0);
4557
4708
  const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;
4558
- const normalizedItems = items.map((item, index2) => normalizeBatchItem(item, index2, claims));
4709
+ const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));
4559
4710
  const ordinaryTables = new Set;
4560
4711
  for (const item of normalizedItems) {
4561
4712
  if (item.kind === "update" && item.blind) {
@@ -4923,24 +5074,24 @@ function createMutationRuntime(options) {
4923
5074
  });
4924
5075
  }
4925
5076
  if (!response.ok) {
4926
- const text3 = await response.text();
4927
- throw new MutationRequestError(text3.length > 0 ? text3 : `Authoritative write responded with ${response.status}`, response.status, parseBatchRejections(text3));
5077
+ const text = await response.text();
5078
+ throw new MutationRequestError(text.length > 0 ? text : `Authoritative write responded with ${response.status}`, response.status, parseBatchRejections(text));
4928
5079
  }
4929
5080
  const responseJson = await response.json();
4930
5081
  acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));
4931
5082
  } catch (error) {
4932
- const failedAtUs2 = nowMicroseconds();
5083
+ const failedAtUs = nowMicroseconds();
4933
5084
  const httpStatus = error instanceof MutationRequestError ? error.status : null;
4934
5085
  const errorMessage = error instanceof Error ? error.message : "Authoritative write failed";
4935
5086
  for (const rows of byContext.values()) {
4936
5087
  await applyMutationStatusUpdates(options.db, rows[0].context, rows.map((row) => {
4937
5088
  const attemptCount = row.attemptCount + 1;
4938
- const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs2);
5089
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);
4939
5090
  return {
4940
5091
  mutationId: row.mutationId,
4941
5092
  status: outcome.status,
4942
5093
  attemptCount,
4943
- updatedAtUs: failedAtUs2,
5094
+ updatedAtUs: failedAtUs,
4944
5095
  lastError: errorMessage,
4945
5096
  nextRetryAtUs: outcome.nextRetryAtUs,
4946
5097
  lastHttpStatus: httpStatus,
@@ -5272,8 +5423,8 @@ function buildTableContext(registry, key, entry, localSchema) {
5272
5423
  return {
5273
5424
  key,
5274
5425
  entry,
5275
- readModel: qualifyLocalIdentifier(localSchema, entry.view != null ? getViewConfig3(entry.view).name : entry.clientProjection?.syncedTable ?? getTableConfig5(entry.table).name),
5276
- syncedTable: qualifyLocalIdentifier(localSchema, entry.clientProjection?.syncedTable ?? getTableConfig5(entry.table).name),
5426
+ readModel: qualifyLocalIdentifier(localSchema, entry.view != null ? getViewConfig3(entry.view).name : entry.clientProjection?.syncedTable ?? getTableConfig6(entry.table).name),
5427
+ syncedTable: qualifyLocalIdentifier(localSchema, entry.clientProjection?.syncedTable ?? getTableConfig6(entry.table).name),
5277
5428
  overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),
5278
5429
  journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),
5279
5430
  journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName2(entry.clientProjection.journalTable)),
@@ -5372,12 +5523,12 @@ function buildEntityKeyFromRecord(context, record) {
5372
5523
  return normalizeEntityKey(context, Object.fromEntries(context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])])));
5373
5524
  }
5374
5525
  function normalizeEntityKey(context, input) {
5375
- return Object.fromEntries(context.pkPropertyKeys.map((propertyKey, index2) => {
5526
+ return Object.fromEntries(context.pkPropertyKeys.map((propertyKey, index) => {
5376
5527
  const value = input[propertyKey];
5377
5528
  if (value === undefined) {
5378
5529
  throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);
5379
5530
  }
5380
- return [context.pkColumnNames[index2], String(value)];
5531
+ return [context.pkColumnNames[index], String(value)];
5381
5532
  }));
5382
5533
  }
5383
5534
  function serializeEntityKey(entityKey) {
@@ -5551,7 +5702,7 @@ function buildProjectedSelectColumns(context, columnsByPropertyKey) {
5551
5702
  }), sql6`, `);
5552
5703
  }
5553
5704
  function buildEntityInputJoin(pkColumnNames, pkColumns) {
5554
- return sql6.join(pkColumnNames.map((columnName, index2) => sql6`${pkColumns[index2]} = input.${sql6.identifier(columnName)}`), sql6` AND `);
5705
+ return sql6.join(pkColumnNames.map((columnName, index) => sql6`${pkColumns[index]} = input.${sql6.identifier(columnName)}`), sql6` AND `);
5555
5706
  }
5556
5707
  function buildResolvedBaseServerVersion(context) {
5557
5708
  const journal = context.tables.journal;
@@ -5561,7 +5712,7 @@ function buildResolvedBaseServerVersion(context) {
5561
5712
  if (!context.syncedServerVersionColumn) {
5562
5713
  return sql6`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;
5563
5714
  }
5564
- const syncedFallback = queryBuilder.select({ value: sql6`${context.syncedServerVersionColumn}` }).from(synced).where(and5(...context.pkColumnNames.map((columnName, index2) => eq6(context.syncedPkColumns[index2], journal[columnName]))));
5715
+ const syncedFallback = queryBuilder.select({ value: sql6`${context.syncedServerVersionColumn}` }).from(synced).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.syncedPkColumns[index], journal[columnName]))));
5565
5716
  return sql6`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;
5566
5717
  }
5567
5718
  function buildPendingRowsProjection(context) {
@@ -5720,11 +5871,11 @@ async function flushBatch(db, tableContexts, batchMutationUrl, maxAttempts, batc
5720
5871
  acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`)
5721
5872
  });
5722
5873
  } else {
5723
- const text3 = await response.text();
5724
- throw new MutationRequestError(text3.length > 0 ? text3 : `Bulk write responded with ${response.status}`, response.status, parseBatchRejections(text3));
5874
+ const text = await response.text();
5875
+ throw new MutationRequestError(text.length > 0 ? text : `Bulk write responded with ${response.status}`, response.status, parseBatchRejections(text));
5725
5876
  }
5726
5877
  } catch (error) {
5727
- const failedAtUs2 = nowMicroseconds();
5878
+ const failedAtUs = nowMicroseconds();
5728
5879
  const httpStatus = error instanceof MutationRequestError ? error.status : null;
5729
5880
  const errorMessage = error instanceof Error ? error.message : "Unknown batch write failure";
5730
5881
  const rejectionById = error instanceof MutationRequestError && error.rejections ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection])) : null;
@@ -5739,7 +5890,7 @@ async function flushBatch(db, tableContexts, batchMutationUrl, maxAttempts, batc
5739
5890
  mutationId: row.mutationId,
5740
5891
  status: "quarantined",
5741
5892
  attemptCount,
5742
- updatedAtUs: failedAtUs2,
5893
+ updatedAtUs: failedAtUs,
5743
5894
  lastError: rejection.reason,
5744
5895
  nextRetryAtUs: null,
5745
5896
  lastHttpStatus: httpStatus,
@@ -5750,14 +5901,14 @@ async function flushBatch(db, tableContexts, batchMutationUrl, maxAttempts, batc
5750
5901
  mutationId: row.mutationId,
5751
5902
  status: "failed",
5752
5903
  attemptCount,
5753
- updatedAtUs: failedAtUs2,
5904
+ updatedAtUs: failedAtUs,
5754
5905
  lastError: "Batch rejected due to a sibling mutation; retrying without it",
5755
5906
  nextRetryAtUs: null,
5756
5907
  lastHttpStatus: httpStatus,
5757
5908
  conflictReason: null
5758
5909
  };
5759
5910
  }
5760
- const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs2);
5911
+ const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);
5761
5912
  if (outcome.status === "quarantined") {
5762
5913
  quarantinedMutationIds.push(row.mutationId);
5763
5914
  }
@@ -5765,7 +5916,7 @@ async function flushBatch(db, tableContexts, batchMutationUrl, maxAttempts, batc
5765
5916
  mutationId: row.mutationId,
5766
5917
  status: outcome.status,
5767
5918
  attemptCount,
5768
- updatedAtUs: failedAtUs2,
5919
+ updatedAtUs: failedAtUs,
5769
5920
  lastError: errorMessage,
5770
5921
  nextRetryAtUs: outcome.nextRetryAtUs,
5771
5922
  lastHttpStatus: httpStatus,
@@ -5938,7 +6089,7 @@ function buildOverlayDiscardQuery(context, entityKey, entityKeyJson, owedStatuse
5938
6089
  const overlay = context.tables.overlay;
5939
6090
  const journal = context.tables.journal;
5940
6091
  const owed = queryBuilder.select({ one: sql6`1` }).from(journal).where(owedStatuses ? and5(eq6(journal.entityKeyJson, entityKeyJson), inArray2(journal.status, owedStatuses)) : eq6(journal.entityKeyJson, entityKeyJson));
5941
- return queryBuilder.delete(overlay).where(and5(...context.pkColumnNames.map((columnName, index2) => eq6(context.overlayPkColumns[index2], entityKey[columnName])), notExists2(owed))).toSQL();
6092
+ return queryBuilder.delete(overlay).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.overlayPkColumns[index], entityKey[columnName])), notExists2(owed))).toSQL();
5942
6093
  }
5943
6094
  async function discardOverlayForSettledEntity(db, context, entityKey, entityKeyJson) {
5944
6095
  const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, ["pending", "sending", "failed"]);
@@ -5966,22 +6117,22 @@ async function reconcileTable(db, context) {
5966
6117
  const blindRetireQuery = queryBuilder.delete(journal).where(and5(eq6(journal.status, "acked"), eq6(journal.writeMode, "pessimistic-blind"))).toSQL();
5967
6118
  await db.query(blindRetireQuery.sql, blindRetireQuery.params);
5968
6119
  const barrier = sql6.raw(buildOverlayResolutionBarrier2(context.entry, {
5969
- journalAlias: quoteIdentifier5(getTableConfig5(journal).name),
5970
- syncedAlias: quoteIdentifier5(getTableConfig5(synced).name)
6120
+ journalAlias: quoteIdentifier6(getTableConfig6(journal).name),
6121
+ syncedAlias: quoteIdentifier6(getTableConfig6(synced).name)
5971
6122
  }));
5972
- const clearedJournal = queryBuilder.$with("cleared_journal").as(queryBuilder.delete(journal).where(and5(eq6(journal.status, "acked"), isNotNull(journal.serverUpdatedAtUs), ne(journal.mutationKind, "delete"), exists(queryBuilder.select({ one: sql6`1` }).from(synced).where(and5(...context.pkColumnNames.map((columnName, index2) => eq6(context.syncedPkColumns[index2], journal[columnName])), barrier))))).returning(Object.fromEntries([
6123
+ const clearedJournal = queryBuilder.$with("cleared_journal").as(queryBuilder.delete(journal).where(and5(eq6(journal.status, "acked"), isNotNull(journal.serverUpdatedAtUs), ne(journal.mutationKind, "delete"), exists(queryBuilder.select({ one: sql6`1` }).from(synced).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.syncedPkColumns[index], journal[columnName])), barrier))))).returning(Object.fromEntries([
5973
6124
  ["entity_key_json", journal.entityKeyJson],
5974
6125
  ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]])
5975
6126
  ])));
5976
6127
  const clearedJournalColumns = clearedJournal;
5977
- const ackedClearQuery = queryBuilder.with(clearedJournal).delete(overlay).where(exists(queryBuilder.select({ one: sql6`1` }).from(clearedJournal).where(and5(...context.pkColumnNames.map((columnName, index2) => eq6(context.overlayPkColumns[index2], clearedJournalColumns[columnName])), notExists2(queryBuilder.select({ one: sql6`1` }).from(journal).where(and5(eq6(journal.entityKeyJson, clearedJournalColumns["entity_key_json"]), inArray2(journal.status, ["pending", "sending", "failed"])))))))).toSQL();
6128
+ const ackedClearQuery = queryBuilder.with(clearedJournal).delete(overlay).where(exists(queryBuilder.select({ one: sql6`1` }).from(clearedJournal).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.overlayPkColumns[index], clearedJournalColumns[columnName])), notExists2(queryBuilder.select({ one: sql6`1` }).from(journal).where(and5(eq6(journal.entityKeyJson, clearedJournalColumns["entity_key_json"]), inArray2(journal.status, ["pending", "sending", "failed"])))))))).toSQL();
5978
6129
  await db.query(ackedClearQuery.sql, ackedClearQuery.params);
5979
6130
  const clearableEntities = queryBuilder.$with("clearable_entities").as(queryBuilder.selectDistinct(Object.fromEntries([
5980
6131
  ["entity_key_json", journal.entityKeyJson],
5981
6132
  ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]])
5982
- ])).from(journal).leftJoin(synced, and5(...context.pkColumnNames.map((columnName, index2) => eq6(context.syncedPkColumns[index2], journal[columnName])))).where(and5(eq6(journal.status, "acked"), eq6(journal.mutationKind, "delete"), isNull3(context.syncedPkColumns[0]))));
6133
+ ])).from(journal).leftJoin(synced, and5(...context.pkColumnNames.map((columnName, index) => eq6(context.syncedPkColumns[index], journal[columnName])))).where(and5(eq6(journal.status, "acked"), eq6(journal.mutationKind, "delete"), isNull3(context.syncedPkColumns[0]))));
5983
6134
  const clearableEntityColumns = clearableEntities;
5984
- const deletedOverlay = queryBuilder.$with("deleted_overlay").as(queryBuilder.delete(overlay).where(exists(queryBuilder.select({ one: sql6`1` }).from(clearableEntities).where(and5(...context.pkColumnNames.map((columnName, index2) => eq6(context.overlayPkColumns[index2], clearableEntityColumns[columnName])))))));
6135
+ const deletedOverlay = queryBuilder.$with("deleted_overlay").as(queryBuilder.delete(overlay).where(exists(queryBuilder.select({ one: sql6`1` }).from(clearableEntities).where(and5(...context.pkColumnNames.map((columnName, index) => eq6(context.overlayPkColumns[index], clearableEntityColumns[columnName])))))));
5985
6136
  const deleteClearQuery = queryBuilder.with(clearableEntities, deletedOverlay).delete(journal).where(and5(eq6(journal.status, "acked"), eq6(journal.mutationKind, "delete"), exists(queryBuilder.select({ one: sql6`1` }).from(clearableEntities).where(and5(...context.pkColumnNames.map((columnName) => eq6(journal[columnName], clearableEntityColumns[columnName]))))))).toSQL();
5986
6137
  await db.query(deleteClearQuery.sql, deleteClearQuery.params);
5987
6138
  await db.exec("COMMIT");
@@ -6037,7 +6188,7 @@ function qualifyLocalIdentifier(schemaName, tableName) {
6037
6188
  if (schemaName === "public") {
6038
6189
  return maybeQuoteIdentifier2(tableName);
6039
6190
  }
6040
- return `${quoteIdentifier5(schemaName)}.${quoteIdentifier5(tableName)}`;
6191
+ return `${quoteIdentifier6(schemaName)}.${quoteIdentifier6(tableName)}`;
6041
6192
  }
6042
6193
  function buildJournalSequenceName2(journalTable) {
6043
6194
  return `${journalTable}_mutation_seq`;
@@ -6092,7 +6243,7 @@ var init_mutation = __esm(() => {
6092
6243
 
6093
6244
  // packages/client/src/mutations-api.ts
6094
6245
  import { and as and6, desc as desc2, eq as eq7, inArray as inArray3, sql as sql7 } from "drizzle-orm";
6095
- import { drizzle as drizzle5 } from "drizzle-orm/pglite";
6246
+ import { drizzle as drizzle5 } from "@pgxsinkit/pgwasm/drizzle";
6096
6247
  function queryBuilder2() {
6097
6248
  return queryBuilderInstance ??= drizzle5.mock();
6098
6249
  }
@@ -6228,7 +6379,66 @@ var init_mutations_api = __esm(() => {
6228
6379
  };
6229
6380
  });
6230
6381
 
6382
+ // packages/client/src/store-ownership-lock.ts
6383
+ function resolveDefaultLocks() {
6384
+ const locks = globalThis.navigator?.locks;
6385
+ return locks != null && typeof locks.request === "function" ? locks : null;
6386
+ }
6387
+ function acquireStoreOwnership(storePath, options) {
6388
+ const locks = options?.locks === undefined ? resolveDefaultLocks() : options.locks;
6389
+ if (locks == null)
6390
+ return Promise.resolve(() => {
6391
+ return;
6392
+ });
6393
+ const waitMs = options?.waitMs ?? STORE_OWNERSHIP_WAIT_MS;
6394
+ return new Promise((resolve, reject) => {
6395
+ const controller = new AbortController;
6396
+ const timer = setTimeout(() => controller.abort(), waitMs);
6397
+ let granted = false;
6398
+ locks.request(storeOwnershipLockName(storePath), { mode: "exclusive", signal: controller.signal }, () => {
6399
+ granted = true;
6400
+ clearTimeout(timer);
6401
+ return new Promise((releaseLock) => {
6402
+ let released = false;
6403
+ resolve(() => {
6404
+ if (released)
6405
+ return;
6406
+ released = true;
6407
+ releaseLock();
6408
+ });
6409
+ });
6410
+ }).catch((error) => {
6411
+ clearTimeout(timer);
6412
+ if (!granted)
6413
+ reject(controller.signal.aborted ? new StoreOwnershipWaitError(storePath, waitMs) : error);
6414
+ });
6415
+ });
6416
+ }
6417
+ async function withStoreOwnership(storePath, effect, options) {
6418
+ const release = await acquireStoreOwnership(storePath, options);
6419
+ try {
6420
+ return await effect();
6421
+ } finally {
6422
+ release();
6423
+ }
6424
+ }
6425
+ var STORE_OWNERSHIP_WAIT_MS = 1e4, StoreOwnershipWaitError;
6426
+ var init_store_ownership_lock = __esm(() => {
6427
+ init_store_path();
6428
+ StoreOwnershipWaitError = class StoreOwnershipWaitError extends Error {
6429
+ storePath;
6430
+ constructor(storePath, waitMs) {
6431
+ super(`[pgxsinkit] the OPFS store "${storePath}" is still owned by another live engine after ${waitMs} ms. ` + "Stop the client (or close the tab) that holds it, then retry.");
6432
+ this.name = "StoreOwnershipWaitError";
6433
+ this.storePath = storePath;
6434
+ }
6435
+ };
6436
+ });
6437
+
6231
6438
  // packages/client/src/opfs-effects.ts
6439
+ function isOpfsRootUnavailableError(error) {
6440
+ return error?.name === "OpfsRootUnavailableError";
6441
+ }
6232
6442
  function isNotFoundError(error) {
6233
6443
  return error?.name === "NotFoundError";
6234
6444
  }
@@ -6249,6 +6459,17 @@ function createOpfsEffects(storePath, deps) {
6249
6459
  handle = await handle.getDirectoryHandle(segment, { create });
6250
6460
  return handle;
6251
6461
  }
6462
+ async function walkDirectoriesForDelete(segments) {
6463
+ let handle;
6464
+ try {
6465
+ handle = await getRoot();
6466
+ } catch (error) {
6467
+ throw new OpfsRootUnavailableError(storePath, error);
6468
+ }
6469
+ for (const segment of segments)
6470
+ handle = await handle.getDirectoryHandle(segment, { create: false });
6471
+ return handle;
6472
+ }
6252
6473
  async function entryExists(path, kind) {
6253
6474
  try {
6254
6475
  let handle = await getRoot();
@@ -6279,7 +6500,7 @@ function createOpfsEffects(storePath, deps) {
6279
6500
  return;
6280
6501
  const path = opfsCommitmentSentinelPath(storePath);
6281
6502
  try {
6282
- const parent = await walkDirectories(path.slice(0, -1), false);
6503
+ const parent = await walkDirectoriesForDelete(path.slice(0, -1));
6283
6504
  await parent.removeEntry(path[path.length - 1]);
6284
6505
  } catch (error) {
6285
6506
  if (!isNotFoundError(error))
@@ -6290,13 +6511,18 @@ function createOpfsEffects(storePath, deps) {
6290
6511
  if (getRoot == null)
6291
6512
  return;
6292
6513
  const path = opfsStoreDirectoryPath(storePath);
6293
- try {
6294
- const parent = await walkDirectories(path.slice(0, -1), false);
6295
- await parent.removeEntry(path[path.length - 1], { recursive: true });
6296
- } catch (error) {
6297
- if (!isNotFoundError(error))
6298
- throw error;
6299
- }
6514
+ await withStoreOwnership(storePath, async () => {
6515
+ try {
6516
+ const parent = await walkDirectoriesForDelete(path.slice(0, -1));
6517
+ await parent.removeEntry(path[path.length - 1], { recursive: true });
6518
+ } catch (error) {
6519
+ if (!isNotFoundError(error))
6520
+ throw error;
6521
+ }
6522
+ }, {
6523
+ ...deps?.locks !== undefined ? { locks: deps.locks } : {},
6524
+ ...deps?.ownershipWaitMs !== undefined ? { waitMs: deps.ownershipWaitMs } : {}
6525
+ });
6300
6526
  },
6301
6527
  async observeCommitmentNamespace() {
6302
6528
  if (getRoot == null)
@@ -6314,8 +6540,16 @@ function createOpfsEffects(storePath, deps) {
6314
6540
  }
6315
6541
  };
6316
6542
  }
6543
+ var OpfsRootUnavailableError;
6317
6544
  var init_opfs_effects = __esm(() => {
6545
+ init_store_ownership_lock();
6318
6546
  init_store_path();
6547
+ OpfsRootUnavailableError = class OpfsRootUnavailableError extends Error {
6548
+ constructor(storePath, cause) {
6549
+ super(`[pgxsinkit] the OPFS root cannot be opened in this context, so the OPFS side of ${JSON.stringify(storePath)} ` + "cannot be deleted here.", { cause });
6550
+ this.name = "OpfsRootUnavailableError";
6551
+ }
6552
+ };
6319
6553
  });
6320
6554
 
6321
6555
  // packages/client/src/store-lifecycle.ts
@@ -6339,18 +6573,6 @@ async function runDestruction(effects) {
6339
6573
  }
6340
6574
 
6341
6575
  // packages/client/src/store-meta.ts
6342
- var exports_store_meta = {};
6343
- __export(exports_store_meta, {
6344
- META_READ_ATTEMPTS: () => META_READ_ATTEMPTS,
6345
- META_STORE_UNAVAILABLE: () => META_STORE_UNAVAILABLE,
6346
- STORE_META_DATABASE: () => STORE_META_DATABASE,
6347
- StoreMetaUnreadableError: () => StoreMetaUnreadableError,
6348
- classifyStoreBoot: () => classifyStoreBoot,
6349
- deleteStoreMetaRecord: () => deleteStoreMetaRecord,
6350
- idbStoreExists: () => idbStoreExists,
6351
- readStoreMetaRecord: () => readStoreMetaRecord,
6352
- writeStoreMetaRecord: () => writeStoreMetaRecord
6353
- });
6354
6576
  function classifyStoreBoot(obs) {
6355
6577
  const { record, opfs, idbStoreExists } = obs;
6356
6578
  if (record != null) {
@@ -6533,7 +6755,121 @@ function idbStoreExists(storePath, deps) {
6533
6755
  };
6534
6756
  });
6535
6757
  }
6536
- var STORE_META_DATABASE = "pgxsinkit-store-meta", META_OBJECT_STORE = "stores", META_READ_ATTEMPTS = 3, META_READ_RETRY_DELAY_MS = 25, StoreMetaUnreadableError, META_STORE_UNAVAILABLE, VALID_PHASES;
6758
+ function openPendingDatabase(indexedDB) {
6759
+ return new Promise((resolve, reject) => {
6760
+ let request;
6761
+ try {
6762
+ request = indexedDB.open(OPFS_DELETION_PENDING_DATABASE, 1);
6763
+ } catch (error) {
6764
+ reject(error);
6765
+ return;
6766
+ }
6767
+ request.onupgradeneeded = () => {
6768
+ const db = request.result;
6769
+ if (!db.objectStoreNames.contains(PENDING_OBJECT_STORE))
6770
+ db.createObjectStore(PENDING_OBJECT_STORE);
6771
+ };
6772
+ request.onsuccess = () => resolve(request.result);
6773
+ request.onerror = () => reject(request.error ?? new Error("indexedDB open failed"));
6774
+ });
6775
+ }
6776
+ function openExistingPendingDatabase(indexedDB) {
6777
+ return new Promise((resolve, reject) => {
6778
+ let existed = true;
6779
+ let request;
6780
+ try {
6781
+ request = indexedDB.open(OPFS_DELETION_PENDING_DATABASE);
6782
+ } catch (error) {
6783
+ reject(error);
6784
+ return;
6785
+ }
6786
+ request.onupgradeneeded = (event) => {
6787
+ existed = false;
6788
+ const transaction = event?.target?.transaction ?? request.transaction;
6789
+ transaction?.abort();
6790
+ };
6791
+ request.onsuccess = () => {
6792
+ if (existed) {
6793
+ resolve(request.result);
6794
+ return;
6795
+ }
6796
+ request.result.close();
6797
+ resolve(undefined);
6798
+ };
6799
+ request.onerror = () => {
6800
+ if (!existed) {
6801
+ resolve(undefined);
6802
+ return;
6803
+ }
6804
+ reject(request.error ?? new Error("indexedDB open failed"));
6805
+ };
6806
+ });
6807
+ }
6808
+ async function readPendingAttempt(indexedDB, key) {
6809
+ const db = await openExistingPendingDatabase(indexedDB);
6810
+ if (db == null)
6811
+ return false;
6812
+ try {
6813
+ if (!db.objectStoreNames.contains(PENDING_OBJECT_STORE))
6814
+ return false;
6815
+ const store = db.transaction(PENDING_OBJECT_STORE, "readonly").objectStore(PENDING_OBJECT_STORE);
6816
+ return await awaitRequest(store.get(key)) !== undefined;
6817
+ } finally {
6818
+ db.close();
6819
+ }
6820
+ }
6821
+ async function readOpfsDeletionPending(storePath, deps) {
6822
+ const indexedDB = resolveIndexedDb(deps);
6823
+ if (indexedDB == null)
6824
+ return false;
6825
+ const key = storeIdentityComponent(storePath);
6826
+ const delay = deps?.delay ?? defaultDelay;
6827
+ let lastError;
6828
+ for (let attempt = 1;attempt <= META_READ_ATTEMPTS; attempt += 1) {
6829
+ try {
6830
+ return await readPendingAttempt(indexedDB, key);
6831
+ } catch (error) {
6832
+ lastError = error;
6833
+ if (attempt < META_READ_ATTEMPTS)
6834
+ await delay(META_READ_RETRY_DELAY_MS);
6835
+ }
6836
+ }
6837
+ throw new StoreMetaUnreadableError(storePath, new Error("the OPFS-deletion-pending marker could not be read", { cause: lastError }));
6838
+ }
6839
+ async function writeOpfsDeletionPending(storePath, deps) {
6840
+ const indexedDB = resolveIndexedDb(deps);
6841
+ if (indexedDB == null)
6842
+ return false;
6843
+ const key = storeIdentityComponent(storePath);
6844
+ const db = await openPendingDatabase(indexedDB);
6845
+ try {
6846
+ const transaction = db.transaction(PENDING_OBJECT_STORE, "readwrite", { durability: "strict" });
6847
+ const store = transaction.objectStore(PENDING_OBJECT_STORE);
6848
+ await awaitAuthorityMutation(transaction, store.put({ updatedAt: Date.now() }, key));
6849
+ } finally {
6850
+ db.close();
6851
+ }
6852
+ return true;
6853
+ }
6854
+ async function clearOpfsDeletionPending(storePath, deps) {
6855
+ const indexedDB = resolveIndexedDb(deps);
6856
+ if (indexedDB == null)
6857
+ return;
6858
+ const key = storeIdentityComponent(storePath);
6859
+ const db = await openExistingPendingDatabase(indexedDB);
6860
+ if (db == null)
6861
+ return;
6862
+ try {
6863
+ if (!db.objectStoreNames.contains(PENDING_OBJECT_STORE))
6864
+ return;
6865
+ const transaction = db.transaction(PENDING_OBJECT_STORE, "readwrite", { durability: "strict" });
6866
+ const store = transaction.objectStore(PENDING_OBJECT_STORE);
6867
+ await awaitAuthorityMutation(transaction, store.delete(key));
6868
+ } finally {
6869
+ db.close();
6870
+ }
6871
+ }
6872
+ var STORE_META_DATABASE = "pgxsinkit-store-meta", META_OBJECT_STORE = "stores", META_READ_ATTEMPTS = 3, META_READ_RETRY_DELAY_MS = 25, StoreMetaUnreadableError, META_STORE_UNAVAILABLE, VALID_PHASES, OPFS_DELETION_PENDING_DATABASE = "pgxsinkit-opfs-deletion-pending", PENDING_OBJECT_STORE = "stores";
6537
6873
  var init_store_meta = __esm(() => {
6538
6874
  init_store_path();
6539
6875
  StoreMetaUnreadableError = class StoreMetaUnreadableError extends Error {
@@ -6606,9 +6942,29 @@ function committedStoreUnreachableFromWire(detail) {
6606
6942
  return;
6607
6943
  return new CommittedStoreUnreachableError(candidate.storePath);
6608
6944
  }
6945
+ async function settlePendingOpfsDeletion(storePath, deps) {
6946
+ if (!await readOpfsDeletionPending(storePath, deps?.meta))
6947
+ return "none";
6948
+ const effects = createOpfsEffects(storePath, deps?.opfs);
6949
+ if (await effects.observeCommitmentNamespace() === "unobservable")
6950
+ return "still-pending";
6951
+ try {
6952
+ await effects.deleteSentinel();
6953
+ await effects.deleteStoreDirectory();
6954
+ } catch (error) {
6955
+ if (isOpfsRootUnavailableError(error))
6956
+ return "still-pending";
6957
+ throw error;
6958
+ }
6959
+ await clearOpfsDeletionPending(storePath, deps?.meta);
6960
+ return "settled";
6961
+ }
6609
6962
  async function resolveDeniedBootAuthority(storePath, deps) {
6610
6963
  const meta = deps?.meta;
6611
- const record = await readStoreMetaRecord(storePath, meta);
6964
+ const [record, pendingOpfsDeletion] = await Promise.all([
6965
+ readStoreMetaRecord(storePath, meta),
6966
+ settlePendingOpfsDeletion(storePath, deps)
6967
+ ]);
6612
6968
  if (record === META_STORE_UNAVAILABLE)
6613
6969
  return false;
6614
6970
  const phase = record?.phase;
@@ -6618,6 +6974,11 @@ async function resolveDeniedBootAuthority(storePath, deps) {
6618
6974
  return false;
6619
6975
  const effects = createOpfsEffects(storePath, deps?.opfs);
6620
6976
  if (await effects.observeCommitmentNamespace() === "unobservable") {
6977
+ if (phase === "deleting" && pendingOpfsDeletion === "still-pending") {
6978
+ await deleteIdbDatabase(storePath, meta);
6979
+ await deleteStoreMetaRecord(storePath, meta);
6980
+ return false;
6981
+ }
6621
6982
  throw new Error(`[pgxsinkit] cannot settle ${JSON.stringify(storePath)} for an IDB boot (record phase ` + `${JSON.stringify(phase)}): the OPFS commitment namespace is unobservable in this scope, so sentinel ` + "removal cannot be confirmed.");
6622
6983
  }
6623
6984
  if (phase === "deleting")
@@ -6657,8 +7018,9 @@ async function resolveStoreBoot(storePath, opts) {
6657
7018
  await writePhase("idb-authoritative");
6658
7019
  return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
6659
7020
  };
7021
+ const pendingOpfsDeletion = settlePendingOpfsDeletion(storePath, opts.deps);
6660
7022
  for (let iteration = 0;iteration < MAX_DELETION_RECLASSIFY; iteration += 1) {
6661
- const metaResult = await readStoreMetaRecord(storePath, meta);
7023
+ const [metaResult] = await Promise.all([readStoreMetaRecord(storePath, meta), pendingOpfsDeletion]);
6662
7024
  const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
6663
7025
  const record = metaUnavailable ? undefined : metaResult;
6664
7026
  const committedFastVerdict = record?.phase === "opfs-committed" ? classifyStoreBoot({ record, opfs: "unobservable", idbStoreExists: false }) : undefined;
@@ -6722,6 +7084,25 @@ var init_store_boot = __esm(() => {
6722
7084
  };
6723
7085
  });
6724
7086
 
7087
+ // packages/client/src/store-build.ts
7088
+ import { StorageBuildMismatchError } from "@pgxsinkit/contracts";
7089
+ function assertStoreBuild(declared, supplied, site) {
7090
+ if (supplied.name !== declared)
7091
+ throw new StorageBuildMismatchError(declared, supplied.name, site);
7092
+ }
7093
+ function isStoreBuildRefusal(error) {
7094
+ return error instanceof Error && STORE_BUILD_REFUSALS.has(error.name);
7095
+ }
7096
+ var STORE_BUILD_REFUSALS;
7097
+ var init_store_build = __esm(() => {
7098
+ STORE_BUILD_REFUSALS = new Set([
7099
+ "StorageBuildMismatchError",
7100
+ "BuildMismatchError",
7101
+ "DataFormatMismatchError",
7102
+ "BuildMarkerUnreadableError"
7103
+ ]);
7104
+ });
7105
+
6725
7106
  // packages/client/src/worker/live-diff.ts
6726
7107
  function rowKey(row, pkColumns) {
6727
7108
  if (pkColumns && pkColumns.length > 0) {
@@ -6884,11 +7265,11 @@ function fingerprintLiveQuery(materialSql, params, pkColumns) {
6884
7265
  var opaqueCounter = 0;
6885
7266
 
6886
7267
  // packages/client/src/worker/live-query-params-guard.ts
6887
- function assertLiveQueryParamsSafe(sql8, params) {
7268
+ function assertLiveQueryParamsSafe(sql, params) {
6888
7269
  if (params.length === 0)
6889
7270
  return;
6890
7271
  const numbers = [];
6891
- for (const match of sql8.matchAll(/\$(\d+)/g))
7272
+ for (const match of sql.matchAll(/\$(\d+)/g))
6892
7273
  numbers.push(Number(match[1]));
6893
7274
  const expected = params.length;
6894
7275
  const safe = numbers.length === expected && numbers.every((n, i) => n === i + 1);
@@ -6927,7 +7308,7 @@ function createLiveQueryManager(deps) {
6927
7308
  maxRetainedQueries: deps.policy?.maxRetainedQueries ?? 16,
6928
7309
  maxRetainedRows: deps.policy?.maxRetainedRows ?? 50000
6929
7310
  };
6930
- const now2 = deps.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
7311
+ const now = deps.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
6931
7312
  const setTimer = deps.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
6932
7313
  const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
6933
7314
  const pendingTeardowns = new Set;
@@ -6943,7 +7324,7 @@ function createLiveQueryManager(deps) {
6943
7324
  subscribers: new Map,
6944
7325
  torn: false,
6945
7326
  generationKeepAliveMs: 0,
6946
- createdAt: now2(),
7327
+ createdAt: now(),
6947
7328
  dedupHits: 0,
6948
7329
  refreshCount: 0,
6949
7330
  refreshTotalMs: 0,
@@ -6952,7 +7333,7 @@ function createLiveQueryManager(deps) {
6952
7333
  setup: undefined
6953
7334
  };
6954
7335
  entry.setup = (async () => {
6955
- const setupStartedAt = now2();
7336
+ const setupStartedAt = now();
6956
7337
  const { materialSql, params, pkColumns } = spec;
6957
7338
  const registered = pkColumns && pkColumns.length === 1 ? await live.incrementalQuery(materialSql, params, pkColumns[0]) : await live.query(materialSql, params);
6958
7339
  const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
@@ -6972,7 +7353,7 @@ function createLiveQueryManager(deps) {
6972
7353
  entry.registered = registered;
6973
7354
  entry.state = state;
6974
7355
  entry.listener = listener;
6975
- entry.setupMs = now2() - setupStartedAt;
7356
+ entry.setupMs = now() - setupStartedAt;
6976
7357
  syncDebug("live-query register", { digest, setupMs: Math.round(entry.setupMs) });
6977
7358
  })();
6978
7359
  entry.setup.catch(() => {
@@ -7050,7 +7431,7 @@ function createLiveQueryManager(deps) {
7050
7431
  const effective = Math.max(policy.defaultKeepAliveMs, entry.generationKeepAliveMs);
7051
7432
  if (effective <= 0 || disposed || entry.torn)
7052
7433
  return tearDownEntry(entry);
7053
- entry.lastUsedAt = now2();
7434
+ entry.lastUsedAt = now();
7054
7435
  retained.add(entry);
7055
7436
  entry.evictionTimer = setTimer(() => onEvictionTimer(entry), effective);
7056
7437
  syncDebug("live-query retained", { digest: entry.digest, keepAliveMs: effective });
@@ -7061,9 +7442,9 @@ function createLiveQueryManager(deps) {
7061
7442
  if (entry.torn || !entry.registered)
7062
7443
  return Promise.resolve();
7063
7444
  if (entry.refreshInFlight === undefined) {
7064
- const startedAt = now2();
7445
+ const startedAt = now();
7065
7446
  entry.refreshInFlight = entry.registered.refresh().finally(() => {
7066
- const ms = now2() - startedAt;
7447
+ const ms = now() - startedAt;
7067
7448
  entry.refreshCount++;
7068
7449
  entry.refreshLastMs = ms;
7069
7450
  entry.refreshTotalMs += ms;
@@ -7116,10 +7497,10 @@ function createLiveQueryManager(deps) {
7116
7497
  const firstOfGeneration = joined.subscribers.size === 0;
7117
7498
  joined.generationKeepAliveMs = firstOfGeneration ? keepAliveMs : Math.max(joined.generationKeepAliveMs, keepAliveMs);
7118
7499
  const token = Symbol("live-subscriber");
7119
- const snapshot2 = [...joined.state.previous.values()];
7500
+ const snapshot = [...joined.state.previous.values()];
7120
7501
  joined.subscribers.set(token, { subscriber, keepAliveMs, scope });
7121
7502
  try {
7122
- subscriber.deliverInitial(snapshot2);
7503
+ subscriber.deliverInitial(snapshot);
7123
7504
  } catch (error) {
7124
7505
  joined.subscribers.delete(token);
7125
7506
  if (joined.subscribers.size === 0)
@@ -7174,7 +7555,7 @@ function createLiveQueryManager(deps) {
7174
7555
  maxMs: entry.refreshMaxMs
7175
7556
  },
7176
7557
  lastUsedAt: entry.lastUsedAt ?? null,
7177
- retainedSinceMs: isRetained && entry.lastUsedAt != null ? Math.max(0, now2() - entry.lastUsedAt) : null,
7558
+ retainedSinceMs: isRetained && entry.lastUsedAt != null ? Math.max(0, now() - entry.lastUsedAt) : null,
7178
7559
  teardownPending: entry.teardownPending
7179
7560
  });
7180
7561
  }
@@ -7194,8 +7575,8 @@ function describeProbeError(error) {
7194
7575
  return String(error);
7195
7576
  }
7196
7577
  function defaultScratchName() {
7197
- const uuid2 = globalThis.crypto?.randomUUID?.();
7198
- return `probe-${uuid2 ? uuid2.slice(0, 8) : Math.random().toString(36).slice(2, 10)}`;
7578
+ const uuid = globalThis.crypto?.randomUUID?.();
7579
+ return `probe-${uuid ? uuid.slice(0, 8) : Math.random().toString(36).slice(2, 10)}`;
7199
7580
  }
7200
7581
  function resolveDefaultGetRoot2() {
7201
7582
  const storage = globalThis.navigator?.storage;
@@ -7205,9 +7586,9 @@ function resolveDefaultGetRoot2() {
7205
7586
  return () => getDirectory.call(storage);
7206
7587
  }
7207
7588
  async function probeOpfsSyncAccess(deps = {}) {
7208
- const now2 = deps.now ?? nowMs3;
7209
- const start = now2();
7210
- const elapsed = () => Math.max(0, now2() - start);
7589
+ const now = deps.now ?? nowMs3;
7590
+ const start = now();
7591
+ const elapsed = () => Math.max(0, now() - start);
7211
7592
  const getRoot = deps.getRoot ?? resolveDefaultGetRoot2();
7212
7593
  if (getRoot == null) {
7213
7594
  return { granted: false, error: OPFS_API_ABSENT_ERROR, ms: elapsed() };
@@ -7239,6 +7620,34 @@ var init_placement_probe = __esm(() => {
7239
7620
  init_store_path();
7240
7621
  });
7241
7622
 
7623
+ // packages/client/src/store-engine.ts
7624
+ async function loadStoreEngineFactory(module, load = importStoreEngineModule) {
7625
+ let loaded;
7626
+ try {
7627
+ loaded = await load(module);
7628
+ } catch (cause) {
7629
+ throw new Error(`[pgxsinkit] the declared store engine "${module}" could not be imported. \`storage.engine.module\` ` + `must be a module URL THIS scope can import \u2014 same-origin, or cross-origin with CORS and (under ` + `cross-origin isolation) Cross-Origin-Resource-Policy: cross-origin.`, { cause });
7630
+ }
7631
+ const exports = loaded ?? {};
7632
+ const factory = typeof exports.default === "function" ? exports.default : exports.createStore;
7633
+ if (typeof factory !== "function") {
7634
+ throw new Error(`[pgxsinkit] the declared store engine "${module}" exports no store factory. Expected a default export (or a named \`createStore\`) of \`(storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>\`.`);
7635
+ }
7636
+ return factory;
7637
+ }
7638
+ function createStoreEngineResolver(load = importStoreEngineModule) {
7639
+ const loading = new Map;
7640
+ return (module) => {
7641
+ let pending = loading.get(module);
7642
+ if (pending === undefined) {
7643
+ pending = loadStoreEngineFactory(module, load);
7644
+ loading.set(module, pending);
7645
+ }
7646
+ return pending;
7647
+ };
7648
+ }
7649
+ var importStoreEngineModule = (url) => import(url);
7650
+
7242
7651
  // packages/client/src/worker/engine-control.ts
7243
7652
  function wrapControlEnvelope(message) {
7244
7653
  return { [ENGINE_CONTROL_ENVELOPE_KEY]: message };
@@ -7701,7 +8110,7 @@ var init_sw_placement = __esm(() => {
7701
8110
 
7702
8111
  // packages/client/src/worker/token-cache.ts
7703
8112
  function createWorkerTokenCache(options) {
7704
- const now2 = options.now ?? (() => Date.now());
8113
+ const now = options.now ?? (() => Date.now());
7705
8114
  let cached = null;
7706
8115
  let inFlight = null;
7707
8116
  let resolveInFlight = null;
@@ -7718,7 +8127,7 @@ function createWorkerTokenCache(options) {
7718
8127
  };
7719
8128
  return {
7720
8129
  getToken: async () => {
7721
- if (cached && cached.expiresAt - now2() > options.marginMs) {
8130
+ if (cached && cached.expiresAt - now() > options.marginMs) {
7722
8131
  return cached.accessToken;
7723
8132
  }
7724
8133
  if (!inFlight) {
@@ -7753,15 +8162,17 @@ function createWorkerTokenCache(options) {
7753
8162
  }
7754
8163
 
7755
8164
  // packages/client/src/worker/define-sync-worker.ts
7756
- import { types } from "@electric-sql/pglite";
7757
8165
  import {
7758
8166
  assertStorageDeclarationCompatible,
7759
8167
  getSyncRegistryStorage,
7760
8168
  isStorageBackend,
8169
+ isStorageBuild,
7761
8170
  isStorageDurability,
8171
+ isStorageEngineDeclaration,
7762
8172
  resolveStorageDeclaration,
7763
8173
  StorageDeclarationRefusedError
7764
8174
  } from "@pgxsinkit/contracts";
8175
+ import { drizzleParsers } from "@pgxsinkit/pgwasm/drizzle";
7765
8176
  function defineSyncWorker(options) {
7766
8177
  validateLiveQueryPolicy(options.liveQueries);
7767
8178
  const codec = options.codec ?? identityCodec;
@@ -7787,17 +8198,42 @@ function defineSyncWorker(options) {
7787
8198
  }
7788
8199
  };
7789
8200
  const currentDurability = () => engineStorage?.durability ?? getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
7790
- const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath, {
8201
+ const currentBuild = () => engineStorage?.build ?? getSyncRegistryStorage(options.registry)?.build ?? "c";
8202
+ const builtInCreatePglite = options.createStore ?? ((storePath, backendOverride) => createPgwasmClient(storePath, {
7791
8203
  ...backendOverride ? { backendOverride } : {},
8204
+ ...options.build ? { build: options.build } : {},
8205
+ declaredBuild: currentBuild(),
8206
+ buildCheckSite: "defineSyncWorker",
7792
8207
  durability: currentDurability(),
7793
8208
  ...placementOpfsAccess ? { hasOpfsSyncAccess: true } : {}
7794
8209
  }));
8210
+ const resolveStoreEngine = createStoreEngineResolver(options.loadStoreEngineModule);
8211
+ const createStore = async (storePath, backendOverride) => {
8212
+ const declaredEngine = engineStorage?.engine?.module;
8213
+ let store;
8214
+ if (declaredEngine === undefined) {
8215
+ store = await builtInCreatePglite(storePath, backendOverride);
8216
+ } else {
8217
+ const factory = await resolveStoreEngine(declaredEngine);
8218
+ syncDebug("worker store engine declared", { storePath, module: declaredEngine });
8219
+ store = await factory(storePath, backendOverride);
8220
+ }
8221
+ try {
8222
+ assertStoreBuild(currentBuild(), store.build, "createStore");
8223
+ } catch (error) {
8224
+ await store.close().catch(() => {
8225
+ return;
8226
+ });
8227
+ throw error;
8228
+ }
8229
+ return store;
8230
+ };
7795
8231
  const workerTestMarker = readTestStoreMarker(options);
7796
8232
  const ports = new Set;
7797
8233
  const liveSubs = new Map;
7798
8234
  let liveManager = null;
7799
8235
  const ensureLiveManager = (active) => liveManager ??= createLiveQueryManager({
7800
- live: active.pglite.live,
8236
+ live: active.pgwasm.live,
7801
8237
  ...options.liveQueries ? { policy: options.liveQueries } : {}
7802
8238
  });
7803
8239
  const pendingSubscribes = new Map;
@@ -7876,6 +8312,30 @@ function defineSyncWorker(options) {
7876
8312
  });
7877
8313
  }
7878
8314
  };
8315
+ let lastSyncedSnapshot = null;
8316
+ const computeSyncedSnapshot = (active) => {
8317
+ const snapshot = {};
8318
+ for (const key of Object.keys(bootedRegistry ?? options.registry)) {
8319
+ snapshot[key] = active.isSynced(key);
8320
+ }
8321
+ return snapshot;
8322
+ };
8323
+ const sameSnapshot = (a, b) => {
8324
+ const keys = Object.keys(a);
8325
+ if (keys.length !== Object.keys(b).length)
8326
+ return false;
8327
+ return keys.every((key) => a[key] === b[key]);
8328
+ };
8329
+ const publishSyncedIfChanged = () => {
8330
+ const active = client;
8331
+ if (active == null)
8332
+ return;
8333
+ const snapshot = computeSyncedSnapshot(active);
8334
+ if (lastSyncedSnapshot != null && sameSnapshot(lastSyncedSnapshot, snapshot))
8335
+ return;
8336
+ lastSyncedSnapshot = snapshot;
8337
+ broadcastEvent({ kind: "synced", tables: snapshot });
8338
+ };
7879
8339
  const emitStatus = (status) => {
7880
8340
  broadcastEvent({ kind: "status", status });
7881
8341
  for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {
@@ -7884,10 +8344,12 @@ function defineSyncWorker(options) {
7884
8344
  broadcastEvent({ kind: "groupReady", groupKey });
7885
8345
  }
7886
8346
  }
8347
+ publishSyncedIfChanged();
7887
8348
  };
7888
8349
  let client = null;
7889
8350
  let bootPromise = null;
7890
8351
  let bootedRole;
8352
+ let bootedRegistry = null;
7891
8353
  let engineReadyFired = false;
7892
8354
  let resolveBooted;
7893
8355
  const bootedPromise = new Promise((resolve) => {
@@ -7901,6 +8363,7 @@ function defineSyncWorker(options) {
7901
8363
  return;
7902
8364
  milestones[stage] = true;
7903
8365
  broadcastEvent({ kind: "milestone", stage });
8366
+ publishSyncedIfChanged();
7904
8367
  };
7905
8368
  const failMilestone = (stage, error) => {
7906
8369
  if (stageErrors[stage])
@@ -7962,6 +8425,7 @@ function defineSyncWorker(options) {
7962
8425
  tokenCache.push(attach.token);
7963
8426
  bootedRole = attach.config?.role;
7964
8427
  const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
8428
+ bootedRegistry = registry;
7965
8429
  if (registry !== options.registry) {
7966
8430
  assertStorageDeclarationCompatible(engineStorage ?? resolveStorageDeclaration(getSyncRegistryStorage(options.registry), undefined), getSyncRegistryStorage(registry) ?? {});
7967
8431
  }
@@ -7970,7 +8434,7 @@ function defineSyncWorker(options) {
7970
8434
  const testMarker = backendOverride === "memory" ? "memory" : workerTestMarker;
7971
8435
  const restoreFrom = attach.restore ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType }) : undefined;
7972
8436
  const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;
7973
- const precreatedPglite = adoptingProvisioned ? provisioned.pglite : restoreFrom ? undefined : options.precreatedPglite;
8437
+ const precreatedPgwasm = adoptingProvisioned ? provisioned.pglite : restoreFrom ? undefined : options.precreatedPgwasm;
7974
8438
  const provisionStamp = adoptingProvisioned ? provisioned.stamp : undefined;
7975
8439
  if (adoptingProvisioned) {
7976
8440
  syncDebug("worker adopting provisioned store", { storePath });
@@ -7989,8 +8453,9 @@ function defineSyncWorker(options) {
7989
8453
  bootMode: "worker",
7990
8454
  ...placementEngineHome ? { engineHome: placementEngineHome } : {},
7991
8455
  ...provisionStamp ? { provisionStamp } : {},
7992
- ...precreatedPglite ? { precreatedPglite } : {},
7993
- ...options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {},
8456
+ ...precreatedPgwasm ? { precreatedPgwasm } : {},
8457
+ ...options.pgwasmInstance && restoreFrom == null ? { pgwasmInstance: options.pgwasmInstance } : {},
8458
+ ...options.build ? { build: options.build } : {},
7994
8459
  ...options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {},
7995
8460
  ...options.prepareLocalDbAfterSchema ? { prepareLocalDbAfterSchema: options.prepareLocalDbAfterSchema } : {},
7996
8461
  ...engineStorage ? { storage: engineStorage } : {},
@@ -8026,12 +8491,12 @@ function defineSyncWorker(options) {
8026
8491
  };
8027
8492
  const dispatchRpc = async (active, op, args) => {
8028
8493
  const runGuardedQueryRpc = () => {
8029
- const [sql8, params, options2, use] = args;
8494
+ const [sql, params, options, use] = args;
8030
8495
  const queryOptions = {
8031
- ...options2?.rowMode ? { rowMode: options2.rowMode } : {},
8032
- parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS
8496
+ ...options?.rowMode ? { rowMode: options.rowMode } : {},
8497
+ parsers: drizzleParsers
8033
8498
  };
8034
- return active.guardedRawQuery(sql8, params, queryOptions, use);
8499
+ return active.guardedRawQuery(sql, params, queryOptions, use);
8035
8500
  };
8036
8501
  switch (op) {
8037
8502
  case "create":
@@ -8092,6 +8557,8 @@ function defineSyncWorker(options) {
8092
8557
  return active.rawQuery(args[0], args[1], args[2]);
8093
8558
  case "rawExec":
8094
8559
  return active.rawExec(args[0], args[1]);
8560
+ case "rawTransaction":
8561
+ return active.rawTransaction(args[0], args[1]);
8095
8562
  case "guardedQuery":
8096
8563
  return runGuardedQueryRpc();
8097
8564
  case "bootReport":
@@ -8140,10 +8607,11 @@ function defineSyncWorker(options) {
8140
8607
  const active = client ?? await bootPromise;
8141
8608
  if (!active)
8142
8609
  throw new Error("subscribe before attach");
8143
- const { queryId, sql: sql8, params, pkColumns, use, fields, keepAliveMs } = payload;
8144
- const prepared = await active.prepareQuery({ sql: sql8, ...use ? { use } : {} });
8145
- const hydratingTables = active.hydratingTablesFor({ sql: sql8, ...use ? { use } : {} });
8146
- const materialSql = wrapLiveQueryForMaterialization(sql8, fields);
8610
+ const { queryId, sql, params, pkColumns, use, fields, keepAliveMs } = payload;
8611
+ const prepared = await active.prepareQuery({ sql, ...use ? { use } : {} });
8612
+ const hydratingTables = active.hydratingTablesFor({ sql, ...use ? { use } : {} });
8613
+ publishSyncedIfChanged();
8614
+ const materialSql = wrapLiveQueryForMaterialization(sql, fields);
8147
8615
  if (closing || pending.cancelled || !ports.has(port)) {
8148
8616
  postBridgeMessage(port, codec, "rpc-result", {
8149
8617
  ok: false,
@@ -8253,7 +8721,7 @@ function defineSyncWorker(options) {
8253
8721
  await writeStoreMetaRecord(storePath, { phase: "opfs-candidate", updatedAt: Date.now() });
8254
8722
  }
8255
8723
  const provisionStartedAt = nowStamp();
8256
- const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
8724
+ const pglite = Promise.resolve().then(() => createStore(storePath, backendOverride));
8257
8725
  const stamp = pglite.then(() => {
8258
8726
  const readyAt = nowStamp();
8259
8727
  return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
@@ -8357,7 +8825,8 @@ function defineSyncWorker(options) {
8357
8825
  postBridgeMessage(port, codec, "attach-ack", {
8358
8826
  alreadyBooted,
8359
8827
  ...engineReadyFired ? { engineReady: true } : {},
8360
- ...milestoneAckFields()
8828
+ ...milestoneAckFields(),
8829
+ synced: computeSyncedSnapshot(booted)
8361
8830
  });
8362
8831
  postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
8363
8832
  }, (error) => {
@@ -8383,16 +8852,20 @@ function defineSyncWorker(options) {
8383
8852
  const { op, args } = payload;
8384
8853
  const id = envelope.id;
8385
8854
  (async () => {
8855
+ let result;
8856
+ let transfer;
8386
8857
  try {
8387
8858
  const active = client ?? await bootPromise;
8388
8859
  if (!active)
8389
8860
  throw new Error("rpc before attach");
8390
8861
  const value = await dispatchRpc(active, op, args);
8391
- const transfer = op === "exportStore" || op === "exportDiagnostics" || op === "exportData" ? [value.buffer] : undefined;
8392
- postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id, transfer);
8862
+ transfer = op === "exportStore" || op === "exportDiagnostics" || op === "exportData" ? [value.buffer] : undefined;
8863
+ result = { ok: true, value };
8393
8864
  } catch (error) {
8394
- postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
8865
+ result = { ok: false, error: serializeError(error) };
8395
8866
  }
8867
+ publishSyncedIfChanged();
8868
+ postBridgeMessage(port, codec, "rpc-result", result, id, transfer);
8396
8869
  })();
8397
8870
  break;
8398
8871
  }
@@ -8656,6 +9129,12 @@ function invalidDeclarationField(declaration) {
8656
9129
  if (declaration.durability !== undefined && !isStorageDurability(declaration.durability)) {
8657
9130
  return `durability "${String(declaration.durability)}"`;
8658
9131
  }
9132
+ if (declaration.build !== undefined && !isStorageBuild(declaration.build)) {
9133
+ return `build "${String(declaration.build)}"`;
9134
+ }
9135
+ if (declaration.engine !== undefined && !isStorageEngineDeclaration(declaration.engine)) {
9136
+ return `engine ${JSON.stringify(declaration.engine)}`;
9137
+ }
8659
9138
  return;
8660
9139
  }
8661
9140
  function bootstrapWorkerScope(deps) {
@@ -8885,13 +9364,14 @@ function wireSharedWorkerPlacement(deps, globalScope) {
8885
9364
  installPortListener(port, state);
8886
9365
  };
8887
9366
  }
8888
- var identityParser = (value) => value, DRIZZLE_PGLITE_IDENTITY_PARSERS, PROVISION_PENDING_HEARTBEAT_MS = 5000, CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort", PLACEMENT_QUERY_KEY = "pgx0049Placement", PLACEMENT_RESULT_KEY = "pgx0049PlacementResult", DESTROY_QUERY_KEY = "pgx0049DestroyQuery", DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict", DECLARATION_KEY = "pgx0050Declaration", DECLARATION_REFUSED_KEY = "pgx0050DeclarationRefused";
9367
+ var PROVISION_PENDING_HEARTBEAT_MS = 5000, CONTROL_PORT_DELIVERY_KEY = "pgx0049ControlPort", PLACEMENT_QUERY_KEY = "pgx0049Placement", PLACEMENT_RESULT_KEY = "pgx0049PlacementResult", DESTROY_QUERY_KEY = "pgx0049DestroyQuery", DESTROY_VERDICT_KEY = "pgx0049DestroyVerdict", DECLARATION_KEY = "pgx0050Declaration", DECLARATION_REFUSED_KEY = "pgx0050DeclarationRefused";
8889
9368
  var init_define_sync_worker = __esm(() => {
8890
9369
  init_convergence();
8891
9370
  init_src();
8892
9371
  init_live_rows_sql();
8893
9372
  init_opfs_effects();
8894
9373
  init_placement_probe();
9374
+ init_store_build();
8895
9375
  init_store_meta();
8896
9376
  init_store_path();
8897
9377
  init_engine_control();
@@ -8899,17 +9379,6 @@ var init_define_sync_worker = __esm(() => {
8899
9379
  init_live_query_manager();
8900
9380
  init_protocol();
8901
9381
  init_sw_placement();
8902
- DRIZZLE_PGLITE_IDENTITY_PARSERS = {
8903
- [types.TIMESTAMP]: identityParser,
8904
- [types.TIMESTAMPTZ]: identityParser,
8905
- [types.INTERVAL]: identityParser,
8906
- [types.DATE]: identityParser,
8907
- 1231: identityParser,
8908
- 1115: identityParser,
8909
- 1185: identityParser,
8910
- 1187: identityParser,
8911
- 1182: identityParser
8912
- };
8913
9382
  });
8914
9383
 
8915
9384
  // packages/client/src/worker/election-coordinator.ts
@@ -9186,20 +9655,6 @@ var init_election_coordinator = __esm(() => {
9186
9655
  });
9187
9656
 
9188
9657
  // packages/client/src/worker/attach-sync-client.ts
9189
- var exports_attach_sync_client = {};
9190
- __export(exports_attach_sync_client, {
9191
- ElectedEngineUnconstructibleError: () => ElectedEngineUnconstructibleError,
9192
- ProvisionExpiredError: () => ProvisionExpiredError,
9193
- StoreDestroyRefusedError: () => StoreDestroyRefusedError,
9194
- attachSyncClient: () => attachSyncClient,
9195
- createStoreDestructionEffects: () => createStoreDestructionEffects,
9196
- destroyStoreArtifacts: () => destroyStoreArtifacts,
9197
- provisionSyncWorker: () => provisionSyncWorker,
9198
- quiesceStoreWorker: () => quiesceStoreWorker,
9199
- resolvedOwnershipRelease: () => resolvedOwnershipRelease,
9200
- runStoreDestruction: () => runStoreDestruction,
9201
- wrapEngineWorker: () => wrapEngineWorker
9202
- });
9203
9658
  import { StorageDeclarationRefusedError as StorageDeclarationRefusedError2 } from "@pgxsinkit/contracts";
9204
9659
  function resolvedOwnershipRelease() {
9205
9660
  return Promise.resolve();
@@ -9264,11 +9719,21 @@ function deleteStoreIdbDatabase(storePath, meta) {
9264
9719
  function createStoreDestructionEffects(storePath, deps) {
9265
9720
  const opfs = createOpfsEffects(storePath, deps?.opfs);
9266
9721
  const meta = deps?.meta;
9722
+ const deleteOpfsOrRecordPending = async (deleteOpfs) => {
9723
+ try {
9724
+ await deleteOpfs();
9725
+ } catch (error) {
9726
+ if (!isOpfsRootUnavailableError(error))
9727
+ throw error;
9728
+ if (!await writeOpfsDeletionPending(storePath, meta))
9729
+ throw error;
9730
+ }
9731
+ };
9267
9732
  return {
9268
9733
  setPhase: (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, meta),
9269
- deleteSentinel: () => opfs.deleteSentinel(),
9734
+ deleteSentinel: () => deleteOpfsOrRecordPending(() => opfs.deleteSentinel()),
9270
9735
  deleteBackendStore: async () => {
9271
- await opfs.deleteStoreDirectory();
9736
+ await deleteOpfsOrRecordPending(() => opfs.deleteStoreDirectory());
9272
9737
  await deleteStoreIdbDatabase(storePath, meta);
9273
9738
  },
9274
9739
  deleteMetaRecord: () => deleteStoreMetaRecord(storePath, meta)
@@ -9332,8 +9797,8 @@ function defaultIsOwnershipError(error) {
9332
9797
  if (name === "NoModificationAllowedError" || name === "InvalidStateError")
9333
9798
  return true;
9334
9799
  const message = error?.message;
9335
- const text3 = (typeof message === "string" ? message : "").toLowerCase();
9336
- return text3.includes("owned") || text3.includes("ownership") || text3.includes("locked") || text3.includes("in use");
9800
+ const text = (typeof message === "string" ? message : "").toLowerCase();
9801
+ return text.includes("owned") || text.includes("ownership") || text.includes("locked") || text.includes("in use");
9337
9802
  }
9338
9803
  async function runStoreDestruction(effects, opts) {
9339
9804
  const maxRetries = opts?.maxOwnershipRetries ?? 5;
@@ -9385,6 +9850,14 @@ function readDeclarationRefusal(data) {
9385
9850
  const message = refusal.message;
9386
9851
  return typeof message === "string" ? refusal : undefined;
9387
9852
  }
9853
+ function copyBlobTransfers(blobs) {
9854
+ const buffers = new Set;
9855
+ for (const blob of blobs) {
9856
+ if (blob !== undefined)
9857
+ buffers.add(blob.buffer);
9858
+ }
9859
+ return buffers.size > 0 ? [...buffers] : undefined;
9860
+ }
9388
9861
  function buildElectedCoordinator(params) {
9389
9862
  const factory = params.createEngineWorker;
9390
9863
  let pendingChannel;
@@ -9404,9 +9877,9 @@ function buildElectedCoordinator(params) {
9404
9877
  },
9405
9878
  createControlChannel: () => {
9406
9879
  if (pendingChannel !== undefined) {
9407
- const channel2 = pendingChannel;
9880
+ const channel = pendingChannel;
9408
9881
  pendingChannel = undefined;
9409
- return { port1: channel2.port1, port2: channel2.port2 };
9882
+ return { port1: channel.port1, port2: channel.port2 };
9410
9883
  }
9411
9884
  const channel = new MessageChannel;
9412
9885
  liveEngine?.deliverControlPort(channel.port2);
@@ -9581,6 +10054,7 @@ async function attachSyncClient(options) {
9581
10054
  let readyResolved = false;
9582
10055
  const readyGroups = new Set;
9583
10056
  const groupWaiters = new Map;
10057
+ let syncedTables = {};
9584
10058
  const pushToken = async () => {
9585
10059
  const token = options.getToken ? await options.getToken() : null;
9586
10060
  postBridgeMessage(currentDataPort(), codec, "token-push", token);
@@ -9611,8 +10085,8 @@ async function attachSyncClient(options) {
9611
10085
  options.onStatusChange?.(event.status);
9612
10086
  if (event.status.phase === "ready")
9613
10087
  markReady();
9614
- for (const [groupKey, ready2] of Object.entries(event.status.groups ?? {})) {
9615
- if (ready2)
10088
+ for (const [groupKey, ready] of Object.entries(event.status.groups ?? {})) {
10089
+ if (ready)
9616
10090
  markGroupReady(groupKey);
9617
10091
  }
9618
10092
  break;
@@ -9621,6 +10095,10 @@ async function attachSyncClient(options) {
9621
10095
  markGroupReady(event.groupKey);
9622
10096
  break;
9623
10097
  }
10098
+ case "synced": {
10099
+ syncedTables = event.tables;
10100
+ break;
10101
+ }
9624
10102
  case "milestone": {
9625
10103
  if (event.stage === "writeReady")
9626
10104
  settleWriteReady();
@@ -9645,10 +10123,10 @@ async function attachSyncClient(options) {
9645
10123
  options.onReject?.(event.details);
9646
10124
  break;
9647
10125
  case "outbox-status": {
9648
- const status2 = event.status;
9649
- lastOutboxStatus = status2;
9650
- for (const listener2 of outboxStatusListeners)
9651
- listener2(status2);
10126
+ const status = event.status;
10127
+ lastOutboxStatus = status;
10128
+ for (const listener of outboxStatusListeners)
10129
+ listener(status);
9652
10130
  break;
9653
10131
  }
9654
10132
  case "event-lane-report": {
@@ -9657,8 +10135,8 @@ async function attachSyncClient(options) {
9657
10135
  console.warn("pgxsinkit: event-lane report (no `onEventLaneReport` subscriber)", report);
9658
10136
  break;
9659
10137
  }
9660
- for (const listener2 of eventLaneReportListeners)
9661
- listener2(report);
10138
+ for (const listener of eventLaneReportListeners)
10139
+ listener(report);
9662
10140
  break;
9663
10141
  }
9664
10142
  case "schema-change":
@@ -9713,6 +10191,8 @@ async function attachSyncClient(options) {
9713
10191
  settleBootSettled();
9714
10192
  if (ack.bootSettledError)
9715
10193
  failBootSettled(rebuildError(ack.bootSettledError));
10194
+ if (ack.synced)
10195
+ syncedTables = ack.synced;
9716
10196
  const settle = pendingAttachAck;
9717
10197
  pendingAttachAck = null;
9718
10198
  settle?.resolve(ack);
@@ -9776,9 +10256,9 @@ async function attachSyncClient(options) {
9776
10256
  }
9777
10257
  };
9778
10258
  const controlListener = (event) => {
9779
- const placementResult2 = readPlacementResult(event.data);
9780
- if (placementResult2 !== undefined) {
9781
- onPlacementResult(placementResult2);
10259
+ const placementResult = readPlacementResult(event.data);
10260
+ if (placementResult !== undefined) {
10261
+ onPlacementResult(placementResult);
9782
10262
  return;
9783
10263
  }
9784
10264
  const declarationRefusal = readDeclarationRefusal(event.data);
@@ -10076,15 +10556,15 @@ async function attachSyncClient(options) {
10076
10556
  }));
10077
10557
  }, overdueMs));
10078
10558
  };
10079
- const rpc = (op, args) => {
10559
+ const rpc = (op, args, transfer) => {
10080
10560
  if (detached)
10081
10561
  return Promise.reject(detachError());
10082
- const kind = MUTATION_RPC_OPS.has(op) ? "mutation" : "read";
10562
+ const kind = MUTATION_RPC_OPS.has(op) || transfer !== undefined && transfer.length > 0 ? "mutation" : "read";
10083
10563
  return new Promise((resolve, reject) => {
10084
10564
  const dispatch = () => {
10085
10565
  const id = newId("rpc");
10086
10566
  rpcPending.set(id, { resolve, reject, kind });
10087
- postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id);
10567
+ postBridgeMessage(currentDataPort(), codec, "rpc", { op, args }, id, transfer);
10088
10568
  armSilence();
10089
10569
  armOverdue(id);
10090
10570
  };
@@ -10219,8 +10699,8 @@ async function attachSyncClient(options) {
10219
10699
  if (pagehideListener)
10220
10700
  pageWindow?.addEventListener("pagehide", pagehideListener);
10221
10701
  const pageLifecycle = options.electionIo?.pageLifecycle ?? (pageWindow ? {
10222
- onPageHide: (listener2) => pageWindow.addEventListener("pagehide", (event) => listener2(event.persisted)),
10223
- onPageShow: (listener2) => pageWindow.addEventListener("pageshow", () => listener2())
10702
+ onPageHide: (listener) => pageWindow.addEventListener("pagehide", (event) => listener(event.persisted)),
10703
+ onPageShow: (listener) => pageWindow.addEventListener("pageshow", () => listener())
10224
10704
  } : undefined);
10225
10705
  const initialToken = options.getToken ? await options.getToken() : null;
10226
10706
  const memoryOverride = readTestStoreMarker(options) === "memory";
@@ -10339,29 +10819,29 @@ async function attachSyncClient(options) {
10339
10819
  };
10340
10820
  };
10341
10821
  const notSupported = (name) => () => {
10342
- throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local PGlite. ` + `Direct store access (client.pglite) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` + `implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` + `(ensureSynced), and the write API ARE proxied to the worker.`);
10822
+ throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local pgwasm. ` + `Direct store access (client.pgwasm) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` + `implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` + `(ensureSynced), and the write API ARE proxied to the worker.`);
10343
10823
  };
10344
10824
  const noBridgeTransaction = () => {
10345
10825
  throw new Error("[pgxsinkit] client.drizzle.transaction() is not available on a worker-attached client: a read " + "transaction needs a local PGlite the tab does not have. Use one-shot reads (client.query) instead.");
10346
10826
  };
10347
- const guardedQueryArgs = (sql8, params, rowMode, use) => {
10348
- const options2 = rowMode ? { rowMode } : {};
10349
- return use ? [sql8, params, options2, use] : [sql8, params, options2];
10827
+ const guardedQueryArgs = (sql, params, rowMode, use) => {
10828
+ const options = rowMode ? { rowMode } : {};
10829
+ return use ? [sql, params, options, use] : [sql, params, options];
10350
10830
  };
10351
10831
  const makeBridgeExecutor = (use) => ({
10352
- query: (sql8, params, options2) => rpc("guardedQuery", guardedQueryArgs(sql8, params, options2?.rowMode, use)),
10832
+ query: (sql, params, options) => rpc("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
10353
10833
  transaction: noBridgeTransaction
10354
10834
  });
10355
- const { drizzle: drizzle6, views, drizzleFor } = buildRegistryReadHandles(options.registry, makeBridgeExecutor());
10835
+ const { drizzle, views, drizzleFor } = buildRegistryReadHandles(options.registry, makeBridgeExecutor());
10356
10836
  const bridgeReadDrizzle = (use) => drizzleFor(makeBridgeExecutor(use));
10357
10837
  const groupKeyForTable = (table) => {
10358
10838
  const entry = options.registry[table];
10359
10839
  return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
10360
10840
  };
10361
10841
  const client = {
10362
- drizzle: drizzle6,
10842
+ drizzle,
10363
10843
  views,
10364
- pglite: undefined,
10844
+ pgwasm: undefined,
10365
10845
  tables: Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
10366
10846
  tableKey,
10367
10847
  {
@@ -10412,30 +10892,30 @@ async function attachSyncClient(options) {
10412
10892
  await runStoreDestruction(effects);
10413
10893
  },
10414
10894
  dropReadCache: notSupported("client.dropReadCache"),
10415
- appendEvent: (stream2, payload) => rpc("appendEvent", [stream2, payload]),
10895
+ appendEvent: (stream, payload) => rpc("appendEvent", [stream, payload]),
10416
10896
  flushEvents: () => rpc("flushEvents", []),
10417
10897
  outboxStatus: () => rpc("outboxStatus", []),
10418
- onOutboxStatus: (listener2) => {
10419
- outboxStatusListeners.add(listener2);
10898
+ onOutboxStatus: (listener) => {
10899
+ outboxStatusListeners.add(listener);
10420
10900
  if (lastOutboxStatus != null) {
10421
- listener2(lastOutboxStatus);
10901
+ listener(lastOutboxStatus);
10422
10902
  } else {
10423
- client.outboxStatus().then((status2) => {
10424
- lastOutboxStatus ??= status2;
10425
- if (outboxStatusListeners.has(listener2))
10426
- listener2(status2);
10903
+ client.outboxStatus().then((status) => {
10904
+ lastOutboxStatus ??= status;
10905
+ if (outboxStatusListeners.has(listener))
10906
+ listener(status);
10427
10907
  }).catch(() => {
10428
10908
  return;
10429
10909
  });
10430
10910
  }
10431
10911
  return () => {
10432
- outboxStatusListeners.delete(listener2);
10912
+ outboxStatusListeners.delete(listener);
10433
10913
  };
10434
10914
  },
10435
- onEventLaneReport: (listener2) => {
10436
- eventLaneReportListeners.add(listener2);
10915
+ onEventLaneReport: (listener) => {
10916
+ eventLaneReportListeners.add(listener);
10437
10917
  return () => {
10438
- eventLaneReportListeners.delete(listener2);
10918
+ eventLaneReportListeners.delete(listener);
10439
10919
  };
10440
10920
  },
10441
10921
  flush: (table) => rpc("flush", [table]),
@@ -10443,9 +10923,10 @@ async function attachSyncClient(options) {
10443
10923
  retryFailed: (table) => rpc("retryFailed", [table]),
10444
10924
  recoverSending: (table) => rpc("recoverSending", [table]),
10445
10925
  readMutationDetails: (table) => rpc("readMutationDetails", [table]),
10446
- rawQuery: (sql8, params, options2) => rpc("rawQuery", [sql8, params, options2]),
10447
- rawExec: (sql8, options2) => rpc("rawExec", [sql8, options2]),
10448
- guardedRawQuery: (sql8, params, options2, use) => rpc("guardedQuery", guardedQueryArgs(sql8, params, options2?.rowMode, use)),
10926
+ rawQuery: (sql, params, options) => rpc("rawQuery", [sql, params, options], copyBlobTransfers([options?.blob])),
10927
+ rawExec: (sql, options) => rpc("rawExec", [sql, options]),
10928
+ rawTransaction: (statements, options) => rpc("rawTransaction", [statements, options], copyBlobTransfers([...statements.map((statement) => statement.blob), options?.blob])),
10929
+ guardedRawQuery: (sql, params, options, use) => rpc("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
10449
10930
  mutate: {
10450
10931
  create: (table, input) => rpc("create", [table, input]),
10451
10932
  update: (table, entityKey, patch) => rpc("update", [table, entityKey, patch]),
@@ -10458,7 +10939,7 @@ async function attachSyncClient(options) {
10458
10939
  mutations: createMutationsApi({
10459
10940
  registry: options.registry,
10460
10941
  subscribeLiveRows,
10461
- query: (sql8, params) => rpc("rawQuery", [sql8, params])
10942
+ query: (sql, params) => rpc("rawQuery", [sql, params])
10462
10943
  }),
10463
10944
  query: (build) => Promise.resolve(build(client)),
10464
10945
  queryRow: async (build) => {
@@ -10471,9 +10952,7 @@ async function attachSyncClient(options) {
10471
10952
  return rows[0] ?? null;
10472
10953
  },
10473
10954
  ensureSynced: (keys) => rpc("ensureSynced", [keys]),
10474
- isSynced: () => {
10475
- throw new Error("[pgxsinkit] client.isSynced is not available on a worker-attached client: it is a SYNCHRONOUS " + "activation-STARTED peek (in-process: isTableStarted), but the tab caches only per-group CATCH-UP " + "readiness (status.groups / groupReady) \u2014 an activated-but-not-caught-up group reads as not-ready \u2014 " + "so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " + "client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.");
10476
- },
10955
+ isSynced: (key) => syncedTables[key] === true,
10477
10956
  desync: (key) => rpc("desync", [key]),
10478
10957
  discardEphemeral: (key) => rpc("discardEphemeral", [key]),
10479
10958
  prepareQuery: async () => ({ lazyTables: [] }),
@@ -10551,8 +11030,8 @@ async function attachSyncClient(options) {
10551
11030
  postBridgeMessage(currentDataPort(), codec, "set-online", { online });
10552
11031
  }
10553
11032
  };
10554
- Object.defineProperty(client, "pglite", {
10555
- get: notSupported("client.pglite"),
11033
+ Object.defineProperty(client, "pgwasm", {
11034
+ get: notSupported("client.pgwasm"),
10556
11035
  enumerable: false,
10557
11036
  configurable: true
10558
11037
  });
@@ -10612,7 +11091,7 @@ function provisionSyncWorker(options) {
10612
11091
  if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack")
10613
11092
  return;
10614
11093
  const ack = codec.decode(message.data.payload);
10615
- settle(() => ack.ok ? resolve() : reject(new Error(ack.error?.message ?? "worker provision failed")));
11094
+ settle(() => ack.ok ? resolve() : reject(ack.error ? rebuildError(ack.error) : new Error("worker provision failed")));
10616
11095
  };
10617
11096
  ackPort.addEventListener("message", ackListener);
10618
11097
  ackPort.start?.();
@@ -10797,16 +11276,14 @@ var init_attach_sync_client = __esm(() => {
10797
11276
  "discardEphemeral",
10798
11277
  "appendEvent",
10799
11278
  "flushEvents",
10800
- "rawExec"
11279
+ "rawExec",
11280
+ "rawTransaction"
10801
11281
  ]);
10802
11282
  sharedCoordinators = new Map;
10803
11283
  pendingProvisionPipes = new Map;
10804
11284
  });
10805
11285
 
10806
11286
  // packages/client/src/index.ts
10807
- import { PGlite as PGlite2 } from "@electric-sql/pglite";
10808
- import { live } from "@electric-sql/pglite/live";
10809
- import { drizzle as drizzle6 } from "drizzle-orm/pglite";
10810
11287
  import { defineRelations } from "drizzle-orm/relations";
10811
11288
  import {
10812
11289
  fingerprintRegistry as fingerprintRegistry2,
@@ -10814,8 +11291,28 @@ import {
10814
11291
  isClaimsDependentRowFilter,
10815
11292
  resolveStorageDeclaration as resolveStorageDeclaration2
10816
11293
  } from "@pgxsinkit/contracts";
10817
- function isOpfsRepackedPersistent(instance) {
10818
- return instance[OPFS_REPACKED_PERSISTENT] === true;
11294
+ import {
11295
+ createPgwasm as createPgwasm2
11296
+ } from "@pgxsinkit/pgwasm";
11297
+ import { cBuild as cBuild2 } from "@pgxsinkit/pgwasm-c";
11298
+ import { drizzle as drizzle6 } from "@pgxsinkit/pgwasm/drizzle";
11299
+ import { live } from "@pgxsinkit/pgwasm/live";
11300
+ function isOpfsRepackedStore(instance) {
11301
+ const storage = instance.storage;
11302
+ return storage.kind === "vfs" && storage.name === OPFS_REPACKED_STORAGE_NAME;
11303
+ }
11304
+ function holdOwnershipUntilClosed(instance, release) {
11305
+ if (typeof instance.close !== "function")
11306
+ return instance;
11307
+ const close = instance.close.bind(instance);
11308
+ instance.close = async () => {
11309
+ try {
11310
+ await close();
11311
+ } finally {
11312
+ release();
11313
+ }
11314
+ };
11315
+ return instance;
10819
11316
  }
10820
11317
  async function openWithBoundedRetries(open, backoffMs) {
10821
11318
  let lastError;
@@ -10823,6 +11320,8 @@ async function openWithBoundedRetries(open, backoffMs) {
10823
11320
  try {
10824
11321
  return await open();
10825
11322
  } catch (error) {
11323
+ if (isStoreBuildRefusal(error))
11324
+ throw error;
10826
11325
  lastError = error;
10827
11326
  if (attempt < OPFS_OPEN_ATTEMPTS && backoffMs > 0) {
10828
11327
  await new Promise((resolve) => setTimeout(resolve, backoffMs * attempt));
@@ -10831,57 +11330,62 @@ async function openWithBoundedRetries(open, backoffMs) {
10831
11330
  }
10832
11331
  throw lastError;
10833
11332
  }
10834
- async function createClientPGlite(store, options) {
11333
+ async function createPgwasmClient(store, options) {
10835
11334
  const normalised = normaliseStorePathInput(store);
10836
11335
  const storePath = normalised.storePath;
10837
11336
  const backendOverride = options?.backendOverride ?? normalised.backendOverride;
11337
+ if (options?.declaredBuild !== undefined) {
11338
+ const suppliedBuild = (options.build ?? cBuild2).identity;
11339
+ assertStoreBuild(options.declaredBuild, suppliedBuild, options.buildCheckSite ?? "createPgwasmClient");
11340
+ }
10838
11341
  if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
10839
11342
  await resolveDeniedBootAuthority(storePath);
10840
11343
  }
10841
11344
  const dataDir = options?.hasOpfsSyncAccess ? resolveStoreDataDir(storePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true }) : resolveStoreDataDir(storePath, backendOverride);
10842
11345
  const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
10843
- const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => {
10844
- return;
10845
- }) : undefined;
11346
+ const build = options?.build ?? cBuild2;
10846
11347
  const relaxedDurability = (options?.durability ?? "relaxed") !== "strict";
11348
+ await build.prepare?.();
10847
11349
  if (dataDir.startsWith("opfs://")) {
10848
- const opfsPglite = await timeAsync("boot pglite.create", async () => {
10849
- const createOpfsRepacked = options?.pgliteFactories?.createOpfsRepacked ?? (await import("@pgxsinkit/pglite-opfs-repacked")).createOpfsRepackedPGlite;
10850
- syncDebug("boot pglite.create phase", { phase: "module-loaded" });
10851
- const getStoreDirectoryHandle = options?.pgliteFactories?.getStoreDirectoryHandle ?? (() => createOpfsEffects(storePath).getStoreDirectoryHandle());
11350
+ const opfsPglite = await timeAsync("boot pgwasm.create", async () => {
11351
+ const createOpfsStore = options?.opfsFactories?.createOpfsPgwasm ?? (await import("@pgxsinkit/pgwasm/opfs")).createOpfsPgwasm;
11352
+ syncDebug("boot pgwasm.create phase", { phase: "module-loaded" });
11353
+ const getStoreDirectoryHandle = options?.opfsFactories?.getStoreDirectoryHandle ?? (() => createOpfsEffects(storePath).getStoreDirectoryHandle());
10852
11354
  const directory = await getStoreDirectoryHandle();
10853
- syncDebug("boot pglite.create phase", { phase: "directory-ready" });
10854
- return openWithBoundedRetries(() => createOpfsRepacked({
10855
- directory,
10856
- durability: relaxedDurability ? "relaxed" : "strict",
10857
- extentSize: OPFS_STORE_EXTENT_SIZE,
10858
- onPhase: (phase) => syncDebug("boot pglite.create phase", { phase }),
10859
- pglite: {
10860
- ...bootAssets ?? {},
10861
- ...options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {},
10862
- extensions: { live }
10863
- }
10864
- }), options?.pgliteFactories?.retryDelayMs ?? OPFS_OPEN_BACKOFF_MS);
11355
+ syncDebug("boot pgwasm.create phase", { phase: "directory-ready" });
11356
+ const releaseOwnership = await acquireStoreOwnership(storePath);
11357
+ let opened;
11358
+ try {
11359
+ opened = await openWithBoundedRetries(() => createOpfsStore({
11360
+ build,
11361
+ directory,
11362
+ durability: relaxedDurability ? "relaxed" : "strict",
11363
+ extentSize: OPFS_STORE_EXTENT_SIZE,
11364
+ onPhase: (phase) => syncDebug("boot pgwasm.create phase", { phase }),
11365
+ pgwasm: {
11366
+ ...options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {},
11367
+ extensions: { live }
11368
+ }
11369
+ }), options?.opfsFactories?.retryDelayMs ?? OPFS_OPEN_BACKOFF_MS);
11370
+ } catch (error) {
11371
+ releaseOwnership();
11372
+ throw error;
11373
+ }
11374
+ return holdOwnershipUntilClosed(opened, releaseOwnership);
10865
11375
  }, { ...dataDirScheme ? { dataDir: dataDirScheme } : {}, relaxedDurability });
10866
- try {
10867
- Object.defineProperty(opfsPglite, OPFS_REPACKED_PERSISTENT, {
10868
- value: true,
10869
- enumerable: false,
10870
- configurable: true
10871
- });
10872
- } catch {}
10873
11376
  return opfsPglite;
10874
11377
  }
10875
- const pglite = await timeAsync("boot pglite.create", () => {
11378
+ const pglite = await timeAsync("boot pgwasm.create", () => {
10876
11379
  const createOptions = {
10877
- ...bootAssets ?? {},
11380
+ build,
11381
+ dataDir,
10878
11382
  relaxedDurability,
10879
11383
  ...options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {},
10880
11384
  extensions: {
10881
11385
  live
10882
11386
  }
10883
11387
  };
10884
- return PGlite2.create(dataDir, createOptions);
11388
+ return createPgwasm2(createOptions);
10885
11389
  }, { ...dataDirScheme ? { dataDir: dataDirScheme } : {}, relaxedDurability });
10886
11390
  return pglite;
10887
11391
  }
@@ -10898,6 +11402,18 @@ function storageBackendFromDataDir(dataDir) {
10898
11402
  return "memory";
10899
11403
  return;
10900
11404
  }
11405
+ function storageBackendFromStorage(storage) {
11406
+ switch (storage.kind) {
11407
+ case "memory":
11408
+ return "memory";
11409
+ case "idb":
11410
+ return "idbfs";
11411
+ case "file":
11412
+ return "filesystem";
11413
+ case "vfs":
11414
+ return storage.name === OPFS_REPACKED_STORAGE_NAME ? "opfs-repacked" : undefined;
11415
+ }
11416
+ }
10901
11417
  function verdictNeedsCommitmentBarrier(verdict, storageBackend) {
10902
11418
  if (storageBackend !== "opfs-repacked")
10903
11419
  return false;
@@ -10938,11 +11454,10 @@ async function resolveFreshBoot(storePath, hasOpfsSyncAccess, backendOverride, s
10938
11454
  };
10939
11455
  }
10940
11456
  function resolveEngineStrictSync(pglite) {
10941
- const strictSync = pglite.strictSync;
10942
- if (typeof strictSync !== "function") {
10943
- throw new Error("[pgxsinkit] fresh commitment: the opfs store does not expose `strictSync()` \u2014 the commitment barrier " + "requires an OPFS-repacked engine (data-before-authority, invariant 3).");
11457
+ if (!isOpfsRepackedStore(pglite)) {
11458
+ throw new Error("[pgxsinkit] fresh commitment: the store is not on the OPFS-repacked filesystem, so it has no strict " + "sync \u2014 the commitment barrier requires an OPFS-repacked engine (data-before-authority, invariant 3).");
10944
11459
  }
10945
- return () => strictSync.call(pglite);
11460
+ return async () => (await import("@pgxsinkit/pgwasm/opfs")).strictSync(pglite);
10946
11461
  }
10947
11462
  async function runFreshCommitmentBarrier(storePath, strictSyncReturns, seams) {
10948
11463
  const opfs = createOpfsEffects(storePath, seams?.opfs);
@@ -10982,10 +11497,23 @@ async function fallbackVirginCandidateToIdb(storePath, openError, seams) {
10982
11497
  (seams?.log ?? ((message, data) => syncDebug(message, data)))("boot fresh commitment: opfs candidate uncreatable after bounded retries \u2014 session idbfs fallback", { storePath, reason });
10983
11498
  return reason;
10984
11499
  }
11500
+ function toPgliteQueryOptions(options, statementBlob) {
11501
+ const bytes = statementBlob ?? options?.blob;
11502
+ const rest = withoutCopyBlob(options);
11503
+ if (bytes === undefined)
11504
+ return rest;
11505
+ return { ...rest, blob: new Blob([bytes]) };
11506
+ }
11507
+ function withoutCopyBlob(options) {
11508
+ if (options === undefined)
11509
+ return;
11510
+ const { blob: _blobBytes, ...rest } = options;
11511
+ return rest;
11512
+ }
10985
11513
  function replAdapter(client) {
10986
11514
  return {
10987
- query: (sql8, params, options) => client.rawQuery(sql8, params, options),
10988
- exec: (sql8, options) => client.rawExec(sql8, options)
11515
+ query: (sql, params, options) => client.rawQuery(sql, params, options),
11516
+ exec: (sql, options) => client.rawExec(sql, options)
10989
11517
  };
10990
11518
  }
10991
11519
  function resolveReadTransport(options) {
@@ -10993,7 +11521,7 @@ function resolveReadTransport(options) {
10993
11521
  throw new Error("[pgxsinkit] createSyncClient needs `controlPlaneUrl` + `streamBaseUrl` \u2014 the control plane grants " + "the streams this client may read, and the edge serves them.");
10994
11522
  }
10995
11523
  if (options.streamBaseUrl == null || options.streamBaseUrl === "") {
10996
- throw new Error("[pgxsinkit] `controlPlaneUrl` needs `streamBaseUrl` beside it: the control plane grants stream " + "paths and the edge serves them, and they are separate deployments.");
11524
+ throw new Error("[pgxsinkit] `controlPlaneUrl` needs `streamBaseUrl` beside it: the control plane grants stream paths and the edge serves them, and they are separate deployments.");
10997
11525
  }
10998
11526
  return { controlPlaneUrl: options.controlPlaneUrl, streamBaseUrl: options.streamBaseUrl };
10999
11527
  }
@@ -11025,12 +11553,12 @@ async function createSyncClient(options) {
11025
11553
  resolveBootSettled = resolve;
11026
11554
  rejectBootSettled = reject;
11027
11555
  });
11028
- if (options.pgliteInstance && options.precreatedPglite) {
11029
- 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, and registry reconciliation).");
11556
+ if (options.pgwasmInstance && options.precreatedPgwasm) {
11557
+ throw new Error("createSyncClient: pass at most one of `pgwasmInstance` or `precreatedPgwasm` \u2014 they claim different ownership of the post-create boot steps (schema exec, prepare hooks, and registry reconciliation).");
11030
11558
  }
11031
11559
  const restoreBoot = options.restoreFrom != null;
11032
- if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
11033
- 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).");
11560
+ if (restoreBoot && (options.pgwasmInstance || options.precreatedPgwasm)) {
11561
+ throw new Error("createSyncClient: `restoreFrom` is mutually exclusive with `pgwasmInstance` / `precreatedPgwasm` \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).");
11034
11562
  }
11035
11563
  let syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
11036
11564
  const readTransport = resolveReadTransport(options);
@@ -11060,15 +11588,23 @@ async function createSyncClient(options) {
11060
11588
  let commitmentBarrierPending = false;
11061
11589
  const probeGranted = options.hasOpfsSyncAccess === true;
11062
11590
  let storageFallbackReason;
11063
- const resolvedDurability = resolveStorageDeclaration2(getSyncRegistryStorage2(options.registry), options.storage).durability;
11591
+ const resolvedDeclaration = resolveStorageDeclaration2(getSyncRegistryStorage2(options.registry), options.storage);
11592
+ const resolvedDurability = resolvedDeclaration.durability;
11593
+ const declaredBuild = resolvedDeclaration.build;
11594
+ const suppliedBuild = options.build ?? cBuild2;
11064
11595
  const createClientOptions = {
11065
- ...options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {},
11596
+ ...options.build ? { build: options.build } : {},
11597
+ declaredBuild,
11598
+ buildCheckSite: "createSyncClient",
11066
11599
  ...backendOverride ? { backendOverride } : {},
11067
11600
  durability: resolvedDurability,
11068
11601
  ...restoreBoot ? { restoreFrom: options.restoreFrom } : {}
11069
11602
  };
11070
11603
  const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
11071
11604
  let openedStorageBackend;
11605
+ if (!options.pgwasmInstance && !options.precreatedPgwasm) {
11606
+ assertStoreBuild(declaredBuild, suppliedBuild.identity, "createSyncClient");
11607
+ }
11072
11608
  if (restoreBoot) {
11073
11609
  const targetExists = await storeTargetExists(fallbackStorePath, backendOverride, bootHasOpfsSyncAccess ? { hasIndexedDb: true, hasOpfsSyncAccess: true } : undefined);
11074
11610
  if (targetExists) {
@@ -11076,9 +11612,10 @@ async function createSyncClient(options) {
11076
11612
  }
11077
11613
  }
11078
11614
  const timedCreate = async () => {
11615
+ await suppliedBuild.prepare?.();
11079
11616
  const startedAt = performance.now();
11080
11617
  const resolvedDataDir = bootHasOpfsSyncAccess ? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true }) : resolveStoreDataDir(fallbackStorePath, backendOverride);
11081
- const created = await createClientPGlite(fallbackStorePath, {
11618
+ const created = await createPgwasmClient(fallbackStorePath, {
11082
11619
  ...createClientOptions,
11083
11620
  ...bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}
11084
11621
  });
@@ -11093,14 +11630,12 @@ async function createSyncClient(options) {
11093
11630
  const refuseIfNonPersistent = (instance) => {
11094
11631
  if (testStoreMarker !== undefined)
11095
11632
  return;
11096
- if (isOpfsRepackedPersistent(instance))
11097
- return;
11098
- const observedDataDir = instance.dataDir;
11099
- const observed = classifyNonPersistentDataDir(observedDataDir);
11633
+ const observed = classifyNonPersistentStorage(instance.storage);
11100
11634
  if (observed !== null)
11101
11635
  throw new NonPersistentStoreError(observed);
11102
11636
  };
11103
11637
  const openOwnedStore = async () => {
11638
+ assertStoreBuild(declaredBuild, suppliedBuild.identity, "createSyncClient");
11104
11639
  if (!bootHasOpfsSyncAccess && backendOverride !== "memory") {
11105
11640
  await resolveDeniedBootAuthority(fallbackStorePath);
11106
11641
  }
@@ -11126,13 +11661,15 @@ async function createSyncClient(options) {
11126
11661
  };
11127
11662
  let pglite;
11128
11663
  let adoptedPrecreated = false;
11129
- if (options.pgliteInstance) {
11130
- refuseIfNonPersistent(options.pgliteInstance);
11131
- pglite = options.pgliteInstance;
11132
- } else if (options.precreatedPglite) {
11133
- const outcome = await options.precreatedPglite.then((instance) => ({ ok: true, instance }), (error) => ({ ok: false, error }));
11664
+ if (options.pgwasmInstance) {
11665
+ refuseIfNonPersistent(options.pgwasmInstance);
11666
+ assertStoreBuild(declaredBuild, options.pgwasmInstance.build, "pgwasmInstance");
11667
+ pglite = options.pgwasmInstance;
11668
+ } else if (options.precreatedPgwasm) {
11669
+ const outcome = await options.precreatedPgwasm.then((instance) => ({ ok: true, instance }), (error) => ({ ok: false, error }));
11134
11670
  if (outcome.ok) {
11135
11671
  refuseIfNonPersistent(outcome.instance);
11672
+ assertStoreBuild(declaredBuild, outcome.instance.build, "precreatedPgwasm");
11136
11673
  pglite = outcome.instance;
11137
11674
  adoptedPrecreated = true;
11138
11675
  } else {
@@ -11150,19 +11687,19 @@ async function createSyncClient(options) {
11150
11687
  if (options.storageFallbackReason != null && backendOverride !== "memory" && !bootHasOpfsSyncAccess) {
11151
11688
  bootReportBuilder.setStorageFallbackReason(options.storageFallbackReason);
11152
11689
  }
11153
- if (options.pgliteInstance != null || adoptedPrecreated) {
11154
- const byoBackend = storageBackendFromDataDir(pglite.dataDir);
11690
+ if (options.pgwasmInstance != null || adoptedPrecreated) {
11691
+ const byoBackend = storageBackendFromStorage(pglite.storage);
11155
11692
  if (byoBackend) {
11156
11693
  openedStorageBackend = byoBackend;
11157
11694
  bootReportBuilder.setStorageBackend(byoBackend);
11158
11695
  }
11159
11696
  }
11160
- const adoptedCommitmentGate = (options.pgliteInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedPersistent(pglite) ? resolveAdoptedCommitmentBarrier(fallbackStorePath) : null;
11697
+ const adoptedCommitmentGate = (options.pgwasmInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedStore(pglite) ? resolveAdoptedCommitmentBarrier(fallbackStorePath) : null;
11161
11698
  if (adoptedCommitmentGate)
11162
11699
  adoptedCommitmentGate.catch(() => {
11163
11700
  return;
11164
11701
  });
11165
- const ownsStoreLifecycle = !options.pgliteInstance;
11702
+ const ownsStoreLifecycle = !options.pgwasmInstance;
11166
11703
  if (adoptedPrecreated && options.provisionStamp) {
11167
11704
  const stamp = await options.provisionStamp.catch(() => null);
11168
11705
  if (stamp) {
@@ -11274,7 +11811,7 @@ async function createSyncClient(options) {
11274
11811
  writeLazyGroupActivation(pglite, options.registry, groupKey);
11275
11812
  }
11276
11813
  });
11277
- if (!options.pgliteInstance) {
11814
+ if (!options.pgwasmInstance) {
11278
11815
  if (options.prepareLocalDbBeforeSchema) {
11279
11816
  const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
11280
11817
  await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
@@ -11310,7 +11847,7 @@ async function createSyncClient(options) {
11310
11847
  db: pglite,
11311
11848
  registry: options.registry,
11312
11849
  batchWriteUrl: options.batchWriteUrl,
11313
- ownsMetaTable: !options.pgliteInstance,
11850
+ ownsMetaTable: !options.pgwasmInstance,
11314
11851
  onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
11315
11852
  ...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
11316
11853
  ...writePathHeaders ? { requestHeaders: writePathHeaders } : {},
@@ -11320,7 +11857,7 @@ async function createSyncClient(options) {
11320
11857
  ...options.onReject ? { onReject: options.onReject } : {}
11321
11858
  });
11322
11859
  const eventLaneUrl = options.batchEventUrl ?? deriveBatchEventUrl(options.batchWriteUrl);
11323
- const eventLane = eventLaneUrl != null && !options.pgliteInstance ? createEventLaneRuntime({
11860
+ const eventLane = eventLaneUrl != null && !options.pgwasmInstance ? createEventLaneRuntime({
11324
11861
  db: pglite,
11325
11862
  registry: options.registry,
11326
11863
  batchEventUrl: eventLaneUrl,
@@ -11331,16 +11868,16 @@ async function createSyncClient(options) {
11331
11868
  const requireEventLane = () => {
11332
11869
  if (eventLane)
11333
11870
  return eventLane;
11334
- throw new Error("pgxsinkit: the Event lane is not available on this client \u2014 either `batchWriteUrl` is not the canonical " + '"\u2026/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' + "`pgliteInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).");
11871
+ throw new Error("pgxsinkit: the Event lane is not available on this client \u2014 either `batchWriteUrl` is not the canonical " + '"\u2026/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' + "`pgwasmInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).");
11335
11872
  };
11336
11873
  let pendingActivations = new Set;
11337
11874
  let versionEvent = null;
11338
11875
  const runBootRecoveryStage = async () => {
11339
- const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgliteInstance, restore: restoreBoot }));
11876
+ const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () => mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgwasmInstance, restore: restoreBoot }));
11340
11877
  bootReportBuilder.setJournalRecovery(recoveryOutcome);
11341
11878
  };
11342
11879
  const runReconcileStage = async () => {
11343
- if (options.pgliteInstance)
11880
+ if (options.pgwasmInstance)
11344
11881
  return;
11345
11882
  versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () => reconcileLocalStoreVersion({
11346
11883
  db: pglite,
@@ -11529,7 +12066,7 @@ async function createSyncClient(options) {
11529
12066
  if (anonymousActivationWarned.has(groupKey))
11530
12067
  return;
11531
12068
  anonymousActivationWarned.add(groupKey);
11532
- console.warn(`pgxsinkit: activating the lazy group [${info.memberKeys.join(", ")}] with no auth token \u2014 its ` + `row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first ` + `query on auth (e.g. the React hooks' \`ready\` option) so the group activates with real claims.`);
12069
+ console.warn(`pgxsinkit: activating the lazy group [${info.memberKeys.join(", ")}] with no auth token \u2014 its ` + `row filter denies unauthenticated callers, so this opens an empty subscription. Gate the first query on auth (e.g. the React hooks' \`ready\` option) so the group activates with real claims.`);
11533
12070
  syncDebug("anonymous activation of a claims-dependent lazy group", {
11534
12071
  groupKey,
11535
12072
  tables: info.memberKeys
@@ -11707,31 +12244,31 @@ async function createSyncClient(options) {
11707
12244
  }
11708
12245
  return await mutationRuntime.flushUnit(unit.id);
11709
12246
  };
11710
- const prepareQuery = async ({ sql: sql8, use }) => {
12247
+ const prepareQuery = async ({ sql, use }) => {
11711
12248
  const toActivate = new Set(use ?? []);
11712
- for (const key of findReferencedLazyKeysInSql(sql8, lazyGuardIndex))
12249
+ for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex))
11713
12250
  toActivate.add(key);
11714
12251
  const lazyTables = [...toActivate];
11715
12252
  await ensureSynced(lazyTables);
11716
12253
  assertLazyRefsActivated({
11717
- sql: sql8,
12254
+ sql,
11718
12255
  index: lazyGuardIndex,
11719
12256
  isActive: (key) => isSynced(key)
11720
12257
  });
11721
12258
  return { lazyTables };
11722
12259
  };
11723
- const gateAndGuardRead = async (sql8, use) => {
12260
+ const gateAndGuardRead = async (sql, use) => {
11724
12261
  await localReadReady;
11725
- await prepareQuery({ sql: sql8, ...use ? { use } : {} });
12262
+ await prepareQuery({ sql, ...use ? { use } : {} });
11726
12263
  };
11727
12264
  const runGuardedQuery = async (build, use) => {
11728
12265
  const builder = build(client);
11729
12266
  await gateAndGuardRead(builder.toSQL().sql, use);
11730
12267
  return builder;
11731
12268
  };
11732
- const guardedRawQuery = async (sql8, params, options2, use) => {
11733
- await gateAndGuardRead(sql8, use);
11734
- return pglite.query(sql8, params, options2);
12269
+ const guardedRawQuery = async (sql, params, options, use) => {
12270
+ await gateAndGuardRead(sql, use);
12271
+ return pglite.query(sql, params, options);
11735
12272
  };
11736
12273
  const liveManager = createLiveQueryManager({
11737
12274
  live: pglite.live,
@@ -11739,7 +12276,7 @@ async function createSyncClient(options) {
11739
12276
  });
11740
12277
  const client = {
11741
12278
  drizzle: drizzleDb,
11742
- pglite,
12279
+ pgwasm: pglite,
11743
12280
  views: buildViews(options.registry),
11744
12281
  tables: Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
11745
12282
  tableKey,
@@ -11782,7 +12319,7 @@ async function createSyncClient(options) {
11782
12319
  throw new Error(`destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`);
11783
12320
  }
11784
12321
  if (eventLane && !(await eventLane.outboxStatus()).empty) {
11785
- throw new Error("destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " + "Flush them first (`flushEvents()`) or call destroy({ force: true }).");
12322
+ throw new Error("destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. Flush them first (`flushEvents()`) or call destroy({ force: true }).");
11786
12323
  }
11787
12324
  }
11788
12325
  await convergenceDriver?.stop();
@@ -11794,11 +12331,11 @@ async function createSyncClient(options) {
11794
12331
  sync?.unsubscribe();
11795
12332
  await liveManager.dispose();
11796
12333
  await pglite.close();
11797
- const { readStoreMetaRecord: readStoreMetaRecord2 } = await Promise.resolve().then(() => (init_store_meta(), exports_store_meta));
11798
- const metaResult = await readStoreMetaRecord2(fallbackStorePath);
12334
+ await Promise.resolve().then(() => init_store_meta());
12335
+ const metaResult = await readStoreMetaRecord(fallbackStorePath);
11799
12336
  if (typeof metaResult === "object" && metaResult !== null || ownsStoreLifecycle && openedStorageBackend === "idbfs") {
11800
- const { runStoreDestruction: runStoreDestruction2, createStoreDestructionEffects: createStoreDestructionEffects2 } = await Promise.resolve().then(() => (init_attach_sync_client(), exports_attach_sync_client));
11801
- await runStoreDestruction2(createStoreDestructionEffects2(fallbackStorePath));
12337
+ await Promise.resolve().then(() => init_attach_sync_client());
12338
+ await runStoreDestruction(createStoreDestructionEffects(fallbackStorePath));
11802
12339
  }
11803
12340
  }),
11804
12341
  dropReadCache: async () => {
@@ -11810,10 +12347,10 @@ async function createSyncClient(options) {
11810
12347
  await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
11811
12348
  });
11812
12349
  },
11813
- appendEvent: async (stream2, payload) => {
12350
+ appendEvent: async (stream, payload) => {
11814
12351
  const lane = requireEventLane();
11815
12352
  await localReadReady;
11816
- const result = await lane.appendEvent(stream2, payload);
12353
+ const result = await lane.appendEvent(stream, payload);
11817
12354
  eventFlushDriver?.requestPass();
11818
12355
  return result;
11819
12356
  },
@@ -11860,8 +12397,20 @@ async function createSyncClient(options) {
11860
12397
  ...eventLane ? { outbox: await eventLane.outboxStatus() } : {}
11861
12398
  }),
11862
12399
  mutations: undefined,
11863
- rawQuery: (sql8, params, options2) => pglite.query(sql8, params, options2),
11864
- rawExec: (sql8, options2) => pglite.exec(sql8, options2),
12400
+ rawQuery: (sql, params, options) => pglite.query(sql, params, toPgliteQueryOptions(options)),
12401
+ rawExec: (sql, options) => pglite.exec(sql, withoutCopyBlob(options)),
12402
+ rawTransaction: async (statements, options) => {
12403
+ if (statements.length === 0) {
12404
+ return [];
12405
+ }
12406
+ return pglite.transaction(async (tx) => {
12407
+ const results = [];
12408
+ for (const statement of statements) {
12409
+ results.push(await tx.query(statement.sql, statement.params, toPgliteQueryOptions(options, statement.blob)));
12410
+ }
12411
+ return results;
12412
+ });
12413
+ },
11865
12414
  guardedRawQuery,
11866
12415
  query: (build) => runGuardedQuery(build),
11867
12416
  queryRow: async (build) => {
@@ -11881,9 +12430,9 @@ async function createSyncClient(options) {
11881
12430
  transaction,
11882
12431
  groupReady: groupReadyForTable,
11883
12432
  hydratingTablesFor,
11884
- subscribeLiveRows: async ({ sql: sql8, params, fields, use, keepAliveMs }, onRows) => {
12433
+ subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
11885
12434
  await localReadReady;
11886
- const materialSql = wrapLiveQueryForMaterialization(sql8, fields);
12435
+ const materialSql = wrapLiveQueryForMaterialization(sql, fields);
11887
12436
  const materializer = new LiveRowsMaterializer(undefined);
11888
12437
  const subscription = await liveManager.subscribe({ materialSql, params }, {
11889
12438
  deliverInitial: (rows) => {
@@ -11896,10 +12445,10 @@ async function createSyncClient(options) {
11896
12445
  const initialRows = materializer.current();
11897
12446
  let unsubscribed = false;
11898
12447
  const lazySet = new Set(use ?? []);
11899
- for (const key of findReferencedLazyKeysInSql(sql8, lazyGuardIndex))
12448
+ for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex))
11900
12449
  lazySet.add(key);
11901
12450
  const lazyTables = [...lazySet];
11902
- const hydratingTables = hydratingTablesFor({ sql: sql8, ...use ? { use } : {} });
12451
+ const hydratingTables = hydratingTablesFor({ sql, ...use ? { use } : {} });
11903
12452
  const hydrated = hydratingTables.length > 0 ? Promise.all(hydratingTables.map((table) => groupReadyForTable(table))).then(async () => {
11904
12453
  if (!unsubscribed)
11905
12454
  await subscription.refresh();
@@ -11937,7 +12486,7 @@ async function createSyncClient(options) {
11937
12486
  exportData: async (exportOptions) => {
11938
12487
  await ready;
11939
12488
  return lifecycleSlot.run("exportData", () => performDataExport({
11940
- pglite,
12489
+ pgwasm: pglite,
11941
12490
  readMutationStats: () => mutationRuntime.readMutationStats(),
11942
12491
  flush: () => mutationRuntime.flush(),
11943
12492
  syncedTableNames: collectDataExportSyncedTableNames(options.registry),
@@ -11950,7 +12499,7 @@ async function createSyncClient(options) {
11950
12499
  client.mutations = createMutationsApi({
11951
12500
  registry: options.registry,
11952
12501
  subscribeLiveRows: client.subscribeLiveRows,
11953
- query: (sql8, params) => pglite.query(sql8, params)
12502
+ query: (sql, params) => pglite.query(sql, params)
11954
12503
  });
11955
12504
  if (adoptedCommitmentGate)
11956
12505
  commitmentBarrierPending = await adoptedCommitmentGate;
@@ -12008,8 +12557,7 @@ async function resetSubscriptionsIfRequested(pglite, keys) {
12008
12557
  }
12009
12558
  function createDrizzleDatabase(client, schema) {
12010
12559
  const relations = defineRelations(schema);
12011
- const createDatabase = drizzle6;
12012
- return createDatabase({ client, relations });
12560
+ return drizzle6(client, { relations });
12013
12561
  }
12014
12562
  function buildSchema(registry) {
12015
12563
  return Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, entry.table]));
@@ -12027,10 +12575,9 @@ function buildRegistryReadHandles(registry, client = {}) {
12027
12575
  }
12028
12576
  function buildRegistryDrizzleFactory(registry) {
12029
12577
  const relations = defineRelations(buildSchema(registry));
12030
- const createDatabase = drizzle6;
12031
- return (client) => createDatabase({ client, relations });
12578
+ return (client) => drizzle6(client, { relations });
12032
12579
  }
12033
- var WriteNotReadyError, ClientDisposedError, OPFS_OPEN_ATTEMPTS = 10, OPFS_OPEN_BACKOFF_MS = 100, OPFS_STORE_EXTENT_SIZE = 65536, READ_SILENCE_MS = 45000, READ_STREAM_SILENT = "read stream silent: no server response inside the silence window while reporting ready", CONTROL_PLANE_UNREACHABLE = "control plane unreachable: subscribe is failing and retrying", STREAM_LOST = "read stream lost; re-subscribing", OPFS_REPACKED_PERSISTENT;
12580
+ var WriteNotReadyError, ClientDisposedError, OPFS_OPEN_ATTEMPTS = 10, OPFS_OPEN_BACKOFF_MS = 100, OPFS_STORE_EXTENT_SIZE = 65536, READ_SILENCE_MS = 45000, READ_STREAM_SILENT = "read stream silent: no server response inside the silence window while reporting ready", CONTROL_PLANE_UNREACHABLE = "control plane unreachable: subscribe is failing and retrying", STREAM_LOST = "read stream lost; re-subscribing", OPFS_REPACKED_STORAGE_NAME = "opfs-repacked";
12034
12581
  var init_src = __esm(() => {
12035
12582
  init_boot_report();
12036
12583
  init_group_sync();
@@ -12047,7 +12594,9 @@ var init_src = __esm(() => {
12047
12594
  init_opfs_effects();
12048
12595
  init_schema();
12049
12596
  init_store_boot();
12597
+ init_store_build();
12050
12598
  init_store_meta();
12599
+ init_store_ownership_lock();
12051
12600
  init_store_path();
12052
12601
  init_metadata_tables();
12053
12602
  init_subscription_state();
@@ -12061,6 +12610,7 @@ var init_src = __esm(() => {
12061
12610
  init_attach_sync_client();
12062
12611
  init_engine_control();
12063
12612
  init_opfs_effects();
12613
+ init_store_ownership_lock();
12064
12614
  init_store_boot();
12065
12615
  init_store_path();
12066
12616
  init_convergence();
@@ -12070,6 +12620,7 @@ var init_src = __esm(() => {
12070
12620
  init_protocol();
12071
12621
  init_lazy_guard();
12072
12622
  init_schema();
12623
+ init_copy();
12073
12624
  init_stream_source();
12074
12625
  init_shape_group();
12075
12626
  init_subscription_client();
@@ -12089,7 +12640,6 @@ var init_src = __esm(() => {
12089
12640
  this.name = "ClientDisposedError";
12090
12641
  }
12091
12642
  };
12092
- OPFS_REPACKED_PERSISTENT = Symbol.for("pgxsinkit.opfsRepackedPersistent");
12093
12643
  });
12094
12644
  init_src();
12095
12645
 
@@ -12123,13 +12673,16 @@ export {
12123
12673
  ProvisionExpiredError,
12124
12674
  ProvisionStalledError,
12125
12675
  RestoreTargetExistsError,
12676
+ STORE_OWNERSHIP_WAIT_MS,
12126
12677
  STREAM_START,
12127
12678
  StoreDestroyRefusedError,
12679
+ StoreOwnershipWaitError,
12128
12680
  StreamInbox,
12129
12681
  UnknownEventStreamError,
12130
12682
  WriteNotReadyError,
12131
12683
  assertLazyRefsActivated,
12132
12684
  attachSyncClient,
12685
+ buildCopyFromBlobStatement,
12133
12686
  buildLazyGuardIndex,
12134
12687
  buildRegistryReadHandles,
12135
12688
  classifyEventBatchFailure,
@@ -12138,7 +12691,6 @@ export {
12138
12691
  computeLiveDiff,
12139
12692
  createBarrierReader,
12140
12693
  createBrowserConvergenceTrigger,
12141
- createClientPGlite,
12142
12694
  createConvergenceDriver,
12143
12695
  createEventFlushDriver,
12144
12696
  createEventLaneRuntime,
@@ -12146,7 +12698,9 @@ export {
12146
12698
  createLifecycleSlot,
12147
12699
  createMutationsApi,
12148
12700
  createOpfsEffects,
12701
+ createPgwasmClient,
12149
12702
  createShapeGroup,
12703
+ createStoreEngineResolver,
12150
12704
  createSyncClient,
12151
12705
  createTokenRecovery,
12152
12706
  createWorkerTokenCache,
@@ -12159,6 +12713,7 @@ export {
12159
12713
  fallbackVirginCandidateToIdb,
12160
12714
  findReferencedLazyKeysInSql,
12161
12715
  findReferencedSyncedKeysInSql,
12716
+ generateCopyData,
12162
12717
  generateLocalSchemaSql,
12163
12718
  getAllMutationsView,
12164
12719
  getJournalTable,
@@ -12170,6 +12725,7 @@ export {
12170
12725
  getSyncedLocalTable,
12171
12726
  identityCodec,
12172
12727
  isBridgeEnvelope,
12728
+ loadStoreEngineFactory,
12173
12729
  openSubscriptionSession,
12174
12730
  parseRetryAfterMs,
12175
12731
  performDataExport,
@@ -12192,6 +12748,7 @@ export {
12192
12748
  runFreshCommitmentBarrier,
12193
12749
  runThrowawayCloneDump,
12194
12750
  seedLiveDiffState,
12751
+ serializeCopyValue,
12195
12752
  setSyncDebugSink,
12196
12753
  startCircuitsSync,
12197
12754
  storeIndexedDbDatabaseName,
@@ -12203,4 +12760,4 @@ export {
12203
12760
  wrapLiveQueryForMaterialization
12204
12761
  };
12205
12762
 
12206
- //# debugId=01F9B47528B300A164756E2164756E21
12763
+ //# debugId=5E51EF959498DEE164756E2164756E21