@korajs/store 1.0.0-beta.1 → 1.0.0-beta.4

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 (58) hide show
  1. package/dist/adapters/better-sqlite3.cjs.map +1 -1
  2. package/dist/adapters/better-sqlite3.js +1 -1
  3. package/dist/adapters/indexeddb.cjs +196 -39
  4. package/dist/adapters/indexeddb.cjs.map +1 -1
  5. package/dist/adapters/indexeddb.d.cts +1 -1
  6. package/dist/adapters/indexeddb.d.ts +1 -1
  7. package/dist/adapters/indexeddb.js +15 -8
  8. package/dist/adapters/indexeddb.js.map +1 -1
  9. package/dist/adapters/sqlite-wasm-shared-host.cjs +80 -53
  10. package/dist/adapters/sqlite-wasm-shared-host.cjs.map +1 -1
  11. package/dist/adapters/sqlite-wasm-shared-host.d.cts +63 -1
  12. package/dist/adapters/sqlite-wasm-shared-host.d.ts +63 -1
  13. package/dist/adapters/sqlite-wasm-shared-host.js +56 -52
  14. package/dist/adapters/sqlite-wasm-shared-host.js.map +1 -1
  15. package/dist/adapters/sqlite-wasm-worker.cjs +25 -3
  16. package/dist/adapters/sqlite-wasm-worker.cjs.map +1 -1
  17. package/dist/adapters/sqlite-wasm-worker.js +25 -3
  18. package/dist/adapters/sqlite-wasm-worker.js.map +1 -1
  19. package/dist/adapters/sqlite-wasm.cjs +186 -34
  20. package/dist/adapters/sqlite-wasm.cjs.map +1 -1
  21. package/dist/adapters/sqlite-wasm.d.cts +29 -3
  22. package/dist/adapters/sqlite-wasm.d.ts +29 -3
  23. package/dist/adapters/sqlite-wasm.js +3 -3
  24. package/dist/{backup-ZV4Y424B.js → backup-IQE4QC7Q.js} +2 -2
  25. package/dist/{chunk-RBPVEAVM.js → chunk-2ZRQGFEF.js} +179 -36
  26. package/dist/chunk-2ZRQGFEF.js.map +1 -0
  27. package/dist/{chunk-IOEFNHHP.js → chunk-COJSQBXW.js} +2 -2
  28. package/dist/{chunk-X57MWW35.js → chunk-OCOGQRHW.js} +12 -9
  29. package/dist/chunk-OCOGQRHW.js.map +1 -0
  30. package/dist/{chunk-FFYA7J5H.js → chunk-RCTG3IJG.js} +3 -2
  31. package/dist/chunk-RCTG3IJG.js.map +1 -0
  32. package/dist/{chunk-QL2XVZRN.js → chunk-TUR7RGEP.js} +12 -1
  33. package/dist/{chunk-QL2XVZRN.js.map → chunk-TUR7RGEP.js.map} +1 -1
  34. package/dist/{chunk-ZLWAYQEQ.js → chunk-UXRWVXBP.js} +32 -28
  35. package/dist/chunk-UXRWVXBP.js.map +1 -0
  36. package/dist/{export-audit-AJ7RORNK.js → export-audit-MT2LTMIN.js} +2 -2
  37. package/dist/index.cjs +167 -141
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +10 -1
  40. package/dist/index.d.ts +10 -1
  41. package/dist/index.js +51 -41
  42. package/dist/index.js.map +1 -1
  43. package/dist/internal.cjs +45 -40
  44. package/dist/internal.cjs.map +1 -1
  45. package/dist/internal.js +2 -2
  46. package/dist/{sqlite-wasm-channel-DUDPclTE.d.cts → sqlite-wasm-channel-CNHRf-m2.d.cts} +1 -1
  47. package/dist/{sqlite-wasm-channel-DUDPclTE.d.ts → sqlite-wasm-channel-CNHRf-m2.d.ts} +1 -1
  48. package/dist/sqlite-wasm-channel-NGSBJR44.js +12 -0
  49. package/package.json +2 -2
  50. package/dist/chunk-FFYA7J5H.js.map +0 -1
  51. package/dist/chunk-RBPVEAVM.js.map +0 -1
  52. package/dist/chunk-X57MWW35.js.map +0 -1
  53. package/dist/chunk-ZLWAYQEQ.js.map +0 -1
  54. package/dist/sqlite-wasm-channel-H43KEZLM.js +0 -12
  55. /package/dist/{backup-ZV4Y424B.js.map → backup-IQE4QC7Q.js.map} +0 -0
  56. /package/dist/{chunk-IOEFNHHP.js.map → chunk-COJSQBXW.js.map} +0 -0
  57. /package/dist/{export-audit-AJ7RORNK.js.map → export-audit-MT2LTMIN.js.map} +0 -0
  58. /package/dist/{sqlite-wasm-channel-H43KEZLM.js.map → sqlite-wasm-channel-NGSBJR44.js.map} +0 -0
@@ -3,9 +3,10 @@ import {
3
3
  } from "./chunk-TVJEC5S2.js";
4
4
  import {
5
5
  AdapterError,
6
+ NoLeaderError,
6
7
  StoreNotOpenError,
7
8
  WorkerTimeoutError
8
- } from "./chunk-QL2XVZRN.js";
9
+ } from "./chunk-TUR7RGEP.js";
9
10
 
10
11
  // src/adapters/sqlite-wasm-adapter.ts
11
12
  import { generateFullDDL } from "@korajs/core";
@@ -89,45 +90,73 @@ var SharedWorkerClientBridge = class {
89
90
  // src/multi-tab/tab-storage.ts
90
91
  var RPC_REQUEST = "kora-worker-request";
91
92
  var RPC_RESPONSE = "kora-worker-response";
93
+ var LEADER_PING = "kora-leader-ping";
94
+ var LEADER_PONG = "kora-leader-pong";
95
+ var DEFAULT_LIVENESS_PROBE_MS = 2e3;
92
96
  function isSharedWorkerStorageSupported() {
93
97
  return typeof globalThis !== "undefined" && typeof SharedWorker !== "undefined";
94
98
  }
95
99
  function isMultiTabStorageSupported() {
96
100
  return typeof globalThis !== "undefined" && typeof BroadcastChannel !== "undefined" && typeof navigator !== "undefined" && typeof navigator.locks?.request === "function";
97
101
  }
98
- async function acquireTabStorageSession(dbName) {
102
+ async function acquireTabStorageSession(dbName, options) {
99
103
  const channelName = `kora-storage-${dbName}`;
104
+ const lockName = `kora-leader-${dbName}`;
100
105
  if (!isMultiTabStorageSupported()) {
101
106
  return { role: "leader", channelName };
102
107
  }
103
108
  return new Promise((resolve) => {
104
109
  let releaseHeld;
105
- void navigator.locks.request(
106
- `kora-leader-${dbName}`,
107
- { mode: "exclusive", ifAvailable: true },
108
- (lock) => {
109
- if (lock === null) {
110
- resolve({ role: "follower", channelName });
111
- return;
112
- }
113
- resolve({
114
- role: "leader",
115
- channelName,
116
- releaseLock: async () => {
117
- releaseHeld?.();
118
- }
119
- });
120
- return new Promise((release) => {
121
- releaseHeld = release;
122
- });
110
+ void navigator.locks.request(lockName, { mode: "exclusive", ifAvailable: true }, (lock) => {
111
+ if (lock === null) {
112
+ resolve(startFollowerSession(channelName, lockName, options));
113
+ return;
123
114
  }
124
- );
115
+ resolve({
116
+ role: "leader",
117
+ channelName,
118
+ releaseLock: async () => {
119
+ releaseHeld?.();
120
+ }
121
+ });
122
+ return new Promise((release) => {
123
+ releaseHeld = release;
124
+ });
125
+ });
126
+ });
127
+ }
128
+ function startFollowerSession(channelName, lockName, options) {
129
+ let promoted = false;
130
+ let releasePromotedLock;
131
+ const abort = new AbortController();
132
+ void navigator.locks.request(lockName, { mode: "exclusive", signal: abort.signal }, () => {
133
+ promoted = true;
134
+ options?.onPromote?.();
135
+ return new Promise((release) => {
136
+ releasePromotedLock = release;
137
+ });
138
+ }).catch(() => {
125
139
  });
140
+ return {
141
+ role: "follower",
142
+ channelName,
143
+ cancelPromotionWatch: () => {
144
+ if (promoted) {
145
+ releasePromotedLock?.();
146
+ } else {
147
+ abort.abort();
148
+ }
149
+ }
150
+ };
126
151
  }
127
152
  function startLeaderRpcRelay(channelName, bridge) {
128
153
  const channel = new BroadcastChannel(channelName);
129
154
  const onMessage = (event) => {
130
155
  const data = event.data;
156
+ if (data?.type === LEADER_PING) {
157
+ channel.postMessage({ type: LEADER_PONG });
158
+ return;
159
+ }
131
160
  if (data?.type !== RPC_REQUEST) {
132
161
  return;
133
162
  }
@@ -163,9 +192,11 @@ var FollowerBroadcastBridge = class {
163
192
  channel;
164
193
  pending = /* @__PURE__ */ new Map();
165
194
  timeoutMs;
195
+ livenessProbeMs;
166
196
  terminated = false;
167
- constructor(channelName, timeoutMs = 3e4) {
197
+ constructor(channelName, timeoutMs = 3e4, livenessProbeMs = DEFAULT_LIVENESS_PROBE_MS) {
168
198
  this.timeoutMs = timeoutMs;
199
+ this.livenessProbeMs = Math.min(livenessProbeMs, timeoutMs);
169
200
  this.channel = new BroadcastChannel(channelName);
170
201
  this.channel.addEventListener("message", (event) => {
171
202
  const data = event.data;
@@ -179,6 +210,48 @@ var FollowerBroadcastBridge = class {
179
210
  }
180
211
  });
181
212
  }
213
+ /**
214
+ * Readiness handshake: resolves `true` as soon as a live leader answers a ping,
215
+ * or `false` if none answers within the budget. The adapter calls this before
216
+ * its first RPC so a follower created before a leader relay is live retries the
217
+ * handshake instead of firing into the void and waiting out the full timeout.
218
+ */
219
+ async waitForLeader(timeoutMs = 3e3, attempts = 3) {
220
+ const perAttempt = Math.max(50, Math.floor(timeoutMs / Math.max(1, attempts)));
221
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
222
+ if (this.terminated) {
223
+ return false;
224
+ }
225
+ if (await this.pingLeader(perAttempt)) {
226
+ return true;
227
+ }
228
+ }
229
+ return false;
230
+ }
231
+ /** Sends one liveness ping and resolves whether a leader answered in time. */
232
+ pingLeader(timeoutMs) {
233
+ if (this.terminated) {
234
+ return Promise.resolve(false);
235
+ }
236
+ return new Promise((resolve) => {
237
+ const onPong = (event) => {
238
+ if (event.data?.type === LEADER_PONG) {
239
+ cleanup();
240
+ resolve(true);
241
+ }
242
+ };
243
+ const cleanup = () => {
244
+ clearTimeout(timer);
245
+ this.channel.removeEventListener("message", onPong);
246
+ };
247
+ const timer = setTimeout(() => {
248
+ cleanup();
249
+ resolve(false);
250
+ }, timeoutMs);
251
+ this.channel.addEventListener("message", onPong);
252
+ this.channel.postMessage({ type: LEADER_PING });
253
+ });
254
+ }
182
255
  async send(request) {
183
256
  if (this.terminated) {
184
257
  return {
@@ -191,19 +264,25 @@ var FollowerBroadcastBridge = class {
191
264
  const requestId = crypto.randomUUID();
192
265
  const msg = { type: RPC_REQUEST, requestId, request };
193
266
  return new Promise((resolve, reject) => {
194
- const timer = setTimeout(() => {
267
+ const settle = (fn) => {
268
+ clearTimeout(timer);
269
+ clearTimeout(probe);
195
270
  this.pending.delete(requestId);
196
- reject(new WorkerTimeoutError(`follower-rpc:${request.type}`, this.timeoutMs));
271
+ fn();
272
+ };
273
+ const timer = setTimeout(() => {
274
+ settle(() => reject(new WorkerTimeoutError(`follower-rpc:${request.type}`, this.timeoutMs)));
197
275
  }, this.timeoutMs);
276
+ const probe = setTimeout(() => {
277
+ void this.pingLeader(this.livenessProbeMs).then((alive) => {
278
+ if (!alive && this.pending.has(requestId)) {
279
+ settle(() => reject(new NoLeaderError(`follower-rpc:${request.type}`)));
280
+ }
281
+ });
282
+ }, this.livenessProbeMs);
198
283
  this.pending.set(requestId, {
199
- resolve: (response) => {
200
- clearTimeout(timer);
201
- resolve(response);
202
- },
203
- reject: (error) => {
204
- clearTimeout(timer);
205
- reject(error);
206
- }
284
+ resolve: (response) => settle(() => resolve(response)),
285
+ reject: (error) => settle(() => reject(error))
207
286
  });
208
287
  this.channel.postMessage(msg);
209
288
  });
@@ -231,14 +310,19 @@ var SqliteWasmAdapter = class {
231
310
  sharedWorkerUrl;
232
311
  workerResponseTimeoutMs;
233
312
  dbName;
313
+ emitter;
234
314
  tabSession = null;
235
315
  sharedWorker = null;
316
+ /** Retained so a follower promoted to leader can re-open its own worker. */
317
+ schema = null;
318
+ promoting = false;
236
319
  constructor(options = {}) {
237
320
  this.injectedBridge = options.bridge;
238
321
  this.workerUrl = options.workerUrl;
239
322
  this.sharedWorkerUrl = options.sharedWorkerUrl;
240
323
  this.workerResponseTimeoutMs = options.workerResponseTimeoutMs ?? 3e4;
241
324
  this.dbName = options.dbName ?? "kora-db";
325
+ this.emitter = options.emitter;
242
326
  }
243
327
  async open(schema) {
244
328
  if (this.opened) return;
@@ -250,17 +334,29 @@ var SqliteWasmAdapter = class {
250
334
  this.sharedWorker = new SharedWorker(sharedUrl, { name: `kora-sw-${this.dbName}` });
251
335
  this.bridge = new SharedWorkerClientBridge(this.sharedWorker, this.dbName, workerUrlString);
252
336
  } else if (this.workerUrl) {
253
- this.tabSession = await acquireTabStorageSession(this.dbName);
254
- const { WebWorkerBridge } = await import("./sqlite-wasm-channel-H43KEZLM.js");
337
+ this.schema = schema;
338
+ this.tabSession = await acquireTabStorageSession(this.dbName, {
339
+ onPromote: () => {
340
+ void this.promoteToLeader();
341
+ }
342
+ });
343
+ const { WebWorkerBridge } = await import("./sqlite-wasm-channel-NGSBJR44.js");
255
344
  if (this.tabSession.role === "leader") {
256
345
  const workerBridge = new WebWorkerBridge(this.workerUrl, this.workerResponseTimeoutMs);
257
346
  this.tabSession.stopRelay = startLeaderRpcRelay(this.tabSession.channelName, workerBridge);
258
347
  this.bridge = workerBridge;
259
348
  } else {
260
- this.bridge = new FollowerBroadcastBridge(
349
+ const followerBridge = new FollowerBroadcastBridge(
261
350
  this.tabSession.channelName,
262
351
  this.workerResponseTimeoutMs
263
352
  );
353
+ this.bridge = followerBridge;
354
+ this.emitter?.emit({
355
+ type: "store:db-name-collision",
356
+ dbName: this.dbName,
357
+ message: `Another runtime on this origin is already using database "${this.dbName}"; this runtime is sharing it as a follower. If these are separate apps, give each a distinct store name.`
358
+ });
359
+ await followerBridge.waitForLeader();
264
360
  }
265
361
  } else {
266
362
  throw new AdapterError(
@@ -280,14 +376,37 @@ var SqliteWasmAdapter = class {
280
376
  dbName: this.dbName
281
377
  });
282
378
  }
379
+ this.reportStorageMode(response.data);
283
380
  this.opened = true;
284
381
  }
382
+ /**
383
+ * Surface a `store:opfs-unavailable` diagnostic when the worker reported that
384
+ * persistence silently degraded to an in-memory database, so a data-loss
385
+ * condition is observable instead of failing silently. A persistent open (or a
386
+ * bridge that does not report a mode, e.g. the Node mock) emits nothing.
387
+ */
388
+ reportStorageMode(data) {
389
+ if (!this.emitter || typeof data !== "object" || data === null) {
390
+ return;
391
+ }
392
+ const mode = data;
393
+ if (mode.persistent === false) {
394
+ const reason = mode.fallbackReason ?? "unsupported";
395
+ this.emitter.emit({
396
+ type: "store:opfs-unavailable",
397
+ dbName: this.dbName,
398
+ reason,
399
+ message: `OPFS persistence is unavailable (${reason}) for database "${this.dbName}"; the store is running in memory and data will not survive a reload.`
400
+ });
401
+ }
402
+ }
285
403
  async close() {
286
404
  if (!this.bridge) return;
287
405
  try {
288
406
  await this.sendRequest({ id: 0, type: "close" });
289
407
  } finally {
290
408
  this.tabSession?.stopRelay?.();
409
+ this.tabSession?.cancelPromotionWatch?.();
291
410
  if (this.tabSession?.releaseLock) {
292
411
  await this.tabSession.releaseLock();
293
412
  }
@@ -298,6 +417,30 @@ var SqliteWasmAdapter = class {
298
417
  this.opened = false;
299
418
  }
300
419
  }
420
+ /**
421
+ * Promotes a follower to leader after the previous leader released the storage
422
+ * lock (its tab closed or crashed). The lock is only granted once the old leader
423
+ * is gone, so opening our own worker here is safe from the OPFS single-writer
424
+ * rule. In-flight follower RPCs are rejected and left to the caller / reactive
425
+ * layer to retry against the new leader.
426
+ */
427
+ async promoteToLeader() {
428
+ if (this.promoting || !this.opened || this.workerUrl === void 0 || this.schema === null) {
429
+ return;
430
+ }
431
+ this.promoting = true;
432
+ const { WebWorkerBridge } = await import("./sqlite-wasm-channel-NGSBJR44.js");
433
+ const workerBridge = new WebWorkerBridge(this.workerUrl, this.workerResponseTimeoutMs);
434
+ const previousBridge = this.bridge;
435
+ this.bridge = workerBridge;
436
+ if (this.tabSession) {
437
+ this.tabSession.role = "leader";
438
+ this.tabSession.stopRelay = startLeaderRpcRelay(this.tabSession.channelName, workerBridge);
439
+ }
440
+ previousBridge?.terminate();
441
+ const ddlStatements = generateFullDDL(this.schema);
442
+ await this.sendRequest({ id: 0, type: "open", ddlStatements, dbName: this.dbName });
443
+ }
301
444
  async execute(sql, params) {
302
445
  this.guardOpen();
303
446
  const response = await this.sendRequest({ id: 0, type: "execute", sql, params });
@@ -422,4 +565,4 @@ var SqliteWasmAdapter = class {
422
565
  export {
423
566
  SqliteWasmAdapter
424
567
  };
425
- //# sourceMappingURL=chunk-RBPVEAVM.js.map
568
+ //# sourceMappingURL=chunk-2ZRQGFEF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/sqlite-wasm-adapter.ts","../src/multi-tab/shared-worker-bridge.ts","../src/multi-tab/tab-storage.ts"],"sourcesContent":["import { generateFullDDL } from '@korajs/core'\nimport type { KoraEventEmitter, SchemaDefinition } from '@korajs/core'\nimport { AdapterError, StoreNotOpenError } from '../errors'\nimport { SharedWorkerClientBridge } from '../multi-tab/shared-worker-bridge'\nimport {\n\tFollowerBroadcastBridge,\n\tacquireTabStorageSession,\n\tisSharedWorkerStorageSupported,\n\tstartLeaderRpcRelay,\n} from '../multi-tab/tab-storage'\nimport type { MigrationPlan, StorageAdapter, Transaction } from '../types'\nimport { Mutex } from './sqlite-wasm-channel'\nimport type { WorkerBridge, WorkerRequest, WorkerResponse } from './sqlite-wasm-channel'\n\n/**\n * Options for creating a SqliteWasmAdapter.\n */\nexport interface SqliteWasmAdapterOptions {\n\t/**\n\t * Injected WorkerBridge for testing. If omitted, a WebWorkerBridge is created\n\t * in browser environments.\n\t */\n\tbridge?: WorkerBridge\n\n\t/**\n\t * Database name for persistence. Used as the OPFS file name or IDB key.\n\t */\n\tdbName?: string\n\n\t/**\n\t * URL to the sqlite-wasm-worker script. Required in browsers if no bridge is provided.\n\t */\n\tworkerUrl?: string | URL\n\n\t/** Timeout for worker / follower RPC responses. Defaults to 30000ms. */\n\tworkerResponseTimeoutMs?: number\n\n\t/**\n\t * Optional SharedWorker host script (`sqlite-wasm-shared-host`). When set and\n\t * {@link isSharedWorkerStorageSupported}, one DedicatedWorker per `dbName` is pooled per origin.\n\t * Requires `workerUrl` for the inner SQLite worker. Falls back to leader election when omitted.\n\t */\n\tsharedWorkerUrl?: string | URL\n\n\t/**\n\t * When set, storage diagnostics are emitted here: `store:opfs-unavailable` when\n\t * persistence silently degraded to a non-persistent in-memory database, and\n\t * `store:db-name-collision` when another runtime on this origin was already\n\t * using this database name.\n\t */\n\temitter?: KoraEventEmitter\n}\n\n/**\n * SQLite WASM adapter that communicates with a SQLite instance through a WorkerBridge.\n *\n * In browsers, the bridge is backed by a Web Worker running SQLite WASM with OPFS persistence.\n * In Node.js tests, the bridge is backed by MockWorkerBridge wrapping better-sqlite3.\n *\n * @example\n * ```typescript\n * // Browser usage\n * const adapter = new SqliteWasmAdapter({ workerUrl: '/sqlite-wasm-worker.js' })\n *\n * // Test usage with MockWorkerBridge\n * import { MockWorkerBridge } from './sqlite-wasm-mock-bridge'\n * const adapter = new SqliteWasmAdapter({ bridge: new MockWorkerBridge() })\n * ```\n */\nexport class SqliteWasmAdapter implements StorageAdapter {\n\tprivate bridge: WorkerBridge | null = null\n\tprivate opened = false\n\tprivate readonly mutex = new Mutex()\n\tprivate readonly injectedBridge: WorkerBridge | undefined\n\tprivate readonly workerUrl: string | URL | undefined\n\tprivate readonly sharedWorkerUrl: string | URL | undefined\n\tprivate readonly workerResponseTimeoutMs: number\n\tprivate readonly dbName: string\n\tprivate readonly emitter: KoraEventEmitter | undefined\n\tprivate tabSession: Awaited<ReturnType<typeof acquireTabStorageSession>> | null = null\n\tprivate sharedWorker: SharedWorker | null = null\n\t/** Retained so a follower promoted to leader can re-open its own worker. */\n\tprivate schema: SchemaDefinition | null = null\n\tprivate promoting = false\n\n\tconstructor(options: SqliteWasmAdapterOptions = {}) {\n\t\tthis.injectedBridge = options.bridge\n\t\tthis.workerUrl = options.workerUrl\n\t\tthis.sharedWorkerUrl = options.sharedWorkerUrl\n\t\tthis.workerResponseTimeoutMs = options.workerResponseTimeoutMs ?? 30_000\n\t\tthis.dbName = options.dbName ?? 'kora-db'\n\t\tthis.emitter = options.emitter\n\t}\n\n\tasync open(schema: SchemaDefinition): Promise<void> {\n\t\tif (this.opened) return\n\n\t\tif (this.injectedBridge) {\n\t\t\tthis.bridge = this.injectedBridge\n\t\t} else if (this.sharedWorkerUrl && this.workerUrl && isSharedWorkerStorageSupported()) {\n\t\t\tconst workerUrlString =\n\t\t\t\ttypeof this.workerUrl === 'string' ? this.workerUrl : this.workerUrl.href\n\t\t\tconst sharedUrl =\n\t\t\t\ttypeof this.sharedWorkerUrl === 'string' ? this.sharedWorkerUrl : this.sharedWorkerUrl.href\n\t\t\tthis.sharedWorker = new SharedWorker(sharedUrl, { name: `kora-sw-${this.dbName}` })\n\t\t\tthis.bridge = new SharedWorkerClientBridge(this.sharedWorker, this.dbName, workerUrlString)\n\t\t} else if (this.workerUrl) {\n\t\t\tthis.schema = schema\n\t\t\tthis.tabSession = await acquireTabStorageSession(this.dbName, {\n\t\t\t\tonPromote: () => {\n\t\t\t\t\tvoid this.promoteToLeader()\n\t\t\t\t},\n\t\t\t})\n\t\t\tconst { WebWorkerBridge } = await import('./sqlite-wasm-channel')\n\n\t\t\tif (this.tabSession.role === 'leader') {\n\t\t\t\tconst workerBridge = new WebWorkerBridge(this.workerUrl, this.workerResponseTimeoutMs)\n\t\t\t\tthis.tabSession.stopRelay = startLeaderRpcRelay(this.tabSession.channelName, workerBridge)\n\t\t\t\tthis.bridge = workerBridge\n\t\t\t} else {\n\t\t\t\tconst followerBridge = new FollowerBroadcastBridge(\n\t\t\t\t\tthis.tabSession.channelName,\n\t\t\t\t\tthis.workerResponseTimeoutMs,\n\t\t\t\t)\n\t\t\t\tthis.bridge = followerBridge\n\t\t\t\t// Another runtime on this origin already owns this database name. That is\n\t\t\t\t// expected for multiple tabs of the same app (they share one leader),\n\t\t\t\t// but a bug if these are logically separate apps, so surface it so the\n\t\t\t\t// developer can give them distinct store names.\n\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\ttype: 'store:db-name-collision',\n\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\tmessage: `Another runtime on this origin is already using database \"${this.dbName}\"; this runtime is sharing it as a follower. If these are separate apps, give each a distinct store name.`,\n\t\t\t\t})\n\t\t\t\t// Readiness handshake: give the leader relay a moment to answer before the\n\t\t\t\t// first RPC, so a follower opened during a leader's startup race retries the\n\t\t\t\t// handshake instead of firing into the void and waiting out the full timeout.\n\t\t\t\tawait followerBridge.waitForLeader()\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new AdapterError(\n\t\t\t\t'SqliteWasmAdapter requires either a bridge (for testing) or a workerUrl (for browsers). ' +\n\t\t\t\t\t'Pass { bridge: new MockWorkerBridge() } for tests, or { workerUrl: \"/worker.js\" } for browsers.',\n\t\t\t)\n\t\t}\n\n\t\tconst ddlStatements = generateFullDDL(schema)\n\t\tconst response = await this.sendRequest({\n\t\t\tid: 0,\n\t\t\ttype: 'open',\n\t\t\tddlStatements,\n\t\t\tdbName: this.dbName,\n\t\t})\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Failed to open database: ${response.message}`, {\n\t\t\t\tcode: response.code,\n\t\t\t\tdbName: this.dbName,\n\t\t\t})\n\t\t}\n\t\tthis.reportStorageMode(response.data)\n\t\tthis.opened = true\n\t}\n\n\t/**\n\t * Surface a `store:opfs-unavailable` diagnostic when the worker reported that\n\t * persistence silently degraded to an in-memory database, so a data-loss\n\t * condition is observable instead of failing silently. A persistent open (or a\n\t * bridge that does not report a mode, e.g. the Node mock) emits nothing.\n\t */\n\tprivate reportStorageMode(data: unknown): void {\n\t\tif (!this.emitter || typeof data !== 'object' || data === null) {\n\t\t\treturn\n\t\t}\n\t\tconst mode = data as {\n\t\t\tpersistent?: boolean\n\t\t\tfallbackReason?: 'lock-conflict' | 'timeout' | 'unsupported'\n\t\t}\n\t\tif (mode.persistent === false) {\n\t\t\tconst reason = mode.fallbackReason ?? 'unsupported'\n\t\t\tthis.emitter.emit({\n\t\t\t\ttype: 'store:opfs-unavailable',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\treason,\n\t\t\t\tmessage: `OPFS persistence is unavailable (${reason}) for database \"${this.dbName}\"; the store is running in memory and data will not survive a reload.`,\n\t\t\t})\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (!this.bridge) return\n\n\t\ttry {\n\t\t\tawait this.sendRequest({ id: 0, type: 'close' })\n\t\t} finally {\n\t\t\tthis.tabSession?.stopRelay?.()\n\t\t\tthis.tabSession?.cancelPromotionWatch?.()\n\t\t\tif (this.tabSession?.releaseLock) {\n\t\t\t\tawait this.tabSession.releaseLock()\n\t\t\t}\n\t\t\tthis.tabSession = null\n\t\t\tthis.sharedWorker = null\n\t\t\tthis.bridge.terminate()\n\t\t\tthis.bridge = null\n\t\t\tthis.opened = false\n\t\t}\n\t}\n\n\t/**\n\t * Promotes a follower to leader after the previous leader released the storage\n\t * lock (its tab closed or crashed). The lock is only granted once the old leader\n\t * is gone, so opening our own worker here is safe from the OPFS single-writer\n\t * rule. In-flight follower RPCs are rejected and left to the caller / reactive\n\t * layer to retry against the new leader.\n\t */\n\tprivate async promoteToLeader(): Promise<void> {\n\t\tif (this.promoting || !this.opened || this.workerUrl === undefined || this.schema === null) {\n\t\t\treturn\n\t\t}\n\t\tthis.promoting = true\n\n\t\tconst { WebWorkerBridge } = await import('./sqlite-wasm-channel')\n\t\tconst workerBridge = new WebWorkerBridge(this.workerUrl, this.workerResponseTimeoutMs)\n\n\t\tconst previousBridge = this.bridge\n\t\tthis.bridge = workerBridge\n\t\tif (this.tabSession) {\n\t\t\tthis.tabSession.role = 'leader'\n\t\t\tthis.tabSession.stopRelay = startLeaderRpcRelay(this.tabSession.channelName, workerBridge)\n\t\t}\n\t\tpreviousBridge?.terminate()\n\n\t\t// Re-open against our own worker. DDL is idempotent, and the OPFS data the old\n\t\t// leader persisted is now readable by this worker.\n\t\tconst ddlStatements = generateFullDDL(this.schema)\n\t\tawait this.sendRequest({ id: 0, type: 'open', ddlStatements, dbName: this.dbName })\n\t}\n\n\tasync execute(sql: string, params?: unknown[]): Promise<void> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'execute', sql, params })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Execute failed: ${response.message}`, { sql, params })\n\t\t}\n\t}\n\n\tasync query<T>(sql: string, params?: unknown[]): Promise<T[]> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'query', sql, params })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Query failed: ${response.message}`, { sql, params })\n\t\t}\n\t\treturn (response.data as T[]) ?? []\n\t}\n\n\tasync transaction(fn: (tx: Transaction) => Promise<void>): Promise<void> {\n\t\tthis.guardOpen()\n\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tawait this.sendChecked({ id: 0, type: 'begin' }, 'BEGIN transaction')\n\n\t\t\tconst tx: Transaction = {\n\t\t\t\texecute: async (sql: string, params?: unknown[]): Promise<void> => {\n\t\t\t\t\tconst response = await this.sendRequest({ id: 0, type: 'execute', sql, params })\n\t\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t\tthrow new AdapterError(`Transaction execute failed: ${response.message}`, {\n\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tquery: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {\n\t\t\t\t\tconst response = await this.sendRequest({ id: 0, type: 'query', sql, params })\n\t\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t\tthrow new AdapterError(`Transaction query failed: ${response.message}`, { sql, params })\n\t\t\t\t\t}\n\t\t\t\t\treturn (response.data as T[]) ?? []\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tawait fn(tx)\n\t\t\tawait this.sendChecked({ id: 0, type: 'commit' }, 'COMMIT transaction')\n\t\t} catch (error) {\n\t\t\t// Attempt rollback, but don't mask the original error\n\t\t\ttry {\n\t\t\t\tawait this.sendRequest({ id: 0, type: 'rollback' })\n\t\t\t} catch {\n\t\t\t\t// Rollback failure is secondary to the original error\n\t\t\t}\n\t\t\tthrow error\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\tasync migrate(from: number, to: number, migration: MigrationPlan): Promise<void> {\n\t\tthis.guardOpen()\n\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tawait this.sendChecked({ id: 0, type: 'begin' }, 'BEGIN migration')\n\n\t\t\tfor (const sql of migration.statements) {\n\t\t\t\tconst response = await this.sendRequest({ id: 0, type: 'execute', sql })\n\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\tthrow new AdapterError(`Migration from v${from} to v${to} failed: ${response.message}`, {\n\t\t\t\t\t\tfrom,\n\t\t\t\t\t\tto,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait this.sendChecked({ id: 0, type: 'commit' }, 'COMMIT migration')\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait this.sendRequest({ id: 0, type: 'rollback' })\n\t\t\t} catch {\n\t\t\t\t// Rollback failure is secondary\n\t\t\t}\n\t\t\tif (error instanceof AdapterError) throw error\n\t\t\tthrow new AdapterError(\n\t\t\t\t`Migration from v${from} to v${to} failed: ${(error as Error).message}`,\n\t\t\t\t{ from, to },\n\t\t\t)\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Export the database as a Uint8Array (for IndexedDB persistence).\n\t * Only available when the database is open.\n\t */\n\tasync exportDatabase(): Promise<Uint8Array> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'export' })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Export failed: ${response.message}`)\n\t\t}\n\t\treturn response.data as Uint8Array\n\t}\n\n\t/**\n\t * Import a serialized database snapshot.\n\t */\n\tasync importDatabase(data: Uint8Array): Promise<void> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'import', data })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Import failed: ${response.message}`)\n\t\t}\n\t}\n\n\tprivate guardOpen(): void {\n\t\tif (!this.opened || !this.bridge) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t}\n\n\tprivate async sendRequest(request: WorkerRequest): Promise<WorkerResponse> {\n\t\t// guardOpen() is always called before sendRequest, so bridge is guaranteed non-null\n\t\tconst bridge = this.bridge\n\t\tif (!bridge) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\treturn bridge.send(request)\n\t}\n\n\tprivate async sendChecked(request: WorkerRequest, description: string): Promise<void> {\n\t\tconst response = await this.sendRequest(request)\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`${description} failed: ${response.message}`)\n\t\t}\n\t}\n}\n","/// <reference lib=\"dom\" />\nimport type { WorkerBridge, WorkerRequest, WorkerResponse } from '../adapters/sqlite-wasm-channel'\nimport { WorkerTimeoutError } from '../errors'\n\nconst SW_REQUEST = 'kora-sw-request'\nconst SW_RESPONSE = 'kora-sw-response'\n\nexport interface SharedWorkerRpcRequest {\n\ttype: typeof SW_REQUEST\n\trequestId: string\n\tdbName: string\n\tworkerUrl: string\n\trequest: WorkerRequest\n}\n\nexport interface SharedWorkerRpcResponse {\n\ttype: typeof SW_RESPONSE\n\trequestId: string\n\tresponse: WorkerResponse\n}\n\n/**\n * Forwards {@link WorkerBridge} RPC to a SharedWorker that hosts one DedicatedWorker per `dbName`.\n * Pair with the bundled `sqlite-wasm-shared-host` worker script.\n */\nexport class SharedWorkerClientBridge implements WorkerBridge {\n\tprivate readonly port: MessagePort\n\tprivate readonly pending = new Map<\n\t\tstring,\n\t\t{ resolve: (r: WorkerResponse) => void; reject: (e: Error) => void }\n\t>()\n\tprivate readonly timeoutMs: number\n\tprivate terminated = false\n\n\tconstructor(\n\t\tsharedWorker: SharedWorker,\n\t\tprivate readonly dbName: string,\n\t\tprivate readonly workerUrl: string,\n\t\ttimeoutMs = 30000,\n\t) {\n\t\tthis.timeoutMs = timeoutMs\n\t\tthis.port = sharedWorker.port\n\t\tthis.port.start()\n\t\tthis.port.addEventListener('message', (event: MessageEvent<SharedWorkerRpcResponse>) => {\n\t\t\tconst data = event.data\n\t\t\tif (data?.type !== SW_RESPONSE) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst entry = this.pending.get(data.requestId)\n\t\t\tif (entry) {\n\t\t\t\tthis.pending.delete(data.requestId)\n\t\t\t\tentry.resolve(data.response)\n\t\t\t}\n\t\t})\n\t}\n\n\tasync send(request: WorkerRequest): Promise<WorkerResponse> {\n\t\tif (this.terminated) {\n\t\t\treturn {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'SharedWorker bridge terminated',\n\t\t\t\tcode: 'BRIDGE_TERMINATED',\n\t\t\t}\n\t\t}\n\n\t\tconst requestId = crypto.randomUUID()\n\t\tconst msg: SharedWorkerRpcRequest = {\n\t\t\ttype: SW_REQUEST,\n\t\t\trequestId,\n\t\t\tdbName: this.dbName,\n\t\t\tworkerUrl: this.workerUrl,\n\t\t\trequest,\n\t\t}\n\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(requestId)\n\t\t\t\treject(new WorkerTimeoutError(`shared-worker:${request.type}`, this.timeoutMs))\n\t\t\t}, this.timeoutMs)\n\n\t\t\tthis.pending.set(requestId, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tresolve(response)\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\treject(error)\n\t\t\t\t},\n\t\t\t})\n\n\t\t\tthis.port.postMessage(msg)\n\t\t})\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.port.close()\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tentry.reject(new Error('SharedWorker bridge terminated'))\n\t\t}\n\t\tthis.pending.clear()\n\t}\n}\n","/**\n * Multi-tab SQLite storage coordination via `navigator.locks` and `BroadcastChannel`.\n *\n * One tab holds the exclusive `kora-leader-${dbName}` lock and owns the SQLite worker.\n * Other tabs send worker RPC over a named broadcast channel.\n */\n\nimport type { WorkerBridge, WorkerRequest, WorkerResponse } from '../adapters/sqlite-wasm-channel'\nimport { NoLeaderError, WorkerTimeoutError } from '../errors'\n\nconst RPC_REQUEST = 'kora-worker-request'\nconst RPC_RESPONSE = 'kora-worker-response'\nconst LEADER_PING = 'kora-leader-ping'\nconst LEADER_PONG = 'kora-leader-pong'\n\n/** Default delay before a stalled follower RPC probes the leader for liveness. */\nconst DEFAULT_LIVENESS_PROBE_MS = 2000\n\ninterface RpcRequestMessage {\n\ttype: typeof RPC_REQUEST\n\trequestId: string\n\trequest: WorkerRequest\n}\n\ninterface RpcResponseMessage {\n\ttype: typeof RPC_RESPONSE\n\trequestId: string\n\tresponse: WorkerResponse\n}\n\nexport type TabStorageRole = 'leader' | 'follower'\n\nexport interface AcquireTabStorageOptions {\n\t/**\n\t * Invoked when a follower is promoted to leader because the previous leader\n\t * released the lock (its tab closed or crashed). The adapter uses this to\n\t * rebuild its bridge as a leader. Never fires for a tab that started as leader.\n\t */\n\tonPromote?: () => void\n}\n\nexport interface TabStorageSession {\n\trole: TabStorageRole\n\tchannelName: string\n\t/** Leader only: release the navigator lock when closing the database. */\n\treleaseLock?: () => Promise<void>\n\t/** Leader only: stop the broadcast RPC relay. */\n\tstopRelay?: () => void\n\t/**\n\t * Follower only: resolves when this tab has been promoted to leader (the old\n\t * leader released the lock). The adapter awaits nothing here directly; it reacts\n\t * via {@link AcquireTabStorageOptions.onPromote}. Present so callers can cancel\n\t * the promotion watch on close.\n\t */\n\tcancelPromotionWatch?: () => void\n}\n\n/**\n * Returns whether a SharedWorker could host a single SQLite WASM instance per origin.\n * Not implemented yet — use {@link isMultiTabStorageSupported} + leader election today.\n */\nexport function isSharedWorkerStorageSupported(): boolean {\n\treturn typeof globalThis !== 'undefined' && typeof SharedWorker !== 'undefined'\n}\n\n/**\n * Returns whether multi-tab coordination APIs exist in this runtime.\n */\nexport function isMultiTabStorageSupported(): boolean {\n\treturn (\n\t\ttypeof globalThis !== 'undefined' &&\n\t\ttypeof BroadcastChannel !== 'undefined' &&\n\t\ttypeof navigator !== 'undefined' &&\n\t\ttypeof navigator.locks?.request === 'function'\n\t)\n}\n\n/**\n * Resolve leader vs follower for a database name.\n * Without lock APIs, every instance is treated as leader (single-tab / Node).\n *\n * A follower additionally queues a blocking request for the same lock. When the\n * current leader releases it (its tab closed or crashed), the browser grants the\n * lock to this follower and {@link AcquireTabStorageOptions.onPromote} fires so the\n * adapter can rebuild itself as the new leader. This is the automatic failover\n * path; a leader that is merely throttled (backgrounded but alive) keeps the lock,\n * and followers stay resilient through the liveness probe on the RPC bridge.\n */\nexport async function acquireTabStorageSession(\n\tdbName: string,\n\toptions?: AcquireTabStorageOptions,\n): Promise<TabStorageSession> {\n\tconst channelName = `kora-storage-${dbName}`\n\tconst lockName = `kora-leader-${dbName}`\n\n\tif (!isMultiTabStorageSupported()) {\n\t\treturn { role: 'leader', channelName }\n\t}\n\n\treturn new Promise<TabStorageSession>((resolve) => {\n\t\tlet releaseHeld: (() => void) | undefined\n\n\t\tvoid navigator.locks.request(lockName, { mode: 'exclusive', ifAvailable: true }, (lock) => {\n\t\t\tif (lock === null) {\n\t\t\t\tresolve(startFollowerSession(channelName, lockName, options))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresolve({\n\t\t\t\trole: 'leader',\n\t\t\t\tchannelName,\n\t\t\t\treleaseLock: async () => {\n\t\t\t\t\treleaseHeld?.()\n\t\t\t\t},\n\t\t\t})\n\n\t\t\treturn new Promise<void>((release) => {\n\t\t\t\treleaseHeld = release\n\t\t\t})\n\t\t})\n\t})\n}\n\n/**\n * Builds a follower session and starts watching for promotion. The follower holds\n * a queued lock request; when it is finally granted (old leader gone), it becomes\n * the leader for the rest of its lifetime and notifies via `onPromote`.\n */\nfunction startFollowerSession(\n\tchannelName: string,\n\tlockName: string,\n\toptions?: AcquireTabStorageOptions,\n): TabStorageSession {\n\tlet promoted = false\n\tlet releasePromotedLock: (() => void) | undefined\n\tconst abort = new AbortController()\n\n\tvoid navigator.locks\n\t\t.request(lockName, { mode: 'exclusive', signal: abort.signal }, () => {\n\t\t\t// Reaching here means the previous leader released the lock and this tab\n\t\t\t// won it. Hold it (never-resolving promise) so this tab is now the leader.\n\t\t\tpromoted = true\n\t\t\toptions?.onPromote?.()\n\t\t\treturn new Promise<void>((release) => {\n\t\t\t\treleasePromotedLock = release\n\t\t\t})\n\t\t})\n\t\t.catch(() => {\n\t\t\t// AbortError when the tab closes before promotion. Nothing to do.\n\t\t})\n\n\treturn {\n\t\trole: 'follower',\n\t\tchannelName,\n\t\tcancelPromotionWatch: () => {\n\t\t\tif (promoted) {\n\t\t\t\treleasePromotedLock?.()\n\t\t\t} else {\n\t\t\t\tabort.abort()\n\t\t\t}\n\t\t},\n\t}\n}\n\n/**\n * Leader tab: forward follower RPC to the real worker bridge.\n */\nexport function startLeaderRpcRelay(channelName: string, bridge: WorkerBridge): () => void {\n\tconst channel = new BroadcastChannel(channelName)\n\n\tconst onMessage = (\n\t\tevent: MessageEvent<RpcRequestMessage | { type: typeof LEADER_PING }>,\n\t): void => {\n\t\tconst data = event.data\n\t\t// Answer liveness probes immediately, without touching the worker, so a\n\t\t// follower can distinguish a slow-but-alive leader from an absent one.\n\t\tif (data?.type === LEADER_PING) {\n\t\t\tchannel.postMessage({ type: LEADER_PONG })\n\t\t\treturn\n\t\t}\n\t\tif (data?.type !== RPC_REQUEST) {\n\t\t\treturn\n\t\t}\n\n\t\tvoid bridge\n\t\t\t.send(data.request)\n\t\t\t.then((response) => {\n\t\t\t\tconst msg: RpcResponseMessage = {\n\t\t\t\t\ttype: RPC_RESPONSE,\n\t\t\t\t\trequestId: data.requestId,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t\tchannel.postMessage(msg)\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tconst message = error instanceof Error ? error.message : 'Worker RPC failed'\n\t\t\t\tconst msg: RpcResponseMessage = {\n\t\t\t\t\ttype: RPC_RESPONSE,\n\t\t\t\t\trequestId: data.requestId,\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\tid: data.request.id,\n\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tcode: 'LEADER_RPC_ERROR',\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tchannel.postMessage(msg)\n\t\t\t})\n\t}\n\n\tchannel.addEventListener('message', onMessage)\n\treturn () => {\n\t\tchannel.removeEventListener('message', onMessage)\n\t\tchannel.close()\n\t}\n}\n\n/**\n * Follower tab: proxy {@link WorkerBridge} over BroadcastChannel to the leader.\n */\nexport class FollowerBroadcastBridge implements WorkerBridge {\n\tprivate readonly channel: BroadcastChannel\n\tprivate readonly pending = new Map<\n\t\tstring,\n\t\t{ resolve: (r: WorkerResponse) => void; reject: (e: Error) => void }\n\t>()\n\tprivate readonly timeoutMs: number\n\tprivate readonly livenessProbeMs: number\n\tprivate terminated = false\n\n\tconstructor(channelName: string, timeoutMs = 30000, livenessProbeMs = DEFAULT_LIVENESS_PROBE_MS) {\n\t\tthis.timeoutMs = timeoutMs\n\t\tthis.livenessProbeMs = Math.min(livenessProbeMs, timeoutMs)\n\t\tthis.channel = new BroadcastChannel(channelName)\n\t\tthis.channel.addEventListener('message', (event: MessageEvent<RpcResponseMessage>) => {\n\t\t\tconst data = event.data\n\t\t\tif (data?.type !== RPC_RESPONSE) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst entry = this.pending.get(data.requestId)\n\t\t\tif (entry) {\n\t\t\t\tthis.pending.delete(data.requestId)\n\t\t\t\tentry.resolve(data.response)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Readiness handshake: resolves `true` as soon as a live leader answers a ping,\n\t * or `false` if none answers within the budget. The adapter calls this before\n\t * its first RPC so a follower created before a leader relay is live retries the\n\t * handshake instead of firing into the void and waiting out the full timeout.\n\t */\n\tasync waitForLeader(timeoutMs = 3000, attempts = 3): Promise<boolean> {\n\t\tconst perAttempt = Math.max(50, Math.floor(timeoutMs / Math.max(1, attempts)))\n\t\tfor (let attempt = 0; attempt < attempts; attempt += 1) {\n\t\t\tif (this.terminated) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (await this.pingLeader(perAttempt)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t/** Sends one liveness ping and resolves whether a leader answered in time. */\n\tprivate pingLeader(timeoutMs: number): Promise<boolean> {\n\t\tif (this.terminated) {\n\t\t\treturn Promise.resolve(false)\n\t\t}\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tconst onPong = (event: MessageEvent<{ type: string }>): void => {\n\t\t\t\tif (event.data?.type === LEADER_PONG) {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tresolve(true)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst cleanup = (): void => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tthis.channel.removeEventListener('message', onPong)\n\t\t\t}\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup()\n\t\t\t\tresolve(false)\n\t\t\t}, timeoutMs)\n\t\t\tthis.channel.addEventListener('message', onPong)\n\t\t\tthis.channel.postMessage({ type: LEADER_PING })\n\t\t})\n\t}\n\n\tasync send(request: WorkerRequest): Promise<WorkerResponse> {\n\t\tif (this.terminated) {\n\t\t\treturn {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'Follower bridge terminated',\n\t\t\t\tcode: 'BRIDGE_TERMINATED',\n\t\t\t}\n\t\t}\n\n\t\tconst requestId = crypto.randomUUID()\n\t\tconst msg: RpcRequestMessage = { type: RPC_REQUEST, requestId, request }\n\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tconst settle = (fn: () => void): void => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tclearTimeout(probe)\n\t\t\t\tthis.pending.delete(requestId)\n\t\t\t\tfn()\n\t\t\t}\n\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tsettle(() => reject(new WorkerTimeoutError(`follower-rpc:${request.type}`, this.timeoutMs)))\n\t\t\t}, this.timeoutMs)\n\n\t\t\t// Liveness watchdog: if the request stalls, probe the leader. A confirmed\n\t\t\t// absent leader fails fast (NoLeaderError) instead of waiting out the full\n\t\t\t// timeout; a slow-but-alive leader keeps its remaining time.\n\t\t\tconst probe = setTimeout(() => {\n\t\t\t\tvoid this.pingLeader(this.livenessProbeMs).then((alive) => {\n\t\t\t\t\tif (!alive && this.pending.has(requestId)) {\n\t\t\t\t\t\tsettle(() => reject(new NoLeaderError(`follower-rpc:${request.type}`)))\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}, this.livenessProbeMs)\n\n\t\t\tthis.pending.set(requestId, {\n\t\t\t\tresolve: (response) => settle(() => resolve(response)),\n\t\t\t\treject: (error) => settle(() => reject(error)),\n\t\t\t})\n\n\t\t\tthis.channel.postMessage(msg)\n\t\t})\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.channel.close()\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tentry.reject(new Error('Follower bridge terminated'))\n\t\t}\n\t\tthis.pending.clear()\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,uBAAuB;;;ACIhC,IAAM,aAAa;AACnB,IAAM,cAAc;AAoBb,IAAM,2BAAN,MAAuD;AAAA,EAS7D,YACC,cACiB,QACA,WACjB,YAAY,KACX;AAHgB;AACA;AAGjB,SAAK,YAAY;AACjB,SAAK,OAAO,aAAa;AACzB,SAAK,KAAK,MAAM;AAChB,SAAK,KAAK,iBAAiB,WAAW,CAAC,UAAiD;AACvF,YAAM,OAAO,MAAM;AACnB,UAAI,MAAM,SAAS,aAAa;AAC/B;AAAA,MACD;AACA,YAAM,QAAQ,KAAK,QAAQ,IAAI,KAAK,SAAS;AAC7C,UAAI,OAAO;AACV,aAAK,QAAQ,OAAO,KAAK,SAAS;AAClC,cAAM,QAAQ,KAAK,QAAQ;AAAA,MAC5B;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAlBkB;AAAA,EACA;AAAA,EAXD;AAAA,EACA,UAAU,oBAAI,IAG7B;AAAA,EACe;AAAA,EACT,aAAa;AAAA,EAwBrB,MAA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AAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAAe,MAAiC;AACrD,SAAK,UAAU;AACf,UAAM,WAAW,MAAM,KAAK,YAAY,EAAE,IAAI,GAAG,MAAM,UAAU,KAAK,CAAC;AACvE,QAAI,SAAS,SAAS,SAAS;AAC9B,YAAM,IAAI,aAAa,kBAAkB,SAAS,OAAO,EAAE;AAAA,IAC5D;AAAA,EACD;AAAA,EAEQ,YAAkB;AACzB,QAAI,CAAC,KAAK,UAAU,CAAC,KAAK,QAAQ;AACjC,YAAM,IAAI,kBAAkB;AAAA,IAC7B;AAAA,EACD;AAAA,EAEA,MAAc,YAAY,SAAiD;AAE1E,UAAM,SAAS,KAAK;AACpB,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI,kBAAkB;AAAA,IAC7B;AACA,WAAO,OAAO,KAAK,OAAO;AAAA,EAC3B;AAAA,EAEA,MAAc,YAAY,SAAwB,aAAoC;AACrF,UAAM,WAAW,MAAM,KAAK,YAAY,OAAO;AAC/C,QAAI,SAAS,SAAS,SAAS;AAC9B,YAAM,IAAI,aAAa,GAAG,WAAW,YAAY,SAAS,OAAO,EAAE;AAAA,IACpE;AAAA,EACD;AACD;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  WorkerTimeoutError
3
- } from "./chunk-QL2XVZRN.js";
3
+ } from "./chunk-TUR7RGEP.js";
4
4
 
5
5
  // src/adapters/sqlite-wasm-channel.ts
6
6
  var WebWorkerBridge = class {
@@ -75,4 +75,4 @@ var WebWorkerBridge = class {
75
75
  export {
76
76
  WebWorkerBridge
77
77
  };
78
- //# sourceMappingURL=chunk-IOEFNHHP.js.map
78
+ //# sourceMappingURL=chunk-COJSQBXW.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-6NKLDBTY.js";
4
4
 
5
5
  // src/backup/backup.ts
6
- import "@korajs/core";
6
+ import { quoteIdent } from "@korajs/core";
7
7
  function encodeSection(name, content) {
8
8
  const nameBytes = new TextEncoder().encode(name);
9
9
  const header = new Uint8Array(8);
@@ -242,7 +242,7 @@ async function restoreBackup(adapter, schema, data, options) {
242
242
  schema_version: op.schemaVersion
243
243
  };
244
244
  await tx.execute(
245
- `INSERT OR IGNORE INTO _kora_ops_${collection} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
245
+ `INSERT OR IGNORE INTO ${quoteIdent(`_kora_ops_${collection}`)} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
246
246
  [
247
247
  opRow.id,
248
248
  opRow.node_id,
@@ -261,8 +261,8 @@ async function restoreBackup(adapter, schema, data, options) {
261
261
  } else {
262
262
  await adapter.transaction(async (tx) => {
263
263
  for (const collection of Object.keys(schema.collections)) {
264
- await tx.execute(`DELETE FROM _kora_ops_${collection}`);
265
- await tx.execute(`DELETE FROM ${collection}`);
264
+ await tx.execute(`DELETE FROM ${quoteIdent(`_kora_ops_${collection}`)}`);
265
+ await tx.execute(`DELETE FROM ${quoteIdent(collection)}`);
266
266
  }
267
267
  await tx.execute("DELETE FROM _kora_version_vector");
268
268
  await tx.execute("DELETE FROM _kora_meta");
@@ -282,7 +282,7 @@ async function restoreBackup(adapter, schema, data, options) {
282
282
  for (const op of operations) {
283
283
  const collection = op.collection;
284
284
  await tx.execute(
285
- `INSERT INTO _kora_ops_${collection} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
285
+ `INSERT INTO ${quoteIdent(`_kora_ops_${collection}`)} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
286
286
  [
287
287
  op.id,
288
288
  op.nodeId,
@@ -314,6 +314,7 @@ async function restoreBackup(adapter, schema, data, options) {
314
314
  for (const record of records) {
315
315
  const keys = Object.keys(record);
316
316
  const placeholders = keys.map(() => "?").join(", ");
317
+ const quotedKeys = keys.map((k) => quoteIdent(k)).join(", ");
317
318
  const values = keys.map((k) => {
318
319
  const v = record[k];
319
320
  if (typeof v === "boolean") return v ? 1 : 0;
@@ -321,7 +322,7 @@ async function restoreBackup(adapter, schema, data, options) {
321
322
  return v;
322
323
  });
323
324
  await tx.execute(
324
- `INSERT OR REPLACE INTO ${col} (${keys.join(", ")}) VALUES (${placeholders})`,
325
+ `INSERT OR REPLACE INTO ${quoteIdent(col)} (${quotedKeys}) VALUES (${placeholders})`,
325
326
  values
326
327
  );
327
328
  }
@@ -354,7 +355,7 @@ async function readAllOperations(adapter, schema) {
354
355
  const allOps = [];
355
356
  for (const collectionName of Object.keys(schema.collections)) {
356
357
  const rows = await adapter.query(
357
- `SELECT * FROM _kora_ops_${collectionName} ORDER BY sequence_number ASC`
358
+ `SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} ORDER BY sequence_number ASC`
358
359
  );
359
360
  for (const row of rows) {
360
361
  allOps.push(deserializeOperationWithCollection(row, collectionName));
@@ -363,7 +364,9 @@ async function readAllOperations(adapter, schema) {
363
364
  return allOps;
364
365
  }
365
366
  async function readCollectionRecords(adapter, collection) {
366
- return adapter.query(`SELECT * FROM ${collection} WHERE _deleted = 0`);
367
+ return adapter.query(
368
+ `SELECT * FROM ${quoteIdent(collection)} WHERE _deleted = 0`
369
+ );
367
370
  }
368
371
  async function computeSha256(data) {
369
372
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
@@ -377,4 +380,4 @@ export {
377
380
  verifyBackupChecksum,
378
381
  restoreBackup
379
382
  };
380
- //# sourceMappingURL=chunk-X57MWW35.js.map
383
+ //# sourceMappingURL=chunk-OCOGQRHW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backup/backup.ts"],"sourcesContent":["import { generateUUIDv7, quoteIdent } from '@korajs/core'\nimport type { Operation, SchemaDefinition, VersionVector } from '@korajs/core'\nimport { deserializeOperationWithCollection } from '../serialization/serializer'\nimport type { OperationRow, StorageAdapter } from '../types'\nimport type {\n\tBackupManifest,\n\tBackupOptions,\n\tBackupProgress,\n\tRestoreOptions,\n\tRestoreResult,\n} from './types'\n\n// ── Section I/O helpers ──────────────────────────────────────────────────────\n\nfunction encodeSection(name: string, content: Uint8Array): Uint8Array {\n\tconst nameBytes = new TextEncoder().encode(name)\n\tconst header = new Uint8Array(8)\n\tconst dv = new DataView(header.buffer)\n\tdv.setUint32(0, nameBytes.length, true)\n\tdv.setUint32(4, content.length, true)\n\n\tconst result = new Uint8Array(header.length + nameBytes.length + content.length)\n\tresult.set(header, 0)\n\tresult.set(nameBytes, 8)\n\tresult.set(content, 8 + nameBytes.length)\n\treturn result\n}\n\nfunction encodeJsonSection(name: string, data: unknown): Uint8Array {\n\tconst json = JSON.stringify(data)\n\treturn encodeSection(name, new TextEncoder().encode(json))\n}\n\nfunction encodeNdjsonSection(name: string, records: unknown[]): Uint8Array {\n\tconst lines = `${records.map((r) => JSON.stringify(r)).join('\\n')}\\n`\n\treturn encodeSection(name, new TextEncoder().encode(lines))\n}\n\nfunction readUint32(view: DataView, offset: number): number {\n\treturn view.getUint32(offset, true)\n}\n\ninterface Section {\n\tname: string\n\tcontent: Uint8Array\n}\n\nfunction parseSections(data: Uint8Array): Section[] {\n\tconst sections: Section[] = []\n\tconst dv = new DataView(data.buffer, data.byteOffset, data.byteLength)\n\tlet offset = 0\n\n\twhile (offset + 8 <= data.byteLength) {\n\t\tconst nameLen = readUint32(dv, offset)\n\t\tconst contentLen = readUint32(dv, offset + 4)\n\t\toffset += 8\n\n\t\tif (offset + nameLen + contentLen > data.byteLength) break\n\n\t\tconst name = new TextDecoder().decode(data.slice(offset, offset + nameLen))\n\t\toffset += nameLen\n\n\t\tconst content = data.slice(offset, offset + contentLen)\n\t\toffset += contentLen\n\n\t\tsections.push({ name, content })\n\t}\n\n\treturn sections\n}\n\nfunction findSection(sections: Section[], name: string): Uint8Array | null {\n\tfor (const s of sections) {\n\t\tif (s.name === name) return s.content\n\t}\n\treturn null\n}\n\nfunction parseJsonSection<T>(sections: Section[], name: string): T | null {\n\tconst content = findSection(sections, name)\n\tif (!content) return null\n\treturn JSON.parse(new TextDecoder().decode(content)) as T\n}\n\n/**\n * Export format version. Bump on breaking changes.\n */\nconst BACKUP_VERSION = 1\n\n/**\n * Export a backup from a store.\n *\n * Reads all data via the adapter and produces a portable binary backup.\n *\n * @param adapter - The storage adapter\n * @param schema - The schema definition\n * @param nodeId - Current node ID\n * @param schemaVersion - Schema version\n * @param options - Backup options\n * @returns Backup as a Uint8Array\n */\nexport async function exportBackup(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tnodeId: string,\n\tschemaVersion: number,\n\toptions?: BackupOptions,\n): Promise<Uint8Array> {\n\tconst onProgress = options?.onProgress ?? (() => {})\n\tconst includeRecords = options?.includeRecords ?? true\n\tconst collectionFilter = options?.collections\n\tconst collections = collectionFilter\n\t\t? Object.keys(schema.collections).filter((c) => collectionFilter.includes(c))\n\t\t: Object.keys(schema.collections)\n\n\tonProgress({ phase: 'reading', progress: 0, message: 'Reading version vector' })\n\tconst versionVector = await readVersionVector(adapter)\n\tonProgress({ phase: 'reading', progress: 0.1, message: 'Reading metadata' })\n\tconst meta = await readMeta(adapter)\n\tonProgress({ phase: 'reading', progress: 0.2, message: 'Reading operations' })\n\tconst operations = await readAllOperations(adapter, schema)\n\tonProgress({ phase: 'reading', progress: 0.5, message: 'Reading records' })\n\n\tconst sections: Uint8Array[] = []\n\tlet allContentForChecksum = new Uint8Array(0)\n\n\t// Helper: add a section and update running checksum content\n\tconst addSection = (name: string, data: Uint8Array) => {\n\t\tsections.push(data)\n\t\tconst newLen = allContentForChecksum.length + data.length\n\t\tconst combined = new Uint8Array(newLen)\n\t\tcombined.set(allContentForChecksum, 0)\n\t\tcombined.set(data, allContentForChecksum.length)\n\t\tallContentForChecksum = combined\n\t}\n\n\t// Version vector section\n\tconst vvObj: Record<string, number> = {}\n\tfor (const [nid, seq] of versionVector) {\n\t\tvvObj[nid] = seq\n\t}\n\taddSection('version_vector', encodeJsonSection('version_vector', vvObj))\n\n\t// Meta section\n\tconst metaObj: Record<string, string> = {}\n\tfor (const row of meta) {\n\t\tmetaObj[row.key] = row.value\n\t}\n\taddSection('meta', encodeJsonSection('meta', metaObj))\n\n\t// Operations section\n\tconst opLines = `${operations.map((op) => JSON.stringify(op)).join('\\n')}\\n`\n\taddSection('operations', encodeSection('operations', new TextEncoder().encode(opLines)))\n\n\t// Records sections (optional)\n\tlet totalRecords = 0\n\tif (includeRecords) {\n\t\tfor (const col of collections) {\n\t\t\tconst records = await readCollectionRecords(adapter, col)\n\t\t\tif (records.length > 0) {\n\t\t\t\tconst lines = `${records.map((r) => JSON.stringify(r)).join('\\n')}\\n`\n\t\t\t\tconst sectionName = `records:${col}`\n\t\t\t\taddSection(sectionName, encodeSection(sectionName, new TextEncoder().encode(lines)))\n\t\t\t\ttotalRecords += records.length\n\t\t\t}\n\t\t}\n\t}\n\tonProgress({ phase: 'reading', progress: 0.9, message: 'Computing checksum' })\n\n\t// Compute SHA-256 checksum over all content sections\n\tconst checksumHex = await computeSha256(allContentForChecksum)\n\tonProgress({ phase: 'writing', progress: 1, message: 'Finalizing' })\n\n\t// Build manifest\n\tconst manifest: BackupManifest = {\n\t\tversion: BACKUP_VERSION,\n\t\tcreatedAt: Date.now(),\n\t\tnodeId,\n\t\tschemaVersion,\n\t\toperationCount: operations.length,\n\t\tcollections,\n\t\tincludesRecords: includeRecords,\n\t\tchecksum: checksumHex,\n\t}\n\n\t// Final output: header + manifest + all content sections + checksum section\n\tconst header = new Uint8Array(0)\n\n\t// Merge manifest + all sections + checksum section\n\tconst manifestSection = encodeJsonSection('manifest', manifest)\n\tconst checksumSection = encodeSection('checksum', new TextEncoder().encode(checksumHex))\n\n\tconst totalLen = manifestSection.length + allContentForChecksum.length + checksumSection.length\n\tconst result = new Uint8Array(totalLen)\n\tlet pos = 0\n\tresult.set(manifestSection, pos)\n\tpos += manifestSection.length\n\tresult.set(allContentForChecksum, pos)\n\tpos += allContentForChecksum.length\n\tresult.set(checksumSection, pos)\n\n\treturn result\n}\n\n/**\n * Read backup manifest without loading the entire backup.\n * Parses only the first section (which is always the manifest).\n *\n * @param data - The raw backup data\n * @returns The backup manifest\n */\nexport function readBackupManifest(data: Uint8Array): BackupManifest {\n\tconst sections = parseSections(data)\n\tconst manifest = parseJsonSection<BackupManifest>(sections, 'manifest')\n\tif (!manifest) {\n\t\tthrow new Error('Invalid backup: manifest section not found')\n\t}\n\treturn manifest\n}\n\n/**\n * Validate the backup checksum.\n *\n * @param data - The raw backup data\n * @returns True if the checksum is valid\n */\nexport async function verifyBackupChecksum(data: Uint8Array): Promise<boolean> {\n\tconst sections = parseSections(data)\n\tconst manifest = parseJsonSection<BackupManifest>(sections, 'manifest')\n\tif (!manifest) return false\n\n\tconst storedChecksum = manifest.checksum\n\tif (!storedChecksum) return false\n\n\t// Recompute checksum over content sections (everything after manifest, before checksum)\n\tconst manifestSection = findSection(sections, 'manifest')\n\tif (!manifestSection) return false\n\n\t// Find the checksum section\n\tconst checksumSection = findSection(sections, 'checksum')\n\n\t// The content spans from end of manifest section to start of checksum section\n\tconst checksumBytes = checksumSection\n\t\t? new TextEncoder().encode(manifest.checksum)\n\t\t: new Uint8Array(0)\n\n\t// Rebuild all content sections and hash them\n\tconst contentSections = sections.filter((s) => s.name !== 'manifest' && s.name !== 'checksum')\n\n\tlet contentForHash = new Uint8Array(0)\n\tfor (const section of contentSections) {\n\t\tconst sectionBytes = encodeSection(section.name, section.content)\n\t\tconst newLen = contentForHash.length + sectionBytes.length\n\t\tconst combined = new Uint8Array(newLen)\n\t\tcombined.set(contentForHash, 0)\n\t\tcombined.set(sectionBytes, contentForHash.length)\n\t\tcontentForHash = combined\n\t}\n\n\tconst computed = await computeSha256(contentForHash)\n\treturn computed === storedChecksum\n}\n\n/**\n * Restore a backup into a store.\n *\n * @param adapter - The storage adapter\n * @param schema - The schema definition\n * @param data - The backup data\n * @param options - Restore options\n * @returns Result of the restore operation\n */\nexport async function restoreBackup(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tdata: Uint8Array,\n\toptions?: RestoreOptions,\n): Promise<RestoreResult> {\n\tconst startTime = Date.now()\n\tconst onProgress = options?.onProgress ?? (() => {})\n\tconst collectionFilter = options?.collections\n\n\tonProgress({ phase: 'verifying', progress: 0, message: 'Parsing backup' })\n\n\tconst sections = parseSections(data)\n\tconst manifest = parseJsonSection<BackupManifest>(sections, 'manifest')\n\tif (!manifest) {\n\t\treturn {\n\t\t\toperationsRestored: 0,\n\t\t\trecordsRestored: 0,\n\t\t\tsuccess: false,\n\t\t\terror: 'Invalid backup: manifest section not found',\n\t\t\tduration: Date.now() - startTime,\n\t\t}\n\t}\n\n\t// Validate format version\n\tif (manifest.version !== BACKUP_VERSION) {\n\t\treturn {\n\t\t\toperationsRestored: 0,\n\t\t\trecordsRestored: 0,\n\t\t\tsuccess: false,\n\t\t\terror: `Unsupported backup version: ${manifest.version}`,\n\t\t\tduration: Date.now() - startTime,\n\t\t}\n\t}\n\n\tonProgress({ phase: 'verifying', progress: 0.2, message: 'Verifying checksum' })\n\n\t// Verify checksum\n\tconst valid = await verifyBackupChecksum(data)\n\tif (!valid) {\n\t\treturn {\n\t\t\toperationsRestored: 0,\n\t\t\trecordsRestored: 0,\n\t\t\tsuccess: false,\n\t\t\terror: 'Backup checksum mismatch: data may be corrupted',\n\t\t\tduration: Date.now() - startTime,\n\t\t}\n\t}\n\n\tonProgress({ phase: 'restoring', progress: 0.3, message: 'Loading operations' })\n\n\t// Parse operations\n\tconst opsContent = findSection(sections, 'operations')\n\tlet operations: Operation[] = []\n\tif (opsContent) {\n\t\tconst text = new TextDecoder().decode(opsContent)\n\t\tconst lines = text\n\t\t\t.trim()\n\t\t\t.split('\\n')\n\t\t\t.filter((l) => l.length > 0)\n\t\toperations = lines.map((line) => JSON.parse(line) as Operation)\n\t}\n\n\t// Filter collections if requested\n\tif (collectionFilter) {\n\t\toperations = operations.filter((op) => collectionFilter.includes(op.collection))\n\t}\n\n\t// Load version vector\n\tconst vvData = parseJsonSection<Record<string, number>>(sections, 'version_vector')\n\n\t// Load meta\n\tconst metaData = parseJsonSection<Record<string, string>>(sections, 'meta')\n\n\tonProgress({ phase: 'restoring', progress: 0.4, message: 'Applying operations' })\n\n\tif (options?.merge) {\n\t\t// Merge mode: replay operations through applyRemoteOperation.\n\t\t// This won't work directly since adapter doesn't have applyRemoteOperation.\n\t\t// Instead, we import the raw data into the adapter.\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\t// Import version vector\n\t\t\tif (vvData) {\n\t\t\t\tfor (const [nid, seq] of Object.entries(vvData)) {\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t'INSERT OR REPLACE INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)',\n\t\t\t\t\t\t[nid, seq],\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Import meta\n\t\t\tif (metaData) {\n\t\t\t\tfor (const [key, value] of Object.entries(metaData)) {\n\t\t\t\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Import operations into _kora_ops_ tables\n\t\t\tfor (const op of operations) {\n\t\t\t\tconst collection = op.collection\n\t\t\t\tconst opRow = {\n\t\t\t\t\tid: op.id,\n\t\t\t\t\tnode_id: op.nodeId,\n\t\t\t\t\ttype: op.type,\n\t\t\t\t\trecord_id: op.recordId,\n\t\t\t\t\tdata: op.data !== null ? JSON.stringify(op.data) : null,\n\t\t\t\t\tprevious_data: op.previousData !== null ? JSON.stringify(op.previousData) : null,\n\t\t\t\t\ttimestamp: JSON.stringify(op.timestamp),\n\t\t\t\t\tsequence_number: op.sequenceNumber,\n\t\t\t\t\tcausal_deps: JSON.stringify(op.causalDeps),\n\t\t\t\t\tschema_version: op.schemaVersion,\n\t\t\t\t}\n\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`INSERT OR IGNORE INTO ${quoteIdent(`_kora_ops_${collection}`)} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\t[\n\t\t\t\t\t\topRow.id,\n\t\t\t\t\t\topRow.node_id,\n\t\t\t\t\t\topRow.type,\n\t\t\t\t\t\topRow.record_id,\n\t\t\t\t\t\topRow.data,\n\t\t\t\t\t\topRow.previous_data,\n\t\t\t\t\t\topRow.timestamp,\n\t\t\t\t\t\topRow.sequence_number,\n\t\t\t\t\t\topRow.causal_deps,\n\t\t\t\t\t\topRow.schema_version,\n\t\t\t\t\t],\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t} else {\n\t\t// Replace mode: clear existing data and bulk import\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\t// Clear existing data\n\t\t\tfor (const collection of Object.keys(schema.collections)) {\n\t\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(`_kora_ops_${collection}`)}`)\n\t\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(collection)}`)\n\t\t\t}\n\t\t\tawait tx.execute('DELETE FROM _kora_version_vector')\n\t\t\tawait tx.execute('DELETE FROM _kora_meta')\n\n\t\t\t// Import version vector\n\t\t\tif (vvData) {\n\t\t\t\tfor (const [nid, seq] of Object.entries(vvData)) {\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t'INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)',\n\t\t\t\t\t\t[nid, seq],\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Import meta\n\t\t\tif (metaData) {\n\t\t\t\tfor (const [key, value] of Object.entries(metaData)) {\n\t\t\t\t\tawait tx.execute('INSERT INTO _kora_meta (key, value) VALUES (?, ?)', [key, value])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Import operations\n\t\t\tfor (const op of operations) {\n\t\t\t\tconst collection = op.collection\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`INSERT INTO ${quoteIdent(`_kora_ops_${collection}`)} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\t[\n\t\t\t\t\t\top.id,\n\t\t\t\t\t\top.nodeId,\n\t\t\t\t\t\top.type,\n\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\top.data !== null ? JSON.stringify(op.data) : null,\n\t\t\t\t\t\top.previousData !== null ? JSON.stringify(op.previousData) : null,\n\t\t\t\t\t\tJSON.stringify(op.timestamp),\n\t\t\t\t\t\top.sequenceNumber,\n\t\t\t\t\t\tJSON.stringify(op.causalDeps),\n\t\t\t\t\t\top.schemaVersion,\n\t\t\t\t\t],\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t}\n\n\tonProgress({ phase: 'restoring', progress: 0.8, message: 'Restoring records' })\n\n\t// Restore records sections (optional)\n\tlet recordsRestored = 0\n\tif (manifest.includesRecords) {\n\t\tfor (const col of manifest.collections) {\n\t\t\tif (collectionFilter && !collectionFilter.includes(col)) continue\n\n\t\t\tconst sectionContent = findSection(sections, `records:${col}`)\n\t\t\tif (!sectionContent) continue\n\n\t\t\tconst text = new TextDecoder().decode(sectionContent)\n\t\t\tconst lines = text\n\t\t\t\t.trim()\n\t\t\t\t.split('\\n')\n\t\t\t\t.filter((l) => l.length > 0)\n\t\t\tconst records = lines.map((line) => JSON.parse(line) as Record<string, unknown>)\n\n\t\t\tif (records.length === 0) continue\n\n\t\t\tawait adapter.transaction(async (tx) => {\n\t\t\t\tfor (const record of records) {\n\t\t\t\t\tconst keys = Object.keys(record)\n\t\t\t\t\tconst placeholders = keys.map(() => '?').join(', ')\n\t\t\t\t\tconst quotedKeys = keys.map((k) => quoteIdent(k)).join(', ')\n\t\t\t\t\tconst values = keys.map((k) => {\n\t\t\t\t\t\tconst v = record[k]\n\t\t\t\t\t\tif (typeof v === 'boolean') return v ? 1 : 0\n\t\t\t\t\t\tif (Array.isArray(v) || (typeof v === 'object' && v !== null)) return JSON.stringify(v)\n\t\t\t\t\t\treturn v\n\t\t\t\t\t})\n\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`INSERT OR REPLACE INTO ${quoteIdent(col)} (${quotedKeys}) VALUES (${placeholders})`,\n\t\t\t\t\t\tvalues,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\trecordsRestored += records.length\n\t\t}\n\t}\n\n\tonProgress({ phase: 'restoring', progress: 1, message: 'Done' })\n\n\treturn {\n\t\toperationsRestored: operations.length,\n\t\trecordsRestored,\n\t\tsuccess: true,\n\t\tduration: Date.now() - startTime,\n\t}\n}\n\n// ── Reading helpers ──────────────────────────────────────────────────────────\n\nasync function readVersionVector(adapter: StorageAdapter): Promise<Map<string, number>> {\n\tconst rows = await adapter.query<{ node_id: string; sequence_number: number }>(\n\t\t'SELECT node_id, sequence_number FROM _kora_version_vector',\n\t)\n\tconst vv = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tvv.set(row.node_id, row.sequence_number)\n\t}\n\treturn vv\n}\n\ninterface MetaRow {\n\tkey: string\n\tvalue: string\n}\n\nasync function readMeta(adapter: StorageAdapter): Promise<MetaRow[]> {\n\treturn adapter.query<MetaRow>('SELECT key, value FROM _kora_meta')\n}\n\nasync function readAllOperations(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<Operation[]> {\n\tconst allOps: Operation[] = []\n\n\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\tconst rows = await adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} ORDER BY sequence_number ASC`,\n\t\t)\n\n\t\tfor (const row of rows) {\n\t\t\tallOps.push(deserializeOperationWithCollection(row, collectionName))\n\t\t}\n\t}\n\n\treturn allOps\n}\n\nasync function readCollectionRecords(\n\tadapter: StorageAdapter,\n\tcollection: string,\n): Promise<Record<string, unknown>[]> {\n\treturn adapter.query<Record<string, unknown>>(\n\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE _deleted = 0`,\n\t)\n}\n\n// ── Crypto helpers ───────────────────────────────────────────────────────────\n\nasync function computeSha256(data: Uint8Array<ArrayBuffer>): Promise<string> {\n\tconst hashBuffer = await crypto.subtle.digest('SHA-256', data)\n\tconst hashArray = Array.from(new Uint8Array(hashBuffer))\n\treturn hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n}\n"],"mappings":";;;;;AAAA,SAAyB,kBAAkB;AAc3C,SAAS,cAAc,MAAc,SAAiC;AACrE,QAAM,YAAY,IAAI,YAAY,EAAE,OAAO,IAAI;AAC/C,QAAM,SAAS,IAAI,WAAW,CAAC;AAC/B,QAAM,KAAK,IAAI,SAAS,OAAO,MAAM;AACrC,KAAG,UAAU,GAAG,UAAU,QAAQ,IAAI;AACtC,KAAG,UAAU,GAAG,QAAQ,QAAQ,IAAI;AAEpC,QAAM,SAAS,IAAI,WAAW,OAAO,SAAS,UAAU,SAAS,QAAQ,MAAM;AAC/E,SAAO,IAAI,QAAQ,CAAC;AACpB,SAAO,IAAI,WAAW,CAAC;AACvB,SAAO,IAAI,SAAS,IAAI,UAAU,MAAM;AACxC,SAAO;AACR;AAEA,SAAS,kBAAkB,MAAc,MAA2B;AACnE,QAAM,OAAO,KAAK,UAAU,IAAI;AAChC,SAAO,cAAc,MAAM,IAAI,YAAY,EAAE,OAAO,IAAI,CAAC;AAC1D;AAOA,SAAS,WAAW,MAAgB,QAAwB;AAC3D,SAAO,KAAK,UAAU,QAAQ,IAAI;AACnC;AAOA,SAAS,cAAc,MAA6B;AACnD,QAAM,WAAsB,CAAC;AAC7B,QAAM,KAAK,IAAI,SAAS,KAAK,Q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7B,aAAW,kBAAkB,OAAO,KAAK,OAAO,WAAW,GAAG;AAC7D,UAAM,OAAO,MAAM,QAAQ;AAAA,MAC1B,iBAAiB,WAAW,aAAa,cAAc,EAAE,CAAC;AAAA,IAC3D;AAEA,eAAW,OAAO,MAAM;AACvB,aAAO,KAAK,mCAAmC,KAAK,cAAc,CAAC;AAAA,IACpE;AAAA,EACD;AAEA,SAAO;AACR;AAEA,eAAe,sBACd,SACA,YACqC;AACrC,SAAO,QAAQ;AAAA,IACd,iBAAiB,WAAW,UAAU,CAAC;AAAA,EACxC;AACD;AAIA,eAAe,cAAc,MAAgD;AAC5E,QAAM,aAAa,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI;AAC7D,QAAM,YAAY,MAAM,KAAK,IAAI,WAAW,UAAU,CAAC;AACvD,SAAO,UAAU,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AACrE;","names":[]}
@@ -8,6 +8,7 @@ import {
8
8
  } from "./chunk-6NKLDBTY.js";
9
9
 
10
10
  // src/audit/export-audit.ts
11
+ import { quoteIdent } from "@korajs/core";
11
12
  function encodeSection(name, content) {
12
13
  const nameBytes = new TextEncoder().encode(name);
13
14
  const header = new Uint8Array(8);
@@ -67,7 +68,7 @@ async function readAllOperations(adapter, schema, collectionFilter) {
67
68
  const allOps = [];
68
69
  for (const collectionName of collections) {
69
70
  const rows = await adapter.query(
70
- `SELECT * FROM _kora_ops_${collectionName} ORDER BY sequence_number ASC`
71
+ `SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} ORDER BY sequence_number ASC`
71
72
  );
72
73
  for (const row of rows) {
73
74
  allOps.push(deserializeOperationWithCollection(row, collectionName));
@@ -185,4 +186,4 @@ export {
185
186
  readAuditExportManifest,
186
187
  verifyAuditExportChecksum
187
188
  };
188
- //# sourceMappingURL=chunk-FFYA7J5H.js.map
189
+ //# sourceMappingURL=chunk-RCTG3IJG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/audit/export-audit.ts"],"sourcesContent":["import type { Operation, SchemaDefinition } from '@korajs/core'\nimport { quoteIdent } from '@korajs/core'\nimport { deserializeOperationWithCollection } from '../serialization/serializer'\nimport type { StorageAdapter } from '../types'\nimport type { OperationRow } from '../types'\nimport { deserializeAuditJson, serializeAuditJson } from './audit-json'\nimport { readAuditTraces } from './audit-trace-store'\nimport type {\n\tAuditExportManifest,\n\tAuditExportOptions,\n\tAuditExportPayload,\n\tAuditTraceQuery,\n\tPersistedAuditTrace,\n} from './types'\n\nfunction encodeSection(name: string, content: Uint8Array): Uint8Array {\n\tconst nameBytes = new TextEncoder().encode(name)\n\tconst header = new Uint8Array(8)\n\tconst view = new DataView(header.buffer)\n\tview.setUint32(0, nameBytes.length, true)\n\tview.setUint32(4, content.length, true)\n\n\tconst result = new Uint8Array(header.length + nameBytes.length + content.length)\n\tresult.set(header, 0)\n\tresult.set(nameBytes, 8)\n\tresult.set(content, 8 + nameBytes.length)\n\treturn result\n}\n\nfunction encodeJsonSection(name: string, data: unknown): Uint8Array {\n\treturn encodeSection(name, new TextEncoder().encode(serializeAuditJson(data)))\n}\n\nfunction encodeNdjsonSection(name: string, records: unknown[]): Uint8Array {\n\tconst lines = `${records.map((record) => serializeAuditJson(record)).join('\\n')}\\n`\n\treturn encodeSection(name, new TextEncoder().encode(lines))\n}\n\nfunction readUint32(view: DataView, offset: number): number {\n\treturn view.getUint32(offset, true)\n}\n\ninterface Section {\n\tname: string\n\tcontent: Uint8Array\n}\n\nfunction parseSections(data: Uint8Array): Section[] {\n\tconst sections: Section[] = []\n\tconst view = new DataView(data.buffer, data.byteOffset, data.byteLength)\n\tlet offset = 0\n\n\twhile (offset + 8 <= data.byteLength) {\n\t\tconst nameLen = readUint32(view, offset)\n\t\tconst contentLen = readUint32(view, offset + 4)\n\t\toffset += 8\n\n\t\tif (offset + nameLen + contentLen > data.byteLength) {\n\t\t\tbreak\n\t\t}\n\n\t\tconst name = new TextDecoder().decode(data.slice(offset, offset + nameLen))\n\t\toffset += nameLen\n\n\t\tconst content = data.slice(offset, offset + contentLen)\n\t\toffset += contentLen\n\n\t\tsections.push({ name, content })\n\t}\n\n\treturn sections\n}\n\nfunction findSection(sections: Section[], name: string): Uint8Array | null {\n\tfor (const section of sections) {\n\t\tif (section.name === name) {\n\t\t\treturn section.content\n\t\t}\n\t}\n\treturn null\n}\n\nasync function computeSha256(data: Uint8Array<ArrayBuffer>): Promise<string> {\n\tconst hashBuffer = await crypto.subtle.digest('SHA-256', data)\n\treturn Array.from(new Uint8Array(hashBuffer))\n\t\t.map((byte) => byte.toString(16).padStart(2, '0'))\n\t\t.join('')\n}\n\nasync function readAllOperations(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tcollectionFilter?: string[],\n): Promise<Operation[]> {\n\tconst collections = collectionFilter\n\t\t? Object.keys(schema.collections).filter((name) => collectionFilter.includes(name))\n\t\t: Object.keys(schema.collections)\n\n\tconst allOps: Operation[] = []\n\tfor (const collectionName of collections) {\n\t\tconst rows = await adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} ORDER BY sequence_number ASC`,\n\t\t)\n\n\t\tfor (const row of rows) {\n\t\t\tallOps.push(deserializeOperationWithCollection(row, collectionName))\n\t\t}\n\t}\n\n\treturn allOps\n}\n\nfunction filterOperationsByCollections(\n\toperations: Operation[],\n\tcollectionFilter?: string[],\n): Operation[] {\n\tif (!collectionFilter || collectionFilter.length === 0) {\n\t\treturn operations\n\t}\n\tconst allowed = new Set(collectionFilter)\n\treturn operations.filter((op) => allowed.has(op.collection))\n}\n\n/**\n * Export operations and persisted merge traces as a portable binary audit bundle.\n */\nexport async function exportAudit(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tnodeId: string,\n\tschemaVersion: number,\n\toptions?: AuditExportOptions,\n): Promise<Uint8Array> {\n\tconst onProgress = options?.onProgress ?? (() => {})\n\tconst traceQuery: AuditTraceQuery = {\n\t\tcollections: options?.collections,\n\t\tsince: options?.since,\n\t\tuntil: options?.until,\n\t}\n\n\tonProgress({ phase: 'reading', progress: 0, message: 'Reading operations' })\n\tconst operations = filterOperationsByCollections(\n\t\tawait readAllOperations(adapter, schema, options?.collections),\n\t\toptions?.collections,\n\t)\n\n\tonProgress({ phase: 'reading', progress: 0.4, message: 'Reading merge traces' })\n\tconst mergeTraces = await readAuditTraces(adapter, traceQuery)\n\n\tonProgress({ phase: 'writing', progress: 0.7, message: 'Encoding audit export' })\n\tconst sections: Uint8Array[] = []\n\tlet contentForChecksum = new Uint8Array(0)\n\n\tconst addSection = (section: Uint8Array): void => {\n\t\tsections.push(section)\n\t\tconst combined = new Uint8Array(contentForChecksum.length + section.length)\n\t\tcombined.set(contentForChecksum, 0)\n\t\tcombined.set(section, contentForChecksum.length)\n\t\tcontentForChecksum = combined\n\t}\n\n\taddSection(encodeNdjsonSection('operations', operations))\n\taddSection(encodeNdjsonSection('merge_traces', mergeTraces))\n\n\tonProgress({ phase: 'verifying', progress: 0.9, message: 'Computing checksum' })\n\tconst checksum = await computeSha256(contentForChecksum as Uint8Array<ArrayBuffer>)\n\n\tconst manifest: AuditExportManifest = {\n\t\tversion: 1,\n\t\texportedAt: Date.now(),\n\t\tnodeId,\n\t\tschemaVersion,\n\t\toperationCount: operations.length,\n\t\tmergeTraceCount: mergeTraces.length,\n\t\tchecksum,\n\t}\n\n\tconst manifestSection = encodeJsonSection('manifest', manifest)\n\tconst checksumSection = encodeSection('checksum', new TextEncoder().encode(checksum))\n\n\tonProgress({ phase: 'writing', progress: 1, message: 'Finalizing' })\n\n\tconst parts = [manifestSection, ...sections, checksumSection]\n\tconst finalOutput = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0))\n\tlet offset = 0\n\tfor (const part of parts) {\n\t\tfinalOutput.set(part, offset)\n\t\toffset += part.length\n\t}\n\n\treturn finalOutput\n}\n\n/**\n * Decode an audit export binary into structured data.\n */\nexport function decodeAuditExport(data: Uint8Array): AuditExportPayload {\n\tconst sections = parseSections(data)\n\tconst manifest = JSON.parse(\n\t\tnew TextDecoder().decode(findSection(sections, 'manifest') ?? new Uint8Array()),\n\t) as AuditExportManifest\n\n\tconst operationsContent = findSection(sections, 'operations')\n\tconst mergeTracesContent = findSection(sections, 'merge_traces')\n\n\tconst operations = parseNdjsonSection<Operation>(operationsContent)\n\tconst mergeTraces = parseNdjsonSection<PersistedAuditTrace>(mergeTracesContent)\n\n\treturn { manifest, operations, mergeTraces }\n}\n\n/**\n * Read only the manifest from an audit export without decoding all sections.\n */\nexport function readAuditExportManifest(data: Uint8Array): AuditExportManifest {\n\tconst sections = parseSections(data)\n\tconst manifestContent = findSection(sections, 'manifest')\n\tif (!manifestContent) {\n\t\tthrow new Error('Invalid audit export: missing manifest section')\n\t}\n\treturn JSON.parse(new TextDecoder().decode(manifestContent)) as AuditExportManifest\n}\n\n/**\n * Verify the checksum of an audit export file.\n */\nexport async function verifyAuditExportChecksum(data: Uint8Array): Promise<boolean> {\n\tconst sections = parseSections(data)\n\tconst manifest = readAuditExportManifest(data)\n\tconst contentSections = sections.filter(\n\t\t(section) => section.name !== 'manifest' && section.name !== 'checksum',\n\t)\n\n\tlet content = new Uint8Array(0)\n\tfor (const section of contentSections) {\n\t\tconst encoded = encodeSection(section.name, section.content)\n\t\tconst combined = new Uint8Array(content.length + encoded.length)\n\t\tcombined.set(content, 0)\n\t\tcombined.set(encoded, content.length)\n\t\tcontent = combined\n\t}\n\n\tconst checksum = await computeSha256(content as Uint8Array<ArrayBuffer>)\n\treturn checksum === manifest.checksum\n}\n\nfunction parseNdjsonSection<T>(content: Uint8Array | null): T[] {\n\tif (!content || content.length === 0) {\n\t\treturn []\n\t}\n\tconst text = new TextDecoder().decode(content).trim()\n\tif (text.length === 0) {\n\t\treturn []\n\t}\n\treturn text.split('\\n').map((line) => deserializeAuditJson<T>(line))\n}\n"],"mappings":";;;;;;;;;;AACA,SAAS,kBAAkB;A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