@pgxsinkit/client 0.3.0 → 0.5.1

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 (109) 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 +8 -8
  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 +10 -10
  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 +196 -100
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1044 -487
  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 +1 -1
  31. package/dist/mutations-api.d.ts.map +1 -1
  32. package/dist/opfs-effects.d.ts +30 -2
  33. package/dist/opfs-effects.d.ts.map +1 -1
  34. package/dist/schema.d.ts +12 -1
  35. package/dist/schema.d.ts.map +1 -1
  36. package/dist/store-boot.d.ts +30 -2
  37. package/dist/store-boot.d.ts.map +1 -1
  38. package/dist/store-build.d.ts +19 -0
  39. package/dist/store-build.d.ts.map +1 -0
  40. package/dist/store-engine.d.ts +22 -0
  41. package/dist/store-engine.d.ts.map +1 -0
  42. package/dist/store-meta.d.ts +29 -3
  43. package/dist/store-meta.d.ts.map +1 -1
  44. package/dist/store-ownership-lock.d.ts +33 -0
  45. package/dist/store-ownership-lock.d.ts.map +1 -0
  46. package/dist/store-path.d.ts +43 -31
  47. package/dist/store-path.d.ts.map +1 -1
  48. package/dist/sync/apply.d.ts +5 -5
  49. package/dist/sync/apply.d.ts.map +1 -1
  50. package/dist/sync/copy.d.ts +82 -6
  51. package/dist/sync/copy.d.ts.map +1 -1
  52. package/dist/sync/drizzle-executor.d.ts +4 -4
  53. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  54. package/dist/sync/subscription-state.d.ts +5 -5
  55. package/dist/sync/subscription-state.d.ts.map +1 -1
  56. package/dist/testing.d.ts +1 -1
  57. package/dist/testing.js +2 -1
  58. package/dist/testing.js.map +4 -4
  59. package/dist/worker/attach-sync-client.d.ts +24 -13
  60. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  61. package/dist/worker/define-sync-worker.d.ts +35 -18
  62. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  63. package/dist/worker/live-query-manager.d.ts +3 -3
  64. package/dist/worker/live-query-manager.d.ts.map +1 -1
  65. package/dist/worker/live-query-params-guard.d.ts +5 -5
  66. package/dist/worker/live-query-params-guard.d.ts.map +1 -1
  67. package/dist/worker/protocol.d.ts +26 -7
  68. package/dist/worker/protocol.d.ts.map +1 -1
  69. package/package.json +11 -8
  70. package/skills/core/SKILL.md +80 -15
  71. package/skills/operating/SKILL.md +129 -129
  72. package/skills/operating/references/postgres-builds.md +48 -0
  73. package/src/boot-report.ts +12 -12
  74. package/src/circuits/envelope-to-change.ts +121 -12
  75. package/src/circuits/group-sync.ts +2 -2
  76. package/src/circuits/stream-source.ts +35 -9
  77. package/src/circuits/sync-engine.ts +6 -4
  78. package/src/event-lane.ts +132 -14
  79. package/src/export-data.ts +4 -4
  80. package/src/export-dump.ts +31 -36
  81. package/src/export-store.ts +20 -20
  82. package/src/index.ts +576 -340
  83. package/src/live-rows-sql.ts +1 -1
  84. package/src/local-store.ts +2 -2
  85. package/src/local-tables.ts +70 -6
  86. package/src/mutation.ts +9 -8
  87. package/src/mutations-api.ts +4 -4
  88. package/src/opfs-effects.ts +74 -10
  89. package/src/schema.ts +124 -18
  90. package/src/store-boot.ts +71 -7
  91. package/src/store-build.ts +37 -0
  92. package/src/store-engine.ts +94 -0
  93. package/src/store-lifecycle.ts +1 -1
  94. package/src/store-meta.ts +155 -4
  95. package/src/store-ownership-lock.ts +109 -0
  96. package/src/store-path.ts +59 -43
  97. package/src/sync/apply.ts +32 -46
  98. package/src/sync/copy.ts +108 -13
  99. package/src/sync/drizzle-executor.ts +18 -19
  100. package/src/sync/metadata-tables.ts +1 -1
  101. package/src/sync/subscription-state.ts +7 -7
  102. package/src/testing.ts +3 -3
  103. package/src/worker/attach-sync-client.ts +146 -60
  104. package/src/worker/define-sync-worker.ts +212 -83
  105. package/src/worker/engine-router.ts +1 -1
  106. package/src/worker/live-query-fingerprint.ts +4 -4
  107. package/src/worker/live-query-manager.ts +12 -12
  108. package/src/worker/live-query-params-guard.ts +16 -15
  109. package/src/worker/protocol.ts +38 -7
package/src/index.ts CHANGED
@@ -1,7 +1,3 @@
1
- import { PGlite, type PGliteOptions, type QueryOptions, type Results } from "@electric-sql/pglite";
2
- import { live, type PGliteWithLive } from "@electric-sql/pglite/live";
3
- import type { PgliteDatabase } from "drizzle-orm/pglite";
4
- import { drizzle } from "drizzle-orm/pglite";
5
1
  import { defineRelations } from "drizzle-orm/relations";
6
2
 
7
3
  import type {
@@ -18,7 +14,9 @@ import type {
18
14
  SyncTableName,
19
15
  SyncTableRegistry,
20
16
  SyncTableUpdateInput,
17
+ StorageBuild,
21
18
  StorageDurability,
19
+ StoreBuildCheckSite,
22
20
  WriteMode,
23
21
  } from "@pgxsinkit/contracts";
24
22
  import {
@@ -27,10 +25,21 @@ import {
27
25
  isClaimsDependentRowFilter,
28
26
  resolveStorageDeclaration,
29
27
  } from "@pgxsinkit/contracts";
30
- // Type-only import (erased at runtime): the opfs-repacked factory's option/return types for the `opfs://`
31
- // branch. The factory VALUE is loaded lazily via dynamic `import()` inside that branch so a Bun unit test
32
- // mocking `@electric-sql/pglite` never evaluates the factory's `class ... extends PGlite` module top level.
33
- import type { CreateOpfsRepackedPGliteOptions, OpfsRepackedPGlite } from "@pgxsinkit/pglite-opfs-repacked";
28
+ import {
29
+ createPgwasm,
30
+ type PgwasmOptions,
31
+ type PostgresBuild,
32
+ type QueryOptions,
33
+ type Results,
34
+ } from "@pgxsinkit/pgwasm";
35
+ import { cBuild } from "@pgxsinkit/pgwasm-c";
36
+ import type { PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
37
+ import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
38
+ import { live, type PgwasmWithLive } from "@pgxsinkit/pgwasm/live";
39
+ // Type-only import (erased at runtime): the OPFS store factory's option/return types for the `opfs://`
40
+ // branch. The `/opfs` VALUES (`createOpfsPgwasm`, `strictSync`) are loaded lazily via dynamic `import()`, so the
41
+ // store's code stays off every bundle and boot that never opens an OPFS store.
42
+ import type { CreateOpfsPgwasmOptions, OpfsPgwasm } from "@pgxsinkit/pgwasm/opfs";
34
43
 
35
44
  import { type BootReport, type BootReportBuilder, createBootReportBuilder } from "./boot-report";
36
45
  import { startCircuitsSync, type CircuitsGroupSyncResult } from "./circuits/group-sync";
@@ -97,6 +106,7 @@ import {
97
106
  type ResolvedStorageBackend,
98
107
  type StoreBootResolution,
99
108
  } from "./store-boot";
109
+ import { assertStoreBuild, isStoreBuildRefusal } from "./store-build";
100
110
  import { runCommitmentBarrier } from "./store-lifecycle";
101
111
  import {
102
112
  META_STORE_UNAVAILABLE,
@@ -105,8 +115,9 @@ import {
105
115
  type StoreMetaDeps,
106
116
  writeStoreMetaRecord,
107
117
  } from "./store-meta";
118
+ import { acquireStoreOwnership } from "./store-ownership-lock";
108
119
  import {
109
- classifyNonPersistentDataDir,
120
+ classifyNonPersistentStorage,
110
121
  NonPersistentStoreError,
111
122
  normaliseStorePathInput,
112
123
  readTestStoreMarker,
@@ -220,6 +231,7 @@ export {
220
231
  type ProvisionStalledWire,
221
232
  } from "./worker/engine-control";
222
233
  export { createOpfsEffects, type OpfsEffects, type OpfsEffectsDeps } from "./opfs-effects";
234
+ export { STORE_OWNERSHIP_WAIT_MS, StoreOwnershipWaitError } from "./store-ownership-lock";
223
235
  export {
224
236
  COMMITTED_STORE_UNREACHABLE_CODE,
225
237
  CommittedStoreUnreachableError,
@@ -230,6 +242,15 @@ export {
230
242
  type ResolveStoreBootOptions,
231
243
  type StoreBootResolution,
232
244
  } from "./store-boot";
245
+ export {
246
+ // The DECLARED store engine (ADR-0050 addendum): loading a `storage.engine.module` and taking its
247
+ // `createStore`. The worker uses it for every declared mint; an app whose in-process fallback must
248
+ // honour the same declaration uses it there.
249
+ createStoreEngineResolver,
250
+ loadStoreEngineFactory,
251
+ type StoreEngineFactory,
252
+ type StoreEngineModuleLoader,
253
+ } from "./store-engine";
233
254
  export {
234
255
  InvalidStorePathError,
235
256
  NonPersistentStoreError,
@@ -306,6 +327,19 @@ export {
306
327
  // surfaces (the board's schema map, debug tooling) need them without re-deriving DDL internals.
307
328
  export { OUTBOX_SEQUENCE, OUTBOX_TABLE } from "./schema";
308
329
 
330
+ // The COPY TEXT bulk-load seam (ADR-0061). PUBLIC because a consumer's LOCAL-ONLY table — one pgxsinkit
331
+ // does not manage, so `mutate`/`tables.*` do not apply to it — has no other way to load 10k rows without
332
+ // paying an INSERT per row: `buildCopyFromBlobStatement` renders the tier-③ `COPY … FROM '/dev/blob'`
333
+ // statement from the REAL Drizzle table object and serializes the rows with the SAME serializer the sync
334
+ // applier uses, and the resulting {@link RawStatement} goes straight to `rawTransaction`/`rawQuery`.
335
+ // `generateCopyData`/`serializeCopyValue` are exported under it for a caller that renders its own COPY.
336
+ export {
337
+ buildCopyFromBlobStatement,
338
+ type CopyFromBlobStatementOptions,
339
+ generateCopyData,
340
+ serializeCopyValue,
341
+ } from "./sync/copy";
342
+
309
343
  // The Circuits-native read transport (ADR-0055 decision 10). Reads terminate on durable-streams
310
344
  // through the edge; everything above the transport stays ours.
311
345
  export { createTokenRecovery, readShapeStream, STREAM_START } from "./circuits/stream-source";
@@ -391,40 +425,39 @@ export class ClientDisposedError extends Error {
391
425
  }
392
426
  }
393
427
 
394
- // The store carries PGlite's own `live` extension and nothing else. The pgxsinkit sync runtime is not an
428
+ // The store carries pgwasm's own `live` extension and nothing else. The pgxsinkit sync runtime is not an
395
429
  // extension at all (ADR-0032 S1): `createSyncClient` starts it BESIDE the store (`startCircuitsSync`)
396
- // rather than attaching a namespace to the instance, so a store's type is exactly PGlite + `live`
430
+ // rather than attaching a namespace to the instance, so a store's type is exactly pgwasm + `live`
397
431
  // whether or not sync ever runs on it.
398
- export type ClientPGlite = PGliteWithLive;
432
+ export type PgwasmClient = PgwasmWithLive;
399
433
 
400
- /**
401
- * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by
402
- * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +
403
- * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy
404
- * asset load — see the field's JSDoc for the accelerator geometry.
405
- */
406
- export interface PgliteBootAssets {
407
- pgliteWasmModule?: WebAssembly.Module;
408
- initdbWasmModule?: WebAssembly.Module;
409
- fsBundle?: Blob;
410
- }
411
-
412
- /** Options for {@link createClientPGlite}. */
413
- export interface CreateClientPGliteOptions {
434
+ /** Options for {@link createPgwasmClient}. */
435
+ export interface CreatePgwasmClientOptions {
414
436
  /**
415
- * Pre-warmed PGlite boot assets (see {@link CreateSyncClientOptions.pgliteBootAssets}). Awaited and
416
- * passed into `PGlite.create`; a rejected warm is caught to `undefined` (falls back to PGlite's own
417
- * asset load), so it never fails the create.
437
+ * The Postgres build the store runs on (see {@link CreateSyncClientOptions.build}); defaults to `cBuild`.
438
+ * Pass `createCBuild({ assets })` to hand in pre-warmed WASM modules and filesystem bundle: a rejected warm
439
+ * falls back to the build's own asset load, so it never fails the create.
418
440
  */
419
- bootAssets?: Promise<PgliteBootAssets>;
441
+ build?: PostgresBuild;
442
+ /**
443
+ * @internal Toolkit-internal declared-build carrier (ADR-0063), NOT a public per-open knob: the registry's
444
+ * resolved `storage.build`, threaded by the sites that resolve a declaration (`createSyncClient`'s mints,
445
+ * the worker's provision and spare mints). When present, the supplied {@link build} must be that build
446
+ * ({@link StorageBuildMismatchError}, thrown before the store is touched); absent, no declaration is checked.
447
+ */
448
+ declaredBuild?: StorageBuild;
449
+ /**
450
+ * @internal The site the {@link declaredBuild} check reports; defaults to `"createPgwasmClient"`.
451
+ */
452
+ buildCheckSite?: StoreBuildCheckSite;
420
453
  /**
421
454
  * @internal Toolkit-internal durability carrier (ADR-0047), NOT a public per-open knob. Durability is
422
455
  * registry-declared: {@link createSyncClient} resolves `storage.durability ?? "relaxed"` off its registry
423
456
  * and threads the resolved mode in here — the ONE resolution point — for every mint it funnels through this
424
457
  * factory (its own boot, the worker provision/spare mint, the pre-expose idb drain read). Defaults to
425
- * `"relaxed"` when absent and is stamped onto the `boot pglite.create` rail (ADR-0047 D3). On idb, relaxed
458
+ * `"relaxed"` when absent and is stamped onto the `boot pgwasm.create` rail (ADR-0047 D3). On idb, relaxed
426
459
  * returns before the whole-datadir snapshot flush and schedules it asynchronously; strict keeps that
427
- * synchronous snapshot (~100–200ms per statement). On OPFS-repacked the package factory keeps PGlite on its
460
+ * synchronous snapshot (~100–200ms per statement). On OPFS-repacked the package factory keeps pgwasm on its
428
461
  * awaited host path: relaxed routine sync asserts health without an ordinary physical flush, while strict
429
462
  * flushes arena data before metadata. Initialization, activation, and open-state close retain strict
430
463
  * ordering in both OPFS modes.
@@ -438,10 +471,10 @@ export interface CreateClientPGliteOptions {
438
471
  backendOverride?: "memory";
439
472
  /**
440
473
  * A store-backup tarball to seed the new store from (ADR-0035 decision 6, restore) — a `File`/`Blob` as
441
- * produced by {@link SyncClient.exportStore}. Passed straight to PGlite's `loadDataDir`, so the created
474
+ * produced by {@link SyncClient.exportStore}. Passed straight to pgwasm's `loadDataDir`, so the created
442
475
  * store boots ON the backup's datadir. Restore is a CREATION-path feature: the caller (`createSyncClient`)
443
476
  * has already proven the target does not yet exist ({@link storeTargetExists}); this option carries no
444
- * freshness check of its own. A corrupt/foreign tarball surfaces as a PGlite boot failure here.
477
+ * freshness check of its own. A corrupt/foreign tarball surfaces as a pgwasm boot failure here.
445
478
  */
446
479
  restoreFrom?: File | Blob;
447
480
  /**
@@ -454,12 +487,14 @@ export interface CreateClientPGliteOptions {
454
487
  /**
455
488
  * @internal ADR-0049 step 10a: the opfs-repacked factory + store-directory seam, injectable so Bun unit
456
489
  * tests exercise the `opfs://` branch WITHOUT loading real WASM/OPFS. In production both default to the real
457
- * implementations (`createOpfsRepackedPGlite` via a lazy `import()`, and the OPFS effects' store directory
490
+ * implementations (`createOpfsPgwasm` via a lazy `import()`, and the OPFS effects' store directory
458
491
  * handle). Never consumer-facing.
459
492
  */
460
- pgliteFactories?: {
461
- /** The opfs-repacked PGlite factory; defaults to a lazily-imported `createOpfsRepackedPGlite`. */
462
- createOpfsRepacked?: (options: CreateOpfsRepackedPGliteOptions) => Promise<OpfsRepackedPGlite>;
493
+ opfsFactories?: {
494
+ /** The OPFS store factory; defaults to a lazily-imported `createOpfsPgwasm` from `@pgxsinkit/pgwasm/opfs`. */
495
+ createOpfsPgwasm?: (
496
+ options: CreateOpfsPgwasmOptions<{ live: typeof live }>,
497
+ ) => Promise<OpfsPgwasm<{ live: typeof live }>>;
463
498
  /** The create-if-absent store directory handle for the factory; defaults to the real OPFS effects. */
464
499
  getStoreDirectoryHandle?: () => Promise<unknown>;
465
500
  /** Backoff between bounded open retries (ms); defaults to a small real delay. Tests pass `0`. */
@@ -500,29 +535,45 @@ const CONTROL_PLANE_UNREACHABLE = "control plane unreachable: subscribe is faili
500
535
  */
501
536
  const STREAM_LOST = "read stream lost; re-subscribing";
502
537
  /**
503
- * Non-enumerable brand stamped on an opfs-repacked instance {@link createClientPGlite} mints (ADR-0049): the
504
- * opfs-repacked VFS owns its store on a dedicated OPFS directory and reports NO `dataDir` (a custom VFS, the
505
- * field is honestly `undefined`), so the BYO "non-persistent" guard ({@link classifyNonPersistentDataDir},
506
- * which reads only `dataDir`) would wrongly reject it as an in-memory default when it is adopted as a
507
- * `precreatedPglite` (the provision-then-attach path). This brand lets the guard recognise it as PROVABLY
508
- * persistent. `Symbol.for` so the brand survives even if the instance is inspected via a different module copy.
538
+ * Is this instance on an OPFS-repacked store? The store reports itself through `pg.storage` (the filesystem's
539
+ * own description, `{ kind: "vfs", name: "opfs-repacked", persistent: true }`), so an ADOPTED instance is
540
+ * recognised without any brand: it is the one provenance that carries the OPFS commitment machinery, which a
541
+ * BYO idb/file/memory instance does not.
509
542
  */
510
- const OPFS_REPACKED_PERSISTENT = Symbol.for("pgxsinkit.opfsRepackedPersistent");
543
+ function isOpfsRepackedStore(instance: PgwasmClient): boolean {
544
+ const storage = instance.storage;
545
+ return storage.kind === "vfs" && storage.name === OPFS_REPACKED_STORAGE_NAME;
546
+ }
547
+
548
+ /** The name the OPFS-repacked filesystem reports in `pg.storage` (`OpfsRepackedFS`'s `description`). */
549
+ const OPFS_REPACKED_STORAGE_NAME = "opfs-repacked";
511
550
 
512
551
  /**
513
- * Was this instance minted by the opfs-repacked factory ({@link OPFS_REPACKED_PERSISTENT})? The brand is the
514
- * ONLY proof available for an adopted instance: an opfs-repacked store reports no `dataDir`, so nothing else
515
- * distinguishes it from a BYO idb/file/memory instance — which carries no OPFS commitment machinery at all.
552
+ * Keep the store's ownership lock until the database has closed (its build releases the OPFS handles in
553
+ * `closeFs` on every close, a failed one included), then release it. `Symbol.asyncDispose` routes through
554
+ * `close`, so both exits are covered; a second close is idempotent here as in pgwasm.
516
555
  */
517
- function isOpfsRepackedPersistent(instance: ClientPGlite): boolean {
518
- return (instance as Record<symbol, unknown>)[OPFS_REPACKED_PERSISTENT] === true;
556
+ function holdOwnershipUntilClosed(instance: PgwasmClient, release: () => void): PgwasmClient {
557
+ // An injected test factory may return a close-less stand-in: nothing can ever close it, so the lock stays
558
+ // held for the context's life (its owner never lets go), exactly the semantics of a live store.
559
+ if (typeof instance.close !== "function") return instance;
560
+ const close = instance.close.bind(instance);
561
+ instance.close = async () => {
562
+ try {
563
+ await close();
564
+ } finally {
565
+ release();
566
+ }
567
+ };
568
+ return instance;
519
569
  }
520
570
 
521
571
  /**
522
- * Open the opfs-repacked factory with bounded retries (3) and a small linear backoff for transient failures,
572
+ * Open the opfs-repacked factory with bounded retries and a small linear backoff for transient failures,
523
573
  * then propagate the last error — a committed store's final failure is HARD, and an uncommitted candidate's
524
- * likewise propagates (the caller never exposes an unopened store). Kept simple: retry the whole factory call,
525
- * always, then throw.
574
+ * likewise propagates (the caller never exposes an unopened store). A typed build refusal (ADR-0063: the
575
+ * directory or backup is another build or data format, or its marker is unreadable) is not transient, so it
576
+ * propagates at once, never retried.
526
577
  */
527
578
  async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: number): Promise<T> {
528
579
  let lastError: unknown;
@@ -530,6 +581,7 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
530
581
  try {
531
582
  return await open();
532
583
  } catch (error) {
584
+ if (isStoreBuildRefusal(error)) throw error;
533
585
  lastError = error;
534
586
  if (attempt < OPFS_OPEN_ATTEMPTS && backoffMs > 0) {
535
587
  await new Promise<void>((resolve) => setTimeout(resolve, backoffMs * attempt));
@@ -540,47 +592,53 @@ async function openWithBoundedRetries<T>(open: () => Promise<T>, backoffMs: numb
540
592
  }
541
593
 
542
594
  /**
543
- * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call
595
+ * Create the raw local pgwasm store the sync client runs on — the SAME `pgwasm.create` call
544
596
  * {@link createSyncClient} makes internally (the `live` extension, pre-warmed boot-asset
545
- * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists
597
+ * consumption, and the `boot pgwasm.create` rail stamp), extracted so exactly one implementation exists
546
598
  * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)
547
- * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare
599
+ * instance to {@link CreateSyncClientOptions.precreatedPgwasm}: the client then owns schema exec, prepare
548
600
  * hooks, journal recovery, and registry reconciliation, exactly as its own `storePath` path does.
549
601
  *
550
602
  * Takes a plain store path (ADR-0036), never a storage URL — the backend is DERIVED from the engine home
551
603
  * (capability-selected opfs-repacked with IndexedDB fallback in a browser, or the filesystem on Bun/Node);
552
604
  * a scheme-bearing path throws {@link InvalidStorePathError}.
553
- * Also accepts the testing helper's output (`createClientPGlite(memoryStoreForTests("x"))`) so a test can
605
+ * Also accepts the testing helper's output (`createPgwasmClient(memoryStoreForTests("x"))`) so a test can
554
606
  * mint a memory store without naming a backend.
555
607
  *
556
608
  * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry
557
609
  * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive
558
610
  * initdb (+ persistent-store open), which is the dominant cold-boot cost once the WASM is pre-warmed.
559
611
  *
560
- * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a
561
- * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.
612
+ * `build` is the Postgres build (see {@link CreateSyncClientOptions.build}); a `createCBuild({ assets })` whose
613
+ * warm rejects loads its own assets — never a failure.
562
614
  */
563
- export async function createClientPGlite(
615
+ export async function createPgwasmClient(
564
616
  store: StorePathInput,
565
- options?: CreateClientPGliteOptions,
566
- ): Promise<ClientPGlite> {
617
+ options?: CreatePgwasmClientOptions,
618
+ ): Promise<PgwasmClient> {
567
619
  // Normalise the store argument to a plain path (+ any internal memory override the testing helper carried),
568
- // then derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
620
+ // then derive the concrete pgwasm dataDir URL (ADR-0036) — the single resolution point. A scheme-bearing/
569
621
  // empty storePath throws here, so the old dataDir-URL contract fails loudly, never silently re-interpreted.
570
622
  const normalised = normaliseStorePathInput(store);
571
623
  const storePath = normalised.storePath;
572
624
  const backendOverride = options?.backendOverride ?? normalised.backendOverride;
625
+ // ADR-0063: with a declaration threaded in, the supplied build must be the declared one — checked before
626
+ // anything below touches a store (the denied-home meta gate included). Absent `build` means `cBuild`.
627
+ if (options?.declaredBuild !== undefined) {
628
+ const suppliedBuild = (options.build ?? cBuild).identity;
629
+ assertStoreBuild(options.declaredBuild, suppliedBuild, options.buildCheckSite ?? "createPgwasmClient");
630
+ }
573
631
  // An eager precreate is itself a store mint, so it passes the SAME pre-mint meta gate the ordinary
574
632
  // createSyncClient path does before a denied browser home opens an IDB store: settle any durable `deleting`
575
633
  // authority, retire an unexposed `opfs-candidate`, and REFUSE an `opfs-committed` store outright ({@link
576
634
  // CommittedStoreUnreachableError}) — an eager tab-side precreate must never be the thing that mints an empty
577
635
  // sibling over the committed store, nor one exposed beneath a record still claiming a candidate.
578
636
  // Keeping this at the documented precreate factory protects callers outside defineSyncWorker; the worker
579
- // provision handler carries the same guard separately because it permits a caller-supplied createPglite factory.
637
+ // provision handler carries the same guard separately because it permits a caller-supplied createStore factory.
580
638
  if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
581
639
  await resolveDeniedBootAuthority(storePath);
582
640
  }
583
- // Derive the concrete PGlite dataDir URL (ADR-0036) — the single resolution point. Browser/worker → `idb://`,
641
+ // Derive the concrete pgwasm dataDir URL (ADR-0036) — the single resolution point. Browser/worker → `idb://`,
584
642
  // Bun/Node → `file://`, the sanctioned test lane → `memory://`. A scheme-bearing/empty storePath throws here.
585
643
  // ADR-0049 step 10a: when the caller threads the placement probe's grant (`hasOpfsSyncAccess`), the browser
586
644
  // store resolves to `opfs://` and routes to the opfs-repacked factory below. Default (undefined/false) leaves
@@ -591,90 +649,96 @@ export async function createClientPGlite(
591
649
  // Stamp the store's scheme on the boot rail (never the full path — it can carry an identity-specific store
592
650
  // name): "idb:" / "file:" / "memory:".
593
651
  const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
594
- // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the
595
- // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled
596
- // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed
597
- // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.
598
- const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;
652
+ // The build a client-owned store runs on: the caller's (e.g. `createCBuild({ assets })` over a warm started
653
+ // on an earlier screen, where a rejected warm falls back to the build's own lazy asset load and never fails
654
+ // the boot), else the shared `cBuild`.
655
+ const build = options?.build ?? cBuild;
599
656
  // Durability (ADR-0047) is registry-declared and resolved by createSyncClient; the resolved mode is threaded
600
657
  // in via the internal `durability` carrier. Every store minting path (createSyncClient's own create, the
601
- // worker's default createPglite factory, spare/prewarm mints) funnels through this function, so the
658
+ // worker's default createStore factory, spare/prewarm mints) funnels through this function, so the
602
659
  // `?? "relaxed"` here is the terminal fallback when no mode was threaded (e.g. an eager caller-owned
603
- // precreate). Maps to PGlite's `relaxedDurability` boolean (`"strict"` → false). On idb the per-query
660
+ // precreate). Maps to pgwasm's `relaxedDurability` boolean (`"strict"` → false). On idb the per-query
604
661
  // synchronous flush dominates write latency; relaxing it schedules the flush asynchronously instead.
605
662
  const relaxedDurability = (options?.durability ?? "relaxed") !== "strict";
606
-
607
- // ADR-0049 step 10a — the `opfs://` branch. PGlite does NOT accept `opfs://` as a dataDir; instead the
608
- // opfs-repacked factory owns the store on a dedicated OPFS directory. The factory is loaded LAZILY (a
609
- // dynamic `import()`) and both it and the store-directory handle are injectable (`pgliteFactories`) so a Bun
663
+ // Wait for everything the build's boot would wait on (a `createCBuild({ assets })` warm still in flight)
664
+ // BEFORE the `boot pgwasm.create` stamp starts, so the stamp measures the create alone, never an unfinished
665
+ // warm. `prepare` never rejects: a failed warm falls back to the build's own lazy asset load.
666
+ await build.prepare?.();
667
+
668
+ // ADR-0049 step 10a — the `opfs://` branch. pgwasm does NOT accept `opfs://` as a dataDir; instead the
669
+ // OPFS store factory owns the store on a dedicated OPFS directory. The factory is loaded LAZILY (a
670
+ // dynamic `import()`) and both it and the store-directory handle are injectable (`opfsFactories`) so a Bun
610
671
  // unit test drives this branch with no real WASM/OPFS. Durability maps from the same `relaxedDurability`
611
672
  // resolution above (ADR-0047's default logic is untouched): `relaxed` → the factory's `"relaxed"`, else
612
673
  // `"strict"`. The open is retried a bounded number of times for transient failures, then propagates.
613
674
  if (dataDir.startsWith("opfs://")) {
614
- const opfsPglite = (await timeAsync(
615
- "boot pglite.create",
675
+ const opfsPgwasm = (await timeAsync(
676
+ "boot pgwasm.create",
616
677
  async () => {
617
- const createOpfsRepacked =
618
- options?.pgliteFactories?.createOpfsRepacked ??
619
- (await import("@pgxsinkit/pglite-opfs-repacked")).createOpfsRepackedPGlite;
620
- // A create that never returns used to leave the rail at `boot pglite.create start` with nothing after
678
+ const createOpfsStore =
679
+ options?.opfsFactories?.createOpfsPgwasm ?? (await import("@pgxsinkit/pgwasm/opfs")).createOpfsPgwasm;
680
+ // A create that never returns used to leave the rail at `boot pgwasm.create start` with nothing after
621
681
  // it — indistinguishable from a lost worker. These four phase lines split the create into its long
622
- // steps (module load, directory handle, handle acquisition, PGlite boot), so a stall is attributable.
623
- syncDebug("boot pglite.create phase", { phase: "module-loaded" });
682
+ // steps (module load, directory handle, handle acquisition, pgwasm boot), so a stall is attributable.
683
+ syncDebug("boot pgwasm.create phase", { phase: "module-loaded" });
624
684
  const getStoreDirectoryHandle =
625
- options?.pgliteFactories?.getStoreDirectoryHandle ??
685
+ options?.opfsFactories?.getStoreDirectoryHandle ??
626
686
  (() => createOpfsEffects(storePath).getStoreDirectoryHandle());
627
687
  const directory = await getStoreDirectoryHandle();
628
- syncDebug("boot pglite.create phase", { phase: "directory-ready" });
629
- return openWithBoundedRetries(
630
- () =>
631
- createOpfsRepacked({
632
- directory: directory as CreateOpfsRepackedPGliteOptions["directory"],
633
- durability: relaxedDurability ? "relaxed" : "strict",
634
- extentSize: OPFS_STORE_EXTENT_SIZE,
635
- // The factory's own two phases: handles acquired (`vfs-opened`) and PGlite booted
636
- // (`pglite-ready`). Same rail line, so one grep shows the whole create.
637
- onPhase: (phase) => syncDebug("boot pglite.create phase", { phase }),
638
- // The store is engine-less by construction (only `live` is a create-time extension); the sync
639
- // engine attaches post-create (ADR-0032 S1). Restore + pre-warmed boot assets ride the same
640
- // `pglite` sub-options the idb path uses.
641
- pglite: {
642
- ...(bootAssets ?? {}),
643
- ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
644
- extensions: { live },
645
- },
646
- }),
647
- options?.pgliteFactories?.retryDelayMs ?? OPFS_OPEN_BACKOFF_MS,
648
- );
688
+ syncDebug("boot pgwasm.create phase", { phase: "directory-ready" });
689
+ // The store's OWNERSHIP LOCK (store-ownership-lock.ts), taken before the handles are opened and held
690
+ // until the database has closed them: a deleter (destroy, wipe, candidate retirement) orders on it, so
691
+ // it can never `removeEntry` under handles this context still holds. Waiting for it also orders this
692
+ // open after a dying predecessor's release, ahead of the contention retries below.
693
+ const releaseOwnership = await acquireStoreOwnership(storePath);
694
+ let opened: PgwasmClient;
695
+ try {
696
+ opened = await openWithBoundedRetries(
697
+ () =>
698
+ createOpfsStore({
699
+ build,
700
+ directory: directory as CreateOpfsPgwasmOptions["directory"],
701
+ durability: relaxedDurability ? "relaxed" : "strict",
702
+ extentSize: OPFS_STORE_EXTENT_SIZE,
703
+ // The factory's own two phases: handles acquired (`store-opened`) and pgwasm booted
704
+ // (`pgwasm-ready`). Same rail line, so one grep shows the whole create.
705
+ onPhase: (phase) => syncDebug("boot pgwasm.create phase", { phase }),
706
+ // The store is engine-less by construction (only `live` is a create-time extension); the sync
707
+ // engine attaches post-create (ADR-0032 S1). Restore rides the same `pgwasm` sub-options the
708
+ // idb path uses; the pre-warmed boot assets ride the `build`.
709
+ pgwasm: {
710
+ ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
711
+ extensions: { live },
712
+ },
713
+ }),
714
+ options?.opfsFactories?.retryDelayMs ?? OPFS_OPEN_BACKOFF_MS,
715
+ );
716
+ } catch (error) {
717
+ releaseOwnership();
718
+ throw error;
719
+ }
720
+ return holdOwnershipUntilClosed(opened, releaseOwnership);
649
721
  },
650
722
  { ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
651
- )) as unknown as ClientPGlite;
652
- // Brand it PROVABLY persistent: the opfs-repacked VFS reports no `dataDir`, so without this the BYO
653
- // non-persistent guard would reject it when it is adopted as a `precreatedPglite` (provision-then-attach).
654
- try {
655
- Object.defineProperty(opfsPglite, OPFS_REPACKED_PERSISTENT, {
656
- value: true,
657
- enumerable: false,
658
- configurable: true,
659
- });
660
- } catch {
661
- // A frozen/exotic instance — the guard still falls back to its dataDir classification (best-effort brand).
662
- }
663
- return opfsPglite;
723
+ )) as PgwasmClient;
724
+ // No brand is needed: the store reports itself as persistent through `pg.storage`, so the BYO
725
+ // non-persistent guard accepts it when it is adopted as a `precreatedPgwasm` (provision-then-attach).
726
+ return opfsPgwasm;
664
727
  }
665
728
 
666
- const pglite = (await timeAsync(
667
- "boot pglite.create",
729
+ const pgwasm = (await timeAsync(
730
+ "boot pgwasm.create",
668
731
  () => {
669
- const createOptions: PGliteOptions = {
670
- ...(bootAssets ?? {}),
732
+ const createOptions: PgwasmOptions<{ live: typeof live }> = {
733
+ build,
734
+ dataDir,
671
735
  relaxedDurability,
672
- // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. PGlite's
736
+ // Restore (ADR-0035 decision 6): seed the brand-new store from the backup tarball. pgwasm's
673
737
  // `loadDataDir` unpacks it into the datadir being created, so the store boots ON the backup's bytes —
674
738
  // the whole synced cache, Overlay, and Mutation journal that travelled inside it. Absent on a normal
675
739
  // create (the store initdbs empty).
676
740
  ...(options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {}),
677
- // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync runtime is NOT
741
+ // Only pgwasm's own `live` extension is a create-time extension; the pgxsinkit sync runtime is NOT
678
742
  // (ADR-0032 S1) — `createSyncClient` starts it beside the store, never on it. So a store minted here
679
743
  // is deliberately SYNC-LESS by construction: a spare/pre-warmed store (e.g. the board's login-screen
680
744
  // mint) carries no subscription session, no shape streams, and no open stream connections until it
@@ -683,16 +747,16 @@ export async function createClientPGlite(
683
747
  live,
684
748
  },
685
749
  };
686
- // idb/file/memory take the dataDir-string form; upstream PGlite's own scheme parser selects the backend.
687
- return PGlite.create(dataDir, createOptions);
750
+ // idb/file/memory take the dataDir-string form; pgwasm's own scheme parser selects the backend.
751
+ return createPgwasm(createOptions);
688
752
  },
689
753
  // Stamp the resolved durability mode + store scheme so every boot-rail capture shows the mode and lane the
690
754
  // store was created under (ADR-0047 diagnosability).
691
755
  { ...(dataDirScheme ? { dataDir: dataDirScheme } : {}), relaxedDurability },
692
- // `as unknown as` because the raw store is deliberately sync-less here (only `live` is a create-time
693
- // extension); the sync runtime never lands on the instance at all (ADR-0032 S1).
694
- )) as unknown as ClientPGlite;
695
- return pglite;
756
+ // The raw store is deliberately sync-less here (only `live` is a create-time extension); the sync runtime
757
+ // never lands on the instance at all (ADR-0032 S1).
758
+ )) as PgwasmClient;
759
+ return pgwasm;
696
760
  }
697
761
 
698
762
  // ─── ADR-0049 step 11c: FRESH/RESTORE commitment boot wiring ───────────────────────────────────────────
@@ -742,7 +806,7 @@ export interface FreshBootResolution {
742
806
  }
743
807
 
744
808
  /**
745
- * Map a resolved PGlite dataDir URL to the ADR-0049 decision 12 `storageBackend` diagnostic — the inverse of
809
+ * Map a resolved pgwasm dataDir URL to the ADR-0049 decision 12 `storageBackend` diagnostic — the inverse of
746
810
  * {@link resolveStoreDataDir}'s scheme selection (`opfs://` → opfs-repacked, `idb://` → idbfs, `file://` →
747
811
  * filesystem, `memory://` → memory). Used to stamp the BootReport at the single client-owned mint seam. Returns
748
812
  * `undefined` for an unrecognised scheme (a BYO instance whose dataDir the toolkit never minted — e.g. an
@@ -757,6 +821,26 @@ function storageBackendFromDataDir(dataDir: string | undefined): NonNullable<Boo
757
821
  return undefined;
758
822
  }
759
823
 
824
+ /**
825
+ * Map an instance's own `pg.storage` to the ADR-0049 decision 12 `storageBackend` diagnostic, for a BYO or adopted
826
+ * store the toolkit did not mint here. Returns `undefined` for a filesystem it does not recognise, so the field is
827
+ * then honestly omitted.
828
+ */
829
+ function storageBackendFromStorage(
830
+ storage: PgwasmClient["storage"],
831
+ ): NonNullable<BootReport["storageBackend"]> | undefined {
832
+ switch (storage.kind) {
833
+ case "memory":
834
+ return "memory";
835
+ case "idb":
836
+ return "idbfs";
837
+ case "file":
838
+ return "filesystem";
839
+ case "vfs":
840
+ return storage.name === OPFS_REPACKED_STORAGE_NAME ? "opfs-repacked" : undefined;
841
+ }
842
+ }
843
+
760
844
  /** Does a boot verdict stand up an UNCOMMITTED opfs candidate the commitment barrier must promote (invariant 3)? */
761
845
  function verdictNeedsCommitmentBarrier(
762
846
  verdict: StoreBootVerdict | undefined,
@@ -839,19 +923,18 @@ export async function resolveFreshBoot(
839
923
  * for unit tests via {@link FreshCommitmentSeams}.
840
924
  */
841
925
  /**
842
- * Extract the live engine's `strictSync()` from an opfs-repacked store for the commitment barrier. The barrier
843
- * requires it (data-before-authority, invariant 3); a store that does not expose it is not an OPFS-repacked
844
- * engine, which is a boot invariant violation.
926
+ * Resolve the live engine's strict sync (`strictSync(pg)` from `@pgxsinkit/pgwasm/opfs`) for the commitment
927
+ * barrier. The barrier requires it (data-before-authority, invariant 3); a store that is not on the OPFS-repacked
928
+ * filesystem has none, which is a boot invariant violation. `/opfs` is imported lazily, as the factory is.
845
929
  */
846
- function resolveEngineStrictSync(pglite: ClientPGlite): () => Promise<void> {
847
- const strictSync = (pglite as unknown as { strictSync?: () => Promise<void> }).strictSync;
848
- if (typeof strictSync !== "function") {
930
+ function resolveEngineStrictSync(pgwasm: PgwasmClient): () => Promise<void> {
931
+ if (!isOpfsRepackedStore(pgwasm)) {
849
932
  throw new Error(
850
- "[pgxsinkit] fresh commitment: the opfs store does not expose `strictSync()` — the commitment barrier " +
851
- "requires an OPFS-repacked engine (data-before-authority, invariant 3).",
933
+ "[pgxsinkit] fresh commitment: the store is not on the OPFS-repacked filesystem, so it has no strict " +
934
+ "sync — the commitment barrier requires an OPFS-repacked engine (data-before-authority, invariant 3).",
852
935
  );
853
936
  }
854
- return () => strictSync.call(pglite);
937
+ return async () => (await import("@pgxsinkit/pgwasm/opfs")).strictSync(pgwasm);
855
938
  }
856
939
 
857
940
  export async function runFreshCommitmentBarrier(
@@ -874,11 +957,11 @@ export async function runFreshCommitmentBarrier(
874
957
  }
875
958
 
876
959
  /**
877
- * @internal The ADOPTED-boot commitment gate. A boot that ADOPTS an instance (`pgliteInstance` /
878
- * `precreatedPglite` — the provision→adopt accelerator, ADR-0032 decision 5) never enters `openOwnedStore`, so
960
+ * @internal The ADOPTED-boot commitment gate. A boot that ADOPTS an instance (`pgwasmInstance` /
961
+ * `precreatedPgwasm` — the provision→adopt accelerator, ADR-0032 decision 5) never enters `openOwnedStore`, so
879
962
  * {@link resolveFreshBoot} never runs and nothing flags the barrier. Left alone, an adopted OPFS store therefore
880
963
  * stays UNCOMMITTED for its whole life: no sentinel, and a record still at `opfs-candidate` (or absent, when the
881
- * adopted instance was built outside the mint seam — a BYO `pgliteInstance`). That state is INDISTINGUISHABLE
964
+ * adopted instance was built outside the mint seam — a BYO `pgwasmInstance`). That state is INDISTINGUISHABLE
882
965
  * from a torn candidate, so the next client-owned boot classifies `delete-candidate-and-rebuild` and DESTROYS a
883
966
  * populated store — offline, with nothing to rebuild from. An adopted opfs boot therefore owes the SAME barrier
884
967
  * ({@link runFreshCommitmentBarrier}) a fresh one does, pre-expose (invariant 3).
@@ -1013,7 +1096,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1013
1096
  */
1014
1097
  readSilenceMs?: number;
1015
1098
  /**
1016
- * The local store's name (ADR-0036) — a PLAIN path/name, never a PGlite storage URL. The storage backend
1099
+ * The local store's name (ADR-0036) — a PLAIN path/name, never a pgwasm storage URL. The storage backend
1017
1100
  * is DERIVED from the engine home (capability-selected opfs-repacked with IndexedDB fallback in a browser,
1018
1101
  * or the filesystem on Bun/Node); a
1019
1102
  * scheme-bearing string (anything containing `://`) is rejected with {@link InvalidStorePathError}
@@ -1035,68 +1118,73 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1035
1118
  * ADR-0049 D1: the placement probe's OPFS-sync-access grant, threaded from the SharedWorker's engine home
1036
1119
  * (`defineSyncWorker`'s SW-direct bootstrap) into this boot so the client-owned create opens the OPFS-repacked
1037
1120
  * backend. Absent/false is the honest IDBFS home — the declared `backend: "idbfs"` mode or a capability-absence
1038
- * fallback (a main thread can never hold handles either). Forwarded verbatim to {@link createClientPGlite}, which
1121
+ * fallback (a main thread can never hold handles either). Forwarded verbatim to {@link createPgwasmClient}, which
1039
1122
  * resolves the actual dataDir from it.
1040
1123
  */
1041
1124
  hasOpfsSyncAccess?: boolean;
1042
1125
  /**
1043
- * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight
1044
- * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —
1045
- * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling
1046
- * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise
1047
- * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips
1048
- * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that
1049
- * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite
1050
- * falls back to loading its own assets, so this is a pure best-effort accelerator.
1126
+ * The Postgres build a client-owned store runs on; defaults to `cBuild`. To hide the ~2.5s cold
1127
+ * `boot pgwasm.create` cost — dominated by the WASM fetch+compile — behind user think-time, pass
1128
+ * `createCBuild({ assets })` from `@pgxsinkit/pgwasm-c`, where `assets` is a `Promise<CBuildAssets>` the host
1129
+ * started fetching/compiling on an earlier screen (e.g. the login/identity picker): by the time a store is
1130
+ * opened the assets are resolved and the build skips its own lazy asset load. Ignored when
1131
+ * {@link pgwasmInstance} is supplied (the caller owns that instance's boot). A rejected/failed warm never
1132
+ * fails the boot — the build falls back to loading its own assets, so the warm is a pure best-effort
1133
+ * accelerator. The boot waits for the build's `prepare()` (the warm) before its `boot pgwasm.create` stamp,
1134
+ * so `pgwasmCreateMs` measures the create alone.
1135
+ *
1136
+ * The build must be the registry's declared `storage.build` (default `"c"`, ADR-0063): a mismatch throws
1137
+ * `StorageBuildMismatchError` before any store is touched. An adopted {@link pgwasmInstance} /
1138
+ * {@link precreatedPgwasm} is checked the same way, against its own `pg.build`.
1051
1139
  */
1052
- pgliteBootAssets?: Promise<PgliteBootAssets>;
1140
+ build?: PostgresBuild;
1053
1141
  resetSubscriptionKeys?: string[];
1054
- prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;
1055
- prepareLocalDbAfterSchema?: (pglite: ClientPGlite) => Promise<void>;
1142
+ prepareLocalDbBeforeSchema?: (pgwasm: PgwasmClient) => Promise<void>;
1143
+ prepareLocalDbAfterSchema?: (pgwasm: PgwasmClient) => Promise<void>;
1056
1144
  onStatusChange?: (status: SyncRuntimeStatus) => void;
1057
1145
  onTableInitialSync?: (tableKey: string) => void;
1058
1146
  /**
1059
- * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its
1147
+ * A fully-provisioned pgwasm instance the CALLER owns end-to-end. The client runs NONE of its
1060
1148
  * post-create boot steps against it — no schema exec, prepare hooks, or registry reconciliation
1061
1149
  * (journal recovery still runs, as it does on every path). Use it only when the caller has already
1062
- * applied the registry schema itself. Contrast the three PGlite-provenance seams:
1150
+ * applied the registry schema itself. Contrast the three store-provenance seams:
1063
1151
  * - {@link storePath} (default) — the client creates the store AND runs every post-create step.
1064
- * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but
1152
+ * - {@link precreatedPgwasm} — the caller creates the raw store (via {@link createPgwasmClient}), but
1065
1153
  * the client still runs every post-create step (schema, prepare hooks, and reconciliation), exactly as
1066
1154
  * `storePath` does.
1067
- * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.
1155
+ * - `pgwasmInstance` — the caller creates AND provisions the store; the client runs none of them.
1068
1156
  *
1069
1157
  * A caller-owned instance is REFUSED with {@link NonPersistentStoreError} if it is provably
1070
- * non-persistent (a `new PGlite()` default, or an in-memory store) — pgxsinkit's durability semantics
1158
+ * non-persistent (a `new pgwasm()` default, or an in-memory store) — pgxsinkit's durability semantics
1071
1159
  * assume a persisted store (ADR-0036). Acknowledge a deliberate test store by spreading
1072
1160
  * `testStoreAcknowledgment()` from `@pgxsinkit/client/testing`.
1073
1161
  *
1074
- * Mutually exclusive with {@link precreatedPglite} (supplying both throws).
1162
+ * Mutually exclusive with {@link precreatedPgwasm} (supplying both throws).
1075
1163
  */
1076
- pgliteInstance?: ClientPGlite;
1164
+ pgwasmInstance?: PgwasmClient;
1077
1165
  /**
1078
- * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an
1166
+ * A raw pgwasm instance the caller created EAGERLY (via {@link createPgwasmClient}) — typically on an
1079
1167
  * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the
1080
1168
  * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and registry
1081
1169
  * reconciliation all run exactly as on the {@link storePath} path. This is the difference from
1082
- * {@link pgliteInstance} (which skips schema, prepare hooks, and reconciliation because the caller owns
1170
+ * {@link pgwasmInstance} (which skips schema, prepare hooks, and reconciliation because the caller owns
1083
1171
  * them); see that
1084
1172
  * option's JSDoc for the three-way distinction.
1085
1173
  *
1086
1174
  * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:
1087
- * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.
1175
+ * - Supplying both this and {@link pgwasmInstance} throws — they claim different ownership.
1088
1176
  * - {@link storePath} is used ONLY as the fallback store name if this promise REJECTS: a failed eager
1089
1177
  * create is caught, logged on the boot rail, and the normal `storePath` create path runs instead (also
1090
- * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot
1178
+ * consuming {@link build} if provided). The pattern is a pure accelerator, never a boot
1091
1179
  * dependency.
1092
1180
  * - A successfully-adopted instance is subject to the same {@link NonPersistentStoreError} refusal as
1093
- * {@link pgliteInstance} (checked after resolution, so the refusal propagates rather than being
1181
+ * {@link pgwasmInstance} (checked after resolution, so the refusal propagates rather than being
1094
1182
  * swallowed by the reject-fallback).
1095
1183
  */
1096
- precreatedPglite?: Promise<ClientPGlite>;
1184
+ precreatedPgwasm?: Promise<PgwasmClient>;
1097
1185
  /**
1098
1186
  * Restore the store from a **store backup** (ADR-0035 decision 6) — a `File`/`Blob` tarball as produced by
1099
- * {@link SyncClient.exportStore}. The client creates its store with the backup handed to PGlite's
1187
+ * {@link SyncClient.exportStore}. The client creates its store with the backup handed to pgwasm's
1100
1188
  * `loadDataDir`, so it boots ON the backup's datadir (synced cache + Overlay + Mutation journal, all the
1101
1189
  * bytes that travelled inside it). Three restore-only rules apply, none of them optional:
1102
1190
  *
@@ -1115,7 +1203,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1115
1203
  * ledger, so replay is unsafe on last-write-wins tables). Release (`retryFailed`) or discard
1116
1204
  * (`discardQuarantined`) them explicitly. When this pass quarantines nothing, the restore comes online (above).
1117
1205
  *
1118
- * Mutually exclusive with {@link pgliteInstance} AND {@link precreatedPglite} — restore owns the store's
1206
+ * Mutually exclusive with {@link pgwasmInstance} AND {@link precreatedPgwasm} — restore owns the store's
1119
1207
  * creation (`loadDataDir` is a create-time seed), so a caller-supplied instance conflicts (supplying either
1120
1208
  * with `restoreFrom` throws).
1121
1209
  */
@@ -1123,7 +1211,7 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1123
1211
  /**
1124
1212
  * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new
1125
1213
  * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync
1126
- * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape
1214
+ * is enabled, and the client owns schema exec — i.e. not the {@link pgwasmInstance} path), the shape
1127
1215
  * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, and registry
1128
1216
  * reconciliation) and buffered in memory, with commits gated until those phases finish — so the network
1129
1217
  * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses
@@ -1184,9 +1272,10 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1184
1272
  batchEventUrl?: string;
1185
1273
  /**
1186
1274
  * The Event lane's client-level flush policy (ADR-0053): batch caps, the fallback interval, backoff
1187
- * tuning, and per-Event-stream overrides. NEVER on the registry — the registry is the contract, cadence is
1188
- * deployment tuning, and a batch-size tweak must not surface as a registry diff. Client batching is
1189
- * additionally clamped by the contracts-level request-shape limits the server enforces independently.
1275
+ * tuning, the acked ledger's retention (ADR-0060), and per-Event-stream overrides. NEVER on the registry —
1276
+ * the registry is the contract, cadence is deployment tuning, and a batch-size tweak must not surface as a
1277
+ * registry diff. Client batching is additionally clamped by the contracts-level request-shape limits the
1278
+ * server enforces independently.
1190
1279
  */
1191
1280
  events?: EventLaneOptions;
1192
1281
  /**
@@ -1226,8 +1315,8 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1226
1315
  /**
1227
1316
  * @internal Provision timing for a boot that ADOPTS a pre-provisioned store (ADR-0034). When the store was
1228
1317
  * minted ahead of boot (a spare's off-thread initdb), the provisioner stamps its create cost and ready
1229
- * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgliteCreateMs = null`.
1230
- * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPglite}
1318
+ * time here; the boot reports them as {@link BootReport.provision} and sets `phases.pgwasmCreateMs = null`.
1319
+ * A promise because the stamp settles with the spare's `create`. Only honoured on the {@link precreatedPgwasm}
1231
1320
  * adoption path (ignored on a fallback create). `provisionReadyAt` must share this process's monotonic clock.
1232
1321
  */
1233
1322
  provisionStamp?: Promise<{ initdbMs: number; provisionReadyAt: number }>;
@@ -1339,7 +1428,7 @@ export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
1339
1428
  * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks
1340
1429
  * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle
1341
1430
  * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;
1342
- * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached
1431
+ * omit for a keyless query). The in-process client runs it directly over `pgwasm.live`; the worker-attached
1343
1432
  * client runs the live query in the worker and streams DIFFs across the bridge.
1344
1433
  */
1345
1434
  export interface SubscribeLiveRowsInput {
@@ -1348,7 +1437,7 @@ export interface SubscribeLiveRowsInput {
1348
1437
  /**
1349
1438
  * The unique output aliases to render the query's columns under so it is SAFE TO MATERIALISE, in the
1350
1439
  * compiled SQL's column order (one per output column). Drizzle emits no output aliases, so a JOIN whose
1351
- * tables share a column name compiles to duplicate output names — which PGlite's `live` extension
1440
+ * tables share a column name compiles to duplicate output names — which pgwasm's `live` extension
1352
1441
  * refuses to materialise (`column "title" specified more than once`) and which silently collapse
1353
1442
  * same-named columns even in a plain query. When supplied, the seam wraps the query so every output
1354
1443
  * column gets its alias and rows come back KEYED BY THESE ALIASES; the consumer's row-mapper must read
@@ -1416,14 +1505,14 @@ export interface PreparedQueryResult<TTable extends string = string> {
1416
1505
  }
1417
1506
 
1418
1507
  export interface SyncClient<TRegistry extends SyncTableRegistry> {
1419
- drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
1420
- pglite: ClientPGlite;
1508
+ drizzle: PgwasmDatabase<RegistryRelations<TRegistry>>;
1509
+ pgwasm: PgwasmClient;
1421
1510
  views: RegistryViews<TRegistry>;
1422
1511
  tables: {
1423
1512
  [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;
1424
1513
  };
1425
1514
  /**
1426
- * Local-read readiness (ADR-0041): resolves once PGlite is open, the durable schema is ready, registry
1515
+ * Local-read readiness (ADR-0041): resolves once pgwasm is open, the durable schema is ready, registry
1427
1516
  * reconciliation has completed, and the drizzle read
1428
1517
  * facade is built — so cached rows are queryable. Resolving this stage requires NO write runtime, NO sync
1429
1518
  * start, and NO network I/O, so an offline boot resolves it promptly. Under the ADR-0041 Option B contract
@@ -1454,7 +1543,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1454
1543
  * scheduling) without awaiting. Idempotent. The first action of every teardown path — stop()/destroy() call it,
1455
1544
  * and the SharedWorker host calls it before draining subscribes / disposing live queries so no teardown step
1456
1545
  * races a still-live engine. Not a substitute for stop()/destroy(): the awaited teardown (unsubscribe, dispose,
1457
- * pglite.close) still follows. Callers rarely invoke it directly.
1546
+ * pgwasm.close) still follows. Callers rarely invoke it directly.
1458
1547
  */
1459
1548
  haltActivity: () => void;
1460
1549
  stop: () => Promise<void>;
@@ -1582,7 +1671,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1582
1671
  * The store's owed-state diagnostics: the mutation journal's per-status counts, plus — when this client has
1583
1672
  * an Event lane — the Outbox's drain signal (ADR-0053 decision 8: the Event lane's durable state takes a
1584
1673
  * position on every lifecycle surface). `outbox` is the boolean signal rather than a count, for the reason
1585
- * {@link onOutboxStatus} carries none; it is absent on a client with no lane.
1674
+ * {@link onOutboxStatus} carries none; it is absent on a client with no lane. It reports what is OWED, so
1675
+ * acked rows held by the ledger's retention (ADR-0060) read as empty.
1586
1676
  */
1587
1677
  diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{
1588
1678
  mutation: MutationDiagnostics;
@@ -1603,17 +1693,45 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1603
1693
  * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /
1604
1694
  * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the
1605
1695
  * store, not to read app state or mutate it.
1696
+ *
1697
+ * `options.blob` makes it the single-statement BULK-LOAD seam too: pass a `COPY … FROM '/dev/blob'`
1698
+ * statement plus its COPY TEXT bytes ({@link buildCopyFromBlobStatement}) to load a chunk of rows into a
1699
+ * LOCAL-ONLY table the app owns without a transaction around it. Use {@link rawTransaction} when the load
1700
+ * must land together with other statements.
1606
1701
  */
1607
1702
  rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
1608
- /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */
1703
+ /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. Takes no `blob`. */
1609
1704
  rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
1705
+ /**
1706
+ * {@link rawQuery}'s ATOMIC form: run the given statements, in order, inside ONE local transaction and
1707
+ * resolve one {@link Results} per statement. All-or-nothing — a statement that throws rolls the whole list
1708
+ * back and rejects with its error; an empty list resolves `[]` without opening a transaction at all.
1709
+ *
1710
+ * The seam exists for a consumer that owns LOCAL-ONLY tables pgxsinkit does not manage (a definition cache,
1711
+ * a personal dictionary — anything that must delete-then-insert without a torn intermediate state). It is
1712
+ * the ONLY way to get that atomicity on a worker-attached client, where the tab has no pgwasm of its own,
1713
+ * and it behaves identically on both client forms rather than making atomicity depend on where the engine
1714
+ * happens to live.
1715
+ *
1716
+ * Every {@link rawQuery} caveat still holds, transaction or not: the statements run raw against the local
1717
+ * store, BYPASSING the mutation journal and optimistic overlay, so a write through here stays local and
1718
+ * will NEVER converge. Use it for the tables the consumer owns — never for a synced table, whose only
1719
+ * write path is `mutate` / `tables.*`.
1720
+ *
1721
+ * A statement may carry {@link RawStatement.blob}: the bytes of a `COPY … FROM '/dev/blob'` BULK load
1722
+ * ({@link buildCopyFromBlobStatement} renders the pair). That is how a chunk of thousands of rows lands
1723
+ * in one statement instead of one INSERT per row — and, in a list, atomically alongside whatever must
1724
+ * land with it. On a worker-attached client those bytes are TRANSFERRED, never copied, so the caller's
1725
+ * buffer is detached when the call dispatches.
1726
+ */
1727
+ rawTransaction: (statements: readonly RawStatement[], options?: RawQueryOptions) => Promise<Results[]>;
1610
1728
  /**
1611
1729
  * @internal The worker host's guarded one-shot read seam (ADR-0032 decision 4): {@link rawQuery} PLUS the
1612
1730
  * ADR-0041 read gate and the ADR-0021 lazy-group guard, sharing one gate+guard core with the in-process
1613
1731
  * `query`/`queryRaw` builder path so the two entry points can never drift on guard semantics.
1614
1732
  * `defineSyncWorker` dispatches the `guardedQuery` RpcOp to this on its owned in-process client; the attach
1615
1733
  * client's Drizzle-over-bridge compiles the SQL on the tab and routes the read here so the guard runs
1616
- * worker-side. Accepts the full PGlite {@link QueryOptions} (the worker re-applies drizzle's identity
1734
+ * worker-side. Accepts the full pgwasm {@link QueryOptions} (the worker re-applies drizzle's identity
1617
1735
  * parsers here — temporal OIDs + numeric[]) plus the raw-fragment `use` list. NOT part of the app-facing
1618
1736
  * read surface — reach for {@link query} / {@link queryRaw} instead; kept `@internal` (above) and excluded
1619
1737
  * from the generated API docs (typedoc excludeInternal).
@@ -1659,8 +1777,19 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1659
1777
  */
1660
1778
  ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;
1661
1779
  /**
1662
- * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`
1663
- * relation; true for eager relations once boot completes (and always when sync is disabled).
1780
+ * Whether a relation's consistency group is STARTED (ADR-0021) — a durable subscription for it exists,
1781
+ * so reads of it are meaningful. The synchronous peek, for guards and render paths that cannot await.
1782
+ *
1783
+ * For an ordinary group that coincides with caught up: it reads `false` while the group is activated but
1784
+ * still catching up, and `true` once its catch-up lands. A **promoted** `lazy + persistent` group (one a
1785
+ * previous session activated, so boot starts it) reads `true` from boot — including offline, while its
1786
+ * subscribe is still retrying — because its local table is durable and populated, which is what "started"
1787
+ * asks. A dormant `lazy` relation reads `false`, as does every relation while sync is PENDING (enabled but
1788
+ * not yet wired, ADR-0041); every key reads `true` when sync is DISABLED (local-only — nothing is dormant).
1789
+ *
1790
+ * Catch-up COMPLETION is the separate, strictly stronger question {@link groupReady} answers. A
1791
+ * worker-attached client answers this from a snapshot the worker computes with this same method on its own
1792
+ * client (ADR-0059), so the two modes cannot diverge.
1664
1793
  */
1665
1794
  isSynced: (key: SyncTableName<TRegistry>) => boolean;
1666
1795
  /**
@@ -1739,9 +1868,9 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1739
1868
  hydratingTablesFor: (query: { sql: string; use?: readonly string[] }) => readonly string[];
1740
1869
  /**
1741
1870
  * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
1742
- * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`
1871
+ * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pgwasm.live`
1743
1872
  * directly), so they run unchanged against both the in-process client (which implements it over
1744
- * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the
1873
+ * `pgwasm.live`) and the worker-attached client (which implements it over the bridge). Prefer the
1745
1874
  * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.
1746
1875
  */
1747
1876
  subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(
@@ -1763,8 +1892,8 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1763
1892
  */
1764
1893
  liveQueryDiagnostics: () => Promise<LiveQueryDiagnostics[]>;
1765
1894
  /**
1766
- * Take a **store backup** (ADR-0035): a full-fidelity, PGlite-restorable tarball of the whole local
1767
- * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via PGlite's
1895
+ * Take a **store backup** (ADR-0035): a full-fidelity, pgwasm-restorable tarball of the whole local
1896
+ * store — synced cache, Overlay, and Mutation journal (unflushed writes included) — via pgwasm's
1768
1897
  * `dumpDataDir`. Taken LIVE (a `CHECKPOINT` serialised behind engine work, then the dump; no engine
1769
1898
  * suspension, no tab disruption), so it never blocks and is the only lossless export an offline device
1770
1899
  * with unflushed writes can take. Awaits engine-ready rather than rejecting during boot, then runs under
@@ -1813,16 +1942,88 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1813
1942
  export type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind, MutationSummary };
1814
1943
 
1815
1944
  /**
1816
- * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept
1945
+ * The structured-clone-safe subset of pgwasm's `QueryOptions` the inspection surface carries. Kept
1817
1946
  * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via
1818
1947
  * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part
1819
- * of this contract. `rowMode: "array"` is what `@electric-sql/pglite-repl` asks for on every exec.
1948
+ * of this contract. `rowMode: "array"` is what `@pgxsinkit/pgwasm-repl` asks for on every exec.
1949
+ *
1950
+ * `blob` diverges from pgwasm's own type for the same reason: pgwasm takes a `Blob`, which is neither
1951
+ * transferable nor (usefully) clonable, so this contract carries BYTES and wraps them into the `Blob` at
1952
+ * the pgwasm call (ADR-0061).
1820
1953
  */
1821
1954
  export interface RawQueryOptions {
1822
1955
  rowMode?: "object" | "array";
1956
+ /**
1957
+ * The bytes pgwasm reads when the statement is a `COPY … FROM '/dev/blob'` — the single-statement form
1958
+ * of {@link RawStatement.blob}, for a bulk load that needs no surrounding transaction. Build the
1959
+ * statement AND these bytes together with {@link buildCopyFromBlobStatement}; any other statement
1960
+ * ignores this option.
1961
+ *
1962
+ * On a worker-attached client the buffer is **TRANSFERRED**, not copied: it is detached the moment the
1963
+ * call dispatches, so the caller must NOT read or reuse it afterwards (build a fresh one per chunk).
1964
+ *
1965
+ * Typed over a real `ArrayBuffer` (not the default `ArrayBufferLike`) because that IS the contract: a
1966
+ * `SharedArrayBuffer`-backed view can neither be transferred nor read as a `Blob` part.
1967
+ */
1968
+ blob?: Uint8Array<ArrayBuffer>;
1969
+ }
1970
+
1971
+ /**
1972
+ * One statement of a {@link SyncClient.rawTransaction} list: the SQL plus its bound params, and optionally
1973
+ * the `blob` bytes a `COPY` statement ingests. Structured-clone safe by construction (a string, plain
1974
+ * values and a `Uint8Array`), because on a worker-attached client the whole list crosses the bridge in a
1975
+ * single RPC.
1976
+ */
1977
+ export interface RawStatement {
1978
+ readonly sql: string;
1979
+ readonly params?: readonly unknown[];
1980
+ /**
1981
+ * The bytes pgwasm reads for this statement's `/dev/blob` — how a LOCAL-ONLY table an app owns is
1982
+ * BULK-LOADED with `COPY` instead of one INSERT per row. It rides ONLY with a `COPY … FROM '/dev/blob'`
1983
+ * statement; any other statement ignores it. Build the pair with {@link buildCopyFromBlobStatement},
1984
+ * which renders the statement and serializes the rows from ONE column list (and with the same COPY TEXT
1985
+ * serializer the sync applier uses), so the SQL and the bytes cannot disagree.
1986
+ *
1987
+ * **On a worker-attached client the buffer is TRANSFERRED, not copied.** It is listed on the RPC's
1988
+ * `postMessage` transfer list, so it is DETACHED (`byteLength === 0`) the moment the call dispatches:
1989
+ * the caller must not read, reuse or re-send it afterwards — serialize a fresh chunk for each call.
1990
+ * Zero-copy is the point: a 1000-row chunk crosses the bridge without a structured-clone copy.
1991
+ *
1992
+ * Typed over a real `ArrayBuffer` (not the default `ArrayBufferLike`) because that IS the contract: a
1993
+ * `SharedArrayBuffer`-backed view can neither be transferred nor read as a `Blob` part.
1994
+ */
1995
+ readonly blob?: Uint8Array<ArrayBuffer>;
1823
1996
  }
1824
1997
 
1825
- /** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */
1998
+ /**
1999
+ * Translate the raw seam's structured-clone-safe options into the pgwasm `QueryOptions` the store takes:
2000
+ * the COPY body travels as BYTES (a `Uint8Array` — transferable across the worker bridge, unlike a `Blob`)
2001
+ * and pgwasm reads `/dev/blob` from a `Blob`, so it is wrapped HERE, at the one place the two meet.
2002
+ * A statement's own `blob` ({@link RawStatement.blob}) wins over the call-level {@link RawQueryOptions.blob}.
2003
+ */
2004
+ function toPgwasmQueryOptions(
2005
+ options?: RawQueryOptions,
2006
+ statementBlob?: Uint8Array<ArrayBuffer>,
2007
+ ): QueryOptions | undefined {
2008
+ const bytes = statementBlob ?? options?.blob;
2009
+ const rest = withoutCopyBlob(options);
2010
+ if (bytes === undefined) return rest;
2011
+ return { ...rest, blob: new Blob([bytes]) };
2012
+ }
2013
+
2014
+ /**
2015
+ * The same options WITHOUT the COPY bytes — for `rawExec`, whose pgwasm counterpart runs a multi-statement
2016
+ * script through the simple protocol and has no `/dev/blob` hook at all. Dropping the field keeps the raw
2017
+ * trio on ONE options type (a caller can pass the same object to all three) while the COPY body reaches
2018
+ * only the two seams that can actually ingest it.
2019
+ */
2020
+ function withoutCopyBlob(options?: RawQueryOptions): QueryOptions | undefined {
2021
+ if (options === undefined) return undefined;
2022
+ const { blob: _blobBytes, ...rest } = options;
2023
+ return rest;
2024
+ }
2025
+
2026
+ /** The `{ query, exec }` duck `@pgxsinkit/pgwasm-repl` drives, backed by a client's inspection surface. */
1826
2027
  export interface ReplInspectionSurface {
1827
2028
  query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;
1828
2029
  exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;
@@ -1830,9 +2031,9 @@ export interface ReplInspectionSurface {
1830
2031
 
1831
2032
  /**
1832
2033
  * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck
1833
- * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter
1834
- * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is
1835
- * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).
2034
+ * `@pgxsinkit/pgwasm-repl` needs. Identical on the in-process and worker-attached client — on the latter
2035
+ * each statement routes through the worker bridge, so the REPL works even though `client.pgwasm` is
2036
+ * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `pgwasm`).
1836
2037
  * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.
1837
2038
  */
1838
2039
  export function replAdapter(
@@ -1882,7 +2083,7 @@ type SyncGroupsRuntime = CircuitsGroupSyncResult;
1882
2083
  export async function createSyncClient<const TRegistry extends SyncTableRegistry>(
1883
2084
  options: CreateSyncClientOptions<TRegistry>,
1884
2085
  ): Promise<SyncClient<TRegistry>> {
1885
- // Fail fast on a bad keep-alive policy — before any PGlite boot work (ADR-0040 decision 4 — bounded).
2086
+ // Fail fast on a bad keep-alive policy — before any pgwasm boot work (ADR-0040 decision 4 — bounded).
1886
2087
  validateLiveQueryPolicy(options.liveQueries);
1887
2088
  const status: SyncRuntimeStatus = {
1888
2089
  phase: "booting",
@@ -1924,9 +2125,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1924
2125
  rejectBootSettled = reject;
1925
2126
  });
1926
2127
 
1927
- if (options.pgliteInstance && options.precreatedPglite) {
2128
+ if (options.pgwasmInstance && options.precreatedPgwasm) {
1928
2129
  throw new Error(
1929
- "createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, and registry reconciliation).",
2130
+ "createSyncClient: pass at most one of `pgwasmInstance` or `precreatedPgwasm` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, and registry reconciliation).",
1930
2131
  );
1931
2132
  }
1932
2133
 
@@ -1934,9 +2135,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1934
2135
  // the fresh store — so it cannot coexist with a caller-supplied instance (which claims the store already
1935
2136
  // exists and is provisioned). Fail loudly rather than silently ignore one.
1936
2137
  const restoreBoot = options.restoreFrom != null;
1937
- if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
2138
+ if (restoreBoot && (options.pgwasmInstance || options.precreatedPgwasm)) {
1938
2139
  throw new Error(
1939
- "createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` — restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).",
2140
+ "createSyncClient: `restoreFrom` is mutually exclusive with `pgwasmInstance` / `precreatedPgwasm` — 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).",
1940
2141
  );
1941
2142
  }
1942
2143
 
@@ -1968,7 +2169,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1968
2169
  const engineHome: BootReport["engineHome"] | undefined = bootMode === "worker" ? options.engineHome : "in-process";
1969
2170
 
1970
2171
  // Boot observability (ADR-0034): build a structured report across the boot, finalized once at initial
1971
- // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the PGlite create).
2172
+ // sync. Created FIRST so its monotonic anchor precedes every timed phase (including the pgwasm create).
1972
2173
  const bootReportBuilder: BootReportBuilder = createBootReportBuilder({
1973
2174
  mode: bootMode,
1974
2175
  freshStore: options.freshStore === true,
@@ -1998,7 +2199,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
1998
2199
  const backendOverride = testStoreMarker === "memory" ? ("memory" as const) : undefined;
1999
2200
 
2000
2201
  // Bind the create options once for the two client-owned create paths (fresh `storePath`, and the
2001
- // `precreatedPglite` reject-fallback), so both consume the same pre-warm + resolve the same backend.
2202
+ // `precreatedPgwasm` reject-fallback), so both consume the same pre-warm + resolve the same backend.
2002
2203
  // ADR-0049 step 11c: the OPFS-home grant the client-owned mint opens under. Starts at the placement probe's
2003
2204
  // value and is ADJUSTED DOWN to `false` by the pre-mint phase machine (an existing idb store is opened in
2004
2205
  // place — the backend is fixed at first mint). Read at mint time by `timedCreate` below, so the phase machine
@@ -2019,14 +2220,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2019
2220
  // declaration (`options.storage`, the ADR-0050 internal carrier; absent for in-process consumers). An
2020
2221
  // explicit disagreement is a typed refusal (the worker handlers refuse conflicts before this throws).
2021
2222
  // The resolved mode threads into every client-owned mint (its own boot create and the precreated-reject
2022
- // fallback) via the internal carrier on `createClientPGlite`; no open site takes a durability option, so
2223
+ // fallback) via the internal carrier on `createPgwasmClient`; no open site takes a durability option, so
2023
2224
  // no mint can contradict the data contract.
2024
- const resolvedDurability: StorageDurability = resolveStorageDeclaration(
2025
- getSyncRegistryStorage(options.registry),
2026
- options.storage,
2027
- ).durability;
2028
- const createClientOptions: CreateClientPGliteOptions = {
2029
- ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
2225
+ const resolvedDeclaration = resolveStorageDeclaration(getSyncRegistryStorage(options.registry), options.storage);
2226
+ const resolvedDurability: StorageDurability = resolvedDeclaration.durability;
2227
+ // ADR-0063: the declared Postgres build (default `"c"`). A client-owned mint runs on the supplied build
2228
+ // (`options.build`, else `cBuild`), which must be the declared one; an adopted instance's `pg.build` must too.
2229
+ const declaredBuild: StorageBuild = resolvedDeclaration.build;
2230
+ const suppliedBuild = options.build ?? cBuild;
2231
+ const createClientOptions: CreatePgwasmClientOptions = {
2232
+ ...(options.build ? { build: options.build } : {}),
2233
+ declaredBuild,
2234
+ buildCheckSite: "createSyncClient",
2030
2235
  ...(backendOverride ? { backendOverride } : {}),
2031
2236
  durability: resolvedDurability,
2032
2237
  // Restore (ADR-0035 decision 6): seed the fresh store from the backup via `loadDataDir`. Restore is
@@ -2037,6 +2242,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2037
2242
  const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
2038
2243
  let openedStorageBackend: NonNullable<BootReport["storageBackend"]> | undefined;
2039
2244
 
2245
+ // A boot that will mint (no adopted instance) refuses a supplied build that is not the declared one here,
2246
+ // before the restore probe or any meta read touches a store. A `precreatedPgwasm` whose create rejected
2247
+ // mints through `openOwnedStore`, which checks again first.
2248
+ if (!options.pgwasmInstance && !options.precreatedPgwasm) {
2249
+ assertStoreBuild(declaredBuild, suppliedBuild.identity, "createSyncClient");
2250
+ }
2251
+
2040
2252
  // Fresh-target gate (ADR-0035 decision 6): restore refuses a store that already exists — it boots a
2041
2253
  // brand-new store and never overlays a live one. Checked BEFORE the create so we never touch (let alone
2042
2254
  // half-write) an existing datadir. The memory test lane is fresh by construction, so the probe is a no-op.
@@ -2050,20 +2262,23 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2050
2262
  throw new RestoreTargetExistsError(fallbackStorePath);
2051
2263
  }
2052
2264
  }
2053
- // Time a client-owned `createClientPGlite` into `phases.pgliteCreateMs`; an ADOPTED store (spare or
2265
+ // Time a client-owned `createPgwasmClient` into `phases.pgwasmCreateMs`; an ADOPTED store (spare or
2054
2266
  // caller-supplied) leaves it `null` (create ran elsewhere — see the provision block below).
2055
- const timedCreate = async (): Promise<ClientPGlite> => {
2267
+ const timedCreate = async (): Promise<PgwasmClient> => {
2268
+ // The build's warm (if any) settles BEFORE the clock starts: `pgwasmCreateMs` measures the create alone,
2269
+ // never an unfinished warm (`prepare` never rejects; a failed warm is the build's own lazy load).
2270
+ await suppliedBuild.prepare?.();
2056
2271
  const startedAt = performance.now();
2057
2272
  // ADR-0049 step 10b/11c: the OPFS-home grant is spread in at MINT time (not baked into `createClientOptions`),
2058
2273
  // so the pre-mint phase machine that ran just above can settle `bootHasOpfsSyncAccess` first — opening the
2059
2274
  // committed opfs store or the existing idb store. Default absent keeps today's backend.
2060
2275
  // ADR-0049 decision 12: this is the SINGLE client-owned mint seam, so stamp `storageBackend` from the resolved
2061
- // dataDir scheme here — the same resolution `createClientPGlite` performs, so the diagnostic never diverges
2276
+ // dataDir scheme here — the same resolution `createPgwasmClient` performs, so the diagnostic never diverges
2062
2277
  // from the backend actually opened. Covers every client-owned mint (in-process, worker, precreated-fallback).
2063
2278
  const resolvedDataDir = bootHasOpfsSyncAccess
2064
2279
  ? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true })
2065
2280
  : resolveStoreDataDir(fallbackStorePath, backendOverride);
2066
- const created = await createClientPGlite(fallbackStorePath, {
2281
+ const created = await createPgwasmClient(fallbackStorePath, {
2067
2282
  ...createClientOptions,
2068
2283
  ...(bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}),
2069
2284
  });
@@ -2075,26 +2290,21 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2075
2290
  openedStorageBackend = mintedBackend;
2076
2291
  bootReportBuilder.setStorageBackend(mintedBackend);
2077
2292
  }
2078
- bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
2293
+ bootReportBuilder.setPgwasmCreateMs(performance.now() - startedAt);
2079
2294
  return created;
2080
2295
  };
2081
2296
 
2082
2297
  // Refuse a caller-owned instance that is PROVABLY non-persistent (ADR-0036 decision 4), unless a testing
2083
- // acknowledgment is present. `classifyNonPersistentDataDir` inspects the instance's own dataDir (the
2084
- // `ClientPGlite` interface hides it, so via a narrow cast) — the two provably-non-persistent shapes are
2085
- // an undefined dataDir (PGlite's in-memory default) and an explicit memory store. Checked AFTER a
2298
+ // acknowledgment is present. `classifyNonPersistentStorage` inspects the instance's own `storage` — the
2299
+ // provably-non-persistent shapes are a memory store (pgwasm's default, or an explicit `memory://`) and a
2300
+ // filesystem that reports itself non-persistent. Checked AFTER a
2086
2301
  // successful resolution of the BYO promise, so the refusal PROPAGATES rather than being swallowed by the
2087
- // `precreatedPglite` reject-fallback below (which only catches a create that never produced a store).
2088
- const refuseIfNonPersistent = (instance: ClientPGlite): void => {
2302
+ // `precreatedPgwasm` reject-fallback below (which only catches a create that never produced a store).
2303
+ const refuseIfNonPersistent = (instance: PgwasmClient): void => {
2089
2304
  if (testStoreMarker !== undefined) return; // a deliberate test store — acknowledged.
2090
- // An opfs-repacked instance is PROVABLY persistent (a dedicated OPFS directory) yet reports no `dataDir`
2091
- // (custom VFS), so honour its brand before the dataDir classification — otherwise adopting a provisioned
2092
- // opfs store (provision-then-attach, ADR-0049) would be wrongly refused as an in-memory default.
2093
- if (isOpfsRepackedPersistent(instance)) return;
2094
- const observedDataDir = (instance as { dataDir?: string }).dataDir;
2095
- // The two provably-non-persistent shapes: an undefined dataDir (a raw `new PGlite()` in-memory default)
2096
- // and a `memory://` store. Every store the funnel mints carries a real `idb://`/`file://` dataDir string.
2097
- const observed = classifyNonPersistentDataDir(observedDataDir);
2305
+ // An opfs-repacked instance reports `{ kind: "vfs", persistent: true }`, so adopting a provisioned opfs
2306
+ // store (provision-then-attach, ADR-0049) passes; every store the funnel mints is idb/file/opfs.
2307
+ const observed = classifyNonPersistentStorage(instance.storage);
2098
2308
  if (observed !== null) throw new NonPersistentStoreError(observed);
2099
2309
  };
2100
2310
 
@@ -2102,7 +2312,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2102
2312
  // accelerator MUST enter here: recovery/classification precede every persistent mint. Keeping the flow in one
2103
2313
  // closure prevents a rejected eager create from bypassing live `deleting` authority or the OPFS commitment
2104
2314
  // phase machine by jumping straight to `timedCreate()`.
2105
- const openOwnedStore = async (): Promise<ClientPGlite> => {
2315
+ const openOwnedStore = async (): Promise<PgwasmClient> => {
2316
+ // ADR-0063: the build this path mints on must be the declared one, before any meta read or mint.
2317
+ assertStoreBuild(declaredBuild, suppliedBuild.identity, "createSyncClient");
2106
2318
  // A capability-denied browser may inherit an interrupted destroy or an unexposed candidate from an earlier
2107
2319
  // granted engine home, and it may be looking at a store that lives in OPFS it cannot open at all. ONE
2108
2320
  // bounded meta read settles all three before any replacement IDB store is minted: a `deleting` handoff
@@ -2151,39 +2363,44 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2151
2363
  return timedCreate();
2152
2364
  };
2153
2365
 
2154
- let pglite: ClientPGlite;
2155
- // Whether the boot adopted the caller's `precreatedPglite` (vs. falling back to a fresh create) — gates
2366
+ let pgwasm: PgwasmClient;
2367
+ // Whether the boot adopted the caller's `precreatedPgwasm` (vs. falling back to a fresh create) — gates
2156
2368
  // whether the provision stamp is honoured (ADR-0034).
2157
2369
  let adoptedPrecreated = false;
2158
- if (options.pgliteInstance) {
2370
+ if (options.pgwasmInstance) {
2159
2371
  // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps
2160
- // (schema, prepare hooks, and reconciliation) — see the `pgliteInstance` JSDoc. No create here →
2161
- // `pgliteCreateMs` null.
2162
- refuseIfNonPersistent(options.pgliteInstance);
2163
- pglite = options.pgliteInstance;
2164
- } else if (options.precreatedPglite) {
2165
- // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every
2372
+ // (schema, prepare hooks, and reconciliation) — see the `pgwasmInstance` JSDoc. No create here →
2373
+ // `pgwasmCreateMs` null.
2374
+ refuseIfNonPersistent(options.pgwasmInstance);
2375
+ // ADR-0063: the adopted instance's own build must be the declared one.
2376
+ assertStoreBuild(declaredBuild, options.pgwasmInstance.build, "pgwasmInstance");
2377
+ pgwasm = options.pgwasmInstance;
2378
+ } else if (options.precreatedPgwasm) {
2379
+ // The caller created the raw store eagerly via `createPgwasmClient`; the client still owns every
2166
2380
  // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
2167
2381
  // `storePath` create, so the pattern stays a pure accelerator. Reify the promise's outcome first, THEN
2168
2382
  // branch — so the {@link NonPersistentStoreError} refusal runs on a SUCCESSFULLY resolved instance,
2169
2383
  // outside any catch, and PROPAGATES (never swallowed by the reject-fallback, which is only for a create
2170
2384
  // that never produced a store).
2171
- const outcome = await options.precreatedPglite.then(
2385
+ const outcome = await options.precreatedPgwasm.then(
2172
2386
  (instance) => ({ ok: true as const, instance }),
2173
2387
  (error: unknown) => ({ ok: false as const, error }),
2174
2388
  );
2175
2389
  if (outcome.ok) {
2176
2390
  refuseIfNonPersistent(outcome.instance);
2177
- pglite = outcome.instance;
2391
+ // ADR-0063: checked outside the reject-fallback, so the refusal propagates (never swallowed as a
2392
+ // rejected create that falls back to minting on the supplied build).
2393
+ assertStoreBuild(declaredBuild, outcome.instance.build, "precreatedPgwasm");
2394
+ pgwasm = outcome.instance;
2178
2395
  adoptedPrecreated = true;
2179
2396
  } else {
2180
- syncDebug("boot precreated pglite rejected — falling back to storePath create", {
2397
+ syncDebug("boot precreated pgwasm rejected — falling back to storePath create", {
2181
2398
  error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
2182
2399
  });
2183
- pglite = await openOwnedStore();
2400
+ pgwasm = await openOwnedStore();
2184
2401
  }
2185
2402
  } else {
2186
- pglite = await openOwnedStore();
2403
+ pgwasm = await openOwnedStore();
2187
2404
  }
2188
2405
  // ADR-0049 decision 12: stamp the fallback reason once the mint's backend is settled. Guarded on `probeGranted`
2189
2406
  // (an opfs-capable boot) — a plain idb boot never enters the fresh phase machine, so it never sets one.
@@ -2198,10 +2415,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2198
2415
  bootReportBuilder.setStorageFallbackReason(options.storageFallbackReason);
2199
2416
  }
2200
2417
  // ADR-0049 decision 12: a BYO instance / adopted-precreated store was created OUTSIDE the mint seam, so derive
2201
- // its `storageBackend` from the instance's own dataDir where recognisable; an opfs-repacked wrapper (or an
2202
- // unknown scheme) leaves it omitted (`setStorageBackend` is first-wins, so a fallback-create is never clobbered).
2203
- if (options.pgliteInstance != null || adoptedPrecreated) {
2204
- const byoBackend = storageBackendFromDataDir((pglite as { dataDir?: string }).dataDir);
2418
+ // its `storageBackend` from the instance's own `storage` where recognisable; an unknown filesystem leaves it
2419
+ // omitted (`setStorageBackend` is first-wins, so a fallback-create is never clobbered).
2420
+ if (options.pgwasmInstance != null || adoptedPrecreated) {
2421
+ const byoBackend = storageBackendFromStorage(pgwasm.storage);
2205
2422
  if (byoBackend) {
2206
2423
  openedStorageBackend = byoBackend;
2207
2424
  bootReportBuilder.setStorageBackend(byoBackend);
@@ -2214,20 +2431,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2214
2431
  // run, and the memory test lane has no meta machinery at all. The bounded meta read is kicked off HERE and folded
2215
2432
  // into `commitmentBarrierPending` at the milestone below, so it overlaps schema exec instead of preceding it.
2216
2433
  const adoptedCommitmentGate =
2217
- (options.pgliteInstance != null || adoptedPrecreated) &&
2218
- backendOverride !== "memory" &&
2219
- isOpfsRepackedPersistent(pglite)
2434
+ (options.pgwasmInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedStore(pgwasm)
2220
2435
  ? resolveAdoptedCommitmentBarrier(fallbackStorePath)
2221
2436
  : null;
2222
2437
  // The gate's rejection is observed at the milestone (fail closed, invariant 12); this only keeps an unrelated
2223
2438
  // earlier boot failure from surfacing it as an unhandled rejection in the meantime.
2224
2439
  if (adoptedCommitmentGate) void adoptedCommitmentGate.catch(() => undefined);
2225
2440
  // Whether THIS client owns the store's lifecycle (so `destroy()` may run the supervised destruction machine
2226
- // over it). A BYO `pgliteInstance` is the caller's to dispose of; every other provenance is ours.
2227
- const ownsStoreLifecycle = !options.pgliteInstance;
2441
+ // over it). A BYO `pgwasmInstance` is the caller's to dispose of; every other provenance is ours.
2442
+ const ownsStoreLifecycle = !options.pgwasmInstance;
2228
2443
 
2229
2444
  // Provision block (ADR-0034): when the boot adopted a pre-provisioned store and the provisioner stamped
2230
- // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgliteCreateMs`
2445
+ // its create timing, report the spare's initdb cost + how long it sat ready, and leave `pgwasmCreateMs`
2231
2446
  // null (the create was paid at provision time, off this boot's clock).
2232
2447
  if (adoptedPrecreated && options.provisionStamp) {
2233
2448
  const stamp = await options.provisionStamp.catch(() => null);
@@ -2300,7 +2515,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2300
2515
  * report, the activation replay — is written against {@link SyncGroupsRuntime}.
2301
2516
  */
2302
2517
  const startSyncRuntime = (promotedGroups: ReadonlySet<string>): Promise<SyncGroupsRuntime> =>
2303
- startCircuitsSync(pglite, {
2518
+ startCircuitsSync(pgwasm, {
2304
2519
  registry: options.registry,
2305
2520
  controlPlaneUrl: readTransport.controlPlaneUrl,
2306
2521
  streamBaseUrl: readTransport.streamBaseUrl,
@@ -2394,14 +2609,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2394
2609
  armReadSilenceWatchdog();
2395
2610
  },
2396
2611
  onLazyActivated: (groupKey: string) => {
2397
- void writeLazyGroupActivation(pglite, options.registry, groupKey);
2612
+ void writeLazyGroupActivation(pgwasm, options.registry, groupKey);
2398
2613
  },
2399
2614
  });
2400
2615
 
2401
- if (!options.pgliteInstance) {
2616
+ if (!options.pgwasmInstance) {
2402
2617
  if (options.prepareLocalDbBeforeSchema) {
2403
2618
  const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
2404
- await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
2619
+ await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pgwasm));
2405
2620
  }
2406
2621
 
2407
2622
  // Durable-schema fingerprint fast path. The whole block stays inside the
@@ -2409,11 +2624,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2409
2624
  await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
2410
2625
  // (2) The minimal bootstrap first — one small crossing so the `local_schema_fingerprint` read/write
2411
2626
  // below has its `pgxsinkit_local_meta` table before the durable replay is decided.
2412
- await pglite.exec(buildLocalMetaBootstrapSql(options.registry));
2627
+ await pgwasm.exec(buildLocalMetaBootstrapSql(options.registry));
2413
2628
 
2414
2629
  // (3) Generate the durable SQL (JS-only) and hash it; compare with the stored fingerprint.
2415
2630
  const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
2416
- const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
2631
+ const storedFingerprint = await readStoredLocalSchemaFingerprint(pgwasm, options.registry);
2417
2632
 
2418
2633
  if (storedFingerprint === currentFingerprint) {
2419
2634
  // (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.
@@ -2429,8 +2644,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2429
2644
  syncDebug("boot local schema fingerprint mismatch — replaying durable schema", {
2430
2645
  hadStored: storedFingerprint != null,
2431
2646
  });
2432
- await pglite.exec(generateDurableLocalSchemaSql(options.registry));
2433
- await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
2647
+ await pgwasm.exec(generateDurableLocalSchemaSql(options.registry));
2648
+ await writeStoredLocalSchemaFingerprint(pgwasm, options.registry, currentFingerprint);
2434
2649
  bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
2435
2650
  }
2436
2651
 
@@ -2438,13 +2653,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2438
2653
  // crossing when the registry declares no ephemeral entry (the generator returns "").
2439
2654
  const ephemeralSql = generateEphemeralLocalSchemaSql(options.registry);
2440
2655
  if (ephemeralSql.length > 0) {
2441
- await pglite.exec(ephemeralSql);
2656
+ await pgwasm.exec(ephemeralSql);
2442
2657
  }
2443
2658
  });
2444
2659
 
2445
2660
  if (options.prepareLocalDbAfterSchema) {
2446
2661
  const prepareLocalDbAfterSchema = options.prepareLocalDbAfterSchema;
2447
- await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDbAfterSchema(pglite));
2662
+ await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDbAfterSchema(pgwasm));
2448
2663
  }
2449
2664
  }
2450
2665
 
@@ -2462,12 +2677,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2462
2677
  // exist below (a write never fires during boot, so it is a harmless no-op until then).
2463
2678
  let activateOrdinaryWriteTables: ((tables: readonly string[]) => void) | null = null;
2464
2679
  const mutationRuntime = createMutationRuntime({
2465
- db: pglite,
2680
+ db: pgwasm,
2466
2681
  registry: options.registry,
2467
2682
  batchWriteUrl: options.batchWriteUrl,
2468
2683
  // pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
2469
- // supplied their own PGlite — then the marker is never touched and recovery runs unconditionally.
2470
- ownsMetaTable: !options.pgliteInstance,
2684
+ // supplied their own pgwasm — then the marker is never touched and recovery runs unconditionally.
2685
+ ownsMetaTable: !options.pgwasmInstance,
2471
2686
  onOrdinaryEnqueue: (tables) => activateOrdinaryWriteTables?.(tables),
2472
2687
  ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
2473
2688
  ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),
@@ -2482,13 +2697,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2482
2697
  // no driver is stood up), so there is no conditional to get wrong when a registry gains its first stream.
2483
2698
  // The ingestion endpoint is the mutation endpoint's sibling — derived from `batchWriteUrl` unless the
2484
2699
  // consumer names it — and it shares the write path's headers (same ingress, same gateway credentials).
2485
- // A caller-owned PGlite (`pgliteInstance`) never had the toolkit's schema applied, so the Outbox table may
2700
+ // A caller-owned pgwasm (`pgwasmInstance`) never had the toolkit's schema applied, so the Outbox table may
2486
2701
  // not exist: the lane stays unconstructed there, exactly as the meta-table marker is left alone.
2487
2702
  const eventLaneUrl = options.batchEventUrl ?? deriveBatchEventUrl(options.batchWriteUrl);
2488
2703
  const eventLane: EventLaneRuntime | null =
2489
- eventLaneUrl != null && !options.pgliteInstance
2704
+ eventLaneUrl != null && !options.pgwasmInstance
2490
2705
  ? createEventLaneRuntime({
2491
- db: pglite,
2706
+ db: pgwasm,
2492
2707
  registry: options.registry,
2493
2708
  batchEventUrl: eventLaneUrl,
2494
2709
  ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
@@ -2502,7 +2717,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2502
2717
  throw new Error(
2503
2718
  "pgxsinkit: the Event lane is not available on this client — either `batchWriteUrl` is not the canonical " +
2504
2719
  '"…/api/mutations" shape (pass `batchEventUrl` explicitly), or this client adopted a caller-owned ' +
2505
- "`pgliteInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).",
2720
+ "`pgwasmInstance` (whose store pgxsinkit never provisioned, so it has no Outbox).",
2506
2721
  );
2507
2722
  };
2508
2723
 
@@ -2522,16 +2737,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2522
2737
  // quarantine, marker clear — and returns the honest `warmBoot` outcome (ADR-0034).
2523
2738
  const runBootRecoveryStage = async (): Promise<void> => {
2524
2739
  const recoveryOutcome = await bootReportBuilder.phase("journalRecovery", "boot journal recovery", () =>
2525
- mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgliteInstance, restore: restoreBoot }),
2740
+ mutationRuntime.runBootRecovery({ ownsMetaTable: !options.pgwasmInstance, restore: restoreBoot }),
2526
2741
  );
2527
2742
  bootReportBuilder.setJournalRecovery(recoveryOutcome);
2528
2743
  };
2529
2744
 
2530
2745
  const runReconcileStage = async (): Promise<void> => {
2531
- if (options.pgliteInstance) return;
2746
+ if (options.pgwasmInstance) return;
2532
2747
  versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
2533
2748
  reconcileLocalStoreVersion({
2534
- db: pglite,
2749
+ db: pgwasm,
2535
2750
  registry: options.registry,
2536
2751
  runtime: mutationRuntime,
2537
2752
  ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),
@@ -2565,7 +2780,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2565
2780
  await runReconcileStage();
2566
2781
  }
2567
2782
 
2568
- const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
2783
+ const drizzleDb = createDrizzleDatabase(pgwasm, buildSchema(options.registry));
2569
2784
  // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.
2570
2785
  const lazyGuardIndex = buildLazyGuardIndex(options.registry);
2571
2786
 
@@ -2577,7 +2792,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2577
2792
  // still in flight (React StrictMode mount/unmount is the canonical case). `disposed` lets the tail bail at
2578
2793
  // each stage boundary — before setting `isRunning`, before starting sync — so no shape stream starts after a
2579
2794
  // stop; and `stop`/`destroy` await `bootSettled` before teardown so the tail can never exec against a
2580
- // closing PGlite.
2795
+ // closing pgwasm.
2581
2796
  let disposed = false;
2582
2797
  // Resolves the moment `sync` is wired (and the activation buffer replayed); rejects if the boot is disposed
2583
2798
  // or the tail fails before wiring — so a read seam awaiting it in the pre-wire window unblocks rather than
@@ -2600,7 +2815,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2600
2815
  // called while the tail is still in flight (React StrictMode mount/unmount). Flag disposal so the tail bails
2601
2816
  // at its next stage boundary (never starting sync after this), gracefully release any read seam parked on
2602
2817
  // `syncWired` (it then falls through to the local-only path), then AWAIT `bootSettled` — swallowing a tail
2603
- // failure — so the tail has fully SETTLED before teardown touches the engine/PGlite. Any sync the tail did
2818
+ // failure — so the tail has fully SETTLED before teardown touches the engine/pgwasm. Any sync the tail did
2604
2819
  // manage to start is assigned to `sync` by the time this resolves, for the caller's `sync?.unsubscribe()`.
2605
2820
  const quiesceTailForTeardown = async (): Promise<void> => {
2606
2821
  disposed = true;
@@ -2674,7 +2889,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2674
2889
  // client that may have booted with sync off, so the relations cannot be a function of a runtime
2675
2890
  // flag. It is also cheap and idempotent: `IF NOT EXISTS` throughout, and the session-scoped halves
2676
2891
  // (ADR-0042) have to be re-created every boot regardless, since they live in `pg_temp`.
2677
- await migrateSubscriptionMetadataTables({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA });
2892
+ await migrateSubscriptionMetadataTables({ pg: pgwasm, metadataSchema: DEFAULT_METADATA_SCHEMA });
2678
2893
  if (disposed) return;
2679
2894
 
2680
2895
  if (syncEnabled) {
@@ -2685,7 +2900,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2685
2900
  versionEvent?.status === "rebuilt"
2686
2901
  ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
2687
2902
  : options.resetSubscriptionKeys;
2688
- await resetSubscriptionsIfRequested(pglite, resetKeys);
2903
+ await resetSubscriptionsIfRequested(pgwasm, resetKeys);
2689
2904
  // Re-check after the awaited reset: a stop during it must still abort BEFORE the network shape streams
2690
2905
  // start (BLOCKER 2 — cannot start sync after stop).
2691
2906
  if (disposed) return;
@@ -2695,7 +2910,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2695
2910
 
2696
2911
  // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
2697
2912
  // (ADR-0021 §2); the sync engine does no DB read of its own.
2698
- const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
2913
+ const promotedGroups = await readActivatedLazyGroups(pgwasm, options.registry);
2699
2914
  if (disposed) return;
2700
2915
 
2701
2916
  sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startSyncRuntime(promotedGroups));
@@ -3011,14 +3226,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3011
3226
  // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot
3012
3227
  // holds the relation dormant again.
3013
3228
  if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);
3014
- if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);
3229
+ if (groupKey != null) await clearLazyGroupActivation(pgwasm, options.registry, groupKey);
3015
3230
  // CRITICAL: delete the group's persisted stream subscription so a later re-activation re-streams the
3016
3231
  // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we
3017
3232
  // truncate below — leaving the relation permanently missing its pre-desync data.
3018
- if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);
3233
+ if (groupKey != null) await resetSubscriptionsIfRequested(pgwasm, [groupKey]);
3019
3234
  // Clean-truncate every member's local cluster.
3020
3235
  for (const member of groupTableKeys) {
3021
- await pglite.exec(buildDesyncTableSql(options.registry, member as string));
3236
+ await pgwasm.exec(buildDesyncTableSql(options.registry, member as string));
3022
3237
  }
3023
3238
  };
3024
3239
 
@@ -3177,26 +3392,26 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3177
3392
  // The worker host's guarded one-shot read (ADR-0032 decision 4) — `rawQuery` PLUS the shared gate+guard.
3178
3393
  // `defineSyncWorker`'s `guardedQuery` handler calls this on its owned in-process client (re-applying
3179
3394
  // drizzle's identity parsers — temporal OIDs + numeric[] — in `options` first, since that parser map cannot cross the bridge);
3180
- // the attach client's Drizzle-over-bridge routes reads here. Returns the full PGlite `Results` so drizzle's
3395
+ // the attach client's Drizzle-over-bridge routes reads here. Returns the full pgwasm `Results` so drizzle's
3181
3396
  // own result mapping runs on the tab.
3182
3397
  const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
3183
3398
  await gateAndGuardRead(sql, use);
3184
- return pglite.query(sql, params as unknown[] | undefined, options);
3399
+ return pgwasm.query(sql, params as unknown[] | undefined, options);
3185
3400
  };
3186
3401
 
3187
3402
  // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
3188
3403
  // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
3189
3404
  // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
3190
- // settles every un-awaited unsubscribe before `pglite.close()`, subsuming the old pending-teardowns set).
3405
+ // settles every un-awaited unsubscribe before `pgwasm.close()`, subsuming the old pending-teardowns set).
3191
3406
  // It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.
3192
3407
  const liveManager: LiveQueryManager = createLiveQueryManager({
3193
- live: pglite.live,
3408
+ live: pgwasm.live,
3194
3409
  ...(options.liveQueries ? { policy: options.liveQueries } : {}),
3195
3410
  });
3196
3411
 
3197
3412
  const client: SyncClient<TRegistry> = {
3198
3413
  drizzle: drizzleDb,
3199
- pglite,
3414
+ pgwasm,
3200
3415
  views: buildViews(options.registry),
3201
3416
  tables: Object.fromEntries(
3202
3417
  Object.keys(options.registry).map((tableKey) => [
@@ -3226,9 +3441,9 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3226
3441
  haltActivity();
3227
3442
  // ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
3228
3443
  // and await its settlement — so no shape stream is left running and nothing execs against the closing
3229
- // PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
3444
+ // pgwasm. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
3230
3445
  await quiesceTailForTeardown();
3231
- // Await any in-flight convergence pass before closing PGlite, so a pass never queries a
3446
+ // Await any in-flight convergence pass before closing pgwasm, so a pass never queries a
3232
3447
  // closed handle. The Event-lane flush pass is awaited on the same rule, for the same reason.
3233
3448
  await convergenceDriver?.stop();
3234
3449
  await eventFlushDriver?.stop();
@@ -3236,13 +3451,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3236
3451
  status.isRunning = false;
3237
3452
  options.onStatusChange?.(status);
3238
3453
  // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact
3239
- // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
3240
- // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.
3454
+ // point the store's own close used to invoke the former extension's close hook (ADR-0032 S1). Order
3455
+ // preserved: convergence stop → sync unsubscribe → status → engine close → pgwasm close.
3241
3456
  sync?.unsubscribe();
3242
- // Dispose the live-query manager before closing PGlite (ADR-0040 decisions 1 & 6): it cancels any
3243
- // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pglite.close()`.
3457
+ // Dispose the live-query manager before closing pgwasm (ADR-0040 decisions 1 & 6): it cancels any
3458
+ // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pgwasm.close()`.
3244
3459
  await liveManager.dispose();
3245
- await pglite.close();
3460
+ await pgwasm.close();
3246
3461
  },
3247
3462
  destroy: (destroyOptions) =>
3248
3463
  // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can
@@ -3273,7 +3488,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3273
3488
  // ADR-0053 decision 8: the same refusal, for the Event lane's durable state. A non-empty Outbox
3274
3489
  // holds events the SERVER has not yet ruled on, and "never discard without a server verdict" is
3275
3490
  // exactly what at-least-once means on this edge — so a non-forced destroy refuses here too,
3276
- // naming the Outbox so the two causes are never confused.
3491
+ // naming the Outbox so the two causes are never confused. Rows the acked ledger is retaining
3492
+ // (ADR-0060) have HAD their verdict, so they are not "empty: false" and never block a destroy.
3277
3493
  if (eventLane && !(await eventLane.outboxStatus()).empty) {
3278
3494
  throw new Error(
3279
3495
  "destroy() refused: the Outbox still holds staged event(s) awaiting a server verdict. " +
@@ -3289,19 +3505,19 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3289
3505
  sync?.unsubscribe();
3290
3506
  status.isRunning = false;
3291
3507
  options.onStatusChange?.(status);
3292
- await pglite.exec(buildWipeLocalStoreSql(options.registry));
3508
+ await pgwasm.exec(buildWipeLocalStoreSql(options.registry));
3293
3509
  // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
3294
- // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).
3510
+ // the former extension close hook fired during `pgwasm.close()` (ADR-0032 S1).
3295
3511
  sync?.unsubscribe();
3296
- // Dispose the live-query manager before closing PGlite — same close-vs-unsubscribe hang guard as
3512
+ // Dispose the live-query manager before closing pgwasm — same close-vs-unsubscribe hang guard as
3297
3513
  // `stop()` (ADR-0040 decisions 1 & 6).
3298
3514
  await liveManager.dispose();
3299
- await pglite.close();
3515
+ await pgwasm.close();
3300
3516
  // ADR-0049 step 10b: phase-aware destructive lifecycle. The wipe + close above cleared the local store;
3301
3517
  // now finish the store-meta / OPFS-namespace side. Every recorded browser store runs the full destructive
3302
3518
  // lifecycle (set `deleting` → delete commitment
3303
3519
  // sentinel → delete both possible backend stores → delete meta). Wiping application tables and closing
3304
- // PGlite do NOT delete its IndexedDB database; retaining that shell would make the next granted boot
3520
+ // pgwasm do NOT delete its IndexedDB database; retaining that shell would make the next granted boot
3305
3521
  // classify it as an existing recordless idb store instead of a genuinely fresh path. A recordless lifecycle-owned
3306
3522
  // IDB store therefore enters the same machine; memory, filesystem, non-browser, and caller-owned stores
3307
3523
  // have no toolkit browser authority to finish.
@@ -3328,18 +3544,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3328
3544
  // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
3329
3545
  // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
3330
3546
  lifecycleSlot.run("dropReadCache", async () => {
3331
- await pglite.exec(buildDropReadCacheSql(options.registry));
3332
- await pglite.exec(generateLocalSchemaSql(options.registry));
3547
+ await pgwasm.exec(buildDropReadCacheSql(options.registry));
3548
+ await pgwasm.exec(generateLocalSchemaSql(options.registry));
3333
3549
  // A full durable-schema exec re-stamps the durable-schema fingerprint (slice 3): exec and stamp
3334
3550
  // travel together so the next boot's fast path can trust the rebuilt cache's fingerprint.
3335
3551
  await writeStoredLocalSchemaFingerprint(
3336
- pglite,
3552
+ pgwasm,
3337
3553
  options.registry,
3338
3554
  computeLocalSchemaFingerprint(options.registry),
3339
3555
  );
3340
3556
  // Reset the read-path subscriptions so the rebuilt synced tables re-stream from scratch
3341
3557
  // rather than the bookkeeping believing they are already caught up (ADR-0006).
3342
- await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
3558
+ await resetSubscriptionsIfRequested(pgwasm, allGroupSubscriptionKeys(options.registry));
3343
3559
  })
3344
3560
  );
3345
3561
  },
@@ -3409,12 +3625,41 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3409
3625
  ...(eventLane ? { outbox: await eventLane.outboxStatus() } : {}),
3410
3626
  }),
3411
3627
  // The registry-wide mutation-status API (slice 4). Assigned just below the object so it can close over
3412
- // this client's own `subscribeLiveRows` + `pglite.query` seams — the SAME factory the worker facade uses.
3628
+ // this client's own `subscribeLiveRows` + `pgwasm.query` seams — the SAME factory the worker facade uses.
3413
3629
  mutations: undefined as unknown as MutationsApi<TRegistry>,
3414
3630
  // Inspection surface (see the interface doc): straight through to the underlying store, no journal /
3415
3631
  // overlay involvement. The worker facade runs the identical call inside the worker's own client.
3416
- rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),
3417
- rawExec: (sql, options) => pglite.exec(sql, options),
3632
+ // `options.blob` is the single-statement COPY form: the bytes are wrapped into the `Blob` pgwasm reads
3633
+ // from `/dev/blob` (see {@link toPgwasmQueryOptions}) — a bulk load that needs no transaction around it.
3634
+ rawQuery: (sql, params, options) =>
3635
+ pgwasm.query(sql, params as unknown[] | undefined, toPgwasmQueryOptions(options)),
3636
+ // `rawExec` takes no blob: pgwasm's `exec` runs a multi-statement script through the simple protocol,
3637
+ // which has no `/dev/blob` hook — a COPY-from-blob load goes through `rawQuery`/`rawTransaction`.
3638
+ rawExec: (sql, options) => pgwasm.exec(sql, withoutCopyBlob(options)),
3639
+ // The atomic form of the same surface. `pgwasm.transaction` opens ONE transaction and rolls it back on a
3640
+ // throw, so the all-or-nothing guarantee is the store's, not a re-implementation here. An empty list is
3641
+ // answered without touching the store at all — an empty transaction would be pure overhead on the single
3642
+ // WASM thread (and, in worker mode, would serialise behind whatever else the engine is doing).
3643
+ rawTransaction: async (statements, options) => {
3644
+ if (statements.length === 0) {
3645
+ return [];
3646
+ }
3647
+ return pgwasm.transaction(async (tx) => {
3648
+ const results: Results[] = [];
3649
+ for (const statement of statements) {
3650
+ // A statement carrying `blob` is a `COPY … FROM '/dev/blob'` bulk load: its bytes become the
3651
+ // `Blob` pgwasm reads, for THAT statement only. Every other statement is unaffected.
3652
+ results.push(
3653
+ await tx.query(
3654
+ statement.sql,
3655
+ statement.params as unknown[] | undefined,
3656
+ toPgwasmQueryOptions(options, statement.blob),
3657
+ ),
3658
+ );
3659
+ }
3660
+ return results;
3661
+ });
3662
+ },
3418
3663
  // @internal: the guarded raw-SQL read the worker host dispatches `guardedQuery` to (ADR-0032 decision 4).
3419
3664
  guardedRawQuery,
3420
3665
  query: (build) => runGuardedQuery(build),
@@ -3436,13 +3681,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3436
3681
  groupReady: groupReadyForTable,
3437
3682
  hydratingTablesFor,
3438
3683
  // The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical
3439
- // contract to the pre-adoption inline `pglite.live.query` seam, but with dedup of identical concurrent
3684
+ // contract to the pre-adoption inline `pgwasm.live.query` seam, but with dedup of identical concurrent
3440
3685
  // subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff
3441
3686
  // stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a
3442
3687
  // per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
3443
3688
  // public `onRows(rows)` / `initialRows` contract is byte-unchanged — and unchanged rows now keep `===`
3444
3689
  // identity across diffs (a bonus the raw `results.rows` path did not give). Keyless (no `pkColumns`)
3445
- // exactly as the inline seam was: PGlite's `live.query` + the manager's value-identity diff.
3690
+ // exactly as the inline seam was: pgwasm's `live.query` + the manager's value-identity diff.
3446
3691
  subscribeLiveRows: async ({ sql, params, fields, use, keepAliveMs }, onRows) => {
3447
3692
  // Read gate (ADR-0041): do not register a live query before the local-read core has finished (a
3448
3693
  // settled-promise await on the steady-state client — cheap, and stage-2-safe).
@@ -3498,7 +3743,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3498
3743
  unsubscribe: () => {
3499
3744
  unsubscribed = true;
3500
3745
  // Non-blocking for the caller; the manager retains the teardown promise so `dispose()` (called by
3501
- // `stop()`/`destroy()`) awaits it before closing PGlite (ADR-0040 decision 1 — the close race).
3746
+ // `stop()`/`destroy()`) awaits it before closing pgwasm (ADR-0040 decision 1 — the close race).
3502
3747
  void subscription.unsubscribe();
3503
3748
  },
3504
3749
  ...(lazyTables.length > 0 ? { lazyTables } : {}),
@@ -3515,13 +3760,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3515
3760
  // Await engine-ready first (ADR-0035: exports wait out a boot rather than rejecting during it), THEN
3516
3761
  // take the lifecycle slot — a concurrent export/lifecycle op is refused with a typed busy error.
3517
3762
  await ready;
3518
- // Name the backup from the configured plain store PATH (ADR-0036), never the PGlite instance's
3763
+ // Name the backup from the configured plain store PATH (ADR-0036), never the pgwasm instance's
3519
3764
  // resolved dataDir URL — a resolved URL is internal plumbing and must not leak into an artefact name
3520
3765
  // as something to imitate. The store id is the path's last segment (see `deriveStoreId`).
3521
3766
  return lifecycleSlot.run("exportStore", () =>
3522
3767
  performStoreExport(
3523
3768
  {
3524
- pglite,
3769
+ pgwasm,
3525
3770
  readMutationStats: () => mutationRuntime.readMutationStats(),
3526
3771
  ...(options.storePath != null ? { storePath: options.storePath } : {}),
3527
3772
  },
@@ -3532,14 +3777,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3532
3777
  exportDiagnostics: async (exportOptions) => {
3533
3778
  // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot
3534
3779
  // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is
3535
- // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pglite`, then
3780
+ // refused with a typed busy error. The diagnostic dump runs the live datadir dump on `pgwasm`, then
3536
3781
  // clones it in memory — the live engine every reference here holds is never closed (the addendum's
3537
3782
  // whole reason for the throwaway clone over the abandoned suspend/reopen seam).
3538
3783
  await ready;
3539
3784
  return lifecycleSlot.run("exportDiagnostics", () =>
3540
3785
  performDiagnosticExport(
3541
3786
  {
3542
- pglite,
3787
+ pgwasm,
3543
3788
  readMutationStats: () => mutationRuntime.readMutationStats(),
3544
3789
  ...(options.storePath != null ? { storePath: options.storePath } : {}),
3545
3790
  },
@@ -3558,7 +3803,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3558
3803
  return lifecycleSlot.run("exportData", () =>
3559
3804
  performDataExport(
3560
3805
  {
3561
- pglite,
3806
+ pgwasm,
3562
3807
  readMutationStats: () => mutationRuntime.readMutationStats(),
3563
3808
  flush: () => mutationRuntime.flush(),
3564
3809
  syncedTableNames: collectDataExportSyncedTableNames(options.registry),
@@ -3573,12 +3818,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3573
3818
  };
3574
3819
 
3575
3820
  // Wire the mutation-status API over this client's shared seams (slice 4): its live-rows seam (over
3576
- // `pglite.live` via the manager) and its one-shot `pglite.query`. The worker facade wires the SAME factory
3821
+ // `pgwasm.live` via the manager) and its one-shot `pgwasm.query`. The worker facade wires the SAME factory
3577
3822
  // over the bridge, so `client.mutations` behaves identically in both modes.
3578
3823
  client.mutations = createMutationsApi({
3579
3824
  registry: options.registry,
3580
3825
  subscribeLiveRows: client.subscribeLiveRows,
3581
- query: (sql, params) => pglite.query<Record<string, unknown>>(sql, params),
3826
+ query: (sql, params) => pgwasm.query<Record<string, unknown>>(sql, params),
3582
3827
  });
3583
3828
 
3584
3829
  // ─── ADR-0049 step 11c: FRESH/RESTORE commitment barrier — the LOCAL-INIT MILESTONE, PRE-EXPOSE ──────────
@@ -3596,7 +3841,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3596
3841
  // `openOwnedStore`, so the fresh flag is necessarily false whenever the gate ran.
3597
3842
  if (adoptedCommitmentGate) commitmentBarrierPending = await adoptedCommitmentGate;
3598
3843
  if (commitmentBarrierPending) {
3599
- await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pglite));
3844
+ await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pgwasm));
3600
3845
  }
3601
3846
 
3602
3847
  // ─── Local-read core complete → resolve `localReadReady`, then run the write/sync tail in the background ──
@@ -3666,7 +3911,7 @@ function allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry:
3666
3911
  return [...new Set(keys)];
3667
3912
  }
3668
3913
 
3669
- async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {
3914
+ async function resetSubscriptionsIfRequested(pgwasm: PgwasmClient, keys: string[] | undefined) {
3670
3915
  if (!keys || keys.length === 0) {
3671
3916
  return;
3672
3917
  }
@@ -3680,23 +3925,18 @@ async function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[
3680
3925
  // No migrate here: boot provisions the metadata relations unconditionally, before this can run.
3681
3926
  await Promise.all(
3682
3927
  uniqueKeys.map((key) =>
3683
- deleteSubscriptionState({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA, subscriptionKey: key }),
3928
+ deleteSubscriptionState({ pg: pgwasm, metadataSchema: DEFAULT_METADATA_SCHEMA, subscriptionKey: key }),
3684
3929
  ),
3685
3930
  );
3686
3931
  }
3687
3932
 
3688
3933
  function createDrizzleDatabase<TRegistry extends SyncTableRegistry>(
3689
- client: ClientPGlite,
3934
+ client: PgwasmClient,
3690
3935
  schema: RegistryTables<TRegistry>,
3691
3936
  ) {
3692
3937
  const relations = defineRelations(schema) as RegistryRelations<TRegistry>;
3693
3938
 
3694
- const createDatabase = drizzle as unknown as (config: {
3695
- client: ClientPGlite;
3696
- relations: RegistryRelations<TRegistry>;
3697
- }) => PgliteDatabase<RegistryRelations<TRegistry>>;
3698
-
3699
- return createDatabase({ client, relations });
3939
+ return drizzle(client, { relations });
3700
3940
  }
3701
3941
 
3702
3942
  function buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
@@ -3717,15 +3957,15 @@ function buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
3717
3957
  * identically. The `client` argument is the executor Drizzle runs against:
3718
3958
  * - Omit it (the default `{}` stub) for a BUILD-ONLY instance — Drizzle only compiles to SQL (`.toSQL()`)
3719
3959
  * and the stub is never invoked; used where execution happens elsewhere (e.g. the live-rows bridge).
3720
- * - Pass a `ClientPGlite`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
3960
+ * - Pass a `PgwasmClient`-shaped BRIDGE executor (its `query` routes to the worker's `guardedQuery` RPC) so
3721
3961
  * that awaiting a builder executes through the bridge and Drizzle's own result mapping (relational/nested
3722
3962
  * queries included) runs on the tab — the one-shot read path `attachSyncClient` wires (ADR-0032 decision 4).
3723
3963
  */
3724
3964
  export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
3725
3965
  registry: TRegistry,
3726
- client: ClientPGlite = {} as ClientPGlite,
3966
+ client: PgwasmClient = {} as PgwasmClient,
3727
3967
  ): {
3728
- drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;
3968
+ drizzle: PgwasmDatabase<RegistryRelations<TRegistry>>;
3729
3969
  views: RegistryViews<TRegistry>;
3730
3970
  /**
3731
3971
  * A drizzle-database FACTORY over this registry's schema (ADR-0032 decision 4): `(client) => db`, reusing
@@ -3733,7 +3973,7 @@ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
3733
3973
  * without recomputing them. `attachSyncClient` uses it to give each `queryRaw`/`queryRawRow` its OWN
3734
3974
  * bridge executor carrying that call's `use` — a scoped db, never a shared mutable stash (no read races).
3735
3975
  */
3736
- drizzleFor: (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>>;
3976
+ drizzleFor: (client: PgwasmClient) => PgwasmDatabase<RegistryRelations<TRegistry>>;
3737
3977
  } {
3738
3978
  const drizzleFor = buildRegistryDrizzleFactory(registry);
3739
3979
  return {
@@ -3751,11 +3991,7 @@ export function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(
3751
3991
  */
3752
3992
  function buildRegistryDrizzleFactory<TRegistry extends SyncTableRegistry>(
3753
3993
  registry: TRegistry,
3754
- ): (client: ClientPGlite) => PgliteDatabase<RegistryRelations<TRegistry>> {
3994
+ ): (client: PgwasmClient) => PgwasmDatabase<RegistryRelations<TRegistry>> {
3755
3995
  const relations = defineRelations(buildSchema(registry)) as RegistryRelations<TRegistry>;
3756
- const createDatabase = drizzle as unknown as (config: {
3757
- client: ClientPGlite;
3758
- relations: RegistryRelations<TRegistry>;
3759
- }) => PgliteDatabase<RegistryRelations<TRegistry>>;
3760
- return (client) => createDatabase({ client, relations });
3996
+ return (client) => drizzle(client, { relations });
3761
3997
  }