@pgxsinkit/client 0.5.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.
package/src/index.ts CHANGED
@@ -672,7 +672,7 @@ export async function createPgwasmClient(
672
672
  // resolution above (ADR-0047's default logic is untouched): `relaxed` → the factory's `"relaxed"`, else
673
673
  // `"strict"`. The open is retried a bounded number of times for transient failures, then propagates.
674
674
  if (dataDir.startsWith("opfs://")) {
675
- const opfsPglite = (await timeAsync(
675
+ const opfsPgwasm = (await timeAsync(
676
676
  "boot pgwasm.create",
677
677
  async () => {
678
678
  const createOpfsStore =
@@ -723,10 +723,10 @@ export async function createPgwasmClient(
723
723
  )) as PgwasmClient;
724
724
  // No brand is needed: the store reports itself as persistent through `pg.storage`, so the BYO
725
725
  // non-persistent guard accepts it when it is adopted as a `precreatedPgwasm` (provision-then-attach).
726
- return opfsPglite;
726
+ return opfsPgwasm;
727
727
  }
728
728
 
729
- const pglite = (await timeAsync(
729
+ const pgwasm = (await timeAsync(
730
730
  "boot pgwasm.create",
731
731
  () => {
732
732
  const createOptions: PgwasmOptions<{ live: typeof live }> = {
@@ -756,7 +756,7 @@ export async function createPgwasmClient(
756
756
  // The raw store is deliberately sync-less here (only `live` is a create-time extension); the sync runtime
757
757
  // never lands on the instance at all (ADR-0032 S1).
758
758
  )) as PgwasmClient;
759
- return pglite;
759
+ return pgwasm;
760
760
  }
761
761
 
762
762
  // ─── ADR-0049 step 11c: FRESH/RESTORE commitment boot wiring ───────────────────────────────────────────
@@ -927,14 +927,14 @@ export async function resolveFreshBoot(
927
927
  * barrier. The barrier requires it (data-before-authority, invariant 3); a store that is not on the OPFS-repacked
928
928
  * filesystem has none, which is a boot invariant violation. `/opfs` is imported lazily, as the factory is.
929
929
  */
930
- function resolveEngineStrictSync(pglite: PgwasmClient): () => Promise<void> {
931
- if (!isOpfsRepackedStore(pglite)) {
930
+ function resolveEngineStrictSync(pgwasm: PgwasmClient): () => Promise<void> {
931
+ if (!isOpfsRepackedStore(pgwasm)) {
932
932
  throw new Error(
933
933
  "[pgxsinkit] fresh commitment: the store is not on the OPFS-repacked filesystem, so it has no strict " +
934
934
  "sync — the commitment barrier requires an OPFS-repacked engine (data-before-authority, invariant 3).",
935
935
  );
936
936
  }
937
- return async () => (await import("@pgxsinkit/pgwasm/opfs")).strictSync(pglite);
937
+ return async () => (await import("@pgxsinkit/pgwasm/opfs")).strictSync(pgwasm);
938
938
  }
939
939
 
940
940
  export async function runFreshCommitmentBarrier(
@@ -1139,15 +1139,15 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1139
1139
  */
1140
1140
  build?: PostgresBuild;
1141
1141
  resetSubscriptionKeys?: string[];
1142
- prepareLocalDbBeforeSchema?: (pglite: PgwasmClient) => Promise<void>;
1143
- prepareLocalDbAfterSchema?: (pglite: PgwasmClient) => Promise<void>;
1142
+ prepareLocalDbBeforeSchema?: (pgwasm: PgwasmClient) => Promise<void>;
1143
+ prepareLocalDbAfterSchema?: (pgwasm: PgwasmClient) => Promise<void>;
1144
1144
  onStatusChange?: (status: SyncRuntimeStatus) => void;
1145
1145
  onTableInitialSync?: (tableKey: string) => void;
1146
1146
  /**
1147
1147
  * A fully-provisioned pgwasm instance the CALLER owns end-to-end. The client runs NONE of its
1148
1148
  * post-create boot steps against it — no schema exec, prepare hooks, or registry reconciliation
1149
1149
  * (journal recovery still runs, as it does on every path). Use it only when the caller has already
1150
- * applied the registry schema itself. Contrast the three PGlite-provenance seams:
1150
+ * applied the registry schema itself. Contrast the three store-provenance seams:
1151
1151
  * - {@link storePath} (default) — the client creates the store AND runs every post-create step.
1152
1152
  * - {@link precreatedPgwasm} — the caller creates the raw store (via {@link createPgwasmClient}), but
1153
1153
  * the client still runs every post-create step (schema, prepare hooks, and reconciliation), exactly as
@@ -1428,7 +1428,7 @@ export interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {
1428
1428
  * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks
1429
1429
  * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle
1430
1430
  * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;
1431
- * 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
1432
1432
  * client runs the live query in the worker and streams DIFFs across the bridge.
1433
1433
  */
1434
1434
  export interface SubscribeLiveRowsInput {
@@ -1543,7 +1543,7 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1543
1543
  * scheduling) without awaiting. Idempotent. The first action of every teardown path — stop()/destroy() call it,
1544
1544
  * and the SharedWorker host calls it before draining subscribes / disposing live queries so no teardown step
1545
1545
  * races a still-live engine. Not a substitute for stop()/destroy(): the awaited teardown (unsubscribe, dispose,
1546
- * pglite.close) still follows. Callers rarely invoke it directly.
1546
+ * pgwasm.close) still follows. Callers rarely invoke it directly.
1547
1547
  */
1548
1548
  haltActivity: () => void;
1549
1549
  stop: () => Promise<void>;
@@ -1868,9 +1868,9 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1868
1868
  hydratingTablesFor: (query: { sql: string; use?: readonly string[] }) => readonly string[];
1869
1869
  /**
1870
1870
  * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered
1871
- * 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`
1872
1872
  * directly), so they run unchanged against both the in-process client (which implements it over
1873
- * `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
1874
1874
  * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.
1875
1875
  */
1876
1876
  subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(
@@ -2001,7 +2001,7 @@ export interface RawStatement {
2001
2001
  * and pgwasm reads `/dev/blob` from a `Blob`, so it is wrapped HERE, at the one place the two meet.
2002
2002
  * A statement's own `blob` ({@link RawStatement.blob}) wins over the call-level {@link RawQueryOptions.blob}.
2003
2003
  */
2004
- function toPgliteQueryOptions(
2004
+ function toPgwasmQueryOptions(
2005
2005
  options?: RawQueryOptions,
2006
2006
  statementBlob?: Uint8Array<ArrayBuffer>,
2007
2007
  ): QueryOptions | undefined {
@@ -2290,7 +2290,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2290
2290
  openedStorageBackend = mintedBackend;
2291
2291
  bootReportBuilder.setStorageBackend(mintedBackend);
2292
2292
  }
2293
- bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
2293
+ bootReportBuilder.setPgwasmCreateMs(performance.now() - startedAt);
2294
2294
  return created;
2295
2295
  };
2296
2296
 
@@ -2363,7 +2363,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2363
2363
  return timedCreate();
2364
2364
  };
2365
2365
 
2366
- let pglite: PgwasmClient;
2366
+ let pgwasm: PgwasmClient;
2367
2367
  // Whether the boot adopted the caller's `precreatedPgwasm` (vs. falling back to a fresh create) — gates
2368
2368
  // whether the provision stamp is honoured (ADR-0034).
2369
2369
  let adoptedPrecreated = false;
@@ -2374,7 +2374,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2374
2374
  refuseIfNonPersistent(options.pgwasmInstance);
2375
2375
  // ADR-0063: the adopted instance's own build must be the declared one.
2376
2376
  assertStoreBuild(declaredBuild, options.pgwasmInstance.build, "pgwasmInstance");
2377
- pglite = options.pgwasmInstance;
2377
+ pgwasm = options.pgwasmInstance;
2378
2378
  } else if (options.precreatedPgwasm) {
2379
2379
  // The caller created the raw store eagerly via `createPgwasmClient`; the client still owns every
2380
2380
  // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal
@@ -2391,16 +2391,16 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2391
2391
  // ADR-0063: checked outside the reject-fallback, so the refusal propagates (never swallowed as a
2392
2392
  // rejected create that falls back to minting on the supplied build).
2393
2393
  assertStoreBuild(declaredBuild, outcome.instance.build, "precreatedPgwasm");
2394
- pglite = outcome.instance;
2394
+ pgwasm = outcome.instance;
2395
2395
  adoptedPrecreated = true;
2396
2396
  } else {
2397
- syncDebug("boot precreated pglite rejected — falling back to storePath create", {
2397
+ syncDebug("boot precreated pgwasm rejected — falling back to storePath create", {
2398
2398
  error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
2399
2399
  });
2400
- pglite = await openOwnedStore();
2400
+ pgwasm = await openOwnedStore();
2401
2401
  }
2402
2402
  } else {
2403
- pglite = await openOwnedStore();
2403
+ pgwasm = await openOwnedStore();
2404
2404
  }
2405
2405
  // ADR-0049 decision 12: stamp the fallback reason once the mint's backend is settled. Guarded on `probeGranted`
2406
2406
  // (an opfs-capable boot) — a plain idb boot never enters the fresh phase machine, so it never sets one.
@@ -2418,7 +2418,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2418
2418
  // its `storageBackend` from the instance's own `storage` where recognisable; an unknown filesystem leaves it
2419
2419
  // omitted (`setStorageBackend` is first-wins, so a fallback-create is never clobbered).
2420
2420
  if (options.pgwasmInstance != null || adoptedPrecreated) {
2421
- const byoBackend = storageBackendFromStorage(pglite.storage);
2421
+ const byoBackend = storageBackendFromStorage(pgwasm.storage);
2422
2422
  if (byoBackend) {
2423
2423
  openedStorageBackend = byoBackend;
2424
2424
  bootReportBuilder.setStorageBackend(byoBackend);
@@ -2431,7 +2431,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2431
2431
  // run, and the memory test lane has no meta machinery at all. The bounded meta read is kicked off HERE and folded
2432
2432
  // into `commitmentBarrierPending` at the milestone below, so it overlaps schema exec instead of preceding it.
2433
2433
  const adoptedCommitmentGate =
2434
- (options.pgwasmInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedStore(pglite)
2434
+ (options.pgwasmInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedStore(pgwasm)
2435
2435
  ? resolveAdoptedCommitmentBarrier(fallbackStorePath)
2436
2436
  : null;
2437
2437
  // The gate's rejection is observed at the milestone (fail closed, invariant 12); this only keeps an unrelated
@@ -2515,7 +2515,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2515
2515
  * report, the activation replay — is written against {@link SyncGroupsRuntime}.
2516
2516
  */
2517
2517
  const startSyncRuntime = (promotedGroups: ReadonlySet<string>): Promise<SyncGroupsRuntime> =>
2518
- startCircuitsSync(pglite, {
2518
+ startCircuitsSync(pgwasm, {
2519
2519
  registry: options.registry,
2520
2520
  controlPlaneUrl: readTransport.controlPlaneUrl,
2521
2521
  streamBaseUrl: readTransport.streamBaseUrl,
@@ -2609,14 +2609,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2609
2609
  armReadSilenceWatchdog();
2610
2610
  },
2611
2611
  onLazyActivated: (groupKey: string) => {
2612
- void writeLazyGroupActivation(pglite, options.registry, groupKey);
2612
+ void writeLazyGroupActivation(pgwasm, options.registry, groupKey);
2613
2613
  },
2614
2614
  });
2615
2615
 
2616
2616
  if (!options.pgwasmInstance) {
2617
2617
  if (options.prepareLocalDbBeforeSchema) {
2618
2618
  const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;
2619
- await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pglite));
2619
+ await bootReportBuilder.phase("prepare", "boot prepare(before-schema)", () => prepareBeforeSchema(pgwasm));
2620
2620
  }
2621
2621
 
2622
2622
  // Durable-schema fingerprint fast path. The whole block stays inside the
@@ -2624,11 +2624,11 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2624
2624
  await bootReportBuilder.phase("schemaExec", "boot local schema", async () => {
2625
2625
  // (2) The minimal bootstrap first — one small crossing so the `local_schema_fingerprint` read/write
2626
2626
  // below has its `pgxsinkit_local_meta` table before the durable replay is decided.
2627
- await pglite.exec(buildLocalMetaBootstrapSql(options.registry));
2627
+ await pgwasm.exec(buildLocalMetaBootstrapSql(options.registry));
2628
2628
 
2629
2629
  // (3) Generate the durable SQL (JS-only) and hash it; compare with the stored fingerprint.
2630
2630
  const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
2631
- const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
2631
+ const storedFingerprint = await readStoredLocalSchemaFingerprint(pgwasm, options.registry);
2632
2632
 
2633
2633
  if (storedFingerprint === currentFingerprint) {
2634
2634
  // (4a) Match → SKIP the durable replay entirely; the persisted durable schema is already current.
@@ -2644,8 +2644,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2644
2644
  syncDebug("boot local schema fingerprint mismatch — replaying durable schema", {
2645
2645
  hadStored: storedFingerprint != null,
2646
2646
  });
2647
- await pglite.exec(generateDurableLocalSchemaSql(options.registry));
2648
- await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
2647
+ await pgwasm.exec(generateDurableLocalSchemaSql(options.registry));
2648
+ await writeStoredLocalSchemaFingerprint(pgwasm, options.registry, currentFingerprint);
2649
2649
  bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
2650
2650
  }
2651
2651
 
@@ -2653,13 +2653,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2653
2653
  // crossing when the registry declares no ephemeral entry (the generator returns "").
2654
2654
  const ephemeralSql = generateEphemeralLocalSchemaSql(options.registry);
2655
2655
  if (ephemeralSql.length > 0) {
2656
- await pglite.exec(ephemeralSql);
2656
+ await pgwasm.exec(ephemeralSql);
2657
2657
  }
2658
2658
  });
2659
2659
 
2660
2660
  if (options.prepareLocalDbAfterSchema) {
2661
2661
  const prepareLocalDbAfterSchema = options.prepareLocalDbAfterSchema;
2662
- await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDbAfterSchema(pglite));
2662
+ await bootReportBuilder.phase("prepare", "boot prepare(local-db)", () => prepareLocalDbAfterSchema(pgwasm));
2663
2663
  }
2664
2664
  }
2665
2665
 
@@ -2677,7 +2677,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2677
2677
  // exist below (a write never fires during boot, so it is a harmless no-op until then).
2678
2678
  let activateOrdinaryWriteTables: ((tables: readonly string[]) => void) | null = null;
2679
2679
  const mutationRuntime = createMutationRuntime({
2680
- db: pglite,
2680
+ db: pgwasm,
2681
2681
  registry: options.registry,
2682
2682
  batchWriteUrl: options.batchWriteUrl,
2683
2683
  // pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` marker table) unless the caller
@@ -2703,7 +2703,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2703
2703
  const eventLane: EventLaneRuntime | null =
2704
2704
  eventLaneUrl != null && !options.pgwasmInstance
2705
2705
  ? createEventLaneRuntime({
2706
- db: pglite,
2706
+ db: pgwasm,
2707
2707
  registry: options.registry,
2708
2708
  batchEventUrl: eventLaneUrl,
2709
2709
  ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),
@@ -2746,7 +2746,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2746
2746
  if (options.pgwasmInstance) return;
2747
2747
  versionEvent = await bootReportBuilder.phase("storeVersionReconcile", "boot store-version reconcile", () =>
2748
2748
  reconcileLocalStoreVersion({
2749
- db: pglite,
2749
+ db: pgwasm,
2750
2750
  registry: options.registry,
2751
2751
  runtime: mutationRuntime,
2752
2752
  ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),
@@ -2780,7 +2780,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2780
2780
  await runReconcileStage();
2781
2781
  }
2782
2782
 
2783
- const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));
2783
+ const drizzleDb = createDrizzleDatabase(pgwasm, buildSchema(options.registry));
2784
2784
  // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.
2785
2785
  const lazyGuardIndex = buildLazyGuardIndex(options.registry);
2786
2786
 
@@ -2889,7 +2889,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2889
2889
  // client that may have booted with sync off, so the relations cannot be a function of a runtime
2890
2890
  // flag. It is also cheap and idempotent: `IF NOT EXISTS` throughout, and the session-scoped halves
2891
2891
  // (ADR-0042) have to be re-created every boot regardless, since they live in `pg_temp`.
2892
- await migrateSubscriptionMetadataTables({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA });
2892
+ await migrateSubscriptionMetadataTables({ pg: pgwasm, metadataSchema: DEFAULT_METADATA_SCHEMA });
2893
2893
  if (disposed) return;
2894
2894
 
2895
2895
  if (syncEnabled) {
@@ -2900,7 +2900,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2900
2900
  versionEvent?.status === "rebuilt"
2901
2901
  ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]
2902
2902
  : options.resetSubscriptionKeys;
2903
- await resetSubscriptionsIfRequested(pglite, resetKeys);
2903
+ await resetSubscriptionsIfRequested(pgwasm, resetKeys);
2904
2904
  // Re-check after the awaited reset: a stop during it must still abort BEFORE the network shape streams
2905
2905
  // start (BLOCKER 2 — cannot start sync after stop).
2906
2906
  if (disposed) return;
@@ -2910,7 +2910,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2910
2910
 
2911
2911
  // Promote any `lazy + persistent` group activated on a previous boot back into the eager set
2912
2912
  // (ADR-0021 §2); the sync engine does no DB read of its own.
2913
- const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);
2913
+ const promotedGroups = await readActivatedLazyGroups(pgwasm, options.registry);
2914
2914
  if (disposed) return;
2915
2915
 
2916
2916
  sync = await bootReportBuilder.phase("syncStart", "boot sync start", () => startSyncRuntime(promotedGroups));
@@ -3226,14 +3226,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3226
3226
  // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot
3227
3227
  // holds the relation dormant again.
3228
3228
  if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);
3229
- if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);
3229
+ if (groupKey != null) await clearLazyGroupActivation(pgwasm, options.registry, groupKey);
3230
3230
  // CRITICAL: delete the group's persisted stream subscription so a later re-activation re-streams the
3231
3231
  // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we
3232
3232
  // truncate below — leaving the relation permanently missing its pre-desync data.
3233
- if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);
3233
+ if (groupKey != null) await resetSubscriptionsIfRequested(pgwasm, [groupKey]);
3234
3234
  // Clean-truncate every member's local cluster.
3235
3235
  for (const member of groupTableKeys) {
3236
- await pglite.exec(buildDesyncTableSql(options.registry, member as string));
3236
+ await pgwasm.exec(buildDesyncTableSql(options.registry, member as string));
3237
3237
  }
3238
3238
  };
3239
3239
 
@@ -3396,22 +3396,22 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3396
3396
  // own result mapping runs on the tab.
3397
3397
  const guardedRawQuery: SyncClient<TRegistry>["guardedRawQuery"] = async (sql, params, options, use) => {
3398
3398
  await gateAndGuardRead(sql, use);
3399
- return pglite.query(sql, params as unknown[] | undefined, options);
3399
+ return pgwasm.query(sql, params as unknown[] | undefined, options);
3400
3400
  };
3401
3401
 
3402
3402
  // The live-query manager (ADR-0040) — the SAME module the worker uses (decision 6), so the in-process
3403
3403
  // client gets one lifecycle contract: dedup of identical concurrent subscriptions within this client,
3404
3404
  // bounded zero-subscriber keep-alive (`options.liveQueries`), and awaited teardown (decision 1 — `dispose()`
3405
- // 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).
3406
3406
  // It cannot dedup across tabs (that is the worker's job) but keeps the contract identical across both forms.
3407
3407
  const liveManager: LiveQueryManager = createLiveQueryManager({
3408
- live: pglite.live,
3408
+ live: pgwasm.live,
3409
3409
  ...(options.liveQueries ? { policy: options.liveQueries } : {}),
3410
3410
  });
3411
3411
 
3412
3412
  const client: SyncClient<TRegistry> = {
3413
3413
  drizzle: drizzleDb,
3414
- pgwasm: pglite,
3414
+ pgwasm,
3415
3415
  views: buildViews(options.registry),
3416
3416
  tables: Object.fromEntries(
3417
3417
  Object.keys(options.registry).map((tableKey) => [
@@ -3451,13 +3451,13 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3451
3451
  status.isRunning = false;
3452
3452
  options.onStatusChange?.(status);
3453
3453
  // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact
3454
- // point PGlite'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 → 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.
3456
3456
  sync?.unsubscribe();
3457
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 `pglite.close()`.
3458
+ // keep-alive timers and awaits every in-flight live `unsubscribe()`, so none races `pgwasm.close()`.
3459
3459
  await liveManager.dispose();
3460
- await pglite.close();
3460
+ await pgwasm.close();
3461
3461
  },
3462
3462
  destroy: (destroyOptions) =>
3463
3463
  // Run inside the SAME lifecycle slot the exports use (ADR-0035 decision 4), so a destructive wipe can
@@ -3505,14 +3505,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3505
3505
  sync?.unsubscribe();
3506
3506
  status.isRunning = false;
3507
3507
  options.onStatusChange?.(status);
3508
- await pglite.exec(buildWipeLocalStoreSql(options.registry));
3508
+ await pgwasm.exec(buildWipeLocalStoreSql(options.registry));
3509
3509
  // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment
3510
- // 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).
3511
3511
  sync?.unsubscribe();
3512
3512
  // Dispose the live-query manager before closing pgwasm — same close-vs-unsubscribe hang guard as
3513
3513
  // `stop()` (ADR-0040 decisions 1 & 6).
3514
3514
  await liveManager.dispose();
3515
- await pglite.close();
3515
+ await pgwasm.close();
3516
3516
  // ADR-0049 step 10b: phase-aware destructive lifecycle. The wipe + close above cleared the local store;
3517
3517
  // now finish the store-meta / OPFS-namespace side. Every recorded browser store runs the full destructive
3518
3518
  // lifecycle (set `deleting` → delete commitment
@@ -3544,18 +3544,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3544
3544
  // racing it would capture a half-rebuilt cache in the artefact (some tables dropped, some re-created,
3545
3545
  // none re-streamed yet). The slot makes the drop+rebuild atomic against any concurrent export.
3546
3546
  lifecycleSlot.run("dropReadCache", async () => {
3547
- await pglite.exec(buildDropReadCacheSql(options.registry));
3548
- await pglite.exec(generateLocalSchemaSql(options.registry));
3547
+ await pgwasm.exec(buildDropReadCacheSql(options.registry));
3548
+ await pgwasm.exec(generateLocalSchemaSql(options.registry));
3549
3549
  // A full durable-schema exec re-stamps the durable-schema fingerprint (slice 3): exec and stamp
3550
3550
  // travel together so the next boot's fast path can trust the rebuilt cache's fingerprint.
3551
3551
  await writeStoredLocalSchemaFingerprint(
3552
- pglite,
3552
+ pgwasm,
3553
3553
  options.registry,
3554
3554
  computeLocalSchemaFingerprint(options.registry),
3555
3555
  );
3556
3556
  // Reset the read-path subscriptions so the rebuilt synced tables re-stream from scratch
3557
3557
  // rather than the bookkeeping believing they are already caught up (ADR-0006).
3558
- await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));
3558
+ await resetSubscriptionsIfRequested(pgwasm, allGroupSubscriptionKeys(options.registry));
3559
3559
  })
3560
3560
  );
3561
3561
  },
@@ -3625,18 +3625,18 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3625
3625
  ...(eventLane ? { outbox: await eventLane.outboxStatus() } : {}),
3626
3626
  }),
3627
3627
  // The registry-wide mutation-status API (slice 4). Assigned just below the object so it can close over
3628
- // 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.
3629
3629
  mutations: undefined as unknown as MutationsApi<TRegistry>,
3630
3630
  // Inspection surface (see the interface doc): straight through to the underlying store, no journal /
3631
3631
  // overlay involvement. The worker facade runs the identical call inside the worker's own client.
3632
3632
  // `options.blob` is the single-statement COPY form: the bytes are wrapped into the `Blob` pgwasm reads
3633
- // from `/dev/blob` (see {@link toPgliteQueryOptions}) — a bulk load that needs no transaction around it.
3633
+ // from `/dev/blob` (see {@link toPgwasmQueryOptions}) — a bulk load that needs no transaction around it.
3634
3634
  rawQuery: (sql, params, options) =>
3635
- pglite.query(sql, params as unknown[] | undefined, toPgliteQueryOptions(options)),
3635
+ pgwasm.query(sql, params as unknown[] | undefined, toPgwasmQueryOptions(options)),
3636
3636
  // `rawExec` takes no blob: pgwasm's `exec` runs a multi-statement script through the simple protocol,
3637
3637
  // which has no `/dev/blob` hook — a COPY-from-blob load goes through `rawQuery`/`rawTransaction`.
3638
- rawExec: (sql, options) => pglite.exec(sql, withoutCopyBlob(options)),
3639
- // The atomic form of the same surface. `pglite.transaction` opens ONE transaction and rolls it back on a
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
3640
  // throw, so the all-or-nothing guarantee is the store's, not a re-implementation here. An empty list is
3641
3641
  // answered without touching the store at all — an empty transaction would be pure overhead on the single
3642
3642
  // WASM thread (and, in worker mode, would serialise behind whatever else the engine is doing).
@@ -3644,7 +3644,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3644
3644
  if (statements.length === 0) {
3645
3645
  return [];
3646
3646
  }
3647
- return pglite.transaction(async (tx) => {
3647
+ return pgwasm.transaction(async (tx) => {
3648
3648
  const results: Results[] = [];
3649
3649
  for (const statement of statements) {
3650
3650
  // A statement carrying `blob` is a `COPY … FROM '/dev/blob'` bulk load: its bytes become the
@@ -3653,7 +3653,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3653
3653
  await tx.query(
3654
3654
  statement.sql,
3655
3655
  statement.params as unknown[] | undefined,
3656
- toPgliteQueryOptions(options, statement.blob),
3656
+ toPgwasmQueryOptions(options, statement.blob),
3657
3657
  ),
3658
3658
  );
3659
3659
  }
@@ -3681,7 +3681,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3681
3681
  groupReady: groupReadyForTable,
3682
3682
  hydratingTablesFor,
3683
3683
  // The live-rows seam, now delegated to the shared `LiveQueryManager` (ADR-0040 decision 6) — identical
3684
- // 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
3685
3685
  // subscriptions, keep-alive (`keepAliveMs`), and awaited teardown for free. The manager delivers a diff
3686
3686
  // stream (`deliverInitial` + `deliverDiff`); we fold it back into FULL ordered row arrays with a
3687
3687
  // per-subscription `LiveRowsMaterializer` (the SAME piece `attachSyncClient` uses tab-side), so the
@@ -3766,7 +3766,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3766
3766
  return lifecycleSlot.run("exportStore", () =>
3767
3767
  performStoreExport(
3768
3768
  {
3769
- pglite,
3769
+ pgwasm,
3770
3770
  readMutationStats: () => mutationRuntime.readMutationStats(),
3771
3771
  ...(options.storePath != null ? { storePath: options.storePath } : {}),
3772
3772
  },
@@ -3777,14 +3777,14 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3777
3777
  exportDiagnostics: async (exportOptions) => {
3778
3778
  // Same lifecycle discipline as `exportStore` (ADR-0035): await engine-ready first (wait out a boot
3779
3779
  // rather than reject during it), THEN take the single slot so a concurrent export/lifecycle op is
3780
- // 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
3781
3781
  // clones it in memory — the live engine every reference here holds is never closed (the addendum's
3782
3782
  // whole reason for the throwaway clone over the abandoned suspend/reopen seam).
3783
3783
  await ready;
3784
3784
  return lifecycleSlot.run("exportDiagnostics", () =>
3785
3785
  performDiagnosticExport(
3786
3786
  {
3787
- pglite,
3787
+ pgwasm,
3788
3788
  readMutationStats: () => mutationRuntime.readMutationStats(),
3789
3789
  ...(options.storePath != null ? { storePath: options.storePath } : {}),
3790
3790
  },
@@ -3803,7 +3803,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3803
3803
  return lifecycleSlot.run("exportData", () =>
3804
3804
  performDataExport(
3805
3805
  {
3806
- pgwasm: pglite,
3806
+ pgwasm,
3807
3807
  readMutationStats: () => mutationRuntime.readMutationStats(),
3808
3808
  flush: () => mutationRuntime.flush(),
3809
3809
  syncedTableNames: collectDataExportSyncedTableNames(options.registry),
@@ -3818,12 +3818,12 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3818
3818
  };
3819
3819
 
3820
3820
  // Wire the mutation-status API over this client's shared seams (slice 4): its live-rows seam (over
3821
- // `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
3822
3822
  // over the bridge, so `client.mutations` behaves identically in both modes.
3823
3823
  client.mutations = createMutationsApi({
3824
3824
  registry: options.registry,
3825
3825
  subscribeLiveRows: client.subscribeLiveRows,
3826
- query: (sql, params) => pglite.query<Record<string, unknown>>(sql, params),
3826
+ query: (sql, params) => pgwasm.query<Record<string, unknown>>(sql, params),
3827
3827
  });
3828
3828
 
3829
3829
  // ─── ADR-0049 step 11c: FRESH/RESTORE commitment barrier — the LOCAL-INIT MILESTONE, PRE-EXPOSE ──────────
@@ -3841,7 +3841,7 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3841
3841
  // `openOwnedStore`, so the fresh flag is necessarily false whenever the gate ran.
3842
3842
  if (adoptedCommitmentGate) commitmentBarrierPending = await adoptedCommitmentGate;
3843
3843
  if (commitmentBarrierPending) {
3844
- await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pglite));
3844
+ await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pgwasm));
3845
3845
  }
3846
3846
 
3847
3847
  // ─── Local-read core complete → resolve `localReadReady`, then run the write/sync tail in the background ──
@@ -3911,7 +3911,7 @@ function allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry:
3911
3911
  return [...new Set(keys)];
3912
3912
  }
3913
3913
 
3914
- async function resetSubscriptionsIfRequested(pglite: PgwasmClient, keys: string[] | undefined) {
3914
+ async function resetSubscriptionsIfRequested(pgwasm: PgwasmClient, keys: string[] | undefined) {
3915
3915
  if (!keys || keys.length === 0) {
3916
3916
  return;
3917
3917
  }
@@ -3925,7 +3925,7 @@ async function resetSubscriptionsIfRequested(pglite: PgwasmClient, keys: string[
3925
3925
  // No migrate here: boot provisions the metadata relations unconditionally, before this can run.
3926
3926
  await Promise.all(
3927
3927
  uniqueKeys.map((key) =>
3928
- deleteSubscriptionState({ pg: pglite, metadataSchema: DEFAULT_METADATA_SCHEMA, subscriptionKey: key }),
3928
+ deleteSubscriptionState({ pg: pgwasm, metadataSchema: DEFAULT_METADATA_SCHEMA, subscriptionKey: key }),
3929
3929
  ),
3930
3930
  );
3931
3931
  }
@@ -4,7 +4,7 @@
4
4
  // journal — the O(writable-table) fan-out the proposal set out to remove.
5
5
  //
6
6
  // It is a FACTORY over the two seams BOTH client modes already share — `subscribeLiveRows` (in-process over
7
- // `pglite.live`; worker-attached over the bridge) and a one-shot `query` (in-process `pglite.query`;
7
+ // `pgwasm.live`; worker-attached over the bridge) and a one-shot `query` (in-process `pgwasm.query`;
8
8
  // worker-attached the `rawQuery` RPC) — so the worker bridge needs ZERO protocol change. Every runtime query
9
9
  // is Drizzle-built over `getAllMutationsView` (tier ①); consumers never touch generated journal relation
10
10
  // names.
@@ -125,7 +125,7 @@ export interface MutationsApiDeps<TRegistry extends SyncTableRegistry> {
125
125
  input: { sql: string; params: readonly unknown[] },
126
126
  onRows: (rows: TRow[]) => void,
127
127
  ) => Promise<{ initialRows: TRow[]; unsubscribe: () => void }>;
128
- /** One-shot query seam (in-process `pglite.query`; worker-attached the `rawQuery` RPC). Rows are UNMAPPED. */
128
+ /** One-shot query seam (in-process `pgwasm.query`; worker-attached the `rawQuery` RPC). Rows are UNMAPPED. */
129
129
  query: (sql: string, params?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
130
130
  }
131
131
 
package/src/store-path.ts CHANGED
@@ -188,10 +188,10 @@ function assertPlainStorePath(storePath: string): void {
188
188
  * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is
189
189
  * internal plumbing; do not surface it to consumers as something to imitate.
190
190
  *
191
- * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
192
- * `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
193
- * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
194
- * exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
191
+ * CRITICAL (ADR-0036 decision 5, probed before the pgwasm switch — ADR-0062): memory selection is ALWAYS the
192
+ * scheme-selected `memory://` form, NEVER pgwasm's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an
193
+ * explicit-`fs` instance silently omits relation files created after initdb, so a restored clone raises "relation
194
+ * does not exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
195
195
  *
196
196
  * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in
197
197
  * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:
@@ -6,17 +6,17 @@ import { drizzle, type PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
6
6
  * `Transaction` — the tier-① authoring/execution surface for the sync engine's metadata-store DML
7
7
  * (ADR-0028 decision 4).
8
8
  *
9
- * The blocker the old convertibility report cited was "`drizzle-orm/pglite` wraps only a pgwasm
10
- * instance, not a Transaction". That is a *type* boundary, not a runtime one: drizzle's pglite session
11
- * layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (verified
12
- * against drizzle-orm 1.0.0-rc.4 `pglite/session.js` — the executor touches nothing but `.query`; the
13
- * only other member it would reach is `.transaction`, and only if someone calls `db.transaction()`).
9
+ * The blocker the old convertibility report cited was "the Drizzle driver wraps only a database
10
+ * instance, not a Transaction". That is a *type* boundary, not a runtime one: the pgwasm driver's session
11
+ * layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (see
12
+ * `@pgxsinkit/pgwasm/drizzle`'s session — the executor touches nothing but `.query`; the only other member
13
+ * it would reach is `.transaction`, and only if someone calls `db.transaction()`).
14
14
  * pgwasm's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle
15
15
  * built over a `Transaction` executes every statement **on that transaction** — participating in the
16
16
  * engine's commit boundary rather than opening its own.
17
17
  *
18
18
  * The cast to `pgwasm` is the narrowest honest one: at runtime the session only calls `.query`, which
19
- * both `PGliteInterface` and `Transaction` satisfy; the type just does not express that union. It is the
19
+ * both `Pgwasm` and `Transaction` satisfy; the type just does not express that union. It is the
20
20
  * expected single-expression cast for this seam.
21
21
  *
22
22
  * CONTRACT: `.transaction()` on the returned handle is **forbidden**. The engine owns transaction
@@ -25,7 +25,7 @@ import { drizzle, type PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
25
25
  * which a `Transaction` is not, and (b) open a nested boundary the engine does not expect. Do not expose
26
26
  * or use it.
27
27
  *
28
- * pgwasm.s driver takes the database as its first argument; a `Transaction` carries the `query` the
28
+ * pgwasm's driver takes the database as its first argument; a `Transaction` carries the `query` the
29
29
  * session needs, hence the cast.
30
30
  */
31
31