@pgxsinkit/client 0.1.53 → 0.2.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 (85) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/export-store.d.ts +1 -1
  9. package/dist/export-store.d.ts.map +1 -1
  10. package/dist/index.d.ts +270 -52
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +4492 -1511
  13. package/dist/index.js.map +34 -24
  14. package/dist/live-rows-sql.d.ts +1 -1
  15. package/dist/local-store.d.ts +16 -31
  16. package/dist/local-store.d.ts.map +1 -1
  17. package/dist/local-tables.d.ts +4 -4
  18. package/dist/mutation.d.ts +12 -15
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/opfs-effects.d.ts +51 -0
  21. package/dist/opfs-effects.d.ts.map +1 -0
  22. package/dist/placement-probe.d.ts +75 -0
  23. package/dist/placement-probe.d.ts.map +1 -0
  24. package/dist/schema.d.ts +11 -16
  25. package/dist/schema.d.ts.map +1 -1
  26. package/dist/store-boot.d.ts +77 -0
  27. package/dist/store-boot.d.ts.map +1 -0
  28. package/dist/store-lifecycle.d.ts +153 -0
  29. package/dist/store-lifecycle.d.ts.map +1 -0
  30. package/dist/store-meta.d.ts +190 -0
  31. package/dist/store-meta.d.ts.map +1 -0
  32. package/dist/store-path.d.ts +77 -7
  33. package/dist/store-path.d.ts.map +1 -1
  34. package/dist/sync/apply.d.ts.map +1 -1
  35. package/dist/sync/shape-inbox.d.ts +1 -1
  36. package/dist/sync/types.d.ts +3 -3
  37. package/dist/testing.js.map +3 -3
  38. package/dist/worker/attach-sync-client.d.ts +235 -12
  39. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  40. package/dist/worker/define-sync-worker.d.ts +138 -22
  41. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  42. package/dist/worker/election-coordinator.d.ts +95 -0
  43. package/dist/worker/election-coordinator.d.ts.map +1 -0
  44. package/dist/worker/engine-control.d.ts +265 -0
  45. package/dist/worker/engine-control.d.ts.map +1 -0
  46. package/dist/worker/engine-router.d.ts +75 -0
  47. package/dist/worker/engine-router.d.ts.map +1 -0
  48. package/dist/worker/live-query-manager.d.ts.map +1 -1
  49. package/dist/worker/protocol.d.ts +15 -10
  50. package/dist/worker/protocol.d.ts.map +1 -1
  51. package/dist/worker/sw-placement.d.ts +37 -0
  52. package/dist/worker/sw-placement.d.ts.map +1 -0
  53. package/package.json +4 -3
  54. package/skills/core/SKILL.md +15 -12
  55. package/skills/operating/SKILL.md +103 -46
  56. package/src/adoption.ts +275 -0
  57. package/src/boot-report.ts +70 -17
  58. package/src/convergence.ts +2 -1
  59. package/src/export-store.ts +1 -1
  60. package/src/index.ts +1109 -115
  61. package/src/live-rows-sql.ts +1 -1
  62. package/src/local-store.ts +18 -40
  63. package/src/local-tables.ts +2 -2
  64. package/src/mutation.ts +67 -49
  65. package/src/mutations-api.ts +3 -3
  66. package/src/opfs-effects.ts +160 -0
  67. package/src/placement-probe.ts +168 -0
  68. package/src/schema.ts +17 -22
  69. package/src/store-boot.ts +343 -0
  70. package/src/store-lifecycle.ts +227 -0
  71. package/src/store-meta.ts +459 -0
  72. package/src/store-path.ts +197 -22
  73. package/src/sync/apply.ts +63 -63
  74. package/src/sync/index.ts +2 -2
  75. package/src/sync/shape-inbox.ts +1 -1
  76. package/src/sync/types.ts +3 -3
  77. package/src/testing.ts +2 -2
  78. package/src/worker/attach-sync-client.ts +1556 -97
  79. package/src/worker/define-sync-worker.ts +723 -73
  80. package/src/worker/election-coordinator.ts +462 -0
  81. package/src/worker/engine-control.ts +379 -0
  82. package/src/worker/engine-router.ts +355 -0
  83. package/src/worker/live-query-manager.ts +4 -1
  84. package/src/worker/protocol.ts +13 -10
  85. package/src/worker/sw-placement.ts +64 -0
package/src/store-path.ts CHANGED
@@ -1,17 +1,24 @@
1
1
  // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker
2
2
  // attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a
3
- // PGlite storage URL. The storage backend is DERIVED from the environment here, never chosen by the
4
- // consumer: IndexedDB in a browser (or a worker), the filesystem on Bun/Node. A memory-backed store is
3
+ // PGlite storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by
4
+ // the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the
5
+ // filesystem on Bun/Node. A memory-backed store is
5
6
  // not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic
6
7
  // Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing
7
8
  // acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal
8
9
  // {@link TEST_STORE_BACKEND} symbol.
9
10
  //
10
- // This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` URLs (the
11
- // export machinery's throwaway clone, a later slice, is the one other internal `memory://` site). A
12
- // resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something
13
- // a consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old
14
- // contract loudly at the boundary rather than silently re-interpreting it.
11
+ // This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` / `opfs://`
12
+ // URLs (the export machinery's throwaway clone is the one other internal `memory://` site). A
13
+ // resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something a
14
+ // consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old contract
15
+ // loudly at the boundary rather than silently re-interpreting it.
16
+ //
17
+ // Under ADR-0049 (capability-driven engine placement) it also owns the browser-side STORE IDENTITY encoding
18
+ // and the disjoint OPFS namespaces the placement probe, the commitment marker, and the store meta record all
19
+ // key on. `storeIdentityComponent` is the one injective encoding for every browser-side identity surface
20
+ // (OPFS namespace entries, leader lock, meta record key, communication-centre SharedWorker name; D11), and the
21
+ // `pgxsinkit/stores|commitments|probe` namespace builders are the one place those names live (D6).
15
22
 
16
23
  /**
17
24
  * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or
@@ -126,48 +133,171 @@ export function normaliseStorePathInput(input: StorePathInput): { storePath: str
126
133
  */
127
134
  export interface StoreEnv {
128
135
  hasIndexedDb: boolean;
136
+ /**
137
+ * ADR-0049 (D1): the PLACEMENT PROBE's injected result — whether a REAL `createSyncAccessHandle` open
138
+ * succeeded in the executing scope (the bench phase-0 mechanism, performed by the async boot path — never
139
+ * method-presence sniffing). Optional so every existing `StoreEnv` construction stays valid; `undefined`
140
+ * means "no OPFS sync access" (false). {@link detectStoreEnv} ALWAYS reports `false` for it: there is no
141
+ * synchronous ambient detection for handle grants, and method-presence sniffing is forbidden — only the
142
+ * boot path's real probe open can flip it true.
143
+ */
144
+ hasOpfsSyncAccess?: boolean;
129
145
  }
130
146
 
131
147
  /** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */
132
148
  function detectStoreEnv(): StoreEnv {
149
+ // `hasOpfsSyncAccess` is deliberately absent (false): the placement probe (an async handle open) is the
150
+ // only honest source, and this synchronous ambient detector must never guess it (ADR-0049 D1).
133
151
  return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== "undefined" };
134
152
  }
135
153
 
154
+ /**
155
+ * The shared plain-`storePath` boundary guard (ADR-0036 decision 1). A storePath is a PLAIN name, never a
156
+ * storage URL: empty/whitespace-only or scheme-bearing (`://`) values fail loudly with
157
+ * {@link InvalidStorePathError}. Factored so {@link resolveStoreDataDir} and {@link storeIdentityComponent}
158
+ * share ONE message set (no drift between the two identity-surface entry points).
159
+ */
160
+ function assertPlainStorePath(storePath: string): void {
161
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
162
+ throw new InvalidStorePathError(
163
+ 'invalid storePath: expected a non-empty plain store name (e.g. "my-app-store"); received an empty or whitespace-only value (ADR-0036).',
164
+ );
165
+ }
166
+ if (storePath.includes("://")) {
167
+ throw new InvalidStorePathError(
168
+ `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +
169
+ 'Pass just the name (e.g. "my-app-store") — the storage backend (capability-selected opfs-repacked ' +
170
+ "with IndexedDB fallback in a browser, or the filesystem on Bun/Node) is derived for you; drop the " +
171
+ "scheme prefix (ADR-0036/ADR-0049).",
172
+ );
173
+ }
174
+ }
175
+
136
176
  /**
137
177
  * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point
138
- * (ADR-0036 decision 2). Browser/worker (`indexedDB` present) → `idb://<storePath>`; Bun/Node → `file://<storePath>`
139
- * (relative paths resolve against the working directory, exactly as PGlite's filesystem backend does — pass
140
- * an absolute path if that matters). The `backendOverride` is internal-only: `"memory"` selects a
141
- * scheme-selected `memory://<storePath>` store for the sanctioned test/ephemeral lanes.
178
+ * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves
179
+ * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;
180
+ * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`
181
+ * is internal-only: `"memory"` selects a scheme-selected `memory://<storePath>` test/ephemeral store.
142
182
  *
143
183
  * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath
144
- * contract fails loudly at the boundary, never silently re-interpreted (no-legacy rule). The returned URL is
184
+ * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is
145
185
  * internal plumbing; do not surface it to consumers as something to imitate.
146
186
  *
147
187
  * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
148
188
  * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
149
189
  * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
150
190
  * exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
191
+ *
192
+ * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in
193
+ * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:
194
+ * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →
195
+ * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — PGlite does NOT accept it as a `dataDir`;
196
+ * {@link createClientPGlite} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
197
+ * builders below. Like every URL resolved here, it never leaks to consumers.
151
198
  */
152
199
  export function resolveStoreDataDir(
153
200
  storePath: string,
154
201
  backendOverride?: "memory",
155
202
  env: StoreEnv = detectStoreEnv(),
156
203
  ): string {
157
- if (typeof storePath !== "string" || storePath.trim().length === 0) {
204
+ assertPlainStorePath(storePath);
205
+ if (backendOverride === "memory") return `memory://${storePath}`;
206
+ if (env.hasOpfsSyncAccess) return `opfs://${storePath}`;
207
+ return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;
208
+ }
209
+
210
+ /**
211
+ * The per-component ENCODED length cap for {@link storeIdentityComponent}. A filesystem-safe bound for a
212
+ * single OPFS name component; the fixed container/namespace names (`pgxsinkit`, `stores`, `commitments`,
213
+ * `probe`) are SEPARATE path components and add nothing to this budget. Encoding is what is capped, not the
214
+ * raw input — a short multi-byte name can expand past the bound.
215
+ */
216
+ const STORE_IDENTITY_ENCODED_CAP = 128;
217
+
218
+ /**
219
+ * The ONE injective encoding for every browser-side identity surface (ADR-0049 D11, invariant 10): OPFS
220
+ * namespace entries ({@link opfsStoreDirectoryPath} / {@link opfsCommitmentSentinelPath}), the leader lock
221
+ * name, the store meta record key, and the communication-centre SharedWorker name all derive from this single
222
+ * canonical component. Percent-encoding (`encodeURIComponent`) — injective, never lossy sanitising, so two
223
+ * distinct store paths can never collapse to one identity (e.g. `"foo/bar"` → `foo%2Fbar` vs the literal
224
+ * `"foo%2Fbar"` → `foo%252Fbar`).
225
+ *
226
+ * Domain (invariant 10):
227
+ * - Same boundary guards as {@link resolveStoreDataDir}: empty/whitespace-only or scheme-bearing (`://`)
228
+ * paths throw {@link InvalidStorePathError} (shared {@link assertPlainStorePath}).
229
+ * - A lone UTF-16 surrogate makes `encodeURIComponent` raise a `URIError`; that is wrapped into
230
+ * {@link InvalidStorePathError} so callers branch one error type at the boundary.
231
+ * - `.` and `..` pass through `encodeURIComponent` UNCHANGED, but the File System Standard reserves them as
232
+ * invalid file names, so both are rejected.
233
+ * - The ENCODED length is capped at {@link STORE_IDENTITY_ENCODED_CAP} (a per-component filesystem-safe
234
+ * bound); overflow is rejected.
235
+ */
236
+ export function storeIdentityComponent(storePath: string): string {
237
+ assertPlainStorePath(storePath);
238
+ let identity: string;
239
+ try {
240
+ identity = encodeURIComponent(storePath);
241
+ } catch (error) {
242
+ // The only `encodeURIComponent` failure is a lone UTF-16 surrogate (`URIError`); rewrap it so the domain
243
+ // presents ONE error type at the boundary (never a bare `URIError`).
244
+ if (error instanceof URIError) {
245
+ throw new InvalidStorePathError(
246
+ `invalid storePath ${JSON.stringify(storePath)}: it contains a lone UTF-16 surrogate, which has no ` +
247
+ "valid encoding as a store identity (ADR-0049).",
248
+ );
249
+ }
250
+ throw error;
251
+ }
252
+ if (identity === "." || identity === "..") {
158
253
  throw new InvalidStorePathError(
159
- 'invalid storePath: expected a non-empty plain store name (e.g. "my-app-store"); received an empty or whitespace-only value (ADR-0036).',
254
+ `invalid storePath ${JSON.stringify(storePath)}: "." and ".." are reserved file names (File System ` +
255
+ "Standard) and cannot be a store identity (ADR-0049).",
160
256
  );
161
257
  }
162
- if (storePath.includes("://")) {
258
+ if (identity.length > STORE_IDENTITY_ENCODED_CAP) {
163
259
  throw new InvalidStorePathError(
164
- `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +
165
- 'Pass just the name (e.g. "my-app-store") — the storage backend (IndexedDB in a browser, the ' +
166
- "filesystem on Bun/Node) is derived for you; drop the scheme prefix (ADR-0036).",
260
+ `invalid storePath ${JSON.stringify(storePath)}: its encoded store identity is ${identity.length} ` +
261
+ `characters, over the ${STORE_IDENTITY_ENCODED_CAP}-character per-component cap (ADR-0049). Note the ` +
262
+ "cap is on the ENCODED form — a short multi-byte name can expand past it.",
167
263
  );
168
264
  }
169
- if (backendOverride === "memory") return `memory://${storePath}`;
170
- return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;
265
+ return identity;
266
+ }
267
+
268
+ /**
269
+ * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,
270
+ * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `"foo"`'s
271
+ * commitment sentinel vs a store literally named `"foo.committed"`). This module is the ONLY place that knows
272
+ * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the sole owner of the `/pglite/`
273
+ * prefix.
274
+ */
275
+ export const OPFS_TOOLKIT_CONTAINER = "pgxsinkit";
276
+
277
+ /**
278
+ * OPFS path (segment array) of a store's four-file VFS directory: `pgxsinkit/stores/<identity>` (ADR-0049 D6).
279
+ * Returned as SEGMENTS, not a joined string, because consumers traverse OPFS via a `getDirectoryHandle` chain.
280
+ */
281
+ export function opfsStoreDirectoryPath(storePath: string): readonly [string, string, string] {
282
+ return [OPFS_TOOLKIT_CONTAINER, "stores", storeIdentityComponent(storePath)];
283
+ }
284
+
285
+ /**
286
+ * OPFS path (segment array) of a store's commitment marker sentinel: `pgxsinkit/commitments/<identity>`
287
+ * (ADR-0049 D6). Disjoint from {@link opfsStoreDirectoryPath} — the store directory holds exactly the four
288
+ * VFS-owned files, and a suffix-sibling sentinel would collide across valid identities. Segments, not a joined
289
+ * string, for the same `getDirectoryHandle`-chain reason.
290
+ */
291
+ export function opfsCommitmentSentinelPath(storePath: string): readonly [string, string, string] {
292
+ return [OPFS_TOOLKIT_CONTAINER, "commitments", storeIdentityComponent(storePath)];
293
+ }
294
+
295
+ /**
296
+ * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No
297
+ * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.
298
+ */
299
+ export function opfsProbeDirectoryPath(): readonly [string, string] {
300
+ return [OPFS_TOOLKIT_CONTAINER, "probe"];
171
301
  }
172
302
 
173
303
  /**
@@ -209,8 +339,17 @@ export function classifyNonPersistentDataDir(
209
339
  }
210
340
 
211
341
  /**
212
- * Does the backend store a plain {@link storePath} resolves to ALREADY exist? The fresh-target gate for a
213
- * restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:
342
+ * The minimal structural shape of an OPFS `FileSystemDirectoryHandle` this module traverses — just the
343
+ * never-creating `getDirectoryHandle` hop. Declared locally so the module carries no DOM lib dependency
344
+ * (matching how the rest of it reads capabilities structurally off `globalThis`).
345
+ */
346
+ interface OpfsDirectoryHandle {
347
+ getDirectoryHandle(name: string, options: { create: false }): Promise<OpfsDirectoryHandle>;
348
+ }
349
+
350
+ /**
351
+ * Does either backend a browser boot could own for a plain {@link storePath} ALREADY exist? The fresh-target
352
+ * gate for a restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:
214
353
  *
215
354
  * - **memory** (`backendOverride === "memory"`) — a scheme-selected memory store is fresh by construction:
216
355
  * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`
@@ -219,6 +358,16 @@ export function classifyNonPersistentDataDir(
219
358
  * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the
220
359
  * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,
221
360
  * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.
361
+ * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at
362
+ * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via
363
+ * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is
364
+ * ONLY the fresh-target gate; it is emphatically NOT commitment authority — a store directory without a
365
+ * commitment marker is an uncommitted CANDIDATE, and deciding that is the store meta record's phase machine
366
+ * (plan step 2), never this function. `navigator.storage`/`getDirectory` absent → best-effort `false`
367
+ * (mirrors the idb `databases()` stance — never fabricate a positive). A `NotFoundError` anywhere in the
368
+ * chain → `false`; any OTHER error propagates (a genuine failure the restore caller must see).
369
+ * A missing OPFS directory does not finish a granted browser check: IDB is also probed, because a predecessor
370
+ * or fixed-placement store may still own the same public path.
222
371
  * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name
223
372
  * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older
224
373
  * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let
@@ -239,6 +388,32 @@ export async function storeTargetExists(
239
388
  const { existsSync } = await import("node:fs");
240
389
  return existsSync(path);
241
390
  }
391
+ if (dataDir.startsWith("opfs://")) {
392
+ // Structural typing off `globalThis` — no DOM lib dependency (like the rest of the module).
393
+ const storage = (
394
+ globalThis as {
395
+ navigator?: {
396
+ storage?: { getDirectory?: () => Promise<OpfsDirectoryHandle> };
397
+ };
398
+ }
399
+ ).navigator?.storage;
400
+ // API absent → best-effort false (never a fabricated positive), same stance as idb `databases()`.
401
+ if (storage?.getDirectory != null) {
402
+ const segments = opfsStoreDirectoryPath(storePath);
403
+ try {
404
+ let handle = await storage.getDirectory();
405
+ for (const segment of segments) {
406
+ // Never-creating existence walk: `{ create: false }` at every hop — this is a gate, not a mkdir.
407
+ handle = await handle.getDirectoryHandle(segment, { create: false });
408
+ }
409
+ return true;
410
+ } catch (error) {
411
+ // A missing entry anywhere in the chain proves OPFS absence; anything else is a real failure to surface.
412
+ if ((error as { name?: string }).name !== "NotFoundError") throw error;
413
+ }
414
+ }
415
+ // A granted browser must also reject an IDB predecessor at this path; fall through to the shared IDB probe.
416
+ }
242
417
  // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in
243
418
  // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.
244
419
  const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;
package/src/sync/apply.ts CHANGED
@@ -203,6 +203,68 @@ async function executeInsertBatch(
203
203
  await pg.query(rendered.sqlText, flat as unknown[]);
204
204
  }
205
205
 
206
+ function getValueSize(value: unknown): number {
207
+ if (value === null) return 0;
208
+ if (value instanceof ArrayBuffer) return value.byteLength;
209
+ if (value instanceof Blob) return value.size;
210
+ if (value instanceof Uint8Array) return value.byteLength;
211
+ if (value instanceof DataView) return value.byteLength;
212
+ if (ArrayBuffer.isView(value)) return value.byteLength;
213
+
214
+ switch (typeof value) {
215
+ case "string":
216
+ return value.length;
217
+ case "number":
218
+ return 8;
219
+ case "boolean":
220
+ return 1;
221
+ case "bigint":
222
+ case "symbol":
223
+ return value.toString().length;
224
+ case "function":
225
+ case "undefined":
226
+ return 0;
227
+ default: {
228
+ // Remaining typeof: object (null was handled above).
229
+ if (value instanceof Date) return 8;
230
+ try {
231
+ return JSON.stringify(value)?.length ?? 0;
232
+ } catch {
233
+ // Non-serialisable nested value (e.g. bigint inside jsonb).
234
+ return 16;
235
+ }
236
+ }
237
+ }
238
+ }
239
+
240
+ function getRowSize(row: Row<unknown>, columns: readonly string[]): number {
241
+ return columns.reduce((size, column) => {
242
+ const value = row[column];
243
+ if (value === null) return size;
244
+
245
+ if (Array.isArray(value)) {
246
+ if (value.length === 0) return size;
247
+ const firstElement = value[0];
248
+
249
+ switch (typeof firstElement) {
250
+ case "number":
251
+ return size + value.length * 8;
252
+ case "string":
253
+ return size + value.reduce((arrSize, str) => arrSize + str.length, 0);
254
+ case "boolean":
255
+ return size + value.length;
256
+ default:
257
+ if (firstElement instanceof Date) {
258
+ return size + value.length * 8;
259
+ }
260
+ return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);
261
+ }
262
+ }
263
+
264
+ return size + getValueSize(value);
265
+ }, 0);
266
+ }
267
+
206
268
  export async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
207
269
  const data: Row<unknown>[] = messages.map((message) => message.value);
208
270
  const firstRow = data[0];
@@ -214,74 +276,12 @@ export async function applyInsertsToTable({ pg, target, messages, debug }: BulkA
214
276
  const columns = Object.keys(firstRow);
215
277
  const db = drizzleOverPg(pg);
216
278
 
217
- const getValueSize = (value: unknown): number => {
218
- if (value === null) return 0;
219
- if (value instanceof ArrayBuffer) return value.byteLength;
220
- if (value instanceof Blob) return value.size;
221
- if (value instanceof Uint8Array) return value.byteLength;
222
- if (value instanceof DataView) return value.byteLength;
223
- if (ArrayBuffer.isView(value)) return value.byteLength;
224
-
225
- switch (typeof value) {
226
- case "string":
227
- return value.length;
228
- case "number":
229
- return 8;
230
- case "boolean":
231
- return 1;
232
- case "bigint":
233
- case "symbol":
234
- return value.toString().length;
235
- case "function":
236
- case "undefined":
237
- return 0;
238
- default: {
239
- // Remaining typeof: object (null was handled above).
240
- if (value instanceof Date) return 8;
241
- try {
242
- return JSON.stringify(value)?.length ?? 0;
243
- } catch {
244
- // Non-serialisable nested value (e.g. bigint inside jsonb).
245
- return 16;
246
- }
247
- }
248
- }
249
- };
250
-
251
- const getRowSize = (row: Row<unknown>): number => {
252
- return columns.reduce((size, column) => {
253
- const value = row[column];
254
- if (value === null) return size;
255
-
256
- if (Array.isArray(value)) {
257
- if (value.length === 0) return size;
258
- const firstElement = value[0];
259
-
260
- switch (typeof firstElement) {
261
- case "number":
262
- return size + value.length * 8;
263
- case "string":
264
- return size + value.reduce((arrSize, str) => arrSize + str.length, 0);
265
- case "boolean":
266
- return size + value.length;
267
- default:
268
- if (firstElement instanceof Date) {
269
- return size + value.length * 8;
270
- }
271
- return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);
272
- }
273
- }
274
-
275
- return size + getValueSize(value);
276
- }, 0);
277
- };
278
-
279
279
  let currentBatch: Row<unknown>[] = [];
280
280
  let currentBatchSize = 0;
281
281
  let currentBatchParams = 0;
282
282
 
283
283
  for (const row of data) {
284
- const rowSize = getRowSize(row);
284
+ const rowSize = getRowSize(row, columns);
285
285
  const rowParams = columns.length;
286
286
 
287
287
  if (
package/src/sync/index.ts CHANGED
@@ -924,8 +924,8 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
924
924
  if (debug) {
925
925
  console.log("received must-refetch", message);
926
926
  }
927
- // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`
928
- // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot
927
+ // Surface the expired-handle / rewind event on the syncDebug rail too (the `debug` option only
928
+ // console.logs it): must-refetch is the trigger for the truncate + re-snapshot
929
929
  // recovery, so it must be visible when diagnosing a convergence loss in a live app.
930
930
  syncDebug("must-refetch received", { shape: message.shape });
931
931
  inbox.resetShape(message.shape);
@@ -504,7 +504,7 @@ function mergeValues(segment: ChangeMessage<Row<unknown>>[]): Row<unknown> {
504
504
  *
505
505
  * - **trailing `delete`** ⇒ a single DELETE;
506
506
  * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values
507
- * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);
507
+ * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert);
508
508
  * - **only `update`s** ⇒ a single UPDATE with merged values;
509
509
  * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the
510
510
  * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT
package/src/sync/types.ts CHANGED
@@ -56,9 +56,9 @@ export interface SyncShapesToTablesOptions {
56
56
  * SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the
57
57
  * durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor
58
58
  * and tags then die with the rows they index, so a returning engine re-streams the shape from scratch
59
- * instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — every
60
- * persistent group's storage is byte-identical to before. One storage-scope bit; the engine never learns
61
- * the retention model.
59
+ * instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — a
60
+ * persistent group's storage is identical whether the bit is `false` or unset; it only scopes an
61
+ * ephemeral group's bookkeeping. One storage-scope bit; the engine never learns the retention model.
62
62
  */
63
63
  sessionScoped?: boolean | undefined;
64
64
  initialInsertMethod?: InitialInsertMethod | undefined;
package/src/testing.ts CHANGED
@@ -11,8 +11,8 @@
11
11
  // The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}
12
12
  // marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
13
13
  //
14
- // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, writeUrl })
15
- // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, writeUrl })
14
+ // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, batchWriteUrl })
15
+ // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, batchWriteUrl })
16
16
 
17
17
  import { TEST_STORE_BACKEND } from "./store-path";
18
18