@pgxsinkit/client 0.1.51 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/error-chain.d.ts +9 -0
  9. package/dist/error-chain.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts.map +1 -1
  11. package/dist/export-store.d.ts +1 -1
  12. package/dist/export-store.d.ts.map +1 -1
  13. package/dist/index.d.ts +309 -38
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4628 -1489
  16. package/dist/index.js.map +36 -24
  17. package/dist/live-rows-sql.d.ts +1 -1
  18. package/dist/local-store.d.ts +16 -31
  19. package/dist/local-store.d.ts.map +1 -1
  20. package/dist/local-tables.d.ts +10 -4
  21. package/dist/local-tables.d.ts.map +1 -1
  22. package/dist/mutation.d.ts +12 -15
  23. package/dist/mutation.d.ts.map +1 -1
  24. package/dist/opfs-effects.d.ts +51 -0
  25. package/dist/opfs-effects.d.ts.map +1 -0
  26. package/dist/placement-probe.d.ts +75 -0
  27. package/dist/placement-probe.d.ts.map +1 -0
  28. package/dist/schema.d.ts +11 -16
  29. package/dist/schema.d.ts.map +1 -1
  30. package/dist/store-boot.d.ts +77 -0
  31. package/dist/store-boot.d.ts.map +1 -0
  32. package/dist/store-lifecycle.d.ts +153 -0
  33. package/dist/store-lifecycle.d.ts.map +1 -0
  34. package/dist/store-meta.d.ts +190 -0
  35. package/dist/store-meta.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +77 -7
  37. package/dist/store-path.d.ts.map +1 -1
  38. package/dist/sync/apply.d.ts +12 -1
  39. package/dist/sync/apply.d.ts.map +1 -1
  40. package/dist/sync/index.d.ts.map +1 -1
  41. package/dist/sync/shape-inbox.d.ts +1 -1
  42. package/dist/sync/types.d.ts +3 -3
  43. package/dist/testing.js.map +3 -3
  44. package/dist/worker/attach-sync-client.d.ts +239 -13
  45. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  46. package/dist/worker/define-sync-worker.d.ts +162 -5
  47. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  48. package/dist/worker/election-coordinator.d.ts +95 -0
  49. package/dist/worker/election-coordinator.d.ts.map +1 -0
  50. package/dist/worker/engine-control.d.ts +265 -0
  51. package/dist/worker/engine-control.d.ts.map +1 -0
  52. package/dist/worker/engine-router.d.ts +75 -0
  53. package/dist/worker/engine-router.d.ts.map +1 -0
  54. package/dist/worker/live-query-manager.d.ts.map +1 -1
  55. package/dist/worker/live-query-params-guard.d.ts +14 -0
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  57. package/dist/worker/protocol.d.ts +32 -11
  58. package/dist/worker/protocol.d.ts.map +1 -1
  59. package/dist/worker/sw-placement.d.ts +37 -0
  60. package/dist/worker/sw-placement.d.ts.map +1 -0
  61. package/package.json +4 -3
  62. package/skills/core/SKILL.md +15 -8
  63. package/skills/operating/SKILL.md +114 -34
  64. package/src/adoption.ts +275 -0
  65. package/src/boot-report.ts +70 -17
  66. package/src/convergence.ts +2 -1
  67. package/src/error-chain.ts +26 -0
  68. package/src/export-dump.ts +5 -1
  69. package/src/export-store.ts +1 -1
  70. package/src/index.ts +1246 -118
  71. package/src/live-rows-sql.ts +1 -1
  72. package/src/local-store.ts +18 -40
  73. package/src/local-tables.ts +9 -2
  74. package/src/mutation.ts +67 -49
  75. package/src/mutations-api.ts +3 -3
  76. package/src/opfs-effects.ts +160 -0
  77. package/src/placement-probe.ts +168 -0
  78. package/src/schema.ts +17 -22
  79. package/src/store-boot.ts +343 -0
  80. package/src/store-lifecycle.ts +227 -0
  81. package/src/store-meta.ts +459 -0
  82. package/src/store-path.ts +197 -22
  83. package/src/sync/apply.ts +227 -89
  84. package/src/sync/index.ts +33 -9
  85. package/src/sync/shape-inbox.ts +1 -1
  86. package/src/sync/types.ts +3 -3
  87. package/src/testing.ts +2 -2
  88. package/src/worker/attach-sync-client.ts +1675 -117
  89. package/src/worker/define-sync-worker.ts +810 -50
  90. package/src/worker/election-coordinator.ts +462 -0
  91. package/src/worker/engine-control.ts +379 -0
  92. package/src/worker/engine-router.ts +355 -0
  93. package/src/worker/live-query-manager.ts +10 -1
  94. package/src/worker/live-query-params-guard.ts +57 -0
  95. package/src/worker/protocol.ts +41 -10
  96. package/src/worker/sw-placement.ts +64 -0
@@ -0,0 +1,459 @@
1
+ // Store meta record — the first-use authority for browser-side engine placement (ADR-0049 decision 6,
2
+ // invariants 12 & 14; CONTEXT.md § "Language — engine placement", entries "Store meta record" and
3
+ // "Commitment marker"). Written at store CREATION for every backend and completed before the backend is
4
+ // exposed, the meta record is a TOTAL phase machine — one of
5
+ // `idb-authoritative | opfs-candidate | adopting | opfs-committed | deleting` — with `deleting` taking
6
+ // precedence over EVERYTHING (a committed store mid-destruction resumes deletion, never the committed
7
+ // verdict) and `adopting` over ordinary idb boot. It lives in a small dedicated IndexedDB database so it is
8
+ // readable in every engine home (SharedWorker-direct or elected worker).
9
+ //
10
+ // This module SEPARATES the pure boot decision (part A — `classifyStoreBoot`, total and unit-testable) from
11
+ // the IndexedDB IO (part B — the record's own database) and the recordless-idb detection (part C — a non-creating
12
+ // idb existence check). It deliberately carries NO DOM lib dependency: like `store-path.ts`, it reads the
13
+ // IndexedDB surface STRUCTURALLY off `globalThis` and accepts an injectable deps object so Bun unit tests
14
+ // (no browser IDB) can fake the whole surface. The store identity encoding and PGlite's idb database naming
15
+ // are consumed from `store-path.ts` — this module never re-derives either.
16
+
17
+ import { storeIdentityComponent, storeIndexedDbDatabaseName } from "./store-path";
18
+
19
+ // =========================================================================================================
20
+ // A. Types + pure boot classifier
21
+ // =========================================================================================================
22
+
23
+ /**
24
+ * The one total phase of the store meta record (invariant 12). `deleting` has precedence over everything;
25
+ * `adopting` over ordinary idb boot. There is deliberately NO boolean cross-product (`committed` +
26
+ * `deletionIntent`) — that left precedence ambiguous; the phase is total (CONTEXT § "Store meta record").
27
+ */
28
+ export type StoreMetaPhase = "idb-authoritative" | "opfs-candidate" | "adopting" | "opfs-committed" | "deleting";
29
+
30
+ /** One store's meta record: its total {@link StoreMetaPhase} plus a last-write timestamp. */
31
+ export interface StoreMetaRecord {
32
+ phase: StoreMetaPhase;
33
+ updatedAt: number;
34
+ }
35
+
36
+ /**
37
+ * The boot observations the classifier decides on — a PLAIN object so {@link classifyStoreBoot} is total and
38
+ * unit-testable without any IO. Callers assemble it from {@link readStoreMetaRecord}, an OPFS commitment
39
+ * namespace observation, and {@link idbStoreExists}.
40
+ */
41
+ export interface StoreBootObservations {
42
+ /**
43
+ * The meta record, `undefined` when absent. Callers MUST have already applied the failed-read policy: an
44
+ * UNREADABLE record never reaches the classifier as `undefined` (invariant 12) — it is a fail-closed error
45
+ * ({@link StoreMetaUnreadableError}) the caller handles before classifying. Only a proven absence is
46
+ * `undefined` here.
47
+ */
48
+ record: StoreMetaRecord | undefined;
49
+ /**
50
+ * The OPFS commitment-namespace observation: `"unobservable"` when the OPFS root threw or the API is absent
51
+ * (present absence is NOT historical proof), otherwise what was actually seen — whether the commitment
52
+ * sentinel and/or the store directory are present.
53
+ */
54
+ opfs: { sentinelPresent: boolean; storeDirectoryPresent: boolean } | "unobservable";
55
+ /** The non-creating idb existence check result (invariant 14 — an existing idb store's data is never overwritten; {@link idbStoreExists}). */
56
+ idbStoreExists: boolean;
57
+ }
58
+
59
+ /**
60
+ * The exhaustive set of boot verdicts. One discriminated union so every branch of {@link classifyStoreBoot}
61
+ * is named and reachable; downstream wiring (plan step 10) switches on `action`.
62
+ */
63
+ export type StoreBootVerdict =
64
+ // phase `deleting` — highest precedence; resume the destructive lifecycle.
65
+ | { action: "resume-deletion" }
66
+ // phase `adopting` — the adoption crash-recovery table (plan) owns the next steps.
67
+ | { action: "adoption-recovery" }
68
+ // phase `opfs-committed`, or the sentinel repair path — open the committed store (hard-open handles failure).
69
+ | { action: "open-committed" }
70
+ // no/older record but a commitment sentinel is present — repair the record, then open committed.
71
+ | { action: "repair-record-then-open-committed" }
72
+ // phase `opfs-candidate`, or a recordless candidate directory — an unexposed candidate has no authority.
73
+ | { action: "delete-candidate-and-rebuild" }
74
+ // phase `idb-authoritative`, or an existing recordless idb store detected — boot idb (the caller writes the record).
75
+ | { action: "boot-idb-authoritative" }
76
+ // nothing anywhere — create per placement, record first.
77
+ | { action: "virgin-create" };
78
+
79
+ /**
80
+ * The PURE boot classifier — plan boot classification 1–7 EXACTLY (invariant 12). Total over every phase and
81
+ * every observation combination; no IO. Precedence, in order:
82
+ *
83
+ * 1. `deleting` → `resume-deletion` (precedence over EVERYTHING, including a committed-looking OPFS).
84
+ * 2. `adopting` → `adoption-recovery` (precedence over ordinary idb boot).
85
+ * 3. `opfs-committed` → `open-committed` (opfs observations are IRRELEVANT here — the hard-open path handles
86
+ * any failure, including an unreachable root; a committed store never re-derives its verdict from OPFS).
87
+ * 4. `opfs-candidate` → `delete-candidate-and-rebuild` (an unexposed candidate has no authority).
88
+ * 5. `idb-authoritative` → `boot-idb-authoritative`.
89
+ * 6. record `undefined`, OPFS observable: `sentinelPresent` → `repair-record-then-open-committed` (sentinel
90
+ * authority — a sentinel-without-record is a real crash state that reads as committed); else a candidate
91
+ * directory without a sentinel → `delete-candidate-and-rebuild`; neither → fall through to 7.
92
+ * 7. record `undefined` and (OPFS unobservable OR nothing present): the RECORDLESS-IDB CHECK —
93
+ * `idbStoreExists` → `boot-idb-authoritative` (an existing recordless idb store — NEVER virgin; this arm
94
+ * is the entry point of the forward idbfs→opfs transition); else `virgin-create`.
95
+ *
96
+ * NOTE (the caller's nuance, not the classifier's): when OPFS is unobservable and the verdict is
97
+ * `virgin-create`, the caller creates an IDB store (a main thread / no-handle scope cannot hold sync-access
98
+ * handles). The double-loss residual — the meta record independently wiped AND OPFS simultaneously
99
+ * unobservable over a committed store — is accepted-risk register item 1: it is outside the browser
100
+ * termination model, and a later sentinel/record conflict surfaces as a hard error, never silently resolved.
101
+ */
102
+ export function classifyStoreBoot(obs: StoreBootObservations): StoreBootVerdict {
103
+ const { record, opfs, idbStoreExists } = obs;
104
+
105
+ if (record != null) {
106
+ switch (record.phase) {
107
+ case "deleting":
108
+ return { action: "resume-deletion" };
109
+ case "adopting":
110
+ return { action: "adoption-recovery" };
111
+ case "opfs-committed":
112
+ return { action: "open-committed" };
113
+ case "opfs-candidate":
114
+ return { action: "delete-candidate-and-rebuild" };
115
+ case "idb-authoritative":
116
+ return { action: "boot-idb-authoritative" };
117
+ default: {
118
+ // Exhaustiveness guard: a new phase MUST be classified explicitly, never silently fall through.
119
+ const unreachable: never = record.phase;
120
+ throw new Error(`[pgxsinkit] unclassified store meta phase: ${String(unreachable)}`);
121
+ }
122
+ }
123
+ }
124
+
125
+ // No record. Classification 6: OPFS observable → decide from the commitment namespace.
126
+ if (opfs !== "unobservable") {
127
+ if (opfs.sentinelPresent) return { action: "repair-record-then-open-committed" };
128
+ if (opfs.storeDirectoryPresent) return { action: "delete-candidate-and-rebuild" };
129
+ // Nothing present in OPFS → fall through to the recordless-idb check.
130
+ }
131
+
132
+ // Classification 7 (also when OPFS is NOT observable): the recordless-idb check.
133
+ return idbStoreExists ? { action: "boot-idb-authoritative" } : { action: "virgin-create" };
134
+ }
135
+
136
+ // =========================================================================================================
137
+ // B. Meta record IO (small dedicated IndexedDB database)
138
+ // =========================================================================================================
139
+
140
+ /** The dedicated IndexedDB database holding every store's meta record — SEPARATE from PGlite's own idb stores. */
141
+ export const STORE_META_DATABASE = "pgxsinkit-store-meta";
142
+
143
+ /** The single object store inside {@link STORE_META_DATABASE}; keyed by {@link storeIdentityComponent}. */
144
+ const META_OBJECT_STORE = "stores";
145
+
146
+ /** The bounded read-retry budget before a failed read fails closed (invariant 12). */
147
+ export const META_READ_ATTEMPTS = 3;
148
+
149
+ /** The delay between failed read attempts (ms); injectable in tests via {@link StoreMetaDeps.delay}. */
150
+ const META_READ_RETRY_DELAY_MS = 25;
151
+
152
+ /**
153
+ * A failed meta read is an ERROR, never "no record" (invariant 12). After {@link META_READ_ATTEMPTS} bounded
154
+ * retries a read that could not be completed fails closed with this distinct type; a stored value of the
155
+ * wrong shape / an unknown phase raises it too (corruption is not absence). A distinct type — not a bare
156
+ * `Error` — so the boot caller can `instanceof`-branch fail-closed from a proven absence.
157
+ */
158
+ export class StoreMetaUnreadableError extends Error {
159
+ constructor(storePath: string, cause?: unknown) {
160
+ super(
161
+ `[pgxsinkit] the store meta record for ${JSON.stringify(storePath)} could not be read after ` +
162
+ `${META_READ_ATTEMPTS} attempts (or was malformed). A failed meta read is an ERROR, never "no ` +
163
+ 'record" — booting fails closed rather than treating an unreadable/corrupt record as absence (ADR-0049 ' +
164
+ "invariant 12).",
165
+ cause == null ? undefined : { cause },
166
+ );
167
+ this.name = "StoreMetaUnreadableError";
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Returned by {@link readStoreMetaRecord} when the `indexedDB` API is ENTIRELY ABSENT — distinct from both a
173
+ * proven absence (`undefined`) and an unreadable record (an error). A no-IDB environment cannot hold a
174
+ * record at all, so absence IS provable there; the caller (plan step 10) maps this into the
175
+ * "OPFS unobservable"-style path. It is emphatically NOT the same as a THROWING IDB, whose outcome is
176
+ * ambiguous → {@link StoreMetaUnreadableError}.
177
+ */
178
+ export const META_STORE_UNAVAILABLE: unique symbol = Symbol("pgxsinkit.storeMeta.unavailable");
179
+
180
+ /** The injectable IO seam so Bun unit tests fake IndexedDB (there is no browser IDB there). */
181
+ export interface StoreMetaDeps {
182
+ /** The IndexedDB surface; defaults to `globalThis.indexedDB`. Explicit `undefined` selects the no-IDB path. */
183
+ indexedDB?: IndexedDbLike | undefined;
184
+ /** The between-retries delay; defaults to a real timer. Injected in tests to prove the retry count. */
185
+ delay?: (ms: number) => Promise<void>;
186
+ }
187
+
188
+ // --- Structural IndexedDB typing (no DOM lib), mirroring store-path.ts's globalThis-structural stance. ----
189
+
190
+ interface IdbRequestLike {
191
+ result: unknown;
192
+ error: unknown;
193
+ onsuccess: (() => void) | null;
194
+ onerror: (() => void) | null;
195
+ }
196
+
197
+ interface IdbObjectStoreLike {
198
+ get(key: string): IdbRequestLike;
199
+ put(value: unknown, key: string): IdbRequestLike;
200
+ delete(key: string): IdbRequestLike;
201
+ }
202
+
203
+ interface IdbTransactionLike {
204
+ objectStore(name: string): IdbObjectStoreLike;
205
+ abort(): void;
206
+ commit?(): void;
207
+ error?: unknown;
208
+ oncomplete: (() => void) | null;
209
+ onabort: (() => void) | null;
210
+ onerror: (() => void) | null;
211
+ }
212
+
213
+ interface IdbDatabaseLike {
214
+ transaction(
215
+ store: string,
216
+ mode: "readonly" | "readwrite",
217
+ options?: { durability?: "default" | "relaxed" | "strict" },
218
+ ): IdbTransactionLike;
219
+ objectStoreNames: { contains(name: string): boolean };
220
+ createObjectStore(name: string): IdbObjectStoreLike;
221
+ close(): void;
222
+ }
223
+
224
+ interface IdbVersionChangeEventLike {
225
+ target: { transaction?: IdbTransactionLike | null } | null;
226
+ }
227
+
228
+ interface IdbOpenDbRequestLike {
229
+ result: IdbDatabaseLike;
230
+ error: unknown;
231
+ transaction: IdbTransactionLike | null;
232
+ onupgradeneeded: ((event: IdbVersionChangeEventLike) => void) | null;
233
+ onsuccess: (() => void) | null;
234
+ onerror: (() => void) | null;
235
+ }
236
+
237
+ interface IndexedDbLike {
238
+ open(name: string, version?: number): IdbOpenDbRequestLike;
239
+ }
240
+
241
+ /** Resolve the IndexedDB surface: injected deps first, else structural off `globalThis`. */
242
+ function resolveIndexedDb(deps?: StoreMetaDeps): IndexedDbLike | undefined {
243
+ if (deps != null && "indexedDB" in deps) return deps.indexedDB;
244
+ return (globalThis as { indexedDB?: IndexedDbLike }).indexedDB;
245
+ }
246
+
247
+ function defaultDelay(ms: number): Promise<void> {
248
+ return new Promise((resolve) => setTimeout(resolve, ms));
249
+ }
250
+
251
+ const VALID_PHASES: ReadonlySet<string> = new Set<StoreMetaPhase>([
252
+ "idb-authoritative",
253
+ "opfs-candidate",
254
+ "adopting",
255
+ "opfs-committed",
256
+ "deleting",
257
+ ]);
258
+
259
+ function isStoreMetaRecord(value: unknown): value is StoreMetaRecord {
260
+ if (value == null || typeof value !== "object") return false;
261
+ const record = value as { phase?: unknown; updatedAt?: unknown };
262
+ return typeof record.updatedAt === "number" && typeof record.phase === "string" && VALID_PHASES.has(record.phase);
263
+ }
264
+
265
+ /** Open (or create) the dedicated meta database, ensuring the single object store exists. */
266
+ function openMetaDatabase(indexedDB: IndexedDbLike): Promise<IdbDatabaseLike> {
267
+ return new Promise((resolve, reject) => {
268
+ let request: IdbOpenDbRequestLike;
269
+ try {
270
+ request = indexedDB.open(STORE_META_DATABASE, 1);
271
+ } catch (error) {
272
+ reject(error);
273
+ return;
274
+ }
275
+ request.onupgradeneeded = () => {
276
+ const db = request.result;
277
+ if (!db.objectStoreNames.contains(META_OBJECT_STORE)) db.createObjectStore(META_OBJECT_STORE);
278
+ };
279
+ request.onsuccess = () => resolve(request.result);
280
+ request.onerror = () => reject(request.error ?? new Error("indexedDB open failed"));
281
+ });
282
+ }
283
+
284
+ /** Promise-wrap a get/put/delete request. */
285
+ function awaitRequest(request: IdbRequestLike): Promise<unknown> {
286
+ return new Promise((resolve, reject) => {
287
+ request.onsuccess = () => resolve(request.result);
288
+ request.onerror = () => reject(request.error ?? new Error("indexedDB request failed"));
289
+ });
290
+ }
291
+
292
+ /** A write is durable authority only once its transaction completes; request success alone is not commit. */
293
+ function awaitTransaction(transaction: IdbTransactionLike): Promise<void> {
294
+ return new Promise((resolve, reject) => {
295
+ transaction.oncomplete = () => resolve();
296
+ transaction.onabort = () => reject(transaction.error ?? new Error("indexedDB transaction aborted"));
297
+ transaction.onerror = () => reject(transaction.error ?? new Error("indexedDB transaction failed"));
298
+ });
299
+ }
300
+
301
+ /** Queue one authority mutation and observe BOTH its request and transaction settlement on every error path. */
302
+ async function awaitAuthorityMutation(transaction: IdbTransactionLike, request: IdbRequestLike): Promise<void> {
303
+ const requestSettlement = awaitRequest(request);
304
+ const transactionSettlement = awaitTransaction(transaction);
305
+ let commitError: unknown;
306
+ try {
307
+ transaction.commit?.();
308
+ } catch (error) {
309
+ commitError = error;
310
+ }
311
+ const [requestResult, transactionResult] = await Promise.allSettled([requestSettlement, transactionSettlement]);
312
+ if (commitError !== undefined) throw commitError;
313
+ if (requestResult.status === "rejected") throw requestResult.reason;
314
+ if (transactionResult.status === "rejected") throw transactionResult.reason;
315
+ }
316
+
317
+ /**
318
+ * One read attempt. Resolves the stored value (`unknown`) — validation happens in {@link readStoreMetaRecord}
319
+ * so a malformed value can be treated as non-retryable corruption while an IO failure retries.
320
+ */
321
+ async function readAttempt(indexedDB: IndexedDbLike, key: string): Promise<unknown> {
322
+ const db = await openMetaDatabase(indexedDB);
323
+ try {
324
+ const store = db.transaction(META_OBJECT_STORE, "readonly").objectStore(META_OBJECT_STORE);
325
+ return await awaitRequest(store.get(key));
326
+ } finally {
327
+ db.close();
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Read a store's meta record, applying the FAILED-READ POLICY (invariant 12):
333
+ * - `indexedDB` entirely absent → {@link META_STORE_UNAVAILABLE} (a no-IDB environment cannot hold a record,
334
+ * so absence is provable; the caller maps this into the "OPFS unobservable"-style path).
335
+ * - A successful read that finds nothing → `undefined` (a proven absence).
336
+ * - An open/get that fails is retried up to {@link META_READ_ATTEMPTS} times (an injectable delay between);
337
+ * if every attempt fails, throws {@link StoreMetaUnreadableError} (fail closed, NEVER "no record").
338
+ * - A stored value of the wrong shape / unknown phase → {@link StoreMetaUnreadableError} immediately
339
+ * (deterministic corruption; retrying cannot help, and it must not classify as absent).
340
+ */
341
+ export async function readStoreMetaRecord(
342
+ storePath: string,
343
+ deps?: StoreMetaDeps,
344
+ ): Promise<StoreMetaRecord | undefined | typeof META_STORE_UNAVAILABLE> {
345
+ const indexedDB = resolveIndexedDb(deps);
346
+ if (indexedDB == null) return META_STORE_UNAVAILABLE;
347
+ const key = storeIdentityComponent(storePath);
348
+ const delay = deps?.delay ?? defaultDelay;
349
+
350
+ let lastError: unknown;
351
+ for (let attempt = 1; attempt <= META_READ_ATTEMPTS; attempt += 1) {
352
+ try {
353
+ const value = await readAttempt(indexedDB, key);
354
+ if (value === undefined) return undefined;
355
+ if (isStoreMetaRecord(value)) return value;
356
+ // A present-but-malformed value is deterministic corruption — fail closed now, do not retry.
357
+ throw new StoreMetaUnreadableError(storePath, new Error("stored meta record has an invalid shape"));
358
+ } catch (error) {
359
+ if (error instanceof StoreMetaUnreadableError) throw error;
360
+ lastError = error;
361
+ if (attempt < META_READ_ATTEMPTS) await delay(META_READ_RETRY_DELAY_MS);
362
+ }
363
+ }
364
+ throw new StoreMetaUnreadableError(storePath, lastError);
365
+ }
366
+
367
+ /**
368
+ * Write (create or overwrite) a store's meta record — done at CREATION for every backend, before exposure,
369
+ * and at each phase transition (invariant 12). A no-IDB environment cannot hold a record, so this is a
370
+ * best-effort no-op there (consistent with {@link readStoreMetaRecord} returning {@link META_STORE_UNAVAILABLE}).
371
+ */
372
+ export async function writeStoreMetaRecord(
373
+ storePath: string,
374
+ record: StoreMetaRecord,
375
+ deps?: StoreMetaDeps,
376
+ ): Promise<void> {
377
+ const indexedDB = resolveIndexedDb(deps);
378
+ if (indexedDB == null) return;
379
+ const key = storeIdentityComponent(storePath);
380
+ const db = await openMetaDatabase(indexedDB);
381
+ try {
382
+ const transaction = db.transaction(META_OBJECT_STORE, "readwrite", { durability: "strict" });
383
+ const store = transaction.objectStore(META_OBJECT_STORE);
384
+ await awaitAuthorityMutation(transaction, store.put(record, key));
385
+ } finally {
386
+ db.close();
387
+ }
388
+ }
389
+
390
+ /** Delete a store's meta record — the terminal step of the destructive lifecycle (invariant 12/13). */
391
+ export async function deleteStoreMetaRecord(storePath: string, deps?: StoreMetaDeps): Promise<void> {
392
+ const indexedDB = resolveIndexedDb(deps);
393
+ if (indexedDB == null) return;
394
+ const key = storeIdentityComponent(storePath);
395
+ const db = await openMetaDatabase(indexedDB);
396
+ try {
397
+ const transaction = db.transaction(META_OBJECT_STORE, "readwrite", { durability: "strict" });
398
+ const store = transaction.objectStore(META_OBJECT_STORE);
399
+ await awaitAuthorityMutation(transaction, store.delete(key));
400
+ } finally {
401
+ db.close();
402
+ }
403
+ }
404
+
405
+ // =========================================================================================================
406
+ // C. Non-creating idb existence check (invariant 14 — an existing idb store's data is never overwritten)
407
+ // =========================================================================================================
408
+
409
+ /**
410
+ * Does PGlite's idb database for this store ALREADY exist, WITHOUT creating it? The recordless-idb recognition
411
+ * check (invariant 14): no meta record + an existing idb store → `idb-authoritative`, never virgin. This is
412
+ * the entry point of the forward idbfs→opfs transition — an existing idb store's data is never overwritten by
413
+ * a fresh opfs mint; it is opened in place (fixed/denied home) or migrated forward via adoption.
414
+ *
415
+ * Technique (per ADR-0049 D6 — NEVER `indexedDB.databases()`, which is absent on some engines): open the
416
+ * database with NO version. If `onupgradeneeded` fires, the database did NOT exist — flag it and ABORT the
417
+ * versionchange transaction (`event.target.transaction.abort()`) so the freshly-created empty database does
418
+ * not persist, then resolve `false`. On `onsuccess` WITHOUT an upgrade the database already existed — close
419
+ * the handle and resolve `true`. The `onerror` that follows an abort is the EXPECTED completion of the
420
+ * non-exist path (the AbortError), not a failure — it resolves `false`. `indexedDB` absent → `false`
421
+ * (no idb store can exist). The database name comes from `store-path.ts`'s {@link storeIndexedDbDatabaseName}
422
+ * (the sole owner of PGlite's `/pglite/` naming) — never re-derived here.
423
+ */
424
+ export function idbStoreExists(storePath: string, deps?: StoreMetaDeps): Promise<boolean> {
425
+ const indexedDB = resolveIndexedDb(deps);
426
+ if (indexedDB == null) return Promise.resolve(false);
427
+ const name = storeIndexedDbDatabaseName(storePath);
428
+
429
+ return new Promise((resolve, reject) => {
430
+ let existed = true;
431
+ let request: IdbOpenDbRequestLike;
432
+ try {
433
+ // No version → never triggers an upgrade on an existing database; a MISSING one upgrades from nothing.
434
+ request = indexedDB.open(name);
435
+ } catch (error) {
436
+ reject(error);
437
+ return;
438
+ }
439
+ request.onupgradeneeded = (event) => {
440
+ // The database did not exist. Abort the versionchange transaction so nothing is persisted.
441
+ existed = false;
442
+ const transaction = event?.target?.transaction ?? request.transaction;
443
+ transaction?.abort();
444
+ };
445
+ request.onsuccess = () => {
446
+ request.result.close();
447
+ resolve(true);
448
+ };
449
+ request.onerror = () => {
450
+ // After an abort, `onerror` is the expected completion of the non-exist path — resolve `false`, do not
451
+ // misreport it as a failure. A genuine open failure (upgrade never fired) is a real error.
452
+ if (!existed) {
453
+ resolve(false);
454
+ return;
455
+ }
456
+ reject(request.error ?? new Error("indexedDB open failed"));
457
+ };
458
+ });
459
+ }