@pgxsinkit/client 0.1.32 → 0.1.40

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 (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,249 @@
1
+ // Store path contract (ADR-0036). The public seams (`createSyncClient`, `createClientPGlite`, the worker
2
+ // attach/provision messages, the board store registry) take a `storePath` — a PLAIN path/name, never a
3
+ // PGlite storage URL. The storage backend is DERIVED from the environment here, never chosen by the
4
+ // consumer: IndexedDB in a browser (or a worker), the filesystem on Bun/Node. A memory-backed store is
5
+ // not a product configuration — pgxsinkit's durability semantics (persistent retention, the optimistic
6
+ // Mutation journal) assume a persisted store — so it exists ONLY behind the explicit testing
7
+ // acknowledgment (`@pgxsinkit/client/testing`), carried into option handling as the module-internal
8
+ // {@link TEST_STORE_BACKEND} symbol.
9
+ //
10
+ // This module is the ONLY place in the toolkit that assembles `idb://` / `file://` / `memory://` URLs (the
11
+ // export machinery's throwaway clone, a later slice, is the one other internal `memory://` site). A
12
+ // resolved URL is internal plumbing: it never leaks into config, results, reports, or errors as something
13
+ // a consumer could copy back into a storePath — hence the scheme-rejection guard below fails the old
14
+ // contract loudly at the boundary rather than silently re-interpreting it.
15
+
16
+ /**
17
+ * Thrown when a `storePath` is not a plain name (ADR-0036 decision 1): it carries a URL scheme (`://`) or
18
+ * is empty/whitespace-only. A distinct type — not a bare `Error` — so a caller can `instanceof`-branch the
19
+ * old dataDir-URL contract from a genuine store failure. The message names the plain-path contract and
20
+ * shows the corrected form, without echoing a resolvable URL a consumer might imitate.
21
+ */
22
+ export class InvalidStorePathError extends Error {
23
+ constructor(message: string) {
24
+ super(`[pgxsinkit] ${message}`);
25
+ this.name = "InvalidStorePathError";
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Thrown when a caller-owned PGlite handed to {@link CreateSyncClientOptions.pgliteInstance} /
31
+ * {@link CreateSyncClientOptions.precreatedPglite} is PROVABLY non-persistent (ADR-0036 decision 4): its
32
+ * `dataDir` is `undefined` (PGlite's in-memory default — the `new PGlite()` a copy-paste reaches) or begins
33
+ * `memory://`. Names both the why (durability semantics assume a persisted store) and the two exits, so a
34
+ * consumer is never left guessing which store to hand us instead.
35
+ */
36
+ export class NonPersistentStoreError extends Error {
37
+ constructor(observed: "in-memory-default" | "memory-scheme") {
38
+ const reason =
39
+ observed === "in-memory-default"
40
+ ? "its dataDir is undefined — PGlite's default is an in-memory store (`new PGlite()`)"
41
+ : "its dataDir is a memory-backed store";
42
+ super(
43
+ `[pgxsinkit] refusing a non-persistent PGlite instance: ${reason}. pgxsinkit's durability semantics ` +
44
+ "(persistent retention, the optimistic Mutation journal) assume a persisted store — a memory store " +
45
+ "would silently forget acked-but-unflushed writes. Either hand a persisted instance (open it under a " +
46
+ "plain store path so the backend is derived), or, for a test/ephemeral store, acknowledge it with " +
47
+ '`memoryStoreForTests` / `testStoreAcknowledgment` from "@pgxsinkit/client/testing" (ADR-0036).',
48
+ );
49
+ this.name = "NonPersistentStoreError";
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Thrown when a restore (`restoreFrom`, ADR-0035 decision 6) targets a store path whose backend store ALREADY
55
+ * exists. Restore is a CREATION-path feature — it boots a brand-new store on `loadDataDir` — and never
56
+ * overlays a live store: silently merging a backup into an existing datadir would corrupt it. A distinct type
57
+ * (not a bare `Error`) so a caller can `instanceof`-branch "target already there" from a genuine boot failure.
58
+ * The remedy is a deliberate manual {@link SyncClient.destroy} of the existing store first (never automatic —
59
+ * dropping a user's local store must be their explicit act).
60
+ */
61
+ export class RestoreTargetExistsError extends Error {
62
+ constructor(storePath: string) {
63
+ super(
64
+ `[pgxsinkit] refusing to restore into ${JSON.stringify(storePath)}: a store already exists at that path. ` +
65
+ "Restore only ever boots a brand-new store (it never overlays an existing one — that would corrupt the " +
66
+ "datadir). Destroy the existing store first (a deliberate `destroy()`), then restore into the now-fresh " +
67
+ "path (ADR-0035 decision 6).",
68
+ );
69
+ this.name = "RestoreTargetExistsError";
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The module-internal marker a testing helper stamps onto the options object so option handling can select
75
+ * the memory backend / unlock the BYO refusal (ADR-0036 decision 3). `Symbol.for` (not a bare `Symbol()`)
76
+ * on purpose: each public entry point is bundled STANDALONE (`scripts/build-public-packages.ts`,
77
+ * `splitting: false`), so a plain module symbol would be DUPLICATED between the main bundle and the
78
+ * `./testing` bundle — two distinct symbols, and the marker set by `./testing` would be invisible to the
79
+ * main entry's reader. The global registry key guarantees ONE symbol across bundles. It is deliberately
80
+ * absent from the main entry's exports and from every public type, so a production consumer cannot name it.
81
+ */
82
+ export const TEST_STORE_BACKEND: unique symbol = Symbol.for("pgxsinkit.internal.testStoreBackend");
83
+
84
+ /**
85
+ * What a testing helper's marker asks of option handling: `"memory"` mints a scheme-selected memory store
86
+ * (and, being ours-under-the-covers, also unlocks the BYO refusal); `"acknowledged"` only unlocks the BYO
87
+ * refusal for a caller who owns the (test) instance themselves. Both are visible, deliberate acts — an
88
+ * import whose name says what it is.
89
+ */
90
+ export type TestStoreMarker = "memory" | "acknowledged";
91
+
92
+ /** An options object that MAY carry the internal testing marker (read via {@link readTestStoreMarker}). */
93
+ export type WithTestStoreMarker = { [TEST_STORE_BACKEND]?: TestStoreMarker };
94
+
95
+ /** Read the internal testing marker off an options object, or `undefined` when none was stamped. */
96
+ export function readTestStoreMarker(options: unknown): TestStoreMarker | undefined {
97
+ if (options == null || typeof options !== "object") return undefined;
98
+ const marker = (options as WithTestStoreMarker)[TEST_STORE_BACKEND];
99
+ return marker === "memory" || marker === "acknowledged" ? marker : undefined;
100
+ }
101
+
102
+ /**
103
+ * What {@link createClientPGlite} (and any store-opening seam) accepts as its store argument: a plain
104
+ * `storePath` string, or the option object a testing helper mints (`memoryStoreForTests(...)`) — carrying a
105
+ * `storePath` plus the invisible internal marker. Accepting the object form is what lets the testing
106
+ * helper's output flow STRAIGHT into `createClientPGlite(memoryStoreForTests("x"))` without a consumer ever
107
+ * naming a backend.
108
+ */
109
+ export type StorePathInput = string | ({ storePath: string } & WithTestStoreMarker);
110
+
111
+ /** Normalise a {@link StorePathInput} to a plain path plus any internal memory-backend override it carried. */
112
+ export function normaliseStorePathInput(input: StorePathInput): { storePath: string; backendOverride?: "memory" } {
113
+ if (typeof input === "string") return { storePath: input };
114
+ return {
115
+ storePath: input.storePath,
116
+ ...(readTestStoreMarker(input) === "memory" ? { backendOverride: "memory" as const } : {}),
117
+ };
118
+ }
119
+
120
+ /**
121
+ * The environment seam the backend derivation reads — factored out so a browser derivation is fakeable in
122
+ * a Bun unit test (there is no `indexedDB` there). `hasIndexedDb` is the browser/worker signal: PGlite's
123
+ * IndexedDB backend needs `indexedDB`, which a browser tab AND a Web/Shared/dedicated worker expose but
124
+ * Bun/Node do not — so it distinguishes "run in the browser" (idb) from "run on the server" (filesystem)
125
+ * without a DOM-lib dependency.
126
+ */
127
+ export interface StoreEnv {
128
+ hasIndexedDb: boolean;
129
+ }
130
+
131
+ /** Detect the ambient store environment off `globalThis` (the library carries no DOM lib dependency). */
132
+ function detectStoreEnv(): StoreEnv {
133
+ return { hasIndexedDb: typeof (globalThis as { indexedDB?: unknown }).indexedDB !== "undefined" };
134
+ }
135
+
136
+ /**
137
+ * Resolve a plain {@link storePath} to the PGlite dataDir URL the store opens at — the ONE derivation point
138
+ * (ADR-0036 decision 2). Browser/worker (`indexedDB` present) → `idb://<storePath>`; Bun/Node → `file://<storePath>`
139
+ * (relative paths resolve against the working directory, exactly as PGlite's filesystem backend does — pass
140
+ * an absolute path if that matters). The `backendOverride` is internal-only: `"memory"` selects a
141
+ * scheme-selected `memory://<storePath>` store for the sanctioned test/ephemeral lanes.
142
+ *
143
+ * Rejects a scheme-bearing or empty/whitespace-only path with {@link InvalidStorePathError} — the storePath
144
+ * contract fails loudly at the boundary, never silently re-interpreted (no-legacy rule). The returned URL is
145
+ * internal plumbing; do not surface it to consumers as something to imitate.
146
+ *
147
+ * CRITICAL (ADR-0036 decision 5, probed on PGlite 0.5.4): memory selection is ALWAYS the scheme-selected
148
+ * `memory://` form, NEVER PGlite's explicit `fs: new MemoryFS()` option — `dumpDataDir` from an explicit-`fs`
149
+ * instance silently omits relation files created after initdb, so a restored clone raises "relation does not
150
+ * exist". Callers that need a memory store must route through this function, never construct `MemoryFS`.
151
+ */
152
+ export function resolveStoreDataDir(
153
+ storePath: string,
154
+ backendOverride?: "memory",
155
+ env: StoreEnv = detectStoreEnv(),
156
+ ): string {
157
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
158
+ throw new InvalidStorePathError(
159
+ 'invalid storePath: expected a non-empty plain store name (e.g. "my-app-store"); received an empty or whitespace-only value (ADR-0036).',
160
+ );
161
+ }
162
+ if (storePath.includes("://")) {
163
+ throw new InvalidStorePathError(
164
+ `invalid storePath ${JSON.stringify(storePath)}: a store path is a plain name, not a storage URL. ` +
165
+ 'Pass just the name (e.g. "my-app-store") — the storage backend (IndexedDB in a browser, the ' +
166
+ "filesystem on Bun/Node) is derived for you; drop the scheme prefix (ADR-0036).",
167
+ );
168
+ }
169
+ if (backendOverride === "memory") return `memory://${storePath}`;
170
+ return env.hasIndexedDb ? `idb://${storePath}` : `file://${storePath}`;
171
+ }
172
+
173
+ /**
174
+ * The IndexedDB database name a browser store occupies (ADR-0036) — a browser-only OPERATIONAL helper for
175
+ * orphan GC / corrupt-store deletion (`indexedDB.deleteDatabase(...)`), NOT part of the create path. PGlite
176
+ * maps `idb://<storePath>` to the IndexedDB database `/pglite/<storePath>` (its `WASM_PREFIX` `/pglite`
177
+ * joined with the path after the scheme; verified against `@electric-sql/pglite` 0.5.4 dist). Exposed so a
178
+ * consumer that GCs its own stores routes that PGlite-internal naming knowledge through the library rather
179
+ * than re-deriving the `/pglite/` prefix itself. Rejects a scheme-bearing/empty path exactly as
180
+ * {@link resolveStoreDataDir} does, so the two stay in lockstep.
181
+ */
182
+ export function storeIndexedDbDatabaseName(storePath: string): string {
183
+ if (typeof storePath !== "string" || storePath.trim().length === 0) {
184
+ throw new InvalidStorePathError(
185
+ "invalid storePath: storeIndexedDbDatabaseName expects a non-empty plain store name (ADR-0036).",
186
+ );
187
+ }
188
+ if (storePath.includes("://")) {
189
+ throw new InvalidStorePathError(
190
+ `invalid storePath ${JSON.stringify(storePath)}: storeIndexedDbDatabaseName expects a plain name, not a storage URL (ADR-0036).`,
191
+ );
192
+ }
193
+ return `/pglite/${storePath}`;
194
+ }
195
+
196
+ /**
197
+ * Classify a PGlite instance's `dataDir` for the BYO refusal (ADR-0036 decision 4). Returns the offending
198
+ * shape when the instance is PROVABLY non-persistent (`undefined` = PGlite's in-memory default; a
199
+ * `memory://` prefix = an explicit memory store), or `null` when it passes — anything else present,
200
+ * including exotic custom-VFS configs we cannot classify, is the caller's own call (the guard catches the
201
+ * two accidental non-persistent shapes, it is not a storage-backend whitelist).
202
+ */
203
+ export function classifyNonPersistentDataDir(
204
+ dataDir: string | undefined,
205
+ ): "in-memory-default" | "memory-scheme" | null {
206
+ if (dataDir == null) return "in-memory-default";
207
+ if (dataDir.startsWith("memory://")) return "memory-scheme";
208
+ return null;
209
+ }
210
+
211
+ /**
212
+ * Does the backend store a plain {@link storePath} resolves to ALREADY exist? The fresh-target gate for a
213
+ * restore (ADR-0035 decision 6) — restore refuses a target that is already there. Per backend:
214
+ *
215
+ * - **memory** (`backendOverride === "memory"`) — a scheme-selected memory store is fresh by construction:
216
+ * it lives only for the instance about to be created, so there is nothing to collide with. Always `false`
217
+ * (the sanctioned test/ephemeral lane never blocks a restore).
218
+ * - **`file://`** (Bun/Node) — filesystem existence of the datadir directory. `node:fs` is imported
219
+ * DYNAMICALLY inside this branch, never at module top level, so a browser bundle (which only ever hits the
220
+ * `idb://` branch below) never pulls `node:fs` in. Relative paths resolve against the working directory,
221
+ * exactly as PGlite's filesystem backend and {@link resolveStoreDataDir} do.
222
+ * - **`idb://`** (browser/worker) — `indexedDB.databases()` enumerated for the store's database name
223
+ * ({@link storeIndexedDbDatabaseName}). BEST-EFFORT: `databases()` is unavailable on some engines (older
224
+ * Firefox, certain worker contexts); when absent we CANNOT prove existence, so we report `false` and let
225
+ * the restore proceed rather than fabricate a result — a real overlay collision would still surface as a
226
+ * PGlite-level boot failure. We never fake a positive.
227
+ */
228
+ export async function storeTargetExists(
229
+ storePath: string,
230
+ backendOverride?: "memory",
231
+ env: StoreEnv = detectStoreEnv(),
232
+ ): Promise<boolean> {
233
+ const dataDir = resolveStoreDataDir(storePath, backendOverride, env);
234
+ if (dataDir.startsWith("memory://")) return false;
235
+ if (dataDir.startsWith("file://")) {
236
+ // The datadir path is everything after the `file://` scheme; `node:fs` handles absolute and
237
+ // cwd-relative paths identically to PGlite's own filesystem backend.
238
+ const path = dataDir.slice("file://".length);
239
+ const { existsSync } = await import("node:fs");
240
+ return existsSync(path);
241
+ }
242
+ // `idb://` — enumerate the IndexedDB databases for this store's database name. `databases()` is optional in
243
+ // the spec, so guard it: when absent, best-effort `false` (documented above), never a fabricated positive.
244
+ const idb = (globalThis as { indexedDB?: { databases?: () => Promise<Array<{ name?: string }>> } }).indexedDB;
245
+ if (idb?.databases == null) return false;
246
+ const target = storeIndexedDbDatabaseName(storePath);
247
+ const databases = await idb.databases();
248
+ return databases.some((db) => db.name === target);
249
+ }