@aztec/kv-store 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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 (192) hide show
  1. package/README.md +10 -1
  2. package/dest/bench/shared_map_bench.d.ts +19 -0
  3. package/dest/bench/shared_map_bench.d.ts.map +1 -0
  4. package/dest/bench/shared_map_bench.js +91 -0
  5. package/dest/deprecated/indexeddb/array.d.ts +22 -0
  6. package/dest/deprecated/indexeddb/array.d.ts.map +1 -0
  7. package/dest/{indexeddb → deprecated/indexeddb}/array.js +21 -7
  8. package/dest/deprecated/indexeddb/index.d.ts +7 -0
  9. package/dest/deprecated/indexeddb/index.d.ts.map +1 -0
  10. package/dest/deprecated/indexeddb/index.js +8 -0
  11. package/dest/deprecated/indexeddb/map.d.ts +38 -0
  12. package/dest/deprecated/indexeddb/map.d.ts.map +1 -0
  13. package/dest/{indexeddb → deprecated/indexeddb}/map.js +23 -13
  14. package/dest/deprecated/indexeddb/multi_map.d.ts +14 -0
  15. package/dest/deprecated/indexeddb/multi_map.d.ts.map +1 -0
  16. package/dest/{indexeddb → deprecated/indexeddb}/multi_map.js +16 -1
  17. package/dest/deprecated/indexeddb/set.d.ts +17 -0
  18. package/dest/deprecated/indexeddb/set.d.ts.map +1 -0
  19. package/dest/deprecated/indexeddb/singleton.d.ts +17 -0
  20. package/dest/deprecated/indexeddb/singleton.d.ts.map +1 -0
  21. package/dest/{indexeddb → deprecated/indexeddb}/singleton.js +3 -1
  22. package/dest/deprecated/indexeddb/store.d.ts +98 -0
  23. package/dest/deprecated/indexeddb/store.d.ts.map +1 -0
  24. package/dest/{indexeddb → deprecated/indexeddb}/store.js +8 -4
  25. package/dest/interfaces/array_test_suite.d.ts +1 -1
  26. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  27. package/dest/interfaces/array_test_suite.js +33 -34
  28. package/dest/interfaces/index.d.ts +2 -2
  29. package/dest/interfaces/index.d.ts.map +1 -1
  30. package/dest/interfaces/map_test_suite.d.ts +1 -1
  31. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  32. package/dest/interfaces/map_test_suite.js +74 -29
  33. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  34. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  35. package/dest/interfaces/multi_map_test_suite.js +84 -60
  36. package/dest/interfaces/set_test_suite.d.ts +1 -1
  37. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  38. package/dest/interfaces/set_test_suite.js +13 -14
  39. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  40. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  41. package/dest/interfaces/singleton_test_suite.js +6 -7
  42. package/dest/interfaces/utils.d.ts +2 -1
  43. package/dest/interfaces/utils.d.ts.map +1 -1
  44. package/dest/interfaces/utils.js +2 -1
  45. package/dest/lmdb/array.js +4 -2
  46. package/dest/lmdb/index.d.ts +3 -3
  47. package/dest/lmdb/index.d.ts.map +1 -1
  48. package/dest/lmdb/index.js +4 -4
  49. package/dest/lmdb/store.d.ts +3 -3
  50. package/dest/lmdb/store.d.ts.map +1 -1
  51. package/dest/lmdb/store.js +13 -9
  52. package/dest/lmdb-v2/array.d.ts +2 -2
  53. package/dest/lmdb-v2/array.d.ts.map +1 -1
  54. package/dest/lmdb-v2/array.js +4 -3
  55. package/dest/lmdb-v2/factory.d.ts +33 -7
  56. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  57. package/dest/lmdb-v2/factory.js +72 -16
  58. package/dest/lmdb-v2/map.d.ts +2 -2
  59. package/dest/lmdb-v2/map.d.ts.map +1 -1
  60. package/dest/lmdb-v2/map.js +1 -2
  61. package/dest/lmdb-v2/multi_map.d.ts +2 -2
  62. package/dest/lmdb-v2/multi_map.d.ts.map +1 -1
  63. package/dest/lmdb-v2/multi_map.js +1 -2
  64. package/dest/lmdb-v2/read_transaction.js +21 -19
  65. package/dest/lmdb-v2/singleton.d.ts +2 -2
  66. package/dest/lmdb-v2/singleton.d.ts.map +1 -1
  67. package/dest/lmdb-v2/singleton.js +1 -2
  68. package/dest/lmdb-v2/store.d.ts +4 -5
  69. package/dest/lmdb-v2/store.d.ts.map +1 -1
  70. package/dest/lmdb-v2/store.js +6 -28
  71. package/dest/lmdb-v2/tx-helpers.d.ts +6 -0
  72. package/dest/lmdb-v2/tx-helpers.d.ts.map +1 -0
  73. package/dest/lmdb-v2/tx-helpers.js +21 -0
  74. package/dest/lmdb-v2/utils.d.ts +1 -10
  75. package/dest/lmdb-v2/utils.d.ts.map +1 -1
  76. package/dest/lmdb-v2/utils.js +0 -94
  77. package/dest/lmdb-v2/write_transaction.d.ts +1 -1
  78. package/dest/lmdb-v2/write_transaction.d.ts.map +1 -1
  79. package/dest/lmdb-v2/write_transaction.js +9 -5
  80. package/dest/sqlite-opfs/array.d.ts +21 -0
  81. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  82. package/dest/sqlite-opfs/array.js +128 -0
  83. package/dest/sqlite-opfs/errors.d.ts +54 -0
  84. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  85. package/dest/sqlite-opfs/errors.js +77 -0
  86. package/dest/sqlite-opfs/index.d.ts +14 -0
  87. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  88. package/dest/sqlite-opfs/index.js +16 -0
  89. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  90. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  91. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  92. package/dest/sqlite-opfs/manage.d.ts +22 -0
  93. package/dest/sqlite-opfs/manage.d.ts.map +1 -0
  94. package/dest/sqlite-opfs/manage.js +38 -0
  95. package/dest/sqlite-opfs/map.d.ts +35 -0
  96. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  97. package/dest/sqlite-opfs/map.js +163 -0
  98. package/dest/sqlite-opfs/messages.d.ts +66 -0
  99. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  100. package/dest/sqlite-opfs/messages.js +5 -0
  101. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  102. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  103. package/dest/sqlite-opfs/multi_map.js +67 -0
  104. package/dest/sqlite-opfs/pool_integrity.d.ts +20 -0
  105. package/dest/sqlite-opfs/pool_integrity.d.ts.map +1 -0
  106. package/dest/sqlite-opfs/pool_integrity.js +282 -0
  107. package/dest/sqlite-opfs/pool_lock.d.ts +8 -0
  108. package/dest/sqlite-opfs/pool_lock.d.ts.map +1 -0
  109. package/dest/sqlite-opfs/pool_lock.js +47 -0
  110. package/dest/sqlite-opfs/set.d.ts +13 -0
  111. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  112. package/dest/sqlite-opfs/set.js +19 -0
  113. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  114. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  115. package/dest/sqlite-opfs/singleton.js +48 -0
  116. package/dest/sqlite-opfs/store.d.ts +84 -0
  117. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  118. package/dest/sqlite-opfs/store.js +317 -0
  119. package/dest/sqlite-opfs/worker.d.ts +2 -0
  120. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  121. package/dest/sqlite-opfs/worker.js +275 -0
  122. package/dest/stores/l2_tips_store.d.ts +18 -10
  123. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  124. package/dest/stores/l2_tips_store.js +43 -55
  125. package/dest/utils.d.ts +9 -6
  126. package/dest/utils.d.ts.map +1 -1
  127. package/dest/utils.js +51 -16
  128. package/package.json +32 -27
  129. package/src/bench/shared_map_bench.ts +111 -0
  130. package/src/{indexeddb → deprecated/indexeddb}/array.ts +6 -6
  131. package/src/deprecated/indexeddb/index.ts +12 -0
  132. package/src/{indexeddb → deprecated/indexeddb}/map.ts +26 -13
  133. package/src/{indexeddb → deprecated/indexeddb}/multi_map.ts +17 -3
  134. package/src/{indexeddb → deprecated/indexeddb}/set.ts +2 -2
  135. package/src/{indexeddb → deprecated/indexeddb}/singleton.ts +3 -3
  136. package/src/{indexeddb → deprecated/indexeddb}/store.ts +23 -15
  137. package/src/interfaces/array_test_suite.ts +33 -35
  138. package/src/interfaces/index.ts +1 -1
  139. package/src/interfaces/map_test_suite.ts +56 -30
  140. package/src/interfaces/multi_map_test_suite.ts +88 -58
  141. package/src/interfaces/set_test_suite.ts +13 -15
  142. package/src/interfaces/singleton_test_suite.ts +6 -8
  143. package/src/interfaces/utils.ts +1 -0
  144. package/src/lmdb/index.ts +10 -5
  145. package/src/lmdb/store.ts +13 -9
  146. package/src/lmdb-v2/array.ts +2 -2
  147. package/src/lmdb-v2/factory.ts +99 -19
  148. package/src/lmdb-v2/map.ts +2 -2
  149. package/src/lmdb-v2/multi_map.ts +2 -2
  150. package/src/lmdb-v2/read_transaction.ts +23 -23
  151. package/src/lmdb-v2/singleton.ts +2 -2
  152. package/src/lmdb-v2/store.ts +9 -33
  153. package/src/lmdb-v2/tx-helpers.ts +29 -0
  154. package/src/lmdb-v2/utils.ts +0 -118
  155. package/src/lmdb-v2/write_transaction.ts +9 -8
  156. package/src/sqlite-opfs/array.ts +124 -0
  157. package/src/sqlite-opfs/errors.ts +94 -0
  158. package/src/sqlite-opfs/index.ts +27 -0
  159. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  160. package/src/sqlite-opfs/manage.ts +46 -0
  161. package/src/sqlite-opfs/map.ts +163 -0
  162. package/src/sqlite-opfs/messages.ts +39 -0
  163. package/src/sqlite-opfs/multi_map.ts +74 -0
  164. package/src/sqlite-opfs/pool_integrity.ts +327 -0
  165. package/src/sqlite-opfs/pool_lock.ts +62 -0
  166. package/src/sqlite-opfs/set.ts +29 -0
  167. package/src/sqlite-opfs/singleton.ts +48 -0
  168. package/src/sqlite-opfs/store.ts +330 -0
  169. package/src/sqlite-opfs/worker.ts +259 -0
  170. package/src/stores/l2_tips_store.ts +43 -57
  171. package/src/utils.ts +79 -21
  172. package/dest/config.d.ts +0 -17
  173. package/dest/config.d.ts.map +0 -1
  174. package/dest/config.js +0 -26
  175. package/dest/indexeddb/array.d.ts +0 -22
  176. package/dest/indexeddb/array.d.ts.map +0 -1
  177. package/dest/indexeddb/index.d.ts +0 -7
  178. package/dest/indexeddb/index.d.ts.map +0 -1
  179. package/dest/indexeddb/index.js +0 -19
  180. package/dest/indexeddb/map.d.ts +0 -32
  181. package/dest/indexeddb/map.d.ts.map +0 -1
  182. package/dest/indexeddb/multi_map.d.ts +0 -13
  183. package/dest/indexeddb/multi_map.d.ts.map +0 -1
  184. package/dest/indexeddb/set.d.ts +0 -17
  185. package/dest/indexeddb/set.d.ts.map +0 -1
  186. package/dest/indexeddb/singleton.d.ts +0 -17
  187. package/dest/indexeddb/singleton.d.ts.map +0 -1
  188. package/dest/indexeddb/store.d.ts +0 -96
  189. package/dest/indexeddb/store.d.ts.map +0 -1
  190. package/src/config.ts +0 -36
  191. package/src/indexeddb/index.ts +0 -29
  192. /package/dest/{indexeddb → deprecated/indexeddb}/set.js +0 -0
@@ -0,0 +1,62 @@
1
+ import { SqlitePoolBusyError, SqliteWebLocksUnavailableError } from './errors.js';
2
+
3
+ export const DEFAULT_SAH_POOL_DIRECTORY = '.aztec-kv';
4
+
5
+ const WEB_LOCK_PREFIX = 'aztec.sqlite-opfs.pool:';
6
+
7
+ export interface PoolLockLease {
8
+ release(): Promise<void>;
9
+ }
10
+
11
+ export function normalizePoolDirectory(poolDirectory?: string): string {
12
+ const path = poolDirectory
13
+ ?.split('/')
14
+ .filter(segment => segment.length > 0)
15
+ .join('/');
16
+ return path || DEFAULT_SAH_POOL_DIRECTORY;
17
+ }
18
+
19
+ export async function acquirePoolLock(poolDirectory?: string): Promise<PoolLockLease> {
20
+ if (!navigator.locks) {
21
+ throw new SqliteWebLocksUnavailableError();
22
+ }
23
+ const normalizedDirectory = normalizePoolDirectory(poolDirectory);
24
+ const acquired = Promise.withResolvers<Lock | null>();
25
+ const hold = Promise.withResolvers<void>();
26
+ const request = navigator.locks.request(
27
+ `${WEB_LOCK_PREFIX}${normalizedDirectory}`,
28
+ { mode: 'exclusive', ifAvailable: true },
29
+ async lock => {
30
+ acquired.resolve(lock);
31
+ if (lock) {
32
+ await hold.promise;
33
+ }
34
+ },
35
+ );
36
+ request.catch(acquired.reject);
37
+
38
+ if (!(await acquired.promise)) {
39
+ await request;
40
+ throw new SqlitePoolBusyError(normalizedDirectory);
41
+ }
42
+
43
+ let released = false;
44
+ return {
45
+ release: async () => {
46
+ if (!released) {
47
+ released = true;
48
+ hold.resolve();
49
+ }
50
+ await request;
51
+ },
52
+ };
53
+ }
54
+
55
+ export async function withPoolLock<T>(poolDirectory: string, callback: () => Promise<T>): Promise<T> {
56
+ const lease = await acquirePoolLock(poolDirectory);
57
+ try {
58
+ return await callback();
59
+ } finally {
60
+ await lease.release();
61
+ }
62
+ }
@@ -0,0 +1,29 @@
1
+ import type { Key, Range } from '../interfaces/common.js';
2
+ import type { AztecAsyncSet } from '../interfaces/set.js';
3
+ import { SQLiteOPFSAztecMap } from './map.js';
4
+ import type { AztecSQLiteOPFSStore } from './store.js';
5
+
6
+ /** Set backed by SQLite. Composes a Map<K, true>. */
7
+ export class SQLiteOPFSAztecSet<K extends Key> implements AztecAsyncSet<K> {
8
+ readonly #map: SQLiteOPFSAztecMap<K, boolean>;
9
+
10
+ constructor(store: AztecSQLiteOPFSStore, name: string) {
11
+ this.#map = new SQLiteOPFSAztecMap<K, boolean>(store, name);
12
+ }
13
+
14
+ hasAsync(key: K): Promise<boolean> {
15
+ return this.#map.hasAsync(key);
16
+ }
17
+
18
+ add(key: K): Promise<void> {
19
+ return this.#map.set(key, true);
20
+ }
21
+
22
+ delete(key: K): Promise<void> {
23
+ return this.#map.delete(key);
24
+ }
25
+
26
+ async *entriesAsync(range: Range<K> = {}): AsyncIterableIterator<K> {
27
+ yield* this.#map.keysAsync(range);
28
+ }
29
+ }
@@ -0,0 +1,48 @@
1
+ import { Encoder } from '#msgpackr';
2
+ import { toBufferKey } from '#ordered-binary';
3
+ import { hash } from 'ohash';
4
+
5
+ import type { Value } from '../interfaces/common.js';
6
+ import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
7
+ import type { AztecSQLiteOPFSStore } from './store.js';
8
+
9
+ /** Stores a single value identified by `name`. */
10
+ export class SQLiteOPFSAztecSingleton<T extends Value> implements AztecAsyncSingleton<T> {
11
+ readonly #container: string;
12
+ readonly #slot: string;
13
+ readonly #encoder = new Encoder();
14
+
15
+ constructor(
16
+ private readonly store: AztecSQLiteOPFSStore,
17
+ name: string,
18
+ ) {
19
+ this.#container = `singleton:${name}`;
20
+ this.#slot = `singleton:${name}:value`;
21
+ }
22
+
23
+ async getAsync(): Promise<T | undefined> {
24
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.#slot]);
25
+ if (rows.length === 0) {
26
+ return undefined;
27
+ }
28
+ const raw = rows[0][0];
29
+ if (raw instanceof Uint8Array) {
30
+ return this.#encoder.unpack(raw) as T;
31
+ }
32
+ return undefined;
33
+ }
34
+
35
+ async set(val: T): Promise<boolean> {
36
+ const { changes } = await this.store.runAsync(
37
+ `INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
38
+ VALUES (?, ?, ?, ?, ?, ?)`,
39
+ [this.#slot, this.#container, toBufferKey([this.#slot]), 1, hash(val), this.#encoder.pack(val)],
40
+ );
41
+ return changes > 0;
42
+ }
43
+
44
+ async delete(): Promise<boolean> {
45
+ await this.store.runAsync('DELETE FROM data WHERE slot = ?', [this.#slot]);
46
+ return true;
47
+ }
48
+ }
@@ -0,0 +1,330 @@
1
+ import type { Logger } from '@aztec/foundation/log';
2
+ import { SerialQueue } from '@aztec/foundation/queue';
3
+
4
+ import type { AztecAsyncArray } from '../interfaces/array.js';
5
+ import type { Key, StoreSize, Value } from '../interfaces/common.js';
6
+ import type { AztecAsyncCounter } from '../interfaces/counter.js';
7
+ import type { AztecAsyncMap } from '../interfaces/map.js';
8
+ import type { AztecAsyncMultiMap } from '../interfaces/multi_map.js';
9
+ import type { AztecAsyncSet } from '../interfaces/set.js';
10
+ import type { AztecAsyncSingleton } from '../interfaces/singleton.js';
11
+ import type { AztecAsyncKVStore } from '../interfaces/store.js';
12
+ import { SQLiteOPFSAztecArray } from './array.js';
13
+ import { SqliteCorruptionError, SqliteEncryptionError, isCorruptionMessage } from './errors.js';
14
+ import { SQLiteOPFSAztecMap } from './map.js';
15
+ import type { ResultRow, SqlValue, WorkerRequest, WorkerResponse } from './messages.js';
16
+ import { SQLiteOPFSAztecMultiMap } from './multi_map.js';
17
+ import { quarantineDuplicatePool } from './pool_integrity.js';
18
+ import { type PoolLockLease, acquirePoolLock, normalizePoolDirectory } from './pool_lock.js';
19
+ import { SQLiteOPFSAztecSet } from './set.js';
20
+ import { SQLiteOPFSAztecSingleton } from './singleton.js';
21
+
22
+ /**
23
+ * Main-thread handle for a SQLite database persisted to OPFS via the `opfs-sahpool`
24
+ * VFS. Owns a dedicated Web Worker (the SAH Pool VFS requires Worker context) and
25
+ * routes every SQL op through it via typed postMessage RPC.
26
+ *
27
+ * Transaction ordering is guaranteed by a `SerialQueue` on the main thread combined
28
+ * with an `#inTx` flag: outside a `transactionAsync` block, each op acquires the
29
+ * queue for its own auto-commit; inside a block, the outer call holds the queue and
30
+ * nested ops bypass it to avoid deadlock.
31
+ */
32
+ export class AztecSQLiteOPFSStore implements AztecAsyncKVStore {
33
+ readonly #worker: Worker;
34
+ readonly #pending = new Map<number, { resolve: (r: WorkerResponse) => void; reject: (err: Error) => void }>();
35
+ readonly #txQueue = new SerialQueue();
36
+ readonly #name: string;
37
+ readonly #log: Logger;
38
+ #nextId = 0;
39
+ #inTx = false;
40
+ #closed = false;
41
+ #workerFailed = false;
42
+
43
+ private constructor(
44
+ worker: Worker,
45
+ name: string,
46
+ log: Logger,
47
+ public readonly isEphemeral: boolean,
48
+ private readonly poolLock?: PoolLockLease,
49
+ ) {
50
+ this.#worker = worker;
51
+ this.#name = name;
52
+ this.#log = log;
53
+ this.#worker.onmessage = (ev: MessageEvent<WorkerResponse>) => {
54
+ const { id } = ev.data;
55
+ const handler = this.#pending.get(id);
56
+ if (!handler) {
57
+ this.#log.warn(`SQLite worker: no pending handler for id ${id}`);
58
+ return;
59
+ }
60
+ this.#pending.delete(id);
61
+ handler.resolve(ev.data);
62
+ };
63
+ this.#worker.onerror = ev => {
64
+ this.#workerFailed = true;
65
+ this.#log.error(`SQLite worker crashed: ${ev.message}`);
66
+ this.#rejectPending(`SQLite worker crashed: ${ev.message}`);
67
+ };
68
+ this.#txQueue.start();
69
+ }
70
+
71
+ /**
72
+ * Opens (or creates) a SQLite database stored in the OPFS SAH Pool. When `ephemeral`
73
+ * is true the database lives only in memory and is lost when the worker terminates.
74
+ * Pass `poolDirectory` to place the SAH Pool in a non-default OPFS subdirectory —
75
+ * required when multiple stores coexist in the same tab, because the SAH Pool holds
76
+ * an exclusive lock on its directory.
77
+ *
78
+ * Persistent stores hold an origin-wide Web Lock for the pool directory until close
79
+ * or delete. If another store instance already owns it, open fails immediately with
80
+ * `SqlitePoolBusyError`.
81
+ *
82
+ * Pass `encryptionKey` (exactly 32 bytes) to enable at-rest encryption via sqlite3mc's
83
+ * ChaCha20 page cipher. The key buffer is **transferred** to the worker — its
84
+ * ArrayBuffer detaches on the caller side after `postMessage`. This is intentional:
85
+ * the API encodes a one-key-one-owner invariant. A caller that wants to use the same
86
+ * key for multiple stores must explicitly clone it per call (e.g.
87
+ * `new Uint8Array(savedKey)`), making the duplication a visible, deliberate decision
88
+ * rather than a silent structured-clone operation. The default path (one `.open()`,
89
+ * one consumption of the key) leaves zero key bytes on the main thread after the call.
90
+ */
91
+ static async open(
92
+ log: Logger,
93
+ name?: string,
94
+ ephemeral: boolean = false,
95
+ poolDirectory?: string,
96
+ encryptionKey?: Uint8Array,
97
+ ): Promise<AztecSQLiteOPFSStore> {
98
+ if (encryptionKey !== undefined && encryptionKey.length !== 32) {
99
+ throw new SqliteEncryptionError(
100
+ 'invalid_key_length',
101
+ `encryptionKey must be 32 bytes (got ${encryptionKey.length})`,
102
+ );
103
+ }
104
+ if (encryptionKey !== undefined && ephemeral) {
105
+ throw new SqliteEncryptionError(
106
+ 'encryption_not_supported_for_ephemeral',
107
+ 'encryptionKey is not supported for ephemeral (:memory:) stores',
108
+ );
109
+ }
110
+ const dbName = name && !ephemeral ? name : `tmp-${globalThis.crypto.getRandomValues(new Uint8Array(8)).join('')}`;
111
+ log.debug(
112
+ `Opening SQLite-OPFS ${ephemeral ? 'ephemeral ' : ''}${encryptionKey ? 'encrypted ' : ''}database ${dbName}`,
113
+ );
114
+ const effectivePoolDirectory = ephemeral ? undefined : normalizePoolDirectory(poolDirectory);
115
+ const poolLock = effectivePoolDirectory ? await acquirePoolLock(effectivePoolDirectory) : undefined;
116
+ let worker: Worker | undefined;
117
+ try {
118
+ if (effectivePoolDirectory) {
119
+ const quarantine = await quarantineDuplicatePool(effectivePoolDirectory);
120
+ if (quarantine) {
121
+ log.warn(`Quarantined SQLite-OPFS pool with duplicate logical file mappings`, quarantine);
122
+ }
123
+ }
124
+ worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
125
+ const store = new AztecSQLiteOPFSStore(worker, dbName, log, ephemeral, poolLock);
126
+ // Transfer (not clone) the key buffer to the worker so we don't leave a
127
+ // second copy on the main thread. Caveat: this detaches the caller's
128
+ // encryptionKey.buffer — subsequent reads from the same Uint8Array are empty.
129
+ const transfer = encryptionKey ? [encryptionKey.buffer as ArrayBuffer] : undefined;
130
+ await store.#sendRequest(
131
+ { type: 'init', id: store.#allocId(), dbName, ephemeral, poolDirectory: effectivePoolDirectory, encryptionKey },
132
+ transfer,
133
+ );
134
+ return store;
135
+ } catch (err) {
136
+ worker?.terminate();
137
+ await poolLock?.release();
138
+ throw err;
139
+ }
140
+ }
141
+
142
+ openMap<K extends Key, V extends Value>(name: string): AztecAsyncMap<K, V> {
143
+ return new SQLiteOPFSAztecMap<K, V>(this, name);
144
+ }
145
+
146
+ openSet<K extends Key>(name: string): AztecAsyncSet<K> {
147
+ return new SQLiteOPFSAztecSet<K>(this, name);
148
+ }
149
+
150
+ openMultiMap<K extends Key, V extends Value>(name: string): AztecAsyncMultiMap<K, V> {
151
+ return new SQLiteOPFSAztecMultiMap<K, V>(this, name);
152
+ }
153
+
154
+ openCounter<K extends Key>(_name: string): AztecAsyncCounter<K> {
155
+ throw new Error('Method not implemented.');
156
+ }
157
+
158
+ openArray<T extends Value>(name: string): AztecAsyncArray<T> {
159
+ return new SQLiteOPFSAztecArray<T>(this, name);
160
+ }
161
+
162
+ openSingleton<T extends Value>(name: string): AztecAsyncSingleton<T> {
163
+ return new SQLiteOPFSAztecSingleton<T>(this, name);
164
+ }
165
+
166
+ transactionAsync<T>(callback: () => Promise<T>): Promise<T> {
167
+ // Nested calls join the outer transaction — SQLite does not support nested BEGIN,
168
+ // and re-acquiring the SerialQueue while the outer call holds it would deadlock.
169
+ // Errors in the nested callback propagate to the outer catch, which rolls back the
170
+ // whole thing (the standard "nested tx = savepoint-free join" semantic).
171
+ if (this.#inTx) {
172
+ return callback();
173
+ }
174
+ return this.#txQueue.put(async () => {
175
+ this.#inTx = true;
176
+ await this.#sendRequest({ type: 'begin', id: this.#allocId() });
177
+ try {
178
+ const result = await callback();
179
+ await this.#sendRequest({ type: 'commit', id: this.#allocId() });
180
+ return result;
181
+ } catch (err) {
182
+ await this.#sendRequest({ type: 'rollback', id: this.#allocId() }).catch(rollbackErr =>
183
+ this.#log.warn(`SQLite ROLLBACK failed: ${rollbackErr instanceof Error ? rollbackErr.message : rollbackErr}`),
184
+ );
185
+ throw err;
186
+ } finally {
187
+ this.#inTx = false;
188
+ }
189
+ });
190
+ }
191
+
192
+ async clear(): Promise<void> {
193
+ await this.runAsync('DELETE FROM data');
194
+ }
195
+
196
+ async delete(): Promise<void> {
197
+ if (this.#closed) {
198
+ return;
199
+ }
200
+ this.#closed = true;
201
+ try {
202
+ await this.#txQueue.end();
203
+ await this.#sendRequest({ type: 'deleteDb', id: this.#allocId(), dbName: this.#name }).catch(err =>
204
+ this.#log.warn(`SQLite deleteDb failed: ${err instanceof Error ? err.message : err}`),
205
+ );
206
+ } finally {
207
+ this.#worker.terminate();
208
+ this.#rejectPending('SQLite store deleted');
209
+ await this.poolLock?.release();
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Placeholder — returns zeros to mirror the IndexedDB backend. SQLite exposes real
215
+ * numbers cheaply via `PRAGMA page_count` / `page_size` / `freelist_count` and
216
+ * `SELECT COUNT(*) FROM data`, which would populate `physicalFileSize`, `actualSize`,
217
+ * and `numItems` meaningfully (`mappingSize` stays 0 — it's an LMDB mmap concept).
218
+ * Upgrade when any caller actually consumes these values; all current consumers
219
+ * tolerate zeros.
220
+ */
221
+ estimateSize(): Promise<StoreSize> {
222
+ return Promise.resolve({ mappingSize: 0, physicalFileSize: 0, actualSize: 0, numItems: 0 });
223
+ }
224
+
225
+ async close(): Promise<void> {
226
+ if (this.#closed) {
227
+ return;
228
+ }
229
+ this.#closed = true;
230
+ try {
231
+ await this.#txQueue.end();
232
+ await this.#sendRequest({ type: 'close', id: this.#allocId() }).catch(() => {});
233
+ } finally {
234
+ this.#worker.terminate();
235
+ this.#rejectPending('SQLite store closed');
236
+ await this.poolLock?.release();
237
+ }
238
+ }
239
+
240
+ backupTo(_dstPath: string, _compact?: boolean): Promise<void> {
241
+ throw new Error('Method not implemented.');
242
+ }
243
+
244
+ /**
245
+ * Returns a raw SQLite image (bytes suitable for writing as a `.sqlite` file and
246
+ * opening in any SQLite tool). Works only for non-ephemeral DBs because the OPFS
247
+ * SAH Pool has to be initialized. Useful for inspection/debugging.
248
+ */
249
+ async exportDb(): Promise<Uint8Array> {
250
+ const resp = await this.#sendRequest({ type: 'export', id: this.#allocId() });
251
+ if (!('bytes' in resp) || !resp.bytes) {
252
+ throw new Error('exportDb: worker returned no bytes');
253
+ }
254
+ return resp.bytes;
255
+ }
256
+
257
+ /**
258
+ * Runs a write statement (INSERT/UPDATE/DELETE/DDL). If called inside a
259
+ * `transactionAsync` block, bypasses the queue; otherwise acquires it so the
260
+ * op runs in its own auto-commit.
261
+ */
262
+ runAsync(sql: string, bind?: SqlValue[]): Promise<{ changes: number }> {
263
+ const send = () =>
264
+ this.#sendRequest({ type: 'run', id: this.#allocId(), sql, bind }).then(r => ({
265
+ changes: 'changes' in r ? (r.changes ?? 0) : 0,
266
+ }));
267
+ return this.#inTx ? send() : this.#txQueue.put(send);
268
+ }
269
+
270
+ /** Runs a SELECT statement and returns rows in array row-mode. */
271
+ allAsync(sql: string, bind?: SqlValue[]): Promise<ResultRow[]> {
272
+ const send = () =>
273
+ this.#sendRequest({ type: 'all', id: this.#allocId(), sql, bind }).then(r => ('rows' in r ? (r.rows ?? []) : []));
274
+ return this.#inTx ? send() : this.#txQueue.put(send);
275
+ }
276
+
277
+ #allocId(): number {
278
+ return ++this.#nextId;
279
+ }
280
+
281
+ /**
282
+ * Reject any in-flight requests with `reason`, so callers awaiting a response to a
283
+ * request sent to a now-terminated worker don't hang forever. Called from
284
+ * close()/delete() and from the worker.onerror handler.
285
+ */
286
+ #rejectPending(reason: string): void {
287
+ if (this.#pending.size === 0) {
288
+ return;
289
+ }
290
+ const err = new Error(reason);
291
+ for (const { reject } of this.#pending.values()) {
292
+ reject(err);
293
+ }
294
+ this.#pending.clear();
295
+ }
296
+
297
+ #sendRequest(req: WorkerRequest, transfer?: Transferable[]): Promise<WorkerResponse> {
298
+ if (this.#workerFailed) {
299
+ return Promise.reject(new Error('SQLite worker has crashed'));
300
+ }
301
+ return new Promise<WorkerResponse>((resolve, reject) => {
302
+ this.#pending.set(req.id, {
303
+ resolve: resp => {
304
+ if (resp.type === 'err') {
305
+ // Re-hydrate typed errors so consumers can pattern-match on
306
+ // `instanceof`. Encryption is tagged on the wire (some cases are
307
+ // pre-flight throws with no message to match); corruption is a
308
+ // single unambiguous message, so we classify it here rather than
309
+ // adding a redundant wire field. Everything else stays a plain Error.
310
+ if (resp.encryptionCode !== undefined) {
311
+ reject(new SqliteEncryptionError(resp.encryptionCode, resp.message));
312
+ } else if (isCorruptionMessage(resp.message)) {
313
+ reject(new SqliteCorruptionError(resp.message));
314
+ } else {
315
+ reject(new Error(resp.message));
316
+ }
317
+ } else {
318
+ resolve(resp);
319
+ }
320
+ },
321
+ reject,
322
+ });
323
+ if (transfer && transfer.length > 0) {
324
+ this.#worker.postMessage(req, transfer);
325
+ } else {
326
+ this.#worker.postMessage(req);
327
+ }
328
+ });
329
+ }
330
+ }