@moyodb/sdk 1.0.0 → 1.1.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 (76) hide show
  1. package/dist/LICENSE +202 -0
  2. package/dist/assets/browser-worker-DP6Mjz7c.js +4 -0
  3. package/dist/assets/browser-worker-DP6Mjz7c.js.map +1 -0
  4. package/dist/assets/shared-worker-DKzhauVf.js +2 -0
  5. package/dist/assets/shared-worker-DKzhauVf.js.map +1 -0
  6. package/dist/browser-worker.d.ts +2 -0
  7. package/dist/browser-worker.d.ts.map +1 -0
  8. package/dist/change-events.d.ts +1 -1
  9. package/dist/chunks/indexing-BzmFhWXs.js +1576 -0
  10. package/dist/chunks/indexing-BzmFhWXs.js.map +1 -0
  11. package/dist/codec.d.ts +1 -1
  12. package/dist/codec.d.ts.map +1 -1
  13. package/dist/compression.d.ts +1 -1
  14. package/dist/compression.d.ts.map +1 -1
  15. package/dist/demo.d.ts +2 -1
  16. package/dist/demo.d.ts.map +1 -1
  17. package/dist/engine/README.md +63 -16
  18. package/dist/engine/moyodb_engine.d.ts +29 -19
  19. package/dist/engine/moyodb_engine.js +78 -28
  20. package/dist/engine/moyodb_engine_bg.wasm +0 -0
  21. package/dist/engine/moyodb_engine_bg.wasm.d.ts +4 -2
  22. package/dist/engine/package.json +1 -1
  23. package/dist/engine/snippets/moyodb-engine-8ebe6af0cc2e81b7/js/opfs_shim.js +151 -62
  24. package/dist/errors.d.ts +6 -3
  25. package/dist/errors.d.ts.map +1 -1
  26. package/dist/index.d.ts +11 -5
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/indexing.d.ts +9 -1
  29. package/dist/indexing.d.ts.map +1 -1
  30. package/dist/moyodb-sdk.js +2253 -589
  31. package/dist/moyodb-sdk.js.map +1 -1
  32. package/dist/node-engine.js +2213 -0
  33. package/dist/node-engine.js.map +1 -0
  34. package/dist/node-storage.d.mts +12 -0
  35. package/dist/node-storage.mjs +634 -0
  36. package/dist/node-worker-client.d.ts +19 -0
  37. package/dist/node-worker-client.d.ts.map +1 -0
  38. package/dist/node-worker.mjs +118 -0
  39. package/dist/node.d.ts +19 -0
  40. package/dist/node.d.ts.map +1 -0
  41. package/dist/node.js +3194 -0
  42. package/dist/node.js.map +1 -0
  43. package/dist/records.d.ts +75 -0
  44. package/dist/records.d.ts.map +1 -0
  45. package/dist/registry.d.ts +13 -4
  46. package/dist/registry.d.ts.map +1 -1
  47. package/dist/shared-worker-client.d.ts +24 -0
  48. package/dist/shared-worker-client.d.ts.map +1 -0
  49. package/dist/shared-worker-protocol.d.ts +16 -0
  50. package/dist/shared-worker-protocol.d.ts.map +1 -0
  51. package/dist/shared-worker.d.ts +33 -0
  52. package/dist/shared-worker.d.ts.map +1 -0
  53. package/dist/sql-parser.d.ts +9 -0
  54. package/dist/sql-parser.d.ts.map +1 -0
  55. package/dist/sql-types.d.ts +82 -0
  56. package/dist/sql-types.d.ts.map +1 -0
  57. package/dist/sql.d.ts +32 -0
  58. package/dist/sql.d.ts.map +1 -0
  59. package/dist/subscriptions.d.ts +2 -2
  60. package/dist/subscriptions.d.ts.map +1 -1
  61. package/dist/types.d.ts +9 -6
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/worker-api.d.ts +5 -6
  64. package/dist/worker-api.d.ts.map +1 -1
  65. package/dist/worker-client.d.ts +32 -5
  66. package/dist/worker-client.d.ts.map +1 -1
  67. package/dist/worker-protocol.d.ts +36 -3
  68. package/dist/worker-protocol.d.ts.map +1 -1
  69. package/dist/worker-server.d.ts +10 -2
  70. package/dist/worker-server.d.ts.map +1 -1
  71. package/dist/worker.d.ts +263 -1
  72. package/dist/worker.d.ts.map +1 -1
  73. package/package.json +14 -5
  74. package/README.md +0 -59
  75. package/dist/assets/worker-R2dy1Ju5.js +0 -4
  76. package/dist/assets/worker-R2dy1Ju5.js.map +0 -1
@@ -0,0 +1,2213 @@
1
+ import { A as prefixRange, At as packedBinaryListBytes, Bt as unpackPackedOptionalValues, Et as isWorkerProtocolRequestMessage, F as utf8Encode, Ft as unpackPackedBatchOpKeys, It as unpackPackedBatchOps, Lt as unpackPackedBinaryList, Nt as prepareWorkerResponsePayload, Pt as serializeWorkerError, Rt as unpackPackedBinaryPairKeys, S as toPublicIndexDefinitions, St as isWorkerProtocolEnvelope, Tt as isWorkerProtocolRequestBatchMessage, Ut as isRecord, Vt as workerProtocolError, _ as indexRangeToPhysicalRange, _t as decodeWorkerCommandPayload, a as createIndexKeyExtractor, b as normalizeIndexDefinitions, bt as isAutocommitCommand, c as decodeIndexedDocument, d as encodeIndexMetadataValue, dt as WORKER_PROTOCOL_READY, f as extractLogicalIndexKey, g as indexKeyExactRange, gt as captureWorkerPayload, ht as WORKER_PROTOCOL_RESPONSE_BATCH, i as compareNormalizedIndexDefinitions, jt as packedOptionalValues, kt as packedBatchOpsBytes, l as encodeIndexEntryKey, m as findIndexDefinition, mt as WORKER_PROTOCOL_RESPONSE, o as decodeIndexEntryKey, p as extractLogicalIndexKeyFromDocument, r as cloneNormalizedIndexDefinitions, s as decodeIndexMetadataValue, t as INDEX_METADATA_STORE, u as encodeIndexMetadataKey, xt as isWorkerCommand, y as isInternalStoreName, zt as unpackPackedBinaryPairs } from "./chunks/indexing-BzmFhWXs.js";
2
+ //#region src/worker-server.ts
3
+ /** The first argument identifies the transaction lane. */
4
+ var TRANSACTION_COMMANDS = /* @__PURE__ */ new Set([
5
+ "commit",
6
+ "rollback",
7
+ "createStore",
8
+ "dropStore",
9
+ "clearStore",
10
+ "get",
11
+ "getMany",
12
+ "has",
13
+ "put",
14
+ "putMany",
15
+ "delete",
16
+ "deleteMany",
17
+ "applyBatch",
18
+ "scan",
19
+ "getByIndex",
20
+ "scanByIndex",
21
+ "scanByIndexPage",
22
+ "getIndexes",
23
+ "reconcileIndexes",
24
+ "setSchemaVersion"
25
+ ]);
26
+ /** These commands require exclusive access to the open engine. */
27
+ var EXCLUSIVE_COMMANDS = /* @__PURE__ */ new Set([
28
+ "open",
29
+ "close",
30
+ "destroy",
31
+ "importSnapshot",
32
+ "reset",
33
+ "compact",
34
+ "rebuild"
35
+ ]);
36
+ /**
37
+ * These commands do not use the open engine, so browser storage calls
38
+ * can run without delaying its close.
39
+ */
40
+ var UNSCHEDULED_COMMANDS = /* @__PURE__ */ new Set([
41
+ "deleteDB",
42
+ "storageInfo",
43
+ "requestPersistence"
44
+ ]);
45
+ var noop = () => {};
46
+ /**
47
+ * Serializes each transaction lane, including awaited work. Readwrite
48
+ * autocommits share one writer lane. Exclusive commands wait for scheduled
49
+ * work and block later scheduled work until they finish.
50
+ */
51
+ var RequestScheduler = class {
52
+ #lanes = /* @__PURE__ */ new Map();
53
+ #inFlight = /* @__PURE__ */ new Set();
54
+ #barrier = Promise.resolve();
55
+ schedule(command, args, task) {
56
+ if (UNSCHEDULED_COMMANDS.has(command)) return task();
57
+ if (EXCLUSIVE_COMMANDS.has(command)) return this.#runExclusive(task);
58
+ return this.#runShared(laneFor(command, args), task);
59
+ }
60
+ #runShared(lane, task) {
61
+ const barrier = this.#barrier;
62
+ const previous = lane === null ? void 0 : this.#lanes.get(lane);
63
+ const result = (async () => {
64
+ await barrier;
65
+ if (previous) await previous;
66
+ return task();
67
+ })();
68
+ const settled = result.then(noop, noop);
69
+ this.#inFlight.add(settled);
70
+ if (lane !== null) this.#lanes.set(lane, settled);
71
+ settled.then(() => {
72
+ this.#inFlight.delete(settled);
73
+ if (lane !== null && this.#lanes.get(lane) === settled) this.#lanes.delete(lane);
74
+ });
75
+ return result;
76
+ }
77
+ #runExclusive(task) {
78
+ const previousBarrier = this.#barrier;
79
+ const pending = Array.from(this.#inFlight);
80
+ const result = (async () => {
81
+ await previousBarrier;
82
+ await Promise.all(pending);
83
+ return task();
84
+ })();
85
+ this.#barrier = result.then(noop, noop);
86
+ return result;
87
+ }
88
+ };
89
+ var AUTOCOMMIT_WRITER_LANE = "autocommit:readwrite";
90
+ function laneFor(command, args) {
91
+ if (TRANSACTION_COMMANDS.has(command) && typeof args[0] === "number") return args[0];
92
+ if (command === "autocommit" && args[0] === "readwrite") return AUTOCOMMIT_WRITER_LANE;
93
+ return null;
94
+ }
95
+ var ResponseQueue = class {
96
+ scope;
97
+ queued = [];
98
+ queuedBytes = 0;
99
+ flushScheduled = false;
100
+ flushChannel = null;
101
+ closed = false;
102
+ constructor(scope) {
103
+ this.scope = scope;
104
+ }
105
+ enqueue = (response, transfer = []) => {
106
+ if (this.closed) return;
107
+ const captured = captureWorkerPayload(response, transfer);
108
+ if (this.queued.length > 0 && this.queuedBytes + captured.byteLength > 1048576) this.flush();
109
+ this.queued.push({
110
+ response: captured.value,
111
+ transfer: captured.transfer
112
+ });
113
+ this.queuedBytes += captured.byteLength;
114
+ if (!this.flushScheduled) {
115
+ this.flushScheduled = true;
116
+ queueMicrotask(() => {
117
+ if (this.closed || this.queued.length === 0) {
118
+ this.flushScheduled = false;
119
+ return;
120
+ }
121
+ this.flushChannel ??= this.createFlushChannel();
122
+ this.flushChannel.port2.postMessage(null);
123
+ });
124
+ }
125
+ if (this.queued.length >= 128 || this.queuedBytes >= 1048576) this.flush();
126
+ };
127
+ close() {
128
+ this.closed = true;
129
+ this.queued = [];
130
+ this.queuedBytes = 0;
131
+ this.flushChannel?.port1.close();
132
+ this.flushChannel?.port2.close();
133
+ this.flushChannel = null;
134
+ }
135
+ createFlushChannel() {
136
+ const channel = new MessageChannel();
137
+ channel.port1.addEventListener("message", () => {
138
+ this.flushScheduled = false;
139
+ this.flush();
140
+ });
141
+ channel.port1.start();
142
+ return channel;
143
+ }
144
+ flush() {
145
+ const queued = this.queued;
146
+ this.queued = [];
147
+ this.queuedBytes = 0;
148
+ if (this.closed || queued.length === 0) return;
149
+ const response = queued.length === 1 ? queued[0].response : {
150
+ type: WORKER_PROTOCOL_RESPONSE_BATCH,
151
+ version: 1,
152
+ responses: queued.map((entry) => entry.response)
153
+ };
154
+ const transfer = [];
155
+ for (const entry of queued) for (const buffer of entry.transfer) transfer.push(buffer);
156
+ postWorkerResponse(this.scope, response, transfer);
157
+ }
158
+ };
159
+ function exposeWorkerApi(api, scope = self) {
160
+ const scheduler = new RequestScheduler();
161
+ const responses = new ResponseQueue(scope);
162
+ const handleMessage = (event) => {
163
+ if (event.origin !== "" && event.origin !== scope.location.origin) return;
164
+ if (isWorkerProtocolRequestBatchMessage(event.data)) {
165
+ let remaining = event.data.requests.length;
166
+ const respond = (response, transfer) => {
167
+ responses.enqueue(response, transfer);
168
+ remaining -= 1;
169
+ if (remaining === 0) responses.flush();
170
+ };
171
+ for (const request of event.data.requests) dispatchWorkerRequest(scope, api, scheduler, request, respond);
172
+ return;
173
+ }
174
+ dispatchWorkerRequest(scope, api, scheduler, event.data);
175
+ };
176
+ scope.addEventListener("message", handleMessage);
177
+ scope.postMessage({
178
+ type: WORKER_PROTOCOL_READY,
179
+ version: 1,
180
+ batching: 1
181
+ });
182
+ return { close() {
183
+ scope.removeEventListener("message", handleMessage);
184
+ responses.close();
185
+ } };
186
+ }
187
+ async function dispatchWorkerRequest(scope, api, scheduler, data, respond = (response, transfer) => postWorkerResponse(scope, response, transfer)) {
188
+ if (!isWorkerProtocolEnvelope(data)) return;
189
+ const id = typeof data.id === "number" && Number.isSafeInteger(data.id) ? data.id : 0;
190
+ if (!isWorkerProtocolRequestMessage(data)) {
191
+ respond(errorResponse(id, workerProtocolError("WorkerProtocolError", "invalid worker protocol request")));
192
+ return;
193
+ }
194
+ if (!isWorkerCommand(data.command)) {
195
+ respond(errorResponse(data.id, workerProtocolError("WorkerProtocolError", `unsupported worker command: ${String(data.command)}`)));
196
+ return;
197
+ }
198
+ const command = data.command;
199
+ const args = data.args;
200
+ try {
201
+ let responseCommand = command;
202
+ let invoke;
203
+ if (command === "autocommit") {
204
+ const [mode, inner, innerArgs] = args;
205
+ if (mode !== "readonly" && mode !== "readwrite" || !isAutocommitCommand(inner) || !Array.isArray(innerArgs)) throw workerProtocolError("WorkerProtocolError", "invalid autocommit request");
206
+ assertImplemented(api, inner);
207
+ responseCommand = inner;
208
+ invoke = () => runAutocommit(api, mode, inner, innerArgs);
209
+ } else {
210
+ assertImplemented(api, command);
211
+ invoke = () => invokeCommand(api, command, args);
212
+ }
213
+ const result = await scheduler.schedule(command, args, invoke);
214
+ const responsePayload = prepareWorkerResponsePayload(responseCommand, result);
215
+ respond(successResponse(data.id, responsePayload.result), responsePayload.transfer);
216
+ } catch (error) {
217
+ respond(errorResponse(data.id, error));
218
+ }
219
+ }
220
+ function assertImplemented(api, command) {
221
+ if (typeof api[command] !== "function") throw workerProtocolError("WorkerProtocolError", `worker command is not implemented: ${command}`);
222
+ }
223
+ function invokeCommand(api, command, args) {
224
+ const packedResult = dispatchPackedCommand(api, command, args);
225
+ if (packedResult !== null) return packedResult;
226
+ return api[command].apply(api, decodeWorkerCommandPayload(command, args));
227
+ }
228
+ async function runAutocommit(api, mode, command, args) {
229
+ const txId = await api.begin(mode);
230
+ let result;
231
+ try {
232
+ result = await invokeCommand(api, command, [txId, ...args]);
233
+ } catch (error) {
234
+ try {
235
+ await api.rollback(txId);
236
+ } catch {}
237
+ throw error;
238
+ }
239
+ if (mode === "readwrite") await api.commit(txId);
240
+ else await api.rollback(txId);
241
+ return result;
242
+ }
243
+ function dispatchPackedCommand(api, command, args) {
244
+ const packedApi = api;
245
+ if (command === "getMany" || command === "deleteMany") {
246
+ const [txId, store, keys] = args;
247
+ if (typeof txId !== "number" || typeof store !== "string") return null;
248
+ const packedKeys = packedBinaryListBytes(keys);
249
+ if (packedKeys === null) return null;
250
+ if (command === "getMany" && typeof packedApi.getManyPacked === "function") return packedApi.getManyPacked(txId, store, packedKeys);
251
+ if (command === "deleteMany" && typeof packedApi.deleteManyPacked === "function") return packedApi.deleteManyPacked(txId, store, packedKeys);
252
+ return null;
253
+ }
254
+ if (command === "putMany") {
255
+ const [txId, store, entries, options] = args;
256
+ if (typeof txId !== "number" || typeof store !== "string" || typeof packedApi.putManyPacked !== "function") return null;
257
+ const packedEntries = packedBinaryListBytes(entries);
258
+ return packedEntries === null ? null : packedApi.putManyPacked(txId, store, packedEntries, options);
259
+ }
260
+ if (command === "applyBatch") {
261
+ const [txId, store, ops] = args;
262
+ if (typeof txId !== "number" || typeof store !== "string" || typeof packedApi.applyBatchPacked !== "function") return null;
263
+ const packedOps = packedBatchOpsBytes(ops);
264
+ return packedOps === null ? null : packedApi.applyBatchPacked(txId, store, packedOps);
265
+ }
266
+ return null;
267
+ }
268
+ function successResponse(id, result) {
269
+ return {
270
+ type: WORKER_PROTOCOL_RESPONSE,
271
+ version: 1,
272
+ id,
273
+ ok: true,
274
+ result
275
+ };
276
+ }
277
+ function errorResponse(id, error) {
278
+ return {
279
+ type: WORKER_PROTOCOL_RESPONSE,
280
+ version: 1,
281
+ id,
282
+ ok: false,
283
+ error: serializeWorkerError(error)
284
+ };
285
+ }
286
+ function postWorkerResponse(scope, response, transfer = []) {
287
+ if (transfer.length > 0) try {
288
+ scope.postMessage(response, transfer);
289
+ return;
290
+ } catch {}
291
+ scope.postMessage(response);
292
+ }
293
+ //#endregion
294
+ //#region src/compression.ts
295
+ var STORE_RECORD_MAGIC = utf8Encode("BDBZVAL1");
296
+ var SNAPSHOT_EXPORT_MAGIC = utf8Encode("BDBZSNP1");
297
+ var ENVELOPE_VERSION = 1;
298
+ var ENVELOPE_HEADER_SIZE = 18;
299
+ var COMPRESSION_TAG_NONE = 0;
300
+ var COMPRESSION_TAG_GZIP = 1;
301
+ var COMPRESSION_TAG_DEFLATE = 2;
302
+ var STORE_FLAG_COMPRESSION_SHIFT = 2;
303
+ var STORE_FLAG_COMPRESSION_MASK = 12;
304
+ var MAX_DECOMPRESSED_STORE_VALUE_BYTES = 8388608;
305
+ var MAX_DECOMPRESSED_SNAPSHOT_BYTES = 268435456;
306
+ var CRC32_TABLE = (() => {
307
+ const table = /* @__PURE__ */ new Uint32Array(256);
308
+ for (let index = 0; index < 256; index += 1) {
309
+ let crc = index;
310
+ for (let bit = 0; bit < 8; bit += 1) if ((crc & 1) !== 0) crc = crc >>> 1 ^ 3988292384;
311
+ else crc >>>= 1;
312
+ table[index] = crc >>> 0;
313
+ }
314
+ return table;
315
+ })();
316
+ function namedError(name, message) {
317
+ const error = new Error(message);
318
+ error.name = name;
319
+ return error;
320
+ }
321
+ function compressionTag(kind) {
322
+ switch (kind) {
323
+ case false: return COMPRESSION_TAG_NONE;
324
+ case "gzip": return COMPRESSION_TAG_GZIP;
325
+ case "deflate": return COMPRESSION_TAG_DEFLATE;
326
+ default: throw namedError("InternalError", `unsupported compression kind: ${String(kind)}`);
327
+ }
328
+ }
329
+ function compressionKindFromTag(tag) {
330
+ switch (tag) {
331
+ case COMPRESSION_TAG_NONE: return false;
332
+ case COMPRESSION_TAG_GZIP: return "gzip";
333
+ case COMPRESSION_TAG_DEFLATE: return "deflate";
334
+ default: throw namedError("CorruptionError", `invalid compression tag: ${tag}`);
335
+ }
336
+ }
337
+ function compressionRuntimeUnavailable() {
338
+ return namedError("UnsupportedPlatformError", "CompressionStream and DecompressionStream are required for moyodb compression");
339
+ }
340
+ function ensureCompressionRuntime() {
341
+ if (typeof CompressionStream !== "function" || typeof DecompressionStream !== "function") throw compressionRuntimeUnavailable();
342
+ }
343
+ function crc32(bytes) {
344
+ let crc = 4294967295;
345
+ for (const byte of bytes) crc = crc >>> 8 ^ CRC32_TABLE[(crc ^ byte) & 255];
346
+ return (crc ^ 4294967295) >>> 0;
347
+ }
348
+ function buildEnvelope(magic, kindTag, rawLength, payload) {
349
+ const out = new Uint8Array(ENVELOPE_HEADER_SIZE + payload.byteLength);
350
+ out.set(magic, 0);
351
+ out[8] = ENVELOPE_VERSION;
352
+ out[9] = kindTag;
353
+ const view = new DataView(out.buffer, out.byteOffset, ENVELOPE_HEADER_SIZE);
354
+ view.setUint32(10, rawLength, true);
355
+ view.setUint32(14, crc32(payload), true);
356
+ out.set(payload, ENVELOPE_HEADER_SIZE);
357
+ return out;
358
+ }
359
+ function copyBytes(bytes) {
360
+ const copy = new Uint8Array(bytes.byteLength);
361
+ copy.set(bytes);
362
+ return copy;
363
+ }
364
+ function byteStream(bytes) {
365
+ let offset = 0;
366
+ return new ReadableStream({ pull(controller) {
367
+ if (offset < bytes.byteLength) {
368
+ const end = Math.min(offset + 65536, bytes.byteLength);
369
+ controller.enqueue(bytes.subarray(offset, end));
370
+ offset = end;
371
+ }
372
+ if (offset === bytes.byteLength) controller.close();
373
+ } });
374
+ }
375
+ function readEnvelopeHeader(magic, bytes, strict = true) {
376
+ if (bytes.byteLength < magic.byteLength) return null;
377
+ for (let index = 0; index < magic.byteLength; index += 1) if (bytes[index] !== magic[index]) return null;
378
+ if (bytes.byteLength < ENVELOPE_HEADER_SIZE) {
379
+ if (strict) throw namedError("CorruptionError", `truncated compression envelope: expected at least ${ENVELOPE_HEADER_SIZE} bytes, got ${bytes.byteLength}`);
380
+ return null;
381
+ }
382
+ const view = new DataView(bytes.buffer, bytes.byteOffset, ENVELOPE_HEADER_SIZE);
383
+ return {
384
+ version: bytes[8],
385
+ kindTag: bytes[9],
386
+ rawLength: view.getUint32(10, true),
387
+ payloadChecksum: view.getUint32(14, true)
388
+ };
389
+ }
390
+ async function compressBytes(data, kind) {
391
+ ensureCompressionRuntime();
392
+ let stream;
393
+ try {
394
+ stream = byteStream(data).pipeThrough(new CompressionStream(kind));
395
+ } catch {
396
+ throw compressionRuntimeUnavailable();
397
+ }
398
+ try {
399
+ return new Uint8Array(await new Response(stream).arrayBuffer());
400
+ } catch (error) {
401
+ throw namedError("InternalError", `failed to compress bytes with ${kind}: ${String(error)}`);
402
+ }
403
+ }
404
+ async function decompressBytes(data, kind, label, maxOutputBytes) {
405
+ ensureCompressionRuntime();
406
+ let stream;
407
+ try {
408
+ stream = byteStream(copyBytes(data)).pipeThrough(new DecompressionStream(kind));
409
+ } catch {
410
+ throw compressionRuntimeUnavailable();
411
+ }
412
+ try {
413
+ return await readBoundedStream(stream, label, maxOutputBytes);
414
+ } catch (error) {
415
+ throw namedError("CorruptionError", `failed to decompress ${label}: ${String(error)}`);
416
+ }
417
+ }
418
+ async function readBoundedStream(stream, label, maxOutputBytes) {
419
+ const reader = stream.getReader();
420
+ const chunks = [];
421
+ let totalBytes = 0;
422
+ try {
423
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
424
+ const value = next.value;
425
+ totalBytes += value.byteLength;
426
+ if (maxOutputBytes !== void 0 && totalBytes > maxOutputBytes) {
427
+ await reader.cancel(`decompressed ${label} exceeded ${maxOutputBytes} bytes`);
428
+ throw namedError("CorruptionError", `decompressed ${label} exceeds ${maxOutputBytes} byte limit`);
429
+ }
430
+ chunks.push(value);
431
+ }
432
+ } finally {
433
+ reader.releaseLock();
434
+ }
435
+ if (chunks.length === 1) return chunks[0];
436
+ const out = new Uint8Array(totalBytes);
437
+ let offset = 0;
438
+ for (const chunk of chunks) {
439
+ out.set(chunk, offset);
440
+ offset += chunk.byteLength;
441
+ }
442
+ return out;
443
+ }
444
+ function compressionFromStoreFlags(flags) {
445
+ const encoded = (flags & STORE_FLAG_COMPRESSION_MASK) >>> STORE_FLAG_COMPRESSION_SHIFT;
446
+ switch (encoded) {
447
+ case 0: return false;
448
+ case 1: return "gzip";
449
+ case 2: return "deflate";
450
+ default: throw namedError("CorruptionError", `invalid store compression flags: ${encoded}`);
451
+ }
452
+ }
453
+ async function encodeStoreValueRecord(value, compression) {
454
+ if (compression === false) return value;
455
+ if (value.byteLength > MAX_DECOMPRESSED_STORE_VALUE_BYTES) throw namedError("ValueTooLargeError", `value has ${value.byteLength} bytes, exceeding the ${MAX_DECOMPRESSED_STORE_VALUE_BYTES} byte limit`);
456
+ if (value.byteLength < 1024) return buildEnvelope(STORE_RECORD_MAGIC, COMPRESSION_TAG_NONE, value.byteLength, value);
457
+ const input = copyBytes(value);
458
+ const compressed = await compressBytes(input, compression);
459
+ if (compressed.byteLength >= input.byteLength) return buildEnvelope(STORE_RECORD_MAGIC, COMPRESSION_TAG_NONE, input.byteLength, input);
460
+ return buildEnvelope(STORE_RECORD_MAGIC, compressionTag(compression), input.byteLength, compressed);
461
+ }
462
+ async function decodeStoreValueRecord(value, options) {
463
+ const header = readEnvelopeHeader(STORE_RECORD_MAGIC, value, options.strict);
464
+ if (!header) return value;
465
+ if (header.version !== ENVELOPE_VERSION) {
466
+ if (options.strict) throw namedError("CorruptionError", `unsupported value record version: ${header.version}`);
467
+ return value;
468
+ }
469
+ let compression;
470
+ try {
471
+ compression = compressionKindFromTag(header.kindTag);
472
+ } catch (error) {
473
+ if (options.strict) throw error;
474
+ return value;
475
+ }
476
+ const payload = value.subarray(ENVELOPE_HEADER_SIZE);
477
+ if (crc32(payload) !== header.payloadChecksum) {
478
+ if (options.strict) throw namedError("CorruptionError", "value record checksum mismatch");
479
+ return value;
480
+ }
481
+ if (compression === false) {
482
+ if (payload.byteLength !== header.rawLength) {
483
+ if (options.strict) throw namedError("CorruptionError", `value record length mismatch: expected ${header.rawLength} bytes, got ${payload.byteLength}`);
484
+ return value;
485
+ }
486
+ return payload.slice();
487
+ }
488
+ if (header.rawLength > MAX_DECOMPRESSED_STORE_VALUE_BYTES) throw namedError("CorruptionError", `compressed value advertises ${header.rawLength} decompressed bytes, exceeding the ${MAX_DECOMPRESSED_STORE_VALUE_BYTES} byte limit`);
489
+ const decompressed = await decompressBytes(payload, compression, `value record (${compression})`, header.rawLength);
490
+ if (decompressed.byteLength !== header.rawLength) throw namedError("CorruptionError", `decompressed value length mismatch: expected ${header.rawLength} bytes, got ${decompressed.byteLength}`);
491
+ return decompressed;
492
+ }
493
+ async function wrapSnapshotWithCompression(snapshot, compression) {
494
+ if (compression === false) return snapshot;
495
+ const input = copyBytes(snapshot);
496
+ const compressed = await compressBytes(input, compression);
497
+ return buildEnvelope(SNAPSHOT_EXPORT_MAGIC, compressionTag(compression), input.byteLength, compressed);
498
+ }
499
+ async function unwrapSnapshotCompression(snapshot) {
500
+ const header = readEnvelopeHeader(SNAPSHOT_EXPORT_MAGIC, snapshot);
501
+ if (!header) return snapshot;
502
+ if (header.version !== ENVELOPE_VERSION) throw namedError("CorruptionError", `unsupported snapshot compression version: ${header.version}`);
503
+ const compression = compressionKindFromTag(header.kindTag);
504
+ if (compression === false) throw namedError("CorruptionError", "snapshot compression envelope cannot store kind \"none\"");
505
+ const payload = snapshot.subarray(ENVELOPE_HEADER_SIZE);
506
+ if (crc32(payload) !== header.payloadChecksum) throw namedError("CorruptionError", "snapshot compression checksum mismatch");
507
+ if (header.rawLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) throw namedError("CorruptionError", `compressed snapshot advertises ${header.rawLength} decompressed bytes, exceeding the ${MAX_DECOMPRESSED_SNAPSHOT_BYTES} byte limit`);
508
+ const decompressed = await decompressBytes(payload, compression, `snapshot export (${compression})`, header.rawLength);
509
+ if (decompressed.byteLength !== header.rawLength) throw namedError("CorruptionError", `decompressed snapshot length mismatch: expected ${header.rawLength} bytes, got ${decompressed.byteLength}`);
510
+ return decompressed;
511
+ }
512
+ //#endregion
513
+ //#region src/worker.ts
514
+ function toWasmU64(value) {
515
+ return BigInt(value);
516
+ }
517
+ function fromWasmU64(value) {
518
+ return typeof value === "bigint" ? Number(value) : value;
519
+ }
520
+ function fromOptionalWasmU64(value) {
521
+ return value === null || value === void 0 ? null : fromWasmU64(value);
522
+ }
523
+ function toWasmPutOptions(options) {
524
+ return options.ttl === void 0 ? options : {
525
+ ...options,
526
+ ttl: toWasmU64(options.ttl)
527
+ };
528
+ }
529
+ function toWasmRange(range) {
530
+ const normalized = {};
531
+ if (range.gt !== void 0) normalized.gt = range.gt;
532
+ if (range.gte !== void 0) normalized.gte = range.gte;
533
+ if (range.lt !== void 0) normalized.lt = range.lt;
534
+ if (range.lte !== void 0) normalized.lte = range.lte;
535
+ if (range.reverse !== void 0) normalized.reverse = range.reverse;
536
+ if (range.limit !== void 0) normalized.limit = range.limit;
537
+ return normalized;
538
+ }
539
+ var EMPTY_RANGE = {};
540
+ var EMPTY_VALUE = /* @__PURE__ */ new Uint8Array(0);
541
+ var MAX_ENGINE_KEY_BYTES = 1024;
542
+ var INDEX_SCAN_PAGE_ROWS = 256;
543
+ var INDEX_SCAN_RAW_CHUNK_ROWS = 512;
544
+ var RECONCILE_DOCUMENT_CACHE_BYTES = 4194304;
545
+ var RECONCILE_DOCUMENT_CACHE_ROWS = 4096;
546
+ var HEX_BYTE_STRINGS = Array.from({ length: 256 }, (_value, byte) => byte.toString(16).padStart(2, "0"));
547
+ var COMPRESSED_READ_CONCURRENCY = 8;
548
+ function getOrInsert(map, key, create) {
549
+ const existing = map.get(key);
550
+ if (existing !== void 0) return existing;
551
+ const created = create();
552
+ map.set(key, created);
553
+ return created;
554
+ }
555
+ var PERSISTENCE_BRIDGE_INIT = "moyodb:persistence-bridge:init";
556
+ var PERSISTENCE_BRIDGE_REQUEST = "moyodb:persistence-bridge:request";
557
+ var PERSISTENCE_BRIDGE_RESPONSE = "moyodb:persistence-bridge:response";
558
+ function isPersistenceBridgeResponse(value) {
559
+ return isRecord(value) && value.type === PERSISTENCE_BRIDGE_RESPONSE && typeof value.id === "number" && typeof value.granted === "boolean";
560
+ }
561
+ var MainThreadPersistenceBridge = class {
562
+ port = null;
563
+ nextRequestId = 1;
564
+ pending = /* @__PURE__ */ new Map();
565
+ readyResolve = null;
566
+ ready;
567
+ constructor() {
568
+ this.ready = new Promise((resolve) => {
569
+ this.readyResolve = resolve;
570
+ });
571
+ self.addEventListener("message", this.handleInitMessage);
572
+ }
573
+ async persisted() {
574
+ return this.request("persisted");
575
+ }
576
+ async persist() {
577
+ return this.request("persist");
578
+ }
579
+ close() {
580
+ self.removeEventListener("message", this.handleInitMessage);
581
+ if (this.readyResolve) {
582
+ this.readyResolve(null);
583
+ this.readyResolve = null;
584
+ }
585
+ if (this.port) {
586
+ this.port.onmessage = null;
587
+ this.port.close();
588
+ this.port = null;
589
+ }
590
+ for (const pending of this.pending.values()) pending.resolve(false);
591
+ this.pending.clear();
592
+ }
593
+ async request(op) {
594
+ const port = await this.ready;
595
+ if (!port || this.port !== port) return false;
596
+ return new Promise((resolve) => {
597
+ const id = this.nextRequestId;
598
+ this.nextRequestId += 1;
599
+ this.pending.set(id, { resolve });
600
+ const request = {
601
+ type: PERSISTENCE_BRIDGE_REQUEST,
602
+ id,
603
+ op
604
+ };
605
+ try {
606
+ port.postMessage(request);
607
+ } catch {
608
+ this.pending.delete(id);
609
+ resolve(false);
610
+ }
611
+ });
612
+ }
613
+ handleInitMessage = (event) => {
614
+ if (event.origin !== "" && event.origin !== self.location.origin) return;
615
+ if (event.data?.type !== PERSISTENCE_BRIDGE_INIT) return;
616
+ if (event.ports.length === 0) return;
617
+ const port = event.ports[0];
618
+ if (this.port) {
619
+ port.close();
620
+ return;
621
+ }
622
+ this.port = port;
623
+ this.port.onmessage = this.handleResponse;
624
+ this.port.start();
625
+ self.removeEventListener("message", this.handleInitMessage);
626
+ this.readyResolve?.(port);
627
+ this.readyResolve = null;
628
+ };
629
+ handleResponse = (event) => {
630
+ const data = event.data;
631
+ if (!isPersistenceBridgeResponse(data)) return;
632
+ const pending = this.pending.get(data.id);
633
+ if (!pending) return;
634
+ this.pending.delete(data.id);
635
+ pending.resolve(Boolean(data.granted));
636
+ };
637
+ };
638
+ async function estimateOriginStorage() {
639
+ const storage = navigator.storage;
640
+ if (typeof storage.estimate !== "function") return {
641
+ usage: 0,
642
+ quota: 0
643
+ };
644
+ const estimate = await storage.estimate();
645
+ return {
646
+ usage: estimate.usage ?? 0,
647
+ quota: estimate.quota ?? 0
648
+ };
649
+ }
650
+ function bytesToHex(bytes) {
651
+ let out = "";
652
+ for (let index = 0; index < bytes.byteLength; index += 1) out += HEX_BYTE_STRINGS[bytes[index]];
653
+ return out;
654
+ }
655
+ function bytesEqual(left, right) {
656
+ if (left.byteLength !== right.byteLength) return false;
657
+ for (let index = 0; index < left.byteLength; index += 1) if (left[index] !== right[index]) return false;
658
+ return true;
659
+ }
660
+ function normalizeWasmBytes(value) {
661
+ if (value instanceof Uint8Array) return value.byteOffset === 0 && value.byteLength === value.buffer.byteLength ? value : value.slice();
662
+ return new Uint8Array(value);
663
+ }
664
+ function errorName(error) {
665
+ if (!isRecord(error)) return null;
666
+ const candidate = error.name ?? error.code;
667
+ return typeof candidate === "string" ? candidate : null;
668
+ }
669
+ function isNamedError(error, name) {
670
+ return errorName(error) === name;
671
+ }
672
+ var INDEX_SNAPSHOT_TRAILER_MAGIC = utf8Encode("BDBIDX1");
673
+ var indexSnapshotDecoder = new TextDecoder("utf-8", { fatal: true });
674
+ function wrapSnapshotWithIndexDefinitions(snapshot, defs) {
675
+ if (defs.length === 0) return snapshot;
676
+ const manifest = utf8Encode(JSON.stringify(toPublicIndexDefinitions(defs)));
677
+ const lengthBuffer = /* @__PURE__ */ new ArrayBuffer(4);
678
+ new DataView(lengthBuffer).setUint32(0, manifest.byteLength, true);
679
+ const out = new Uint8Array(snapshot.byteLength + manifest.byteLength + 4 + INDEX_SNAPSHOT_TRAILER_MAGIC.byteLength);
680
+ let offset = 0;
681
+ out.set(snapshot, offset);
682
+ offset += snapshot.byteLength;
683
+ out.set(manifest, offset);
684
+ offset += manifest.byteLength;
685
+ out.set(new Uint8Array(lengthBuffer), offset);
686
+ offset += 4;
687
+ out.set(INDEX_SNAPSHOT_TRAILER_MAGIC, offset);
688
+ return out;
689
+ }
690
+ function unwrapSnapshotWithIndexDefinitions(data) {
691
+ const magicLength = INDEX_SNAPSHOT_TRAILER_MAGIC.byteLength;
692
+ if (data.byteLength < magicLength + 4) return {
693
+ snapshot: data,
694
+ indexes: []
695
+ };
696
+ const magicOffset = data.byteLength - magicLength;
697
+ if (!bytesEqual(data.subarray(magicOffset), INDEX_SNAPSHOT_TRAILER_MAGIC)) return {
698
+ snapshot: data,
699
+ indexes: []
700
+ };
701
+ const lengthOffset = magicOffset - 4;
702
+ if (lengthOffset < 0) return {
703
+ snapshot: data,
704
+ indexes: []
705
+ };
706
+ const manifestOffset = lengthOffset - new DataView(data.buffer, data.byteOffset + lengthOffset, 4).getUint32(0, true);
707
+ if (manifestOffset < 0) throw remoteError("CorruptionError", "invalid snapshot index trailer length");
708
+ let parsed;
709
+ try {
710
+ parsed = JSON.parse(indexSnapshotDecoder.decode(data.subarray(manifestOffset, lengthOffset)));
711
+ } catch (error) {
712
+ throw remoteError("CorruptionError", `invalid snapshot index trailer: ${String(error)}`);
713
+ }
714
+ return {
715
+ snapshot: data.subarray(0, manifestOffset),
716
+ indexes: normalizeIndexDefinitions(parsed)
717
+ };
718
+ }
719
+ function lifecycleEventChannel(dbName) {
720
+ return new BroadcastChannel(`db:${dbName}:events`);
721
+ }
722
+ function broadcastLifecycleEvent(dbName, type) {
723
+ const channel = lifecycleEventChannel(dbName);
724
+ try {
725
+ channel.postMessage({
726
+ type,
727
+ dbName,
728
+ txid: null
729
+ });
730
+ } finally {
731
+ channel.close();
732
+ }
733
+ }
734
+ var OwnershipLease = class {
735
+ releaseResolver = null;
736
+ requestPromise = null;
737
+ held = false;
738
+ async acquire(dbName, ownerWaitMs) {
739
+ const holdPromise = new Promise((resolve) => {
740
+ this.releaseResolver = resolve;
741
+ });
742
+ const lockName = `db:${dbName}:owner`;
743
+ if (ownerWaitMs === 0) {
744
+ let acquiredResolve = null;
745
+ const acquiredPromise = new Promise((resolve) => {
746
+ acquiredResolve = resolve;
747
+ });
748
+ const request = navigator.locks.request(lockName, {
749
+ mode: "exclusive",
750
+ ifAvailable: true
751
+ }, async (lock) => {
752
+ if (!lock) {
753
+ acquiredResolve?.(false);
754
+ return false;
755
+ }
756
+ this.held = true;
757
+ acquiredResolve?.(true);
758
+ await holdPromise;
759
+ return true;
760
+ });
761
+ if (!await acquiredPromise) throw remoteError("DatabaseBusyError", `database ${dbName} is already owned by another tab`);
762
+ this.requestPromise = request;
763
+ return;
764
+ }
765
+ const controller = new AbortController();
766
+ const timeout = setTimeout(() => controller.abort(), ownerWaitMs);
767
+ let acquiredResolve = null;
768
+ const acquiredPromise = new Promise((resolve) => {
769
+ acquiredResolve = resolve;
770
+ });
771
+ this.requestPromise = navigator.locks.request(lockName, {
772
+ mode: "exclusive",
773
+ signal: controller.signal
774
+ }, async (_lock) => {
775
+ clearTimeout(timeout);
776
+ this.held = true;
777
+ acquiredResolve?.();
778
+ await holdPromise;
779
+ return true;
780
+ });
781
+ try {
782
+ await Promise.race([acquiredPromise, this.requestPromise]);
783
+ } catch {
784
+ if (!this.held) throw remoteError("DatabaseBusyError", `timed out waiting for ownership of ${dbName}`);
785
+ }
786
+ }
787
+ async release() {
788
+ if (!this.held) return;
789
+ this.releaseResolver?.();
790
+ try {
791
+ await this.requestPromise;
792
+ } finally {
793
+ this.releaseResolver = null;
794
+ this.requestPromise = null;
795
+ this.held = false;
796
+ }
797
+ }
798
+ };
799
+ var DbWorker = class {
800
+ options;
801
+ dbName = null;
802
+ engine = null;
803
+ events = null;
804
+ lease = null;
805
+ wasmReady = null;
806
+ persistenceBridge;
807
+ txChanges = /* @__PURE__ */ new Map();
808
+ txModes = /* @__PURE__ */ new Map();
809
+ /**
810
+ * Shared committed schema at begin. Reconciliation replaces the array;
811
+ * it never mutates the shared schema.
812
+ */
813
+ txIndexSchemas = /* @__PURE__ */ new Map();
814
+ indexesBySchema = /* @__PURE__ */ new WeakMap();
815
+ txEnsuredRawStores = /* @__PURE__ */ new Map();
816
+ txIndexSchemaChanged = /* @__PURE__ */ new Set();
817
+ txStoreCompression = /* @__PURE__ */ new Map();
818
+ committedIndexes = null;
819
+ committedStoreCompression = null;
820
+ openOptions = null;
821
+ maintenanceOperation = null;
822
+ constructor(options = {}) {
823
+ this.options = options;
824
+ this.persistenceBridge = options.persistence ?? new MainThreadPersistenceBridge();
825
+ }
826
+ async open(request) {
827
+ if (this.engine) return;
828
+ assertSecureContext();
829
+ assertCapabilities();
830
+ this.dbName = request.dbName;
831
+ this.events = new BroadcastChannel(`db:${request.dbName}:events`);
832
+ this.lease = new OwnershipLease();
833
+ let engine = null;
834
+ try {
835
+ await this.lease.acquire(request.dbName, request.options.ownerWaitMs);
836
+ engine = new (await (this.loadWasm())).WasmEngine();
837
+ await engine.open(request.dbName, {
838
+ create_if_missing: request.options.createIfMissing,
839
+ cache_pages: request.options.cachePages
840
+ });
841
+ if (request.options.changeFeed) applyChangeFeedPolicy(engine, request.options.changeFeed);
842
+ if (request.options.debugFailpoint) engine.set_failpoint(request.options.debugFailpoint);
843
+ this.engine = engine;
844
+ this.openOptions = request.options;
845
+ this.clearRuntimeCaches();
846
+ this.maintenanceOperation = null;
847
+ this.events.postMessage({
848
+ type: "owner_changed",
849
+ dbName: request.dbName,
850
+ txid: null
851
+ });
852
+ } catch (err) {
853
+ await this.cleanupAfterFailedOpen(engine);
854
+ throw remapError(err);
855
+ }
856
+ }
857
+ async close() {
858
+ this.ensureNotInMaintenance();
859
+ const dbName = this.dbName;
860
+ this.clearRuntimeCaches();
861
+ try {
862
+ this.engine?.close();
863
+ } catch (err) {
864
+ throw remapError(err);
865
+ } finally {
866
+ this.engine = null;
867
+ if (dbName && this.events) this.events.postMessage({
868
+ type: "db_closed",
869
+ dbName,
870
+ txid: null
871
+ });
872
+ this.events?.close();
873
+ this.events = null;
874
+ if (dbName && this.lease) await this.lease.release();
875
+ if (dbName) broadcastLifecycleEvent(dbName, "owner_changed");
876
+ this.disposePersistenceBridge();
877
+ this.lease = null;
878
+ this.dbName = null;
879
+ this.openOptions = null;
880
+ this.maintenanceOperation = null;
881
+ }
882
+ }
883
+ async destroy() {
884
+ this.ensureNotInMaintenance();
885
+ const dbName = this.dbName;
886
+ if (!dbName) return;
887
+ let failure = null;
888
+ try {
889
+ this.rollbackAllTransactions();
890
+ this.engine?.abandon();
891
+ await (await this.loadWasm()).deleteDB(dbName);
892
+ broadcastLifecycleEvent(dbName, "db_deleted");
893
+ } catch (err) {
894
+ failure = err;
895
+ } finally {
896
+ this.engine = null;
897
+ this.clearRuntimeCaches();
898
+ this.events?.close();
899
+ this.events = null;
900
+ if (this.lease) try {
901
+ await this.lease.release();
902
+ } catch (err) {
903
+ if (failure === null) failure = err;
904
+ }
905
+ broadcastLifecycleEvent(dbName, "owner_changed");
906
+ this.disposePersistenceBridge();
907
+ this.lease = null;
908
+ this.dbName = null;
909
+ this.openOptions = null;
910
+ this.maintenanceOperation = null;
911
+ }
912
+ if (failure !== null) throw remapError(failure);
913
+ }
914
+ async deleteDB(dbName) {
915
+ assertSecureContext();
916
+ assertCapabilities();
917
+ const lease = new OwnershipLease();
918
+ let failure = null;
919
+ let acquired = false;
920
+ try {
921
+ await lease.acquire(dbName, 0);
922
+ acquired = true;
923
+ await (await this.loadWasm()).deleteDB(dbName);
924
+ broadcastLifecycleEvent(dbName, "db_deleted");
925
+ } catch (err) {
926
+ failure = err;
927
+ } finally {
928
+ try {
929
+ await lease.release();
930
+ } catch (err) {
931
+ if (failure === null) failure = err;
932
+ }
933
+ if (acquired) broadcastLifecycleEvent(dbName, "owner_changed");
934
+ }
935
+ if (failure !== null) throw remapError(failure);
936
+ }
937
+ begin(mode) {
938
+ this.recoverEngineIfNeeded();
939
+ const indexSchema = this.loadCommittedIndexSchema();
940
+ const storeCompression = this.loadCommittedStoreCompression();
941
+ const txId = fromWasmU64(this.withEngine((engine) => engine.begin_tx(mode)));
942
+ this.txChanges.set(txId, /* @__PURE__ */ new Map());
943
+ this.txModes.set(txId, mode);
944
+ this.txIndexSchemas.set(txId, indexSchema);
945
+ this.txStoreCompression.set(txId, {
946
+ owned: false,
947
+ values: storeCompression
948
+ });
949
+ return Promise.resolve(txId);
950
+ }
951
+ commit(txId) {
952
+ const tracked = this.txChanges.get(txId) ?? /* @__PURE__ */ new Map();
953
+ const indexOverride = this.txIndexSchemaChanged.has(txId) ? this.txIndexSchemas.get(txId) : void 0;
954
+ const storeCompressionSnapshot = this.txStoreCompression.get(txId);
955
+ const txMode = this.txModes.get(txId);
956
+ let txid;
957
+ try {
958
+ txid = fromWasmU64(this.withEngine((engine) => engine.commit_tx(toWasmU64(txId))));
959
+ } catch (err) {
960
+ try {
961
+ if (this.engine && !this.engine.needs_recovery()) this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)));
962
+ } catch {}
963
+ this.cleanupTxState(txId);
964
+ const recovery = this.recoverEngineIfNeeded();
965
+ if (!recovery?.pendingCommitted || recovery.pendingTxid === null || isNamedError(err, "RecoveryRequiredError") || isNamedError(err, "InjectedFailureError")) throw err;
966
+ txid = recovery.pendingTxid;
967
+ }
968
+ if (indexOverride) this.committedIndexes = cloneNormalizedIndexDefinitions(indexOverride);
969
+ if (txMode === "readwrite" && storeCompressionSnapshot) this.committedStoreCompression = storeCompressionSnapshot.values;
970
+ this.cleanupTxState(txId);
971
+ if (this.dbName && this.events) {
972
+ const event = {
973
+ type: "commit_applied",
974
+ dbName: this.dbName,
975
+ txid,
976
+ stores: this.finalizeTrackedChanges(tracked)
977
+ };
978
+ this.events.postMessage(event);
979
+ }
980
+ return Promise.resolve(txid);
981
+ }
982
+ rollback(txId) {
983
+ try {
984
+ this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)));
985
+ } finally {
986
+ this.cleanupTxState(txId);
987
+ }
988
+ return Promise.resolve();
989
+ }
990
+ async autocommit(mode, command, args) {
991
+ const txId = await this.begin(mode);
992
+ const method = this[command];
993
+ let result;
994
+ try {
995
+ result = await method.apply(this, [txId, ...args]);
996
+ } catch (error) {
997
+ try {
998
+ await this.rollback(txId);
999
+ } catch {}
1000
+ throw error;
1001
+ }
1002
+ if (mode === "readwrite") await this.commit(txId);
1003
+ else await this.rollback(txId);
1004
+ return result;
1005
+ }
1006
+ createStore(txId, name, options = {}) {
1007
+ const compression = options.compression ?? false;
1008
+ this.txEnsuredRawStores.get(txId)?.delete(name);
1009
+ this.withEngine((engine) => engine.create_store(toWasmU64(txId), name, { compression }));
1010
+ this.recordStoreCompressionCreate(txId, name, compression);
1011
+ this.ensureInternalStoresForStore(txId, name);
1012
+ this.markStoreTouched(txId, name);
1013
+ return Promise.resolve();
1014
+ }
1015
+ dropStore(txId, name) {
1016
+ const defs = this.indexesForStoreInTx(txId, name);
1017
+ this.txEnsuredRawStores.get(txId)?.delete(name);
1018
+ this.withEngine((engine) => engine.drop_store(toWasmU64(txId), name));
1019
+ this.recordStoreCompressionDrop(txId, name);
1020
+ for (const def of defs) this.dropRawStoreIfExists(txId, def.internalStore);
1021
+ this.recordStoreLevelChange(txId, name, "drop");
1022
+ return Promise.resolve();
1023
+ }
1024
+ clearStore(txId, name) {
1025
+ const defs = this.indexesForStoreInTx(txId, name);
1026
+ this.txEnsuredRawStores.get(txId)?.delete(name);
1027
+ this.withEngine((engine) => engine.clear_store(toWasmU64(txId), name));
1028
+ for (const def of defs) this.clearRawStoreIfExists(txId, def.internalStore);
1029
+ this.recordStoreLevelChange(txId, name, "clear");
1030
+ return Promise.resolve();
1031
+ }
1032
+ async get(txId, store, key) {
1033
+ return this.readStoreValue(txId, store, key);
1034
+ }
1035
+ async getMany(txId, store, keys) {
1036
+ const values = this.withEngine((engine) => engine.get_many(toWasmU64(txId), store, keys));
1037
+ const compressed = !isInternalStoreName(store) && this.storeCompressionForTx(txId, store) !== false;
1038
+ for (let index = 0; index < values.length; index += 1) {
1039
+ const value = values[index];
1040
+ if (value !== null) values[index] = normalizeWasmBytes(value);
1041
+ }
1042
+ return compressed ? this.decodeStoreValues(txId, store, values) : values;
1043
+ }
1044
+ async getManyPacked(txId, store, packedKeys) {
1045
+ const packed = normalizeWasmBytes(this.withEngine((engine) => engine.get_many_packed(toWasmU64(txId), store, packedKeys)));
1046
+ if (isInternalStoreName(store) || this.storeCompressionForTx(txId, store) === false) return packedOptionalValues(packed);
1047
+ return this.decodeStoreValues(txId, store, unpackPackedOptionalValues(packed));
1048
+ }
1049
+ has(txId, store, key) {
1050
+ return Promise.resolve(this.withEngine((engine) => engine.has(toWasmU64(txId), store, key)));
1051
+ }
1052
+ async put(txId, store, key, value, options = {}) {
1053
+ const defs = this.indexesForStoreInTx(txId, store);
1054
+ if (defs.length === 0) {
1055
+ const storedValue = await this.encodeStoreValueForWrite(txId, store, value);
1056
+ const baselineExists = this.withEngine((engine) => engine.put(toWasmU64(txId), store, key, storedValue, toWasmPutOptions(options)));
1057
+ this.recordPutChange(txId, store, key, baselineExists);
1058
+ return;
1059
+ }
1060
+ const oldValue = await this.readStoreValue(txId, store, key);
1061
+ const oldKeyFor = oldValue === null ? null : createIndexKeyExtractor(oldValue);
1062
+ const newKeyFor = createIndexKeyExtractor(value);
1063
+ const plans = defs.map((def) => {
1064
+ return {
1065
+ def,
1066
+ oldLogicalKey: oldKeyFor === null ? null : oldKeyFor(def),
1067
+ newLogicalKey: newKeyFor(def),
1068
+ newPhysicalKey: null
1069
+ };
1070
+ });
1071
+ this.ensureInternalStoresForDefinitions(txId, defs);
1072
+ for (const plan of plans) {
1073
+ if (plan.newLogicalKey === null) continue;
1074
+ plan.newPhysicalKey = this.buildIndexEntryKey(plan.def, plan.newLogicalKey, key);
1075
+ if (plan.oldLogicalKey !== null && bytesEqual(plan.oldLogicalKey, plan.newLogicalKey)) continue;
1076
+ await this.assertUniqueIndexAvailability(txId, plan.def, plan.newLogicalKey, key);
1077
+ }
1078
+ const storedValue = await this.encodeStoreValueForWrite(txId, store, value);
1079
+ const baselineExists = this.withEngine((engine) => engine.put(toWasmU64(txId), store, key, storedValue, toWasmPutOptions(options)));
1080
+ for (const plan of plans) {
1081
+ if (plan.oldLogicalKey === null) continue;
1082
+ if (plan.newLogicalKey !== null && bytesEqual(plan.oldLogicalKey, plan.newLogicalKey)) continue;
1083
+ this.deleteIndexEntryIfPresent(txId, plan.def, plan.oldLogicalKey, key);
1084
+ }
1085
+ for (const plan of plans) {
1086
+ if (plan.newLogicalKey === null) continue;
1087
+ if (plan.oldLogicalKey !== null && bytesEqual(plan.oldLogicalKey, plan.newLogicalKey)) continue;
1088
+ if (plan.newPhysicalKey === null) throw remoteError("InternalError", "missing index entry key");
1089
+ this.putIndexEntry(txId, plan.def, plan.newPhysicalKey, EMPTY_VALUE);
1090
+ }
1091
+ this.recordPutChange(txId, store, key, baselineExists);
1092
+ }
1093
+ async putMany(txId, store, entries, options = {}) {
1094
+ if (entries.length === 0) return;
1095
+ if (this.indexesForStoreInTx(txId, store).length === 0) {
1096
+ const storedEntries = await this.encodeEntriesForWrite(txId, store, entries);
1097
+ let baselines;
1098
+ try {
1099
+ baselines = this.withEngine((engine) => engine.put_many(toWasmU64(txId), store, storedEntries, toWasmPutOptions(options)));
1100
+ } catch (error) {
1101
+ const partial = partialBooleanOutcomes(error);
1102
+ this.recordPutChanges(txId, store, entries, partial);
1103
+ throw error;
1104
+ }
1105
+ if (baselines.length !== entries.length) throw remoteError("InternalError", `put_many outcome count mismatch: ${baselines.length} != ${entries.length}`);
1106
+ this.recordPutChanges(txId, store, entries, baselines);
1107
+ return;
1108
+ }
1109
+ for (const [key, value] of entries) await this.put(txId, store, key, value, options);
1110
+ }
1111
+ async putManyPacked(txId, store, packedEntries, options = {}) {
1112
+ if (this.indexesForStoreInTx(txId, store).length !== 0 || this.storeCompressionForTx(txId, store) !== false) {
1113
+ await this.putMany(txId, store, unpackPackedBinaryPairs(packedEntries), options);
1114
+ return;
1115
+ }
1116
+ const keys = unpackPackedBinaryPairKeys(packedEntries);
1117
+ if (keys.length === 0) return;
1118
+ let baselines;
1119
+ try {
1120
+ baselines = this.withEngine((engine) => engine.put_many_packed(toWasmU64(txId), store, packedEntries, toWasmPutOptions(options)));
1121
+ } catch (error) {
1122
+ const partial = partialBooleanOutcomes(error);
1123
+ this.recordPutKeyChanges(txId, store, keys, partial);
1124
+ throw error;
1125
+ }
1126
+ if (baselines.length !== keys.length) throw remoteError("InternalError", `put_many_packed outcome count mismatch: ${baselines.length} != ${keys.length}`);
1127
+ this.recordPutKeyChanges(txId, store, keys, baselines);
1128
+ }
1129
+ async delete(txId, store, key) {
1130
+ const defs = this.indexesForStoreInTx(txId, store);
1131
+ const oldValue = defs.length === 0 ? null : await this.readStoreValue(txId, store, key);
1132
+ const oldKeyFor = oldValue === null ? null : createIndexKeyExtractor(oldValue);
1133
+ const oldLogicalKeys = oldKeyFor === null ? [] : defs.map((def) => ({
1134
+ def,
1135
+ logicalKey: oldKeyFor(def)
1136
+ }));
1137
+ if (!this.withEngine((engine) => engine.delete(toWasmU64(txId), store, key))) {
1138
+ this.recordDeleteChange(txId, store, key, false);
1139
+ return false;
1140
+ }
1141
+ for (const entry of oldLogicalKeys) if (entry.logicalKey !== null) this.deleteIndexEntryIfPresent(txId, entry.def, entry.logicalKey, key);
1142
+ this.recordDeleteChange(txId, store, key, true);
1143
+ return true;
1144
+ }
1145
+ async deleteMany(txId, store, keys) {
1146
+ if (keys.length === 0) return;
1147
+ if (this.indexesForStoreInTx(txId, store).length === 0) {
1148
+ let deleted;
1149
+ try {
1150
+ deleted = this.withEngine((engine) => engine.delete_many(toWasmU64(txId), store, keys));
1151
+ } catch (error) {
1152
+ const partial = partialBooleanOutcomes(error);
1153
+ for (let i = 0; i < partial.length && i < keys.length; i += 1) this.recordDeleteChange(txId, store, keys[i], partial[i]);
1154
+ throw error;
1155
+ }
1156
+ if (deleted.length !== keys.length) throw remoteError("InternalError", `delete_many outcome count mismatch: ${deleted.length} != ${keys.length}`);
1157
+ for (let i = 0; i < keys.length; i += 1) this.recordDeleteChange(txId, store, keys[i], deleted[i]);
1158
+ return;
1159
+ }
1160
+ for (const key of keys) await this.delete(txId, store, key);
1161
+ }
1162
+ async deleteManyPacked(txId, store, packedKeys) {
1163
+ const defs = this.indexesForStoreInTx(txId, store);
1164
+ const keys = unpackPackedBinaryList(packedKeys);
1165
+ if (keys.length === 0) return;
1166
+ if (defs.length !== 0) {
1167
+ await this.deleteMany(txId, store, keys);
1168
+ return;
1169
+ }
1170
+ let deleted;
1171
+ try {
1172
+ deleted = this.withEngine((engine) => engine.delete_many_packed(toWasmU64(txId), store, packedKeys));
1173
+ } catch (error) {
1174
+ const partial = partialBooleanOutcomes(error);
1175
+ for (let i = 0; i < partial.length && i < keys.length; i += 1) this.recordDeleteChange(txId, store, keys[i], partial[i]);
1176
+ throw error;
1177
+ }
1178
+ if (deleted.length !== keys.length) throw remoteError("InternalError", `delete_many_packed outcome count mismatch: ${deleted.length} != ${keys.length}`);
1179
+ for (let i = 0; i < keys.length; i += 1) this.recordDeleteChange(txId, store, keys[i], deleted[i] === 1);
1180
+ }
1181
+ async applyBatch(txId, store, ops) {
1182
+ if (ops.length === 0) return;
1183
+ if (this.indexesForStoreInTx(txId, store).length === 0) {
1184
+ const storedOps = await this.encodeBatchOpsForWrite(txId, store, ops);
1185
+ let outcomes;
1186
+ try {
1187
+ outcomes = this.withEngine((engine) => engine.apply_batch(toWasmU64(txId), store, storedOps));
1188
+ } catch (error) {
1189
+ this.recordBatchOutcomes(txId, store, ops, partialBatchOutcomes(error));
1190
+ throw error;
1191
+ }
1192
+ if (outcomes.length !== ops.length) throw remoteError("InternalError", `apply_batch outcome count mismatch: ${outcomes.length} != ${ops.length}`);
1193
+ this.recordBatchOutcomes(txId, store, ops, outcomes);
1194
+ return;
1195
+ }
1196
+ for (const op of ops) if (op.kind === "put") await this.put(txId, store, op.key, op.value);
1197
+ else await this.delete(txId, store, op.key);
1198
+ }
1199
+ async applyBatchPacked(txId, store, packedOps) {
1200
+ if (this.indexesForStoreInTx(txId, store).length !== 0 || this.storeCompressionForTx(txId, store) !== false) {
1201
+ const ops = unpackPackedBatchOps(packedOps);
1202
+ if (ops.length === 0) return;
1203
+ await this.applyBatch(txId, store, ops);
1204
+ return;
1205
+ }
1206
+ const ops = unpackPackedBatchOpKeys(packedOps);
1207
+ if (ops.length === 0) return;
1208
+ let flags;
1209
+ try {
1210
+ flags = this.withEngine((engine) => engine.apply_batch_packed(toWasmU64(txId), store, packedOps));
1211
+ } catch (error) {
1212
+ this.recordBatchKeyOutcomes(txId, store, ops, partialBatchOutcomes(error));
1213
+ throw error;
1214
+ }
1215
+ if (flags.length !== ops.length) throw remoteError("InternalError", `apply_batch_packed outcome count mismatch: ${flags.length} != ${ops.length}`);
1216
+ for (let i = 0; i < ops.length; i += 1) {
1217
+ const op = ops[i];
1218
+ if (op.kind === "put") this.recordPutChange(txId, store, op.key, flags[i] === 1);
1219
+ else this.recordDeleteChange(txId, store, op.key, flags[i] === 1);
1220
+ }
1221
+ }
1222
+ async scan(txId, store, range) {
1223
+ return this.readStoreScan(txId, store, range);
1224
+ }
1225
+ async getByIndex(txId, store, indexName, key) {
1226
+ const def = this.resolveIndexDefinition(txId, store, indexName);
1227
+ const page = await this.loadVisibleIndexPage(txId, def, prefixRange(key), null, 1);
1228
+ return page.rows.length === 0 ? null : page.rows[0].value;
1229
+ }
1230
+ async scanByIndex(txId, store, indexName, range = {}) {
1231
+ const def = this.resolveIndexDefinition(txId, store, indexName);
1232
+ const rows = [];
1233
+ let remaining = range.limit ?? Number.POSITIVE_INFINITY;
1234
+ let cursor = null;
1235
+ while (remaining > 0) {
1236
+ const page = await this.loadVisibleIndexPage(txId, def, range, cursor, Math.min(remaining, INDEX_SCAN_PAGE_ROWS));
1237
+ rows.push(...page.rows);
1238
+ remaining -= page.rows.length;
1239
+ if (page.cursor === null) break;
1240
+ cursor = page.cursor;
1241
+ }
1242
+ return rows;
1243
+ }
1244
+ async scanByIndexPage(txId, store, indexName, range, cursor, limit) {
1245
+ if (!Number.isSafeInteger(limit) || limit <= 0) throw remoteError("InvalidRangeError", "index scan page limit must be a positive integer");
1246
+ const def = this.resolveIndexDefinition(txId, store, indexName);
1247
+ return this.loadVisibleIndexPage(txId, def, range, cursor, limit);
1248
+ }
1249
+ getIndexes(txId) {
1250
+ return Promise.resolve(toPublicIndexDefinitions(txId === void 0 ? this.loadCommittedIndexSchema() : this.indexSchemaForTx(txId)));
1251
+ }
1252
+ async reconcileIndexes(txId, indexes) {
1253
+ const target = normalizeIndexDefinitions(indexes);
1254
+ this.ensureRawStore(txId, INDEX_METADATA_STORE);
1255
+ const current = this.readIndexSchemaInTx(txId);
1256
+ const targetStores = new Set(target.map((def) => def.internalStore));
1257
+ for (const def of current) if (!targetStores.has(def.internalStore)) this.dropRawStoreIfExists(txId, def.internalStore);
1258
+ this.clearRawStoreIfExists(txId, INDEX_METADATA_STORE);
1259
+ let documentStore = null;
1260
+ let cachedBytes = 0;
1261
+ let sourceRows = null;
1262
+ const canRefreshVisibility = typeof this.engine?.has_many === "function";
1263
+ const documents = /* @__PURE__ */ new Map();
1264
+ for (const def of target) {
1265
+ if (documentStore !== def.store) {
1266
+ documents.clear();
1267
+ cachedBytes = 0;
1268
+ sourceRows = null;
1269
+ documentStore = def.store;
1270
+ }
1271
+ this.ensureRawStore(txId, def.internalStore);
1272
+ this.clearRawStoreIfExists(txId, def.internalStore);
1273
+ if (this.rawStoreExistsInTx(txId, def.store)) {
1274
+ let rows;
1275
+ if (sourceRows !== null) {
1276
+ const visible = this.withEngine((engine) => engine.has_many(toWasmU64(txId), def.store, sourceRows.map((row) => row.key)));
1277
+ if (visible.length !== sourceRows.length) throw remoteError("InternalError", `has_many outcome count mismatch: ${visible.length} != ${sourceRows.length}`);
1278
+ rows = sourceRows.filter((_row, index) => visible[index]);
1279
+ } else {
1280
+ rows = await this.readStoreScan(txId, def.store, EMPTY_RANGE);
1281
+ if (canRefreshVisibility && rows.length <= RECONCILE_DOCUMENT_CACHE_ROWS) {
1282
+ let inputBytes = 0;
1283
+ for (const row of rows) {
1284
+ inputBytes += row.key.byteLength + row.value.byteLength;
1285
+ if (inputBytes > RECONCILE_DOCUMENT_CACHE_BYTES) break;
1286
+ }
1287
+ if (inputBytes <= RECONCILE_DOCUMENT_CACHE_BYTES) sourceRows = rows;
1288
+ }
1289
+ }
1290
+ for (const row of rows) {
1291
+ const token = bytesToHex(row.key);
1292
+ const cached = documents.get(token);
1293
+ let document;
1294
+ if (cached && (cached.bytes === row.value || bytesEqual(cached.bytes, row.value))) {
1295
+ document = cached.document;
1296
+ cached.bytes = row.value;
1297
+ } else {
1298
+ document = decodeIndexedDocument(row.value);
1299
+ const previousBytes = cached?.inputBytes ?? 0;
1300
+ const inputBytes = row.key.byteLength + row.value.byteLength;
1301
+ if ((cached || documents.size < RECONCILE_DOCUMENT_CACHE_ROWS) && cachedBytes - previousBytes + inputBytes <= RECONCILE_DOCUMENT_CACHE_BYTES) {
1302
+ documents.set(token, {
1303
+ bytes: row.value,
1304
+ inputBytes,
1305
+ document
1306
+ });
1307
+ cachedBytes += inputBytes - previousBytes;
1308
+ } else if (cached) {
1309
+ documents.delete(token);
1310
+ cachedBytes -= previousBytes;
1311
+ }
1312
+ }
1313
+ const logicalKey = extractLogicalIndexKeyFromDocument(def, document);
1314
+ if (logicalKey === null) continue;
1315
+ await this.assertUniqueIndexAvailability(txId, def, logicalKey, row.key);
1316
+ this.putIndexEntry(txId, def, this.buildIndexEntryKey(def, logicalKey, row.key), EMPTY_VALUE);
1317
+ }
1318
+ }
1319
+ this.putRawValue(txId, INDEX_METADATA_STORE, encodeIndexMetadataKey(def.store, def.name), encodeIndexMetadataValue(def));
1320
+ }
1321
+ this.txIndexSchemas.set(txId, cloneNormalizedIndexDefinitions(target));
1322
+ this.txIndexSchemaChanged.add(txId);
1323
+ }
1324
+ listStores() {
1325
+ return Promise.resolve(this.currentStoreNames());
1326
+ }
1327
+ getVersion() {
1328
+ return Promise.resolve(fromWasmU64(this.withEngine((engine) => engine.get_schema_version())));
1329
+ }
1330
+ async changesSince(txId, options = {}) {
1331
+ const visibleStores = options.stores?.filter((store) => !isInternalStoreName(store));
1332
+ const engineOptions = {
1333
+ ...options,
1334
+ stores: visibleStores ? [...visibleStores] : void 0,
1335
+ limit: visibleStores ? options.limit : void 0
1336
+ };
1337
+ const feed = this.withEngine((engine) => engine.changes_since(toWasmU64(txId), engineOptions));
1338
+ const allowedStores = visibleStores ? new Set(visibleStores) : null;
1339
+ const changes = [];
1340
+ for (const change of feed.changes) {
1341
+ if (isInternalStoreName(change.store)) continue;
1342
+ if (allowedStores && !allowedStores.has(change.store)) continue;
1343
+ const key = options.limit === void 0 || changes.length < options.limit ? normalizeWasmBytes(change.key) : null;
1344
+ let value;
1345
+ if (change.value !== void 0) value = await this.decodeStoreValueForFeed(change.store, normalizeWasmBytes(change.value));
1346
+ if (key === null) continue;
1347
+ changes.push({
1348
+ txId: fromWasmU64(change.txId),
1349
+ store: change.store,
1350
+ key,
1351
+ kind: change.kind,
1352
+ value
1353
+ });
1354
+ }
1355
+ return {
1356
+ latestTxId: fromWasmU64(feed.latestTxId),
1357
+ changes
1358
+ };
1359
+ }
1360
+ setSchemaVersion(txId, version) {
1361
+ this.withEngine((engine) => engine.set_schema_version(toWasmU64(txId), toWasmU64(version)));
1362
+ return Promise.resolve();
1363
+ }
1364
+ async exportSnapshot(options = {}) {
1365
+ const defs = cloneNormalizedIndexDefinitions(this.loadCommittedIndexSchema());
1366
+ return await wrapSnapshotWithCompression(wrapSnapshotWithIndexDefinitions(normalizeWasmBytes(this.withEngine((engine) => engine.export_snapshot())), defs), options.compression ?? false);
1367
+ }
1368
+ async importSnapshot(data) {
1369
+ this.rollbackAllTransactions();
1370
+ const parsed = unwrapSnapshotWithIndexDefinitions(await unwrapSnapshotCompression(data));
1371
+ this.withEngine((engine) => engine.import_snapshot(parsed.snapshot));
1372
+ this.committedIndexes = [];
1373
+ this.committedStoreCompression = null;
1374
+ await this.applyCommittedIndexSchema(parsed.indexes);
1375
+ }
1376
+ async reset() {
1377
+ const dbName = this.dbName;
1378
+ if (!dbName) throw remoteError("InternalError", "engine is not open");
1379
+ const defs = cloneNormalizedIndexDefinitions(this.loadCommittedIndexSchema());
1380
+ this.rollbackAllTransactions();
1381
+ const stores = this.currentStoreNames().map((store) => ({
1382
+ store,
1383
+ changes: [{
1384
+ key: /* @__PURE__ */ new Uint8Array(0),
1385
+ kind: "clear"
1386
+ }]
1387
+ }));
1388
+ const txid = fromWasmU64(this.withEngine((engine) => engine.reset()));
1389
+ this.committedIndexes = [];
1390
+ await this.applyCommittedIndexSchema(defs);
1391
+ if (this.events) {
1392
+ const event = {
1393
+ type: "commit_applied",
1394
+ dbName,
1395
+ txid,
1396
+ stores
1397
+ };
1398
+ this.events.postMessage(event);
1399
+ }
1400
+ }
1401
+ async compact() {
1402
+ return this.runCompactionOperation("compact");
1403
+ }
1404
+ async rebuild() {
1405
+ return this.runCompactionOperation("rebuild");
1406
+ }
1407
+ stats() {
1408
+ const stats = this.withEngine((engine) => engine.stats());
1409
+ return Promise.resolve({
1410
+ ...stats,
1411
+ db_id: fromWasmU64(stats.db_id),
1412
+ catalog_root_page_id: fromWasmU64(stats.catalog_root_page_id),
1413
+ next_page_id: fromWasmU64(stats.next_page_id),
1414
+ last_committed_txid: fromWasmU64(stats.last_committed_txid),
1415
+ last_replayed_wal_offset: fromWasmU64(stats.last_replayed_wal_offset),
1416
+ manifest_len: fromWasmU64(stats.manifest_len),
1417
+ main_len: fromWasmU64(stats.main_len),
1418
+ wal_len: fromWasmU64(stats.wal_len),
1419
+ health: normalizeEngineHealth(stats.health),
1420
+ store_count: this.currentStoreNames().length
1421
+ });
1422
+ }
1423
+ async storageInfo() {
1424
+ const [dbSize, estimate, persisted] = await Promise.all([
1425
+ this.dbDirectorySize(),
1426
+ estimateOriginStorage(),
1427
+ this.persistenceBridge.persisted()
1428
+ ]);
1429
+ return {
1430
+ dbSize,
1431
+ originUsage: estimate.usage,
1432
+ originQuota: estimate.quota,
1433
+ persisted
1434
+ };
1435
+ }
1436
+ async requestPersistence() {
1437
+ return this.persistenceBridge.persist();
1438
+ }
1439
+ setFailpoint(failpoint) {
1440
+ this.withEngine((engine) => engine.set_failpoint(failpoint));
1441
+ return Promise.resolve();
1442
+ }
1443
+ requireDbName() {
1444
+ if (!this.dbName) throw remoteError("InternalError", "engine is not open");
1445
+ return this.dbName;
1446
+ }
1447
+ ensureNotInMaintenance() {
1448
+ if (!this.maintenanceOperation) return;
1449
+ throw remoteError("DatabaseBusyError", `database ${this.dbName ?? "database"} is busy: ${this.maintenanceOperation} in progress`);
1450
+ }
1451
+ currentCachePages() {
1452
+ return this.openOptions?.cachePages ?? 256;
1453
+ }
1454
+ async dbDirectorySize() {
1455
+ return (await this.loadWasm()).dbDirectorySize(this.requireDbName());
1456
+ }
1457
+ async applyCommittedIndexSchema(defs) {
1458
+ const normalized = cloneNormalizedIndexDefinitions(defs);
1459
+ if (normalized.length === 0) {
1460
+ this.committedIndexes = [];
1461
+ return;
1462
+ }
1463
+ const txId = fromWasmU64(this.withEngine((engine) => engine.begin_tx("readwrite"), { allowDuringMaintenance: true }));
1464
+ this.txChanges.set(txId, /* @__PURE__ */ new Map());
1465
+ this.txModes.set(txId, "readwrite");
1466
+ this.txStoreCompression.set(txId, {
1467
+ owned: false,
1468
+ values: this.loadCommittedStoreCompression()
1469
+ });
1470
+ try {
1471
+ await this.reconcileIndexes(txId, toPublicIndexDefinitions(normalized));
1472
+ this.withEngine((engine) => engine.commit_tx(toWasmU64(txId)), { allowDuringMaintenance: true });
1473
+ this.committedIndexes = cloneNormalizedIndexDefinitions(normalized);
1474
+ } catch (error) {
1475
+ try {
1476
+ this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)), { allowDuringMaintenance: true });
1477
+ } catch {}
1478
+ throw error;
1479
+ } finally {
1480
+ this.cleanupTxState(txId);
1481
+ }
1482
+ }
1483
+ /**
1484
+ * Publishes a fresh generation only if the active generation has not changed.
1485
+ * A failed swap may have reached storage; read the control file before cleanup.
1486
+ * After publication, abandon the old engine to avoid a checkpoint into inactive files.
1487
+ */
1488
+ async runCompactionOperation(operation) {
1489
+ const dbName = this.requireDbName();
1490
+ if (this.maintenanceOperation) throw remoteError("DatabaseBusyError", `database ${dbName} is busy: ${this.maintenanceOperation} in progress`);
1491
+ this.maintenanceOperation = operation;
1492
+ const start = performance.now();
1493
+ const wasm = await this.loadWasm();
1494
+ let rebuiltEngine = null;
1495
+ let generationName = null;
1496
+ let published = false;
1497
+ try {
1498
+ const sizeBefore = await wasm.dbDirectorySize(dbName);
1499
+ const defs = cloneNormalizedIndexDefinitions(this.loadCommittedIndexSchema());
1500
+ this.rollbackAllTransactions({ allowDuringMaintenance: true });
1501
+ const expectedGeneration = await wasm.readActiveGeneration(dbName);
1502
+ generationName = (await wasm.prepareRebuildTarget(dbName)).generationName;
1503
+ rebuiltEngine = new wasm.WasmEngine();
1504
+ await rebuiltEngine.openGeneration(dbName, generationName, {
1505
+ create_if_missing: true,
1506
+ cache_pages: this.currentCachePages()
1507
+ });
1508
+ const target = rebuiltEngine;
1509
+ this.withEngine((engine) => operation === "rebuild" ? engine.compact_into_skipping_stores(target, [...defs.map((def) => def.internalStore), INDEX_METADATA_STORE]) : engine.compact_into(target), { allowDuringMaintenance: true });
1510
+ if (operation === "rebuild" && defs.length > 0) {
1511
+ const previousEngine = this.engine;
1512
+ const previousMaintenance = this.maintenanceOperation;
1513
+ this.engine = target;
1514
+ this.maintenanceOperation = null;
1515
+ try {
1516
+ this.committedIndexes = [];
1517
+ this.committedStoreCompression = null;
1518
+ await this.applyCommittedIndexSchema(defs);
1519
+ } finally {
1520
+ this.engine = previousEngine;
1521
+ this.maintenanceOperation = previousMaintenance;
1522
+ this.committedStoreCompression = null;
1523
+ }
1524
+ }
1525
+ try {
1526
+ await wasm.swapActiveGeneration(dbName, generationName, expectedGeneration);
1527
+ published = true;
1528
+ } catch (swapError) {
1529
+ published = await readActiveGenerationOrNull(wasm, dbName) === generationName;
1530
+ if (!published) throw swapError;
1531
+ }
1532
+ const previousEngine = this.engine;
1533
+ this.engine = rebuiltEngine;
1534
+ rebuiltEngine = null;
1535
+ this.committedIndexes = defs;
1536
+ this.committedStoreCompression = null;
1537
+ try {
1538
+ previousEngine?.abandon();
1539
+ } catch {}
1540
+ try {
1541
+ await wasm.cleanupInactiveEntries(dbName);
1542
+ } catch {}
1543
+ const sizeAfter = await wasm.dbDirectorySize(dbName);
1544
+ return {
1545
+ sizeBefore,
1546
+ sizeAfter,
1547
+ reclaimedBytes: Math.max(0, sizeBefore - sizeAfter),
1548
+ durationMs: performance.now() - start
1549
+ };
1550
+ } catch (error) {
1551
+ if (!published) {
1552
+ this.committedIndexes = null;
1553
+ this.committedStoreCompression = null;
1554
+ try {
1555
+ rebuiltEngine?.abandon();
1556
+ } catch {}
1557
+ if (generationName !== null) {
1558
+ const active = await readActiveGenerationOrNull(wasm, dbName);
1559
+ if (active !== void 0 && active !== generationName) try {
1560
+ await wasm.cleanupInactiveEntries(dbName);
1561
+ } catch {}
1562
+ }
1563
+ }
1564
+ throw remapError(error);
1565
+ } finally {
1566
+ this.maintenanceOperation = null;
1567
+ }
1568
+ }
1569
+ /**
1570
+ * Returns null when no recovery is needed. A recovery attempt invalidates
1571
+ * all open transactions, even if recovery fails.
1572
+ */
1573
+ recoverEngineIfNeeded() {
1574
+ const engine = this.engine;
1575
+ if (!engine || !engine.needs_recovery()) return null;
1576
+ let report;
1577
+ try {
1578
+ report = engine.recover();
1579
+ } catch (error) {
1580
+ throw remoteError("RecoveryRequiredError", `database ${this.dbName ?? ""} needs recovery and recovery failed: ${remapError(error).message}`);
1581
+ } finally {
1582
+ this.clearRuntimeCaches();
1583
+ }
1584
+ return {
1585
+ pendingTxid: fromOptionalWasmU64(report.pendingTxid),
1586
+ pendingCommitted: report.pendingCommitted === true
1587
+ };
1588
+ }
1589
+ cleanupTxState(txId) {
1590
+ this.txChanges.delete(txId);
1591
+ this.txModes.delete(txId);
1592
+ this.txIndexSchemas.delete(txId);
1593
+ this.txEnsuredRawStores.delete(txId);
1594
+ this.txIndexSchemaChanged.delete(txId);
1595
+ this.txStoreCompression.delete(txId);
1596
+ }
1597
+ getOrCreateTrackedTxn(txId) {
1598
+ return getOrInsert(this.txChanges, txId, () => /* @__PURE__ */ new Map());
1599
+ }
1600
+ getOrCreateTrackedStore(txId, store) {
1601
+ return getOrInsert(this.getOrCreateTrackedTxn(txId), store, () => ({
1602
+ touched: false,
1603
+ storeLevel: null,
1604
+ keys: /* @__PURE__ */ new Map()
1605
+ }));
1606
+ }
1607
+ recordStoreLevelChange(txId, store, kind) {
1608
+ if (isInternalStoreName(store)) return;
1609
+ const trackedStore = this.getOrCreateTrackedStore(txId, store);
1610
+ trackedStore.touched = true;
1611
+ trackedStore.storeLevel = kind;
1612
+ trackedStore.keys.clear();
1613
+ }
1614
+ recordPutChange(txId, store, key, baselineExists) {
1615
+ this.recordKeyChange(txId, store, key, baselineExists, "put");
1616
+ }
1617
+ recordPutChanges(txId, store, entries, baselines) {
1618
+ if (isInternalStoreName(store)) return;
1619
+ const trackedStore = this.getOrCreateTrackedStore(txId, store);
1620
+ trackedStore.touched = true;
1621
+ const count = Math.min(entries.length, baselines.length);
1622
+ for (let i = 0; i < count; i += 1) this.setTrackedKeyChange(trackedStore, entries[i][0], baselines[i], "put");
1623
+ }
1624
+ recordPutKeyChanges(txId, store, keys, baselines) {
1625
+ if (isInternalStoreName(store)) return;
1626
+ const trackedStore = this.getOrCreateTrackedStore(txId, store);
1627
+ trackedStore.touched = true;
1628
+ const count = Math.min(keys.length, baselines.length);
1629
+ for (let i = 0; i < count; i += 1) this.setTrackedKeyChange(trackedStore, keys[i], baselines[i] === true || baselines[i] === 1, "put");
1630
+ }
1631
+ recordDeleteChange(txId, store, key, deleted) {
1632
+ if (deleted) this.recordKeyChange(txId, store, key, true, "delete");
1633
+ }
1634
+ recordKeyChange(txId, store, key, baselineExists, finalKind) {
1635
+ if (isInternalStoreName(store)) return;
1636
+ const trackedStore = this.getOrCreateTrackedStore(txId, store);
1637
+ trackedStore.touched = true;
1638
+ this.setTrackedKeyChange(trackedStore, key, baselineExists, finalKind);
1639
+ }
1640
+ setTrackedKeyChange(trackedStore, key, baselineExists, finalKind) {
1641
+ const keyId = bytesToHex(key);
1642
+ const existing = trackedStore.keys.get(keyId);
1643
+ trackedStore.keys.set(keyId, {
1644
+ key: existing?.key ?? key.slice(),
1645
+ baselineExists: existing?.baselineExists ?? baselineExists,
1646
+ finalKind
1647
+ });
1648
+ }
1649
+ markStoreTouched(txId, store) {
1650
+ if (isInternalStoreName(store)) return;
1651
+ this.getOrCreateTrackedStore(txId, store).touched = true;
1652
+ }
1653
+ recordBatchOutcomes(txId, store, ops, outcomes) {
1654
+ for (let i = 0; i < outcomes.length && i < ops.length; i += 1) {
1655
+ const op = ops[i];
1656
+ const outcome = outcomes[i];
1657
+ if (op.kind === "put" && outcome.kind === "put") this.recordPutChange(txId, store, op.key, outcome.baselineExists);
1658
+ else if (op.kind === "delete" && outcome.kind === "delete") this.recordDeleteChange(txId, store, op.key, outcome.deleted);
1659
+ }
1660
+ }
1661
+ recordBatchKeyOutcomes(txId, store, ops, outcomes) {
1662
+ for (let i = 0; i < outcomes.length && i < ops.length; i += 1) {
1663
+ const op = ops[i];
1664
+ const outcome = outcomes[i];
1665
+ if (op.kind === "put" && outcome.kind === "put") this.recordPutChange(txId, store, op.key, outcome.baselineExists);
1666
+ else if (op.kind === "delete" && outcome.kind === "delete") this.recordDeleteChange(txId, store, op.key, outcome.deleted);
1667
+ }
1668
+ }
1669
+ finalizeTrackedChanges(tracked) {
1670
+ const stores = [];
1671
+ for (const [store, trackedStore] of tracked) {
1672
+ if (!trackedStore.touched || isInternalStoreName(store)) continue;
1673
+ const changes = [];
1674
+ if (trackedStore.storeLevel !== null) changes.push({
1675
+ key: /* @__PURE__ */ new Uint8Array(0),
1676
+ kind: trackedStore.storeLevel
1677
+ });
1678
+ for (const change of trackedStore.keys.values()) {
1679
+ if (change.finalKind === "delete" && !change.baselineExists) continue;
1680
+ changes.push({
1681
+ key: change.key,
1682
+ kind: change.finalKind
1683
+ });
1684
+ }
1685
+ stores.push({
1686
+ store,
1687
+ changes
1688
+ });
1689
+ }
1690
+ return stores;
1691
+ }
1692
+ rollbackAllTransactions(options = {}) {
1693
+ if (!this.engine || this.txChanges.size === 0) {
1694
+ this.clearTxCaches();
1695
+ return;
1696
+ }
1697
+ const txIds = Array.from(this.txChanges.keys());
1698
+ for (const txId of txIds) try {
1699
+ this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)), options);
1700
+ } finally {
1701
+ this.cleanupTxState(txId);
1702
+ }
1703
+ }
1704
+ currentStoreNames() {
1705
+ return this.allRawStoreNames().filter((store) => !isInternalStoreName(store));
1706
+ }
1707
+ allRawStoreNames() {
1708
+ return this.withEngine((engine) => engine.list_stores());
1709
+ }
1710
+ loadCommittedStoreCompression() {
1711
+ if (this.committedStoreCompression) return this.committedStoreCompression;
1712
+ const rows = this.withEngine((engine) => engine.list_store_configs());
1713
+ const loaded = /* @__PURE__ */ new Map();
1714
+ for (const row of rows) {
1715
+ if (typeof row.name !== "string") throw remoteError("CorruptionError", "invalid store config row: missing name");
1716
+ const flags = typeof row.flags === "bigint" ? Number(row.flags) : row.flags;
1717
+ if (typeof flags !== "number" || !Number.isSafeInteger(flags) || flags < 0) throw remoteError("CorruptionError", `invalid store flags for ${row.name}`);
1718
+ loaded.set(row.name, compressionFromStoreFlags(flags));
1719
+ }
1720
+ this.committedStoreCompression = loaded;
1721
+ return loaded;
1722
+ }
1723
+ ensureTxStoreCompression(txId) {
1724
+ const snapshot = this.txStoreCompression.get(txId);
1725
+ if (snapshot?.owned) return snapshot.values;
1726
+ const values = new Map(snapshot?.values);
1727
+ this.txStoreCompression.set(txId, {
1728
+ owned: true,
1729
+ values
1730
+ });
1731
+ return values;
1732
+ }
1733
+ recordStoreCompressionCreate(txId, store, compression) {
1734
+ if (isInternalStoreName(store)) return;
1735
+ this.ensureTxStoreCompression(txId).set(store, compression);
1736
+ }
1737
+ recordStoreCompressionDrop(txId, store) {
1738
+ if (isInternalStoreName(store)) return;
1739
+ this.ensureTxStoreCompression(txId).delete(store);
1740
+ }
1741
+ storeCompressionForTx(txId, store) {
1742
+ if (isInternalStoreName(store)) return false;
1743
+ const snapshot = this.txStoreCompression.get(txId);
1744
+ if (snapshot) return snapshot.values.get(store) ?? false;
1745
+ return this.loadCommittedStoreCompression().get(store) ?? false;
1746
+ }
1747
+ async encodeEntriesForWrite(txId, store, entries) {
1748
+ if (isInternalStoreName(store)) return entries;
1749
+ const compression = this.storeCompressionForTx(txId, store);
1750
+ if (compression === false) return entries;
1751
+ const storedEntries = [];
1752
+ for (const [key, value] of entries) storedEntries.push([key, await encodeStoreValueRecord(value, compression)]);
1753
+ return storedEntries;
1754
+ }
1755
+ async encodeBatchOpsForWrite(txId, store, ops) {
1756
+ if (isInternalStoreName(store)) return ops;
1757
+ const compression = this.storeCompressionForTx(txId, store);
1758
+ if (compression === false) return ops;
1759
+ const storedOps = [];
1760
+ for (const op of ops) storedOps.push(op.kind === "put" ? {
1761
+ kind: "put",
1762
+ key: op.key,
1763
+ value: await encodeStoreValueRecord(op.value, compression)
1764
+ } : op);
1765
+ return storedOps;
1766
+ }
1767
+ async encodeStoreValueForWrite(txId, store, value) {
1768
+ if (isInternalStoreName(store)) return value;
1769
+ return encodeStoreValueRecord(value, this.storeCompressionForTx(txId, store));
1770
+ }
1771
+ async decodeStoreValue(txId, store, value) {
1772
+ if (isInternalStoreName(store)) return value;
1773
+ if (this.storeCompressionForTx(txId, store) === false) return value;
1774
+ return decodeStoreValueRecord(value, { strict: true });
1775
+ }
1776
+ async decodeStoreValueForFeed(store, value) {
1777
+ if (isInternalStoreName(store)) return value;
1778
+ return decodeStoreValueRecord(value, { strict: (this.loadCommittedStoreCompression().get(store) ?? false) !== false });
1779
+ }
1780
+ async readStoreValue(txId, store, key) {
1781
+ const value = this.readRawValue(txId, store, key);
1782
+ return value === null ? null : this.decodeStoreValue(txId, store, value);
1783
+ }
1784
+ async readStoreScan(txId, store, range) {
1785
+ const rows = this.readRawScan(txId, store, range);
1786
+ if (isInternalStoreName(store) || this.storeCompressionForTx(txId, store) === false) return rows;
1787
+ const values = rows.map((row) => row.value);
1788
+ await this.decodeStoreValues(txId, store, values);
1789
+ for (let index = 0; index < rows.length; index += 1) rows[index].value = values[index];
1790
+ return rows;
1791
+ }
1792
+ async decodeStoreValues(txId, store, values) {
1793
+ const state = {
1794
+ next: 0,
1795
+ failed: false,
1796
+ failure: void 0
1797
+ };
1798
+ const decodeNext = async () => {
1799
+ while (!state.failed && state.next < values.length) {
1800
+ const index = state.next++;
1801
+ const value = values[index];
1802
+ if (value === null) continue;
1803
+ try {
1804
+ values[index] = await this.decodeStoreValue(txId, store, value);
1805
+ } catch (error) {
1806
+ if (!state.failed) {
1807
+ state.failed = true;
1808
+ state.failure = error;
1809
+ }
1810
+ }
1811
+ }
1812
+ };
1813
+ await Promise.all(Array.from({ length: Math.min(COMPRESSED_READ_CONCURRENCY, values.length) }, decodeNext));
1814
+ if (state.failed) throw state.failure;
1815
+ return values;
1816
+ }
1817
+ indexesForStoreInTx(txId, store) {
1818
+ const schema = this.indexSchemaForTx(txId);
1819
+ let byStore = this.indexesBySchema.get(schema);
1820
+ if (!byStore) {
1821
+ byStore = /* @__PURE__ */ new Map();
1822
+ for (const def of schema) {
1823
+ const defs = byStore.get(def.store);
1824
+ if (defs) defs.push(def);
1825
+ else byStore.set(def.store, [def]);
1826
+ }
1827
+ this.indexesBySchema.set(schema, byStore);
1828
+ }
1829
+ return byStore.get(store) ?? [];
1830
+ }
1831
+ resolveIndexDefinition(txId, store, indexName) {
1832
+ if (!this.rawStoreExistsInTx(txId, store)) throw remoteError("StoreNotFoundError", `store not found: ${store}`);
1833
+ const def = findIndexDefinition(this.indexesForStoreInTx(txId, store), store, indexName);
1834
+ if (!def) throw remoteError("IndexNotFoundError", `index not found: ${store}.${indexName}`);
1835
+ return def;
1836
+ }
1837
+ indexSchemaForTx(txId) {
1838
+ const override = this.txIndexSchemas.get(txId);
1839
+ if (override) return override;
1840
+ if (this.committedIndexes) return this.committedIndexes;
1841
+ const loaded = this.readIndexSchemaInTx(txId);
1842
+ this.committedIndexes = cloneNormalizedIndexDefinitions(loaded);
1843
+ return this.committedIndexes;
1844
+ }
1845
+ loadCommittedIndexSchema() {
1846
+ if (this.committedIndexes) return this.committedIndexes;
1847
+ const txId = fromWasmU64(this.withEngine((engine) => engine.begin_tx("readonly")));
1848
+ try {
1849
+ const loaded = this.readIndexSchemaInTx(txId);
1850
+ this.committedIndexes = cloneNormalizedIndexDefinitions(loaded);
1851
+ return this.committedIndexes;
1852
+ } finally {
1853
+ this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)));
1854
+ }
1855
+ }
1856
+ readIndexSchemaInTx(txId) {
1857
+ if (!this.rawStoreExistsInTx(txId, "__browserdb:indexes")) return [];
1858
+ const defs = this.readRawScan(txId, INDEX_METADATA_STORE, EMPTY_RANGE).map((row) => decodeIndexMetadataValue(row.value));
1859
+ defs.sort(compareNormalizedIndexDefinitions);
1860
+ return defs;
1861
+ }
1862
+ rawStoreExistsInTx(txId, store) {
1863
+ try {
1864
+ this.readRawScan(txId, store, { limit: 0 });
1865
+ return true;
1866
+ } catch (error) {
1867
+ if (isNamedError(error, "StoreNotFoundError")) return false;
1868
+ throw error;
1869
+ }
1870
+ }
1871
+ ensureRawStore(txId, store) {
1872
+ const cacheable = this.txModes.get(txId) === "readwrite";
1873
+ if (cacheable && this.txEnsuredRawStores.get(txId)?.has(store)) return;
1874
+ this.ignoreNamedError("StoreExistsError", () => {
1875
+ this.withEngine((engine) => engine.create_store(toWasmU64(txId), store));
1876
+ });
1877
+ if (cacheable) getOrInsert(this.txEnsuredRawStores, txId, () => /* @__PURE__ */ new Set()).add(store);
1878
+ }
1879
+ clearRawStoreIfExists(txId, store) {
1880
+ try {
1881
+ this.withEngine((engine) => engine.clear_store(toWasmU64(txId), store));
1882
+ } catch (error) {
1883
+ if (!isNamedError(error, "StoreNotFoundError")) throw error;
1884
+ this.txEnsuredRawStores.get(txId)?.delete(store);
1885
+ }
1886
+ }
1887
+ dropRawStoreIfExists(txId, store) {
1888
+ this.txEnsuredRawStores.get(txId)?.delete(store);
1889
+ this.ignoreNamedError("StoreNotFoundError", () => {
1890
+ this.withEngine((engine) => engine.drop_store(toWasmU64(txId), store));
1891
+ });
1892
+ }
1893
+ ensureInternalStoresForDefinitions(txId, defs) {
1894
+ for (const def of defs) this.ensureRawStore(txId, def.internalStore);
1895
+ }
1896
+ ensureInternalStoresForStore(txId, store) {
1897
+ this.ensureInternalStoresForDefinitions(txId, this.indexesForStoreInTx(txId, store));
1898
+ }
1899
+ readRawValue(txId, store, key) {
1900
+ const value = this.withEngine((engine) => engine.get(toWasmU64(txId), store, key));
1901
+ return value === null ? null : normalizeWasmBytes(value);
1902
+ }
1903
+ readRawScan(txId, store, range) {
1904
+ const rows = this.withEngine((engine) => engine.scan(toWasmU64(txId), store, toWasmRange(range)));
1905
+ for (const row of rows) {
1906
+ row.key = normalizeWasmBytes(row.key);
1907
+ row.value = normalizeWasmBytes(row.value);
1908
+ }
1909
+ return rows;
1910
+ }
1911
+ putRawValue(txId, store, key, value) {
1912
+ this.withEngine((engine) => engine.put(toWasmU64(txId), store, key, value));
1913
+ }
1914
+ putIndexEntry(txId, def, physicalKey, value) {
1915
+ this.putRawValue(txId, def.internalStore, physicalKey, value);
1916
+ }
1917
+ deleteIndexEntryIfPresent(txId, def, logicalKey, primaryKey) {
1918
+ const physicalKey = this.buildIndexEntryKey(def, logicalKey, primaryKey);
1919
+ this.ignoreNamedError("StoreNotFoundError", () => {
1920
+ this.withEngine((engine) => engine.delete(toWasmU64(txId), def.internalStore, physicalKey));
1921
+ });
1922
+ }
1923
+ buildIndexEntryKey(def, logicalKey, primaryKey) {
1924
+ const physicalKey = encodeIndexEntryKey(logicalKey, primaryKey);
1925
+ if (physicalKey.byteLength > MAX_ENGINE_KEY_BYTES) throw remoteError("KeyTooLargeError", `index key too large for ${def.store}.${def.name}`);
1926
+ return physicalKey;
1927
+ }
1928
+ async assertUniqueIndexAvailability(txId, def, logicalKey, primaryKey) {
1929
+ if (!def.unique) return;
1930
+ const physical = indexKeyExactRange(logicalKey);
1931
+ let cursor = null;
1932
+ let chunkLimit = 1;
1933
+ for (;;) {
1934
+ const range = {
1935
+ ...physical,
1936
+ limit: chunkLimit
1937
+ };
1938
+ if (cursor !== null) {
1939
+ range.gt = cursor;
1940
+ delete range.gte;
1941
+ }
1942
+ const rows = this.readRawScan(txId, def.internalStore, range);
1943
+ for (const row of rows) {
1944
+ cursor = row.key;
1945
+ const decoded = decodeIndexEntryKey(row.key);
1946
+ if (bytesEqual(decoded.primaryKey, primaryKey)) continue;
1947
+ const value = await this.readStoreValue(txId, def.store, decoded.primaryKey);
1948
+ if (value === null) {
1949
+ this.cleanupStaleIndexRow(txId, def, row.key);
1950
+ continue;
1951
+ }
1952
+ const currentLogicalKey = extractLogicalIndexKey(def, value);
1953
+ if (currentLogicalKey === null || !bytesEqual(currentLogicalKey, logicalKey)) {
1954
+ this.cleanupStaleIndexRow(txId, def, row.key);
1955
+ continue;
1956
+ }
1957
+ throw remoteError("UniqueIndexConstraintError", `unique index constraint violation on ${def.store}.${def.name}`);
1958
+ }
1959
+ if (rows.length < chunkLimit) return;
1960
+ chunkLimit = Math.min(INDEX_SCAN_RAW_CHUNK_ROWS, chunkLimit * 2);
1961
+ }
1962
+ }
1963
+ /**
1964
+ * Resumes after a physical index key in the scan direction. Bounded raw
1965
+ * chunks prevent stale entries from forcing the whole range into memory.
1966
+ * The output limit counts only live rows.
1967
+ */
1968
+ async loadVisibleIndexPage(txId, def, range, cursor, limit) {
1969
+ const { limit: _ignored, ...withoutLimit } = range;
1970
+ const physical = indexRangeToPhysicalRange(withoutLimit);
1971
+ const reverse = physical.reverse === true;
1972
+ let resumeAfter = cursor;
1973
+ const visible = [];
1974
+ let staleChunkFloor = 1;
1975
+ for (;;) {
1976
+ const chunkLimit = Math.min(INDEX_SCAN_RAW_CHUNK_ROWS, Math.max(limit - visible.length, staleChunkFloor));
1977
+ const chunkRange = {
1978
+ ...physical,
1979
+ limit: chunkLimit
1980
+ };
1981
+ if (resumeAfter !== null) {
1982
+ if (reverse) {
1983
+ delete chunkRange.lte;
1984
+ chunkRange.lt = resumeAfter;
1985
+ } else {
1986
+ delete chunkRange.gte;
1987
+ chunkRange.gt = resumeAfter;
1988
+ }
1989
+ }
1990
+ let rawRows;
1991
+ try {
1992
+ rawRows = this.readRawScan(txId, def.internalStore, chunkRange);
1993
+ } catch (error) {
1994
+ if (isNamedError(error, "StoreNotFoundError")) return {
1995
+ rows: [],
1996
+ cursor: null
1997
+ };
1998
+ throw error;
1999
+ }
2000
+ const visibleBefore = visible.length;
2001
+ let batchStart = 0;
2002
+ let batchEnd = 0;
2003
+ let batch = null;
2004
+ for (let index = 0; index < rawRows.length; index += 1) {
2005
+ if (index === batchEnd) {
2006
+ batchStart = index;
2007
+ batchEnd = Math.min(rawRows.length, index + limit - visible.length);
2008
+ batch = this.readIndexPrimaryValues(txId, def, rawRows, batchStart, batchEnd);
2009
+ }
2010
+ const row = rawRows[index];
2011
+ resumeAfter = row.key;
2012
+ const resolved = batch ? await this.resolveVisibleIndexedValue(txId, def, row.key, batch.entries[index - batchStart], batch.values[index - batchStart]) : await this.resolveVisibleIndexedRow(txId, def, row.key);
2013
+ if (!resolved) continue;
2014
+ visible.push(resolved);
2015
+ if (visible.length >= limit) return {
2016
+ rows: visible,
2017
+ cursor: row.key.slice()
2018
+ };
2019
+ }
2020
+ if (rawRows.length < chunkLimit) return {
2021
+ rows: visible,
2022
+ cursor: null
2023
+ };
2024
+ staleChunkFloor = visible.length === visibleBefore ? Math.min(INDEX_SCAN_RAW_CHUNK_ROWS, chunkLimit * 2) : 1;
2025
+ }
2026
+ }
2027
+ readIndexPrimaryValues(txId, def, rows, start, end) {
2028
+ if (this.txModes.get(txId) !== "readonly" || end - start <= 1) return null;
2029
+ let entries;
2030
+ let values;
2031
+ try {
2032
+ entries = rows.slice(start, end).map((row) => decodeIndexEntryKey(row.key));
2033
+ values = this.withEngine((engine) => engine.get_many(toWasmU64(txId), def.store, entries.map((entry) => entry.primaryKey)));
2034
+ } catch {
2035
+ return null;
2036
+ }
2037
+ if (values.length !== entries.length) throw remoteError("InternalError", `get_many outcome count mismatch: ${values.length} != ${entries.length}`);
2038
+ return {
2039
+ entries,
2040
+ values
2041
+ };
2042
+ }
2043
+ async resolveVisibleIndexedRow(txId, def, physicalKey) {
2044
+ const decoded = decodeIndexEntryKey(physicalKey);
2045
+ const value = this.readRawValue(txId, def.store, decoded.primaryKey);
2046
+ return this.resolveVisibleIndexedValue(txId, def, physicalKey, decoded, value);
2047
+ }
2048
+ async resolveVisibleIndexedValue(txId, def, physicalKey, decoded, rawValue) {
2049
+ if (rawValue === null) {
2050
+ this.cleanupStaleIndexRow(txId, def, physicalKey);
2051
+ return null;
2052
+ }
2053
+ const value = await this.decodeStoreValue(txId, def.store, normalizeWasmBytes(rawValue));
2054
+ const currentLogicalKey = extractLogicalIndexKey(def, value);
2055
+ if (currentLogicalKey === null || !bytesEqual(currentLogicalKey, decoded.logicalKey)) {
2056
+ this.cleanupStaleIndexRow(txId, def, physicalKey);
2057
+ return null;
2058
+ }
2059
+ return {
2060
+ key: decoded.primaryKey,
2061
+ value
2062
+ };
2063
+ }
2064
+ cleanupStaleIndexRow(txId, def, physicalKey) {
2065
+ if (this.txModes.get(txId) !== "readwrite") return;
2066
+ try {
2067
+ this.withEngine((engine) => engine.delete(toWasmU64(txId), def.internalStore, physicalKey));
2068
+ } catch {}
2069
+ }
2070
+ async loadWasm() {
2071
+ if (!this.wasmReady) this.wasmReady = this.options.loadWasm ? this.options.loadWasm() : (async () => {
2072
+ const moduleUrl = new URL("/engine/moyodb_engine.js", import.meta.url).href;
2073
+ const wasmUrl = new URL("/engine/moyodb_engine_bg.wasm", import.meta.url).href;
2074
+ const wasmModule = await import(
2075
+ /* @vite-ignore */
2076
+ moduleUrl
2077
+ );
2078
+ await wasmModule.default({ module_or_path: wasmUrl });
2079
+ return wasmModule;
2080
+ })();
2081
+ return this.wasmReady;
2082
+ }
2083
+ withEngine(fn, options = {}) {
2084
+ if (this.maintenanceOperation && !options.allowDuringMaintenance) this.ensureNotInMaintenance();
2085
+ if (!this.engine) throw remoteError("InternalError", "engine is not open");
2086
+ try {
2087
+ return fn(this.engine);
2088
+ } catch (err) {
2089
+ throw remapError(err);
2090
+ }
2091
+ }
2092
+ ignoreNamedError(name, fn) {
2093
+ try {
2094
+ fn();
2095
+ } catch (error) {
2096
+ if (isNamedError(error, name)) return;
2097
+ throw error;
2098
+ }
2099
+ }
2100
+ clearTxCaches() {
2101
+ this.txChanges.clear();
2102
+ this.txModes.clear();
2103
+ this.txIndexSchemas.clear();
2104
+ this.txEnsuredRawStores.clear();
2105
+ this.txIndexSchemaChanged.clear();
2106
+ this.txStoreCompression.clear();
2107
+ }
2108
+ clearRuntimeCaches() {
2109
+ this.clearTxCaches();
2110
+ this.committedIndexes = null;
2111
+ this.committedStoreCompression = null;
2112
+ }
2113
+ async cleanupAfterFailedOpen(engine) {
2114
+ try {
2115
+ engine?.abandon();
2116
+ } catch {}
2117
+ this.engine = null;
2118
+ this.clearRuntimeCaches();
2119
+ this.events?.close();
2120
+ this.events = null;
2121
+ if (this.lease) try {
2122
+ await this.lease.release();
2123
+ } catch {}
2124
+ this.lease = null;
2125
+ this.disposePersistenceBridge();
2126
+ this.dbName = null;
2127
+ this.openOptions = null;
2128
+ this.maintenanceOperation = null;
2129
+ }
2130
+ disposePersistenceBridge() {
2131
+ this.persistenceBridge.close();
2132
+ }
2133
+ };
2134
+ function assertCapabilities() {
2135
+ if (typeof navigator.storage.getDirectory !== "function") throw remoteError("UnsupportedPlatformError", "navigator.storage.getDirectory is unavailable");
2136
+ if (typeof BroadcastChannel === "undefined") throw remoteError("UnsupportedPlatformError", "BroadcastChannel is unavailable");
2137
+ if (typeof FileSystemFileHandle === "undefined" || typeof FileSystemFileHandle.prototype.createSyncAccessHandle !== "function") throw remoteError("UnsupportedPlatformError", "createSyncAccessHandle is unavailable");
2138
+ }
2139
+ function assertSecureContext() {
2140
+ if (!self.isSecureContext) throw remoteError("UnsupportedPlatformError", "moyodb requires a secure context (HTTPS)");
2141
+ }
2142
+ function remoteError(code, message) {
2143
+ const error = new Error(message);
2144
+ error.name = code;
2145
+ Object.defineProperty(error, "code", {
2146
+ value: code,
2147
+ enumerable: true,
2148
+ configurable: true
2149
+ });
2150
+ return error;
2151
+ }
2152
+ function applyChangeFeedPolicy(engine, settings) {
2153
+ const current = engine.change_feed_policy();
2154
+ const currentRetain = fromOptionalWasmU64(current.retainTxids);
2155
+ if (current.enabled === settings.enabled && (!settings.enabled || currentRetain === settings.retainTxids)) return;
2156
+ const txId = engine.begin_tx("readwrite");
2157
+ try {
2158
+ engine.set_change_feed_policy(txId, {
2159
+ enabled: settings.enabled,
2160
+ retainTxids: settings.retainTxids
2161
+ });
2162
+ engine.commit_tx(txId);
2163
+ } catch (error) {
2164
+ try {
2165
+ engine.rollback_tx(txId);
2166
+ } catch {}
2167
+ throw remapError(error);
2168
+ }
2169
+ }
2170
+ /** Active generation, null for legacy storage, undefined if reading fails. */
2171
+ async function readActiveGenerationOrNull(wasm, dbName) {
2172
+ try {
2173
+ return await wasm.readActiveGeneration(dbName);
2174
+ } catch {
2175
+ return;
2176
+ }
2177
+ }
2178
+ function normalizeEngineHealth(health) {
2179
+ if (health.state === "recoveryRequired") return {
2180
+ state: "recoveryRequired",
2181
+ reason: health.reason,
2182
+ pendingTxid: fromOptionalWasmU64(health.pendingTxid)
2183
+ };
2184
+ return { state: health.state };
2185
+ }
2186
+ function partialBooleanOutcomes(error) {
2187
+ if (!isRecord(error) || !Array.isArray(error.partial)) return [];
2188
+ return error.partial.filter((value) => typeof value === "boolean");
2189
+ }
2190
+ function partialBatchOutcomes(error) {
2191
+ if (!isRecord(error) || !Array.isArray(error.partial)) return [];
2192
+ return error.partial.filter((value) => {
2193
+ if (!isRecord(value) || typeof value.kind !== "string") return false;
2194
+ return value.kind === "put" && typeof value.baselineExists === "boolean" || value.kind === "delete" && typeof value.deleted === "boolean";
2195
+ });
2196
+ }
2197
+ function remapError(err) {
2198
+ if (err instanceof Error) return err;
2199
+ if (isRecord(err)) {
2200
+ const error = remoteError(typeof err.code === "string" ? err.code : typeof err.name === "string" ? err.name : "Error", typeof err.message === "string" ? err.message : "Unknown error");
2201
+ if ("partial" in err) Object.defineProperty(error, "partial", {
2202
+ value: err.partial,
2203
+ enumerable: true,
2204
+ configurable: true
2205
+ });
2206
+ return error;
2207
+ }
2208
+ return remoteError("Error", String(err));
2209
+ }
2210
+ //#endregion
2211
+ export { DbWorker, exposeWorkerApi };
2212
+
2213
+ //# sourceMappingURL=node-engine.js.map