@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/store-path.ts CHANGED
@@ -1,6 +1,9 @@
1
- // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker
1
+ import type { StorageDescription } from "@pgxsinkit/pgwasm";
2
+ import { idbDatabaseName } from "@pgxsinkit/pgwasm-c";
3
+
4
+ // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createPgwasmClient`, the worker
2
5
  // attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a
3
- // PGlite storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by
6
+ // pgwasm storage URL. The storage backend is DERIVED from the engine home's capabilities here, never chosen by
4
7
  // the consumer: opfs-repacked when that home holds sync access, IndexedDB as the browser fallback, and the
5
8
  // filesystem on Bun/Node. A memory-backed store is
6
9
  // not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic
@@ -34,20 +37,21 @@ export class InvalidStorePathError extends Error {
34
37
  }
35
38
 
36
39
  /**
37
- * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /
38
- * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its
39
- * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins
40
- * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a
41
- * consumer is never left guessing which store to hand us instead.
40
+ * Thrown when a caller-owned store handed to {@link CreateSyncClientOptions.pgwasmInstance} /
41
+ * {@link CreateSyncClientOptions.precreatedPgwasm} is PROVABLY non-persistent (ADR-0036 decision 4): its
42
+ * `storage` is memory (pgwasm's default — the bare `createPgwasm({ build })` a copy-paste reaches — or an
43
+ * explicit `memory://`), or a filesystem that explicitly reports itself non-persistent. Names both the why (durability
44
+ * semantics assume a persisted store) and the two exits, so a consumer is never left guessing which store to
45
+ * hand us instead.
42
46
  */
43
47
  export class NonPersistentStoreError extends Error {
44
- constructor(observed: "in-memory-default" | "memory-scheme") {
48
+ constructor(observed: NonPersistentStorage) {
45
49
  const reason =
46
- observed === "in-memory-default"
47
- ? "its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)"
48
- : "its dataDir is a memory-backed store";
50
+ observed === "memory"
51
+ ? "its storage is in memory (pgwasm's default without a `dataDir`, or `memory://`)"
52
+ : "its storage is a filesystem that explicitly reports itself non-persistent";
49
53
  super(
50
- `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +
54
+ `[pgxsinkit] refusing a non-persistent store: ${reason}. pgxsinkit's durability semantics ` +
51
55
  "(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store " +
52
56
  "would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a " +
53
57
  "plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with " +
@@ -107,10 +111,10 @@ export function readTestStoreMarker(options: unknown): TestStoreMarker | undefin
107
111
  }
108
112
 
109
113
  /**
110
- * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain
114
+ * What {@link createPgwasmClient} (and any store-opening seam) accepts as its store argument: a plain
111
115
  * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a
112
116
  * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing
113
- * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests("x"))` without a consumer ever
117
+ * helper's output flow STRAIGHT into `createPgwasmClient(memoryStoreForTests("x"))` without a consumer ever
114
118
  * naming a backend.
115
119
  */
116
120
  export type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);
@@ -126,7 +130,7 @@ export function normaliseStorePathInput(input: StorePathInput): { storePath: str
126
130
 
127
131
  /**
128
132
  * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in
129
- * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's
133
+ * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: pgwasm's
130
134
  * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but
131
135
  * Bun/Node do not — so it distinguishes "run in the browser" (idb) from "run on the server" (filesystem)
132
136
  * without a DOM-lib dependency.
@@ -174,7 +178,7 @@ function assertPlainStorePath(storePath: string): void {
174
178
  }
175
179
 
176
180
  /**
177
- * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point
181
+ * Resolve a plain {@link storePath} to the pgwasm dataDir URL the store opens at — the ONE derivation point
178
182
  * (ADR-0036 decision 2, amended by ADR-0049). A browser worker with a proven OPFS sync-access grant resolves
179
183
  * to `opfs://<storePath>`; another browser context (`indexedDB` present) resolves to `idb://<storePath>`;
180
184
  * Bun/Node resolves to `file://<storePath>` (relative paths use the working directory). The `backendOverride`
@@ -184,16 +188,16 @@ function assertPlainStorePath(storePath: string): void {
184
188
  * contract fails loudly at the boundary, never silently re-interpreted. The returned URL is
185
189
  * internal plumbing; do not surface it to consumers as something to imitate.
186
190
  *
187
- * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
188
- * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
189
- * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
190
- * 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`.
191
195
  *
192
196
  * ADR-0049 (D1) adds the `opfs://<storePath>` form: when the placement probe granted a sync-access handle in
193
197
  * the executing scope (`env.hasOpfsSyncAccess`), the browser store lives on `opfs-repacked`. Precedence:
194
198
  * memory override (test/ephemeral) → `opfs://` (probe granted) → `idb://` (browser, handle denied) →
195
- * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — PGlite does NOT accept it as a `dataDir`;
196
- * {@link createClientPGlite} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
199
+ * `file://` (Bun/Node). `opfs://` is TOOLKIT-INTERNAL plumbing — pgwasm does NOT accept it as a `dataDir`;
200
+ * {@link createPgwasmClient} (plan step 10) interprets it via the opfs-repacked factory + the OPFS namespace
197
201
  * builders below. Like every URL resolved here, it never leaks to consumers.
198
202
  */
199
203
  export function resolveStoreDataDir(
@@ -269,8 +273,8 @@ export function storeIdentityComponent(storePath: string): string {
269
273
  * The toolkit-owned OPFS container at the root (ADR-0049 D6). Its child namespaces (`stores`, `commitments`,
270
274
  * `probe`) are DISJOINT so two valid identities can never contend for one OPFS entry (e.g. store `"foo"`'s
271
275
  * commitment sentinel vs a store literally named `"foo.committed"`). This module is the ONLY place that knows
272
- * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the sole owner of the `/pglite/`
273
- * prefix.
276
+ * these names — the same rule that keeps {@link storeIndexedDbDatabaseName} the client's sole route to the
277
+ * IndexedDB database names.
274
278
  */
275
279
  export const OPFS_TOOLKIT_CONTAINER = "pgxsinkit";
276
280
 
@@ -292,6 +296,16 @@ export function opfsCommitmentSentinelPath(storePath: string): readonly [string,
292
296
  return [OPFS_TOOLKIT_CONTAINER, "commitments", storeIdentityComponent(storePath)];
293
297
  }
294
298
 
299
+ /**
300
+ * The Web Lock name of a store's OPFS OWNERSHIP (`store-ownership-lock.ts`): held EXCLUSIVELY by the context
301
+ * that holds the store directory's sync-access handles, from before it opens them until after it closes them,
302
+ * and taken by anything that deletes the directory. Keyed on the same injective identity as the OPFS paths, so
303
+ * two valid identities never share a lock.
304
+ */
305
+ export function storeOwnershipLockName(storePath: string): string {
306
+ return `${OPFS_TOOLKIT_CONTAINER}:store-owner:${storeIdentityComponent(storePath)}`;
307
+ }
308
+
295
309
  /**
296
310
  * OPFS path (segment array) of the placement-probe scratch namespace: `pgxsinkit/probe` (ADR-0049 D6). No
297
311
  * identity — the probe is per-SharedWorker-scope, not per-store. Segments, not a joined string.
@@ -302,11 +316,11 @@ export function opfsProbeDirectoryPath(): readonly [string, string] {
302
316
 
303
317
  /**
304
318
  * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for
305
- * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite
306
- * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`
307
- * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a
308
- * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather
309
- * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as
319
+ * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. pgwasm
320
+ * maps `idb://<storePath>` to the IndexedDB database `/pgwasm/<storePath>` (the IDBFS mount point: its root
321
+ * `/pgwasm` joined with the path after the scheme), and the name comes from `@pgxsinkit/pgwasm-c`'s own
322
+ * `idbDatabaseName`, never re-encoded here. Exposed so a consumer that GCs its own stores routes that
323
+ * pgwasm-internal naming knowledge through the library rather than re-deriving the prefix itself. Rejects a scheme-bearing/empty path exactly as
310
324
  * {@link resolveStoreDataDir} does, so the two stay in lockstep.
311
325
  */
312
326
  export function storeIndexedDbDatabaseName(storePath: string): string {
@@ -320,21 +334,23 @@ export function storeIndexedDbDatabaseName(storePath: string): string {
320
334
  `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,
321
335
  );
322
336
  }
323
- return `/pglite/${storePath}`;
337
+ return idbDatabaseName(storePath);
324
338
  }
325
339
 
340
+ /** The provably-non-persistent storage shapes {@link classifyNonPersistentStorage} reports. */
341
+ export type NonPersistentStorage = "memory" | "non-persistent-vfs";
342
+
326
343
  /**
327
- * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending
328
- * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a
329
- * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,
330
- * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the
331
- * two accidental non-persistent shapes, it is not a storage-backend whitelist).
344
+ * Classify a store's own `pg.storage` for the BYO refusal (ADR-0036 decision 4). Returns the offending shape
345
+ * when the store is PROVABLY non-persistent (`memory`, pgwasm's default or an explicit `memory://`; a `vfs`
346
+ * filesystem explicitly reporting `persistent: false`), or `null` when it passes: `idb`, `file`, a persistent
347
+ * `vfs` (the OPFS-repacked store) and a `vfs` that doesn't declare its persistence (a custom filesystem is
348
+ * the caller's own call). The guard catches the accidental non-persistent shapes; it is not a
349
+ * storage-backend whitelist.
332
350
  */
333
- export function classifyNonPersistentDataDir(
334
- dataDir: string | undefined,
335
- ): "in-memory-default" | "memory-scheme" | null {
336
- if (dataDir == null) return "in-memory-default";
337
- if (dataDir.startsWith("memory://")) return "memory-scheme";
351
+ export function classifyNonPersistentStorage(storage: StorageDescription): NonPersistentStorage | null {
352
+ if (storage.kind === "memory") return "memory";
353
+ if (storage.kind === "vfs" && storage.persistent === false) return "non-persistent-vfs";
338
354
  return null;
339
355
  }
340
356
 
@@ -357,7 +373,7 @@ interface OpfsDirectoryHandle {
357
373
  * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported
358
374
  * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the
359
375
  * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,
360
- * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.
376
+ * exactly as pgwasm's filesystem backend and {@link resolveStoreDataDir} do.
361
377
  * - **`opfs://`** (browser, placement probe granted) — existence of the store DIRECTORY at
362
378
  * `pgxsinkit/stores/<identity>` ({@link opfsStoreDirectoryPath}), walked via
363
379
  * `navigator.storage.getDirectory()` and a `getDirectoryHandle` chain with `{ create: false }`. This is
@@ -372,7 +388,7 @@ interface OpfsDirectoryHandle {
372
388
  * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older
373
389
  * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let
374
390
  * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a
375
- * PGlite-level boot failure. We never fake a positive.
391
+ * pgwasm-level boot failure. We never fake a positive.
376
392
  */
377
393
  export async function storeTargetExists(
378
394
  storePath: string,
@@ -383,7 +399,7 @@ export async function storeTargetExists(
383
399
  if (dataDir.startsWith("memory://")) return false;
384
400
  if (dataDir.startsWith("file://")) {
385
401
  // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and
386
- // cwd-relative paths identically to PGlite's own filesystem backend.
402
+ // cwd-relative paths identically to pgwasm's own filesystem backend.
387
403
  const path = dataDir.slice("file://".length);
388
404
  const { existsSync } = await import("node:fs");
389
405
  return existsSync(path);
package/src/sync/apply.ts CHANGED
@@ -1,13 +1,13 @@
1
- // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
- // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
4
1
  import { and, eq, fillPlaceholders, type SQL, sql } from "drizzle-orm";
5
2
  import { getTableConfig, type PgColumn } from "drizzle-orm/pg-core";
6
3
 
7
- import { quoteIdentifier, type SyncChange, type SyncColumnType, type SyncRow } from "@pgxsinkit/contracts";
4
+ import { jsonUdtName, quoteIdentifier, type SyncChange, type SyncColumnType, type SyncRow } from "@pgxsinkit/contracts";
5
+ // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
6
+ // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
7
+ import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
8
8
 
9
9
  import type { ApplyTarget } from "../local-tables";
10
- import { generateCopyData } from "./copy";
10
+ import { buildCopyFromBlobStatement } from "./copy";
11
11
  import { drizzleOverPg } from "./drizzle-executor";
12
12
  import type { UpsertChangeMessage } from "./types";
13
13
 
@@ -60,7 +60,7 @@ function hasGeneratedIdentityColumn(target: ApplyTarget, colNames: readonly stri
60
60
  * locally-generated one — so OVERRIDING SYSTEM VALUE is the semantically correct clause (and it makes
61
61
  * drizzle re-include the column it would otherwise drop). Tables without a generated column get a plain
62
62
  * insert, so the clause is emitted only where it is required. (The local synced table renders the identity
63
- * PK as a PLAIN column — the generator emits `getSQLType()` with no identity clause — and PGlite accepts
63
+ * PK as a PLAIN column — the generator emits `getSQLType()` with no identity clause — and pgwasm accepts
64
64
  * OVERRIDING SYSTEM VALUE against a plain column as a no-op, so this is safe there too.)
65
65
  */
66
66
  function insertInto(db: ReturnType<typeof drizzleOverPg>, target: ApplyTarget, colNames: readonly string[]) {
@@ -86,7 +86,7 @@ function castTypeFor(column: SyncColumnType, tableSchema: string | undefined): s
86
86
  }
87
87
 
88
88
  export interface ApplyMessageToTableOptions {
89
- pg: PGliteInterface | Transaction;
89
+ pg: Pgwasm | Transaction;
90
90
  target: ApplyTarget;
91
91
  message: SyncChange;
92
92
  debug: boolean;
@@ -121,7 +121,7 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
121
121
  }
122
122
 
123
123
  export interface BulkApplyMessagesToTableOptions {
124
- pg: PGliteInterface | Transaction;
124
+ pg: Pgwasm | Transaction;
125
125
  target: ApplyTarget;
126
126
  messages: UpsertChangeMessage[];
127
127
  debug: boolean;
@@ -163,7 +163,7 @@ function renderInsert(
163
163
  * byte-identical to a plain `.values()` bind), then run the pre-rendered statement on the executor.
164
164
  */
165
165
  async function executeInsertBatch(
166
- pg: PGliteInterface | Transaction,
166
+ pg: Pgwasm | Transaction,
167
167
  db: ReturnType<typeof drizzleOverPg>,
168
168
  target: ApplyTarget,
169
169
  colNames: string[],
@@ -505,19 +505,17 @@ export async function applyUpsertsToTableWithJson(options: BulkApplyMessagesToTa
505
505
 
506
506
  /**
507
507
  * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to
508
- * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by
509
- * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}), never introspected
510
- * (ADR-0029 D2).
508
+ * disambiguate `json`/`jsonb` (whose decoded values are indistinguishable from SQL arrays/objects by
509
+ * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}) through the contracts'
510
+ * `jsonUdtName` — the same classifier the read path's json decode uses, so the serializer and the decode
511
+ * cannot disagree about which columns carry JSON — never introspected (ADR-0029 D2).
511
512
  */
512
513
  function copyColumnUdts(target: ApplyTarget): Record<string, string> {
513
514
  const map: Record<string, string> = {};
514
515
  for (const column of target.columnTypes) {
515
- const base = column.sqlType
516
- .replace(/\(.*\)/g, "")
517
- .trim()
518
- .toLowerCase();
519
- if (base === "json" || base === "jsonb") {
520
- map[column.name] = column.isArray ? `_${base}` : base;
516
+ const udt = jsonUdtName(column);
517
+ if (udt !== undefined) {
518
+ map[column.name] = udt;
521
519
  }
522
520
  }
523
521
  return map;
@@ -534,33 +532,21 @@ export async function applyMessagesToTableWithCopy({ pg, target, messages, debug
534
532
  const columns = Object.keys(firstRow);
535
533
  assertUniformColumnSet(target, columns, data, "applyMessagesToTableWithCopy");
536
534
 
537
- // Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's
538
- // CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),
539
- // json/jsonb, bytea, timestamps and strings with embedded delimiters/newlines all round-trip,
540
- // unlike the previous hand-rolled CSV encoder.
541
- const columnUdts = copyColumnUdts(target);
542
- const copyData = generateCopyData(data, columns, columnUdts);
543
- const copyBlob = new Blob([copyData], { type: "text/plain" });
544
-
545
- // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\N`, both of
546
- // which generateCopyData emits.
547
- //
548
- // Tier ③ (ADR-0028 allow-list): `COPY … FROM '/dev/blob'` is PGlite's blob-ingest grammar — it has no
549
- // Drizzle builder form, so the statement stays a raw string. The table reference is taken from the real
550
- // synced table object: a bare name (ephemeral → `pg_temp` via search_path) or a schema-qualified one.
551
- const { name: tableName, schema } = getTableConfig(target.table);
552
- const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);
553
- await pg.query(
554
- `
555
- COPY ${copyTarget} (${columns.map((column) => quoteIdentifier(column)).join(", ")})
556
- FROM '/dev/blob'
557
- WITH (FORMAT text)
558
- `,
559
- [],
560
- {
561
- blob: copyBlob,
562
- },
563
- );
535
+ // ONE implementation of the COPY-from-blob load, shared with the public raw seam
536
+ // ({@link buildCopyFromBlobStatement}): it renders the tier-③ statement from the REAL table object
537
+ // (`getTableConfig` — a bare name for an ephemeral relation, schema-qualified otherwise) and serializes
538
+ // the rows with Postgres' own COPY TEXT format — a faithful port of the backend's CopyAttributeOutText /
539
+ // array_out routines (see ./copy) — so arrays (incl. multi-dimensional), json/jsonb, bytea, timestamps
540
+ // and strings with embedded delimiters/newlines all round-trip.
541
+ const statement = buildCopyFromBlobStatement({
542
+ table: target.table,
543
+ columns,
544
+ rows: data,
545
+ udtNames: copyColumnUdts(target),
546
+ });
547
+ // The statement carries its body as BYTES (that is what crosses the worker bridge as a transferable on
548
+ // the raw seam); pgwasm reads `/dev/blob` from a `Blob`, so wrap them here.
549
+ await pg.query(statement.sql, [], { blob: new Blob([statement.blob], { type: "text/plain" }) });
564
550
 
565
551
  if (debug) console.log(`Inserted ${messages.length} rows using COPY`);
566
552
  }
@@ -585,7 +571,7 @@ function recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonR
585
571
  }
586
572
 
587
573
  export interface BulkKeyedApplyOptions {
588
- pg: PGliteInterface | Transaction;
574
+ pg: Pgwasm | Transaction;
589
575
  target: ApplyTarget;
590
576
  /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */
591
577
  messages: SyncChange[];
package/src/sync/copy.ts CHANGED
@@ -1,19 +1,26 @@
1
- // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE) —
2
- // specifically a port of the serializer from electric-sql/pglite PR #1035.
3
- // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
1
+ // Ports PostgreSQL's CopyAttributeOutText (src/backend/commands/copyto.c) and array_out
2
+ // (src/backend/utils/adt/arrayfuncs.c) — PostgreSQL License, © The PostgreSQL Global Development Group (see NOTICE).
4
3
  /**
5
4
  * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT
6
5
  * text)` stream.
7
6
  *
8
- * Values reach this module already decoded — the read path hands the applier
9
- * JSON cell values, never Postgres wire text — so the runtime types it accepts
10
- * are the decoded ones: `int2`/`int4`/`float4`/`float8` as `number`, `bool` as
11
- * `boolean`, `json`/`jsonb` as parsed objects/arrays, array columns as
12
- * (possibly nested) JS arrays, `int8` as `bigint`, and every other type as its
13
- * raw Postgres text representation (a `string`). To feed those values back into
7
+ * Values reach this module already decoded, so the runtime types it accepts are
8
+ * the decoded ones: `int2`/`int4`/`float4`/`float8` as `number`, `bool` as
9
+ * `boolean`, `json`/`jsonb` as parsed objects/arrays/scalars, `int8` as
10
+ * `bigint`, and every other type — **array columns included** — as its raw
11
+ * Postgres text representation (a `string`). To feed those values back into
14
12
  * `COPY` we have to reverse that: turn each value into the exact text Postgres'
15
13
  * input functions expect, then apply the COPY framing.
16
14
  *
15
+ * Only the json ones are decoded on the way in, and by exactly one step:
16
+ * `envelopeToChange`'s `decodeJsonColumns` (`../circuits/envelope-to-change`).
17
+ * The wire itself carries EVERY non-int/float/bool cell as Postgres output text
18
+ * — a `jsonb` column included — so without that step the `JSON.stringify` below
19
+ * would encode already-encoded JSON a second time and the column would land as a
20
+ * JSON string scalar. An array column's `array_out` text is deliberately left
21
+ * alone: it passes through {@link valueToText} unchanged and `COPY`'s `array_in`
22
+ * parses it, which is why a `json[]` value here is a `string`, not a JS array.
23
+ *
17
24
  * Rather than invent an escaping scheme (the previous CSV-based approach broke
18
25
  * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the
19
26
  * two relevant PostgreSQL backend routines:
@@ -26,6 +33,12 @@
26
33
  * every built-in type.
27
34
  */
28
35
 
36
+ import { type AnyPgTable, getTableConfig } from "drizzle-orm/pg-core";
37
+
38
+ import { quoteIdentifier } from "@pgxsinkit/contracts";
39
+
40
+ import type { RawStatement } from "../index";
41
+
29
42
  // Defaults for COPY ... WITH (FORMAT text), matching the Postgres backend.
30
43
  const DELIMITER = "\t";
31
44
  const NULL_MARKER = "\\N";
@@ -153,10 +166,10 @@ function jsonArrayToText(arr: ReadonlyArray<unknown>): string {
153
166
 
154
167
  /**
155
168
  * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. These columns
156
- * arrive already run through `JSON.parse`, so the value is the
157
- * decoded JS value (object, array, string, number, boolean or null) and always
158
- * needs `JSON.stringify` to become valid JSON input again — including scalars
159
- * (the string `hi` must be written as `"hi"`).
169
+ * arrive already run through `JSON.parse` (the read path's `decodeJsonColumns`),
170
+ * so the value is the decoded JS value (object, array, string, number, boolean or
171
+ * null) and always needs `JSON.stringify` to become valid JSON input again —
172
+ * including scalars (the string `hi` must be written as `"hi"`).
160
173
  */
161
174
  function jsonToText(value: unknown): string {
162
175
  return JSON.stringify(value);
@@ -177,6 +190,14 @@ const JSON_ARRAY_UDT_NAMES = new Set(["_json", "_jsonb"]);
177
190
  * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates
178
191
  * `json`/`jsonb` columns; when omitted the value's runtime type is used (which
179
192
  * cannot tell a `jsonb` array from a SQL array).
193
+ *
194
+ * PUBLIC (re-exported from the package root) so an app that bulk-loads a table
195
+ * pgxsinkit does not manage writes the SAME COPY TEXT the applier does. The
196
+ * value contract is the one this module's header states: numbers/booleans/
197
+ * bigints as JS primitives, `json`/`jsonb` as **parsed** values (an object, an
198
+ * array, or a scalar — never pre-stringified JSON, which would land as a JSON
199
+ * string), a `Date` or its text for the temporal types, a JS array (or the
200
+ * Postgres array text) for an array column, and every other type as a `string`.
180
201
  */
181
202
  export function serializeCopyValue(value: unknown, udtName?: string): string {
182
203
  if (value === null || value === undefined) return NULL_MARKER;
@@ -194,6 +215,21 @@ export function serializeCopyValue(value: unknown, udtName?: string): string {
194
215
  *
195
216
  * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass
196
217
  * it so `json`/`jsonb` columns serialize correctly.
218
+ *
219
+ * PUBLIC (re-exported from the package root) for an app-owned, pgxsinkit-unmanaged
220
+ * table. Two contracts bind the caller:
221
+ *
222
+ * - **`columns` IS the column list of the COPY statement.** The fields are
223
+ * emitted in exactly this order, so the same array must be named — in the
224
+ * same order — in the `COPY <table> (...)` that ingests the bytes.
225
+ * {@link buildCopyFromBlobStatement} renders both from one array so they
226
+ * cannot drift.
227
+ * - **`columnTypes` keys are DB column names, values are Postgres `udt_name`s**
228
+ * (`text`, `int4`, `jsonb`, `timestamptz`, `_text` for `text[]`, …). Only the
229
+ * json ones (`json`/`jsonb`/`_json`/`_jsonb`) change behaviour — everything
230
+ * else dispatches on the value's runtime type — but passing the full map is
231
+ * harmless. A `json`/`jsonb` value MUST be the parsed value, per
232
+ * {@link serializeCopyValue}.
197
233
  */
198
234
  export function generateCopyData(
199
235
  rows: ReadonlyArray<Record<string, unknown>>,
@@ -204,3 +240,62 @@ export function generateCopyData(
204
240
  .map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER))
205
241
  .join(ROW_SEPARATOR);
206
242
  }
243
+
244
+ /** One shared UTF-8 encoder for the COPY TEXT body — `TextEncoder` is stateless, so module-level. */
245
+ const COPY_TEXT_ENCODER = new TextEncoder();
246
+
247
+ /** The inputs {@link buildCopyFromBlobStatement} renders a COPY-from-blob statement from. */
248
+ export interface CopyFromBlobStatementOptions {
249
+ /**
250
+ * The REAL Drizzle table object to load into — the identifier is read off it with `getTableConfig`,
251
+ * never taken as a hand-written string, so a rename can never leave a stale name in the SQL. A bare
252
+ * (schemaless) table renders unqualified and resolves through `search_path` (that is how the applier
253
+ * reaches an ephemeral relation in `pg_temp`).
254
+ */
255
+ table: AnyPgTable;
256
+ /**
257
+ * The DB column names to load, in order. ONE array drives both halves of the statement: the COPY
258
+ * column list and the field order of the serialized body, so they cannot drift.
259
+ */
260
+ columns: readonly string[];
261
+ /** The rows to load, keyed by DB column name (a key missing from a row is loaded as NULL). */
262
+ rows: ReadonlyArray<Record<string, unknown>>;
263
+ /**
264
+ * DB column name → Postgres `udt_name`, per {@link generateCopyData}. Needed for `json`/`jsonb`
265
+ * (and `_json`/`_jsonb`) columns; ignored for every other type.
266
+ */
267
+ udtNames?: Readonly<Record<string, string | undefined>>;
268
+ }
269
+
270
+ /**
271
+ * Render the `COPY <table> (<columns>) FROM '/dev/blob' WITH (FORMAT text)` statement for `rows`,
272
+ * together with the COPY TEXT bytes pgwasm must read for it — a {@link RawStatement} whose `blob`
273
+ * carries the body (narrowed to a non-optional `blob`: this builder ALWAYS produces one).
274
+ *
275
+ * This is the ONE implementation of the COPY-from-blob load: the sync applier's bulk path
276
+ * (`applyMessagesToTableWithCopy`) and the public raw seam both call it, so an app-owned table
277
+ * bulk-loads on exactly the contract the applier is tested against.
278
+ *
279
+ * Hand it to `rawTransaction` (to bulk-load inside one local transaction, e.g. delete-then-COPY) or
280
+ * to `rawQuery`'s `blob` option for a single statement. On a worker-attached client the bytes are
281
+ * TRANSFERRED, not copied — see {@link RawStatement.blob}: the buffer is detached after the call.
282
+ *
283
+ * Tier ③ (ADR-0028 allow-list), exactly as the applier's copy of this statement was: `COPY … FROM
284
+ * '/dev/blob'` is pgwasm's blob-ingest grammar and has NO Drizzle builder form, so the statement text
285
+ * stays a raw string. Every identifier in it is still derived — the table from `getTableConfig`, each
286
+ * column through `quoteIdentifier` — so nothing in the string is a hand-written identifier.
287
+ */
288
+ export function buildCopyFromBlobStatement({
289
+ table,
290
+ columns,
291
+ rows,
292
+ udtNames,
293
+ }: CopyFromBlobStatementOptions): RawStatement & { blob: Uint8Array<ArrayBuffer> } {
294
+ const { name: tableName, schema } = getTableConfig(table);
295
+ const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);
296
+ const columnList = columns.map((column) => quoteIdentifier(column)).join(", ");
297
+ // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\N`, both of
298
+ // which generateCopyData emits.
299
+ const sql = `COPY ${copyTarget} (${columnList}) FROM '/dev/blob' WITH (FORMAT text)`;
300
+ return { sql, params: [], blob: COPY_TEXT_ENCODER.encode(generateCopyData(rows, columns, udtNames)) };
301
+ }
@@ -1,33 +1,32 @@
1
- import type { PGlite, PGliteInterface, Transaction } from "@electric-sql/pglite";
2
- import { drizzle, type PgliteDatabase } from "drizzle-orm/pglite";
1
+ import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
2
+ import { drizzle, type PgwasmDatabase } from "@pgxsinkit/pgwasm/drizzle";
3
3
 
4
4
  /**
5
- * A Drizzle handle whose executor is an already-open PGlite connection *or* an open PGlite
5
+ * A Drizzle handle whose executor is an already-open pgwasm connection *or* an open pgwasm
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 PGlite
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()`).
14
- * PGlite's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle
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
+ * 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
- * The cast to `PGlite` 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
18
+ * The cast to `pgwasm` is the narrowest honest one: at runtime the session only calls `.query`, which
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
23
23
  * boundaries itself (`pg.transaction(async (tx) => …)` + explicit `tx.rollback()` on unsubscribe, sync
24
- * index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full PGlite,
24
+ * index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full pgwasm,
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
- * MUST be the `{ client }` config form: drizzle's pglite driver destructures `{ connection, client }`
29
- * from a bare first argument, so `drizzle(pg)` misdetects the handle as a config object and silently
30
- * constructs a NEW in-memory PGlite — every statement would then hit an empty, throwaway database.
28
+ * pgwasm's driver takes the database as its first argument; a `Transaction` carries the `query` the
29
+ * session needs, hence the cast.
31
30
  */
32
31
 
33
32
  // One drizzle handle per underlying connection/transaction object. The handle for a given `Transaction`
@@ -35,13 +34,13 @@ import { drizzle, type PgliteDatabase } from "drizzle-orm/pglite";
35
34
  // commit — the tag-store hot path — so memoizing per handle avoids re-wrapping on every statement while
36
35
  // never leaking across transactions (a `Transaction` object is a fresh identity each commit, and the
37
36
  // WeakMap drops it once the commit's closure is collected).
38
- const handles = new WeakMap<PGliteInterface | Transaction, PgliteDatabase<never>>();
37
+ const handles = new WeakMap<Pgwasm | Transaction, PgwasmDatabase<never>>();
39
38
 
40
- /** A (memoized) Drizzle handle over an open PGlite connection or transaction — engine-internal. */
41
- export function drizzleOverPg(pg: PGliteInterface | Transaction): PgliteDatabase<never> {
39
+ /** A (memoized) Drizzle handle over an open pgwasm connection or transaction — engine-internal. */
40
+ export function drizzleOverPg(pg: Pgwasm | Transaction): PgwasmDatabase<never> {
42
41
  let db = handles.get(pg);
43
42
  if (!db) {
44
- db = drizzle({ client: pg as unknown as PGlite }) as PgliteDatabase<never>;
43
+ db = drizzle(pg as unknown as Pgwasm) as PgwasmDatabase<never>;
45
44
  handles.set(pg, db);
46
45
  }
47
46
  return db;
@@ -71,7 +71,7 @@ export interface MetadataTables {
71
71
  * group's sync bookkeeping (cursor + tags) is scoped to the engine session by placing it in `pg_temp`
72
72
  * relations that die with the engine — the cursor's lifetime is mechanically tied to the TEMP cluster
73
73
  * whose rows it indexes. `pg_temp` is a per-session alias Postgres accepts in DML qualification (probed
74
- * on real PGlite), so the DML paths select these objects unchanged. Same relation NAMES as the durable
74
+ * on real pgwasm), so the DML paths select these objects unchanged. Same relation NAMES as the durable
75
75
  * variants, distinguished by schema alone (maintainer ruling).
76
76
  */
77
77
  const SESSION_METADATA_SCHEMA = "pg_temp";