@aztec/kv-store 0.0.1-commit.b655e406 → 0.0.1-commit.b9865e97

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 (193) hide show
  1. package/README.md +8 -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/indexeddb/array.d.ts +1 -1
  6. package/dest/indexeddb/array.d.ts.map +1 -1
  7. package/dest/indexeddb/array.js +21 -7
  8. package/dest/indexeddb/index.d.ts +3 -3
  9. package/dest/indexeddb/index.d.ts.map +1 -1
  10. package/dest/indexeddb/index.js +3 -6
  11. package/dest/indexeddb/map.d.ts +8 -2
  12. package/dest/indexeddb/map.d.ts.map +1 -1
  13. package/dest/indexeddb/map.js +23 -13
  14. package/dest/indexeddb/multi_map.d.ts +3 -1
  15. package/dest/indexeddb/multi_map.d.ts.map +1 -1
  16. package/dest/indexeddb/multi_map.js +30 -1
  17. package/dest/indexeddb/set.d.ts +1 -1
  18. package/dest/indexeddb/set.d.ts.map +1 -1
  19. package/dest/indexeddb/singleton.d.ts +1 -1
  20. package/dest/indexeddb/singleton.d.ts.map +1 -1
  21. package/dest/indexeddb/singleton.js +3 -1
  22. package/dest/indexeddb/store.d.ts +3 -3
  23. package/dest/indexeddb/store.d.ts.map +1 -1
  24. package/dest/indexeddb/store.js +6 -4
  25. package/dest/interfaces/array.d.ts +1 -1
  26. package/dest/interfaces/array_test_suite.d.ts +1 -1
  27. package/dest/interfaces/array_test_suite.d.ts.map +1 -1
  28. package/dest/interfaces/array_test_suite.js +33 -34
  29. package/dest/interfaces/common.d.ts +1 -1
  30. package/dest/interfaces/counter.d.ts +1 -1
  31. package/dest/interfaces/index.d.ts +2 -2
  32. package/dest/interfaces/index.d.ts.map +1 -1
  33. package/dest/interfaces/map.d.ts +1 -1
  34. package/dest/interfaces/map_test_suite.d.ts +1 -1
  35. package/dest/interfaces/map_test_suite.d.ts.map +1 -1
  36. package/dest/interfaces/map_test_suite.js +74 -29
  37. package/dest/interfaces/multi_map.d.ts +7 -1
  38. package/dest/interfaces/multi_map.d.ts.map +1 -1
  39. package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
  40. package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
  41. package/dest/interfaces/multi_map_test_suite.js +154 -36
  42. package/dest/interfaces/set.d.ts +1 -1
  43. package/dest/interfaces/set_test_suite.d.ts +1 -1
  44. package/dest/interfaces/set_test_suite.d.ts.map +1 -1
  45. package/dest/interfaces/set_test_suite.js +13 -14
  46. package/dest/interfaces/singleton.d.ts +1 -1
  47. package/dest/interfaces/singleton_test_suite.d.ts +1 -1
  48. package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
  49. package/dest/interfaces/singleton_test_suite.js +6 -7
  50. package/dest/interfaces/store.d.ts +1 -1
  51. package/dest/interfaces/utils.d.ts +2 -1
  52. package/dest/interfaces/utils.d.ts.map +1 -1
  53. package/dest/interfaces/utils.js +2 -1
  54. package/dest/lmdb/array.d.ts +1 -1
  55. package/dest/lmdb/array.d.ts.map +1 -1
  56. package/dest/lmdb/array.js +4 -2
  57. package/dest/lmdb/counter.d.ts +1 -1
  58. package/dest/lmdb/counter.d.ts.map +1 -1
  59. package/dest/lmdb/index.d.ts +3 -3
  60. package/dest/lmdb/index.d.ts.map +1 -1
  61. package/dest/lmdb/index.js +4 -4
  62. package/dest/lmdb/map.d.ts +1 -1
  63. package/dest/lmdb/map.d.ts.map +1 -1
  64. package/dest/lmdb/multi_map.d.ts +2 -1
  65. package/dest/lmdb/multi_map.d.ts.map +1 -1
  66. package/dest/lmdb/multi_map.js +15 -0
  67. package/dest/lmdb/set.d.ts +1 -1
  68. package/dest/lmdb/set.d.ts.map +1 -1
  69. package/dest/lmdb/singleton.d.ts +1 -1
  70. package/dest/lmdb/singleton.d.ts.map +1 -1
  71. package/dest/lmdb/store.d.ts +4 -5
  72. package/dest/lmdb/store.d.ts.map +1 -1
  73. package/dest/lmdb/store.js +13 -9
  74. package/dest/lmdb-v2/array.d.ts +2 -2
  75. package/dest/lmdb-v2/array.d.ts.map +1 -1
  76. package/dest/lmdb-v2/array.js +4 -3
  77. package/dest/lmdb-v2/factory.d.ts +32 -10
  78. package/dest/lmdb-v2/factory.d.ts.map +1 -1
  79. package/dest/lmdb-v2/factory.js +71 -16
  80. package/dest/lmdb-v2/index.d.ts +1 -1
  81. package/dest/lmdb-v2/map.d.ts +2 -2
  82. package/dest/lmdb-v2/map.d.ts.map +1 -1
  83. package/dest/lmdb-v2/map.js +1 -2
  84. package/dest/lmdb-v2/message.d.ts +1 -1
  85. package/dest/lmdb-v2/multi_map.d.ts +3 -2
  86. package/dest/lmdb-v2/multi_map.d.ts.map +1 -1
  87. package/dest/lmdb-v2/multi_map.js +11 -1
  88. package/dest/lmdb-v2/read_transaction.d.ts +1 -1
  89. package/dest/lmdb-v2/read_transaction.d.ts.map +1 -1
  90. package/dest/lmdb-v2/read_transaction.js +21 -19
  91. package/dest/lmdb-v2/set.d.ts +1 -1
  92. package/dest/lmdb-v2/set.d.ts.map +1 -1
  93. package/dest/lmdb-v2/singleton.d.ts +2 -2
  94. package/dest/lmdb-v2/singleton.d.ts.map +1 -1
  95. package/dest/lmdb-v2/singleton.js +1 -2
  96. package/dest/lmdb-v2/store.d.ts +4 -5
  97. package/dest/lmdb-v2/store.d.ts.map +1 -1
  98. package/dest/lmdb-v2/store.js +6 -28
  99. package/dest/lmdb-v2/tx-helpers.d.ts +6 -0
  100. package/dest/lmdb-v2/tx-helpers.d.ts.map +1 -0
  101. package/dest/lmdb-v2/tx-helpers.js +21 -0
  102. package/dest/lmdb-v2/utils.d.ts +1 -10
  103. package/dest/lmdb-v2/utils.d.ts.map +1 -1
  104. package/dest/lmdb-v2/utils.js +0 -94
  105. package/dest/lmdb-v2/write_transaction.d.ts +1 -1
  106. package/dest/lmdb-v2/write_transaction.d.ts.map +1 -1
  107. package/dest/lmdb-v2/write_transaction.js +9 -5
  108. package/dest/sqlite-opfs/array.d.ts +21 -0
  109. package/dest/sqlite-opfs/array.d.ts.map +1 -0
  110. package/dest/sqlite-opfs/array.js +128 -0
  111. package/dest/sqlite-opfs/errors.d.ts +27 -0
  112. package/dest/sqlite-opfs/errors.d.ts.map +1 -0
  113. package/dest/sqlite-opfs/errors.js +34 -0
  114. package/dest/sqlite-opfs/index.d.ts +16 -0
  115. package/dest/sqlite-opfs/index.d.ts.map +1 -0
  116. package/dest/sqlite-opfs/index.js +22 -0
  117. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
  118. package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
  119. package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
  120. package/dest/sqlite-opfs/map.d.ts +35 -0
  121. package/dest/sqlite-opfs/map.d.ts.map +1 -0
  122. package/dest/sqlite-opfs/map.js +163 -0
  123. package/dest/sqlite-opfs/messages.d.ts +66 -0
  124. package/dest/sqlite-opfs/messages.d.ts.map +1 -0
  125. package/dest/sqlite-opfs/messages.js +5 -0
  126. package/dest/sqlite-opfs/multi_map.d.ts +16 -0
  127. package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
  128. package/dest/sqlite-opfs/multi_map.js +67 -0
  129. package/dest/sqlite-opfs/set.d.ts +13 -0
  130. package/dest/sqlite-opfs/set.d.ts.map +1 -0
  131. package/dest/sqlite-opfs/set.js +19 -0
  132. package/dest/sqlite-opfs/singleton.d.ts +13 -0
  133. package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
  134. package/dest/sqlite-opfs/singleton.js +48 -0
  135. package/dest/sqlite-opfs/store.d.ts +79 -0
  136. package/dest/sqlite-opfs/store.d.ts.map +1 -0
  137. package/dest/sqlite-opfs/store.js +281 -0
  138. package/dest/sqlite-opfs/worker.d.ts +2 -0
  139. package/dest/sqlite-opfs/worker.d.ts.map +1 -0
  140. package/dest/sqlite-opfs/worker.js +249 -0
  141. package/dest/stores/index.d.ts +1 -1
  142. package/dest/stores/l2_tips_store.d.ts +25 -10
  143. package/dest/stores/l2_tips_store.d.ts.map +1 -1
  144. package/dest/stores/l2_tips_store.js +62 -53
  145. package/dest/utils.d.ts +9 -6
  146. package/dest/utils.d.ts.map +1 -1
  147. package/dest/utils.js +51 -16
  148. package/package.json +33 -26
  149. package/src/bench/shared_map_bench.ts +111 -0
  150. package/src/indexeddb/array.ts +4 -4
  151. package/src/indexeddb/index.ts +9 -7
  152. package/src/indexeddb/map.ts +24 -11
  153. package/src/indexeddb/multi_map.ts +27 -1
  154. package/src/indexeddb/singleton.ts +1 -1
  155. package/src/indexeddb/store.ts +13 -6
  156. package/src/interfaces/array_test_suite.ts +33 -35
  157. package/src/interfaces/index.ts +1 -1
  158. package/src/interfaces/map_test_suite.ts +56 -30
  159. package/src/interfaces/multi_map.ts +7 -0
  160. package/src/interfaces/multi_map_test_suite.ts +167 -37
  161. package/src/interfaces/set_test_suite.ts +13 -15
  162. package/src/interfaces/singleton_test_suite.ts +6 -8
  163. package/src/interfaces/utils.ts +1 -0
  164. package/src/lmdb/index.ts +10 -5
  165. package/src/lmdb/multi_map.ts +16 -0
  166. package/src/lmdb/store.ts +13 -9
  167. package/src/lmdb-v2/array.ts +2 -2
  168. package/src/lmdb-v2/factory.ts +93 -19
  169. package/src/lmdb-v2/map.ts +2 -2
  170. package/src/lmdb-v2/multi_map.ts +10 -1
  171. package/src/lmdb-v2/read_transaction.ts +23 -23
  172. package/src/lmdb-v2/singleton.ts +2 -2
  173. package/src/lmdb-v2/store.ts +9 -33
  174. package/src/lmdb-v2/tx-helpers.ts +29 -0
  175. package/src/lmdb-v2/utils.ts +0 -118
  176. package/src/lmdb-v2/write_transaction.ts +9 -8
  177. package/src/sqlite-opfs/array.ts +124 -0
  178. package/src/sqlite-opfs/errors.ts +44 -0
  179. package/src/sqlite-opfs/index.ts +39 -0
  180. package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
  181. package/src/sqlite-opfs/map.ts +163 -0
  182. package/src/sqlite-opfs/messages.ts +39 -0
  183. package/src/sqlite-opfs/multi_map.ts +74 -0
  184. package/src/sqlite-opfs/set.ts +29 -0
  185. package/src/sqlite-opfs/singleton.ts +48 -0
  186. package/src/sqlite-opfs/store.ts +296 -0
  187. package/src/sqlite-opfs/worker.ts +231 -0
  188. package/src/stores/l2_tips_store.ts +66 -56
  189. package/src/utils.ts +79 -21
  190. package/dest/config.d.ts +0 -17
  191. package/dest/config.d.ts.map +0 -1
  192. package/dest/config.js +0 -26
  193. package/src/config.ts +0 -36
@@ -0,0 +1,124 @@
1
+ import { Encoder } from '#msgpackr';
2
+ import { toBufferKey } from '#ordered-binary';
3
+ import { hash } from 'ohash';
4
+
5
+ import type { AztecAsyncArray } from '../interfaces/array.js';
6
+ import type { Value } from '../interfaces/common.js';
7
+ import type { AztecSQLiteOPFSStore } from './store.js';
8
+
9
+ /**
10
+ * Persistent array backed by SQLite. Entries share a common `key` (the array name)
11
+ * and are ordered by `key_count`, which doubles as the 1-indexed slot number.
12
+ */
13
+ export class SQLiteOPFSAztecArray<T extends Value> implements AztecAsyncArray<T> {
14
+ readonly #name: string;
15
+ readonly #container: string;
16
+ readonly #encoder = new Encoder();
17
+
18
+ constructor(
19
+ private readonly store: AztecSQLiteOPFSStore,
20
+ name: string,
21
+ ) {
22
+ this.#name = name;
23
+ this.#container = `array:${name}`;
24
+ }
25
+
26
+ async lengthAsync(): Promise<number> {
27
+ const rows = await this.store.allAsync('SELECT COUNT(*) FROM data WHERE container = ? AND key = ?', [
28
+ this.#container,
29
+ this.#encodedKey(),
30
+ ]);
31
+ return Number(rows[0]?.[0] ?? 0);
32
+ }
33
+
34
+ async push(...vals: T[]): Promise<number> {
35
+ if (vals.length === 0) {
36
+ return this.lengthAsync();
37
+ }
38
+ return await this.store.transactionAsync(async () => {
39
+ let length = await this.lengthAsync();
40
+ for (const val of vals) {
41
+ await this.store.runAsync(
42
+ `INSERT INTO data (slot, container, key, key_count, hash, value)
43
+ VALUES (?, ?, ?, ?, ?, ?)`,
44
+ [this.#slot(length), this.#container, this.#encodedKey(), length + 1, hash(val), this.#encoder.pack(val)],
45
+ );
46
+ length += 1;
47
+ }
48
+ return length;
49
+ });
50
+ }
51
+
52
+ async pop(): Promise<T | undefined> {
53
+ return await this.store.transactionAsync(async () => {
54
+ const length = await this.lengthAsync();
55
+ if (length === 0) {
56
+ return undefined;
57
+ }
58
+ const slot = this.#slot(length - 1);
59
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [slot]);
60
+ await this.store.runAsync('DELETE FROM data WHERE slot = ?', [slot]);
61
+ const raw = rows[0]?.[0];
62
+ return raw instanceof Uint8Array ? (this.#encoder.unpack(raw) as T) : undefined;
63
+ });
64
+ }
65
+
66
+ async atAsync(index: number): Promise<T | undefined> {
67
+ const length = await this.lengthAsync();
68
+ const resolved = index < 0 ? length + index : index;
69
+ if (resolved < 0 || resolved >= length) {
70
+ return undefined;
71
+ }
72
+ const rows = await this.store.allAsync('SELECT value FROM data WHERE slot = ? LIMIT 1', [this.#slot(resolved)]);
73
+ const raw = rows[0]?.[0];
74
+ return raw instanceof Uint8Array ? (this.#encoder.unpack(raw) as T) : undefined;
75
+ }
76
+
77
+ async setAt(index: number, val: T): Promise<boolean> {
78
+ return await this.store.transactionAsync(async () => {
79
+ const length = await this.lengthAsync();
80
+ const resolved = index < 0 ? length + index : index;
81
+ if (resolved < 0 || resolved >= length) {
82
+ return false;
83
+ }
84
+ await this.store.runAsync(
85
+ `INSERT OR REPLACE INTO data (slot, container, key, key_count, hash, value)
86
+ VALUES (?, ?, ?, ?, ?, ?)`,
87
+ [this.#slot(resolved), this.#container, this.#encodedKey(), resolved + 1, hash(val), this.#encoder.pack(val)],
88
+ );
89
+ return true;
90
+ });
91
+ }
92
+
93
+ async *entriesAsync(): AsyncIterableIterator<[number, T]> {
94
+ const rows = await this.store.allAsync(
95
+ 'SELECT key_count, value FROM data WHERE container = ? AND key = ? ORDER BY key_count ASC',
96
+ [this.#container, this.#encodedKey()],
97
+ );
98
+ for (const row of rows) {
99
+ const keyCount = Number(row[0]);
100
+ const raw = row[1];
101
+ if (raw instanceof Uint8Array) {
102
+ yield [keyCount - 1, this.#encoder.unpack(raw) as T];
103
+ }
104
+ }
105
+ }
106
+
107
+ async *valuesAsync(): AsyncIterableIterator<T> {
108
+ for await (const [, val] of this.entriesAsync()) {
109
+ yield val;
110
+ }
111
+ }
112
+
113
+ [Symbol.asyncIterator](): AsyncIterableIterator<T> {
114
+ return this.valuesAsync();
115
+ }
116
+
117
+ #encodedKey(): Buffer {
118
+ return toBufferKey([this.#name]);
119
+ }
120
+
121
+ #slot(index: number): string {
122
+ return `array:${this.#name}:slot:${index}`;
123
+ }
124
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Typed error surface for sqlite3mc-backed page-level encryption failures.
3
+ *
4
+ * Three concrete failure modes are surfaced:
5
+ *
6
+ * - `invalid_key_length`: caller-side pre-flight (key not 32 bytes).
7
+ * - `encryption_not_supported_for_ephemeral`: caller-side pre-flight (encryption was requested on an ephemeral
8
+ * `:memory:` store, which sqlite3mc does not support).
9
+ * - `decrypt_failed`: runtime failure raised when sqlite3mc cannot decode page 1 of an existing database. Covers
10
+ * both "wrong key supplied" and "no key supplied to an encrypted DB".
11
+ */
12
+ export type SqliteEncryptionErrorCode =
13
+ | 'invalid_key_length'
14
+ | 'encryption_not_supported_for_ephemeral'
15
+ | 'decrypt_failed';
16
+
17
+ /**
18
+ * Error thrown by sqlite-opfs when an encryption operation fails.
19
+ **/
20
+ export class SqliteEncryptionError extends Error {
21
+ readonly code: SqliteEncryptionErrorCode;
22
+
23
+ constructor(code: SqliteEncryptionErrorCode, message: string, opts?: { cause?: unknown }) {
24
+ super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);
25
+ this.name = 'SqliteEncryptionError';
26
+ this.code = code;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Strings raised by sqlite3mc when page 1 cannot be decoded.
32
+ **/
33
+ const SQLITE3MC_DECRYPT_ERROR_PATTERNS: readonly RegExp[] = [
34
+ /file is not a database/i,
35
+ /file is encrypted or is not a database/i,
36
+ ];
37
+
38
+ /**
39
+ * Returns `true` if `message` matches one of the known sqlite3mc decrypt-failure
40
+ * strings.
41
+ **/
42
+ export function isDecryptFailureMessage(message: string): boolean {
43
+ return SQLITE3MC_DECRYPT_ERROR_PATTERNS.some(p => p.test(message));
44
+ }
@@ -0,0 +1,39 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
3
+
4
+ import { initStoreForRollupAndSchemaVersion } from '../utils.js';
5
+ import { AztecSQLiteOPFSStore } from './store.js';
6
+
7
+ export { AztecSQLiteOPFSStore } from './store.js';
8
+ export { SqliteEncryptionError } from './errors.js';
9
+ export type { SqliteEncryptionErrorCode } from './errors.js';
10
+
11
+ export async function createStore(
12
+ name: string,
13
+ config: DataStoreConfig,
14
+ schemaVersion: number | undefined = undefined,
15
+ log: Logger = createLogger('kv-store'),
16
+ ) {
17
+ const { dataDirectory } = config;
18
+ log.info(
19
+ dataDirectory
20
+ ? `Creating ${name} SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`
21
+ : `Creating ${name} ephemeral SQLite-OPFS data store with map size ${config.dataStoreMapSizeKb} KB`,
22
+ );
23
+ const store = await AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false);
24
+ return initStoreForRollupAndSchemaVersion(store, schemaVersion, config.rollupAddress, log);
25
+ }
26
+
27
+ export function openTmpStore(ephemeral: boolean = false): Promise<AztecSQLiteOPFSStore> {
28
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), undefined, ephemeral);
29
+ }
30
+
31
+ /**
32
+ * Convenience helper for tests and consumers that want an encrypted sqlite-opfs
33
+ * store without dealing with the full `open()` parameter order. Key must be 32
34
+ * bytes. Creates a fresh persistent store (sqlite3mc does not support encryption
35
+ * on ephemeral `:memory:` databases) in an auto-generated OPFS directory.
36
+ */
37
+ export function openEncryptedStore(encryptionKey: Uint8Array, name?: string, poolDirectory?: string) {
38
+ return AztecSQLiteOPFSStore.open(createLogger('kv-store:sqlite-opfs'), name, false, poolDirectory, encryptionKey);
39
+ }
@@ -0,0 +1,465 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Vendored from `ordered-binary@1.5.3/index.js` with one targeted edit:
4
+ * the `readString` definition (originally a dynamically-generated
5
+ * unrolled-loop function) is replaced with a hand-written interpreted
6
+ * equivalent that does the same work without code-generation-from-strings.
7
+ *
8
+ * Why vendor: upstream has no CSP-safe build, and the codegen is a
9
+ * module-init-time string-passed-to-evaluator that trips MV3 CSP
10
+ * (`script-src 'self' 'wasm-unsafe-eval'`). The codegen is a perf
11
+ * optimization on the string-decoding path only — the interpreted
12
+ * version is functionally identical, just slower per call.
13
+ *
14
+ * Parity with upstream is enforced by `ordered-binary-browser.test.ts`,
15
+ * which compares byte-exact output for a representative key set on every
16
+ * Node-mode test run. If `ordered-binary` is bumped, re-vendor by
17
+ * recopying upstream and reapplying the patch in the section marked
18
+ * `// CSP PATCH BEGIN` ... `// CSP PATCH END`.
19
+ */
20
+ /*
21
+ control character types:
22
+ 1 - metadata
23
+ 2 - symbols
24
+ 6 - false
25
+ 7 - true
26
+ 8- 16 - negative doubles
27
+ 16-24 positive doubles
28
+ 27 - String starts with a character 27 or less or is an empty string
29
+ 0 - multipart separator
30
+ > 27 normal string characters
31
+ */
32
+ /*
33
+ * Convert arbitrary scalar values to buffer bytes with type preservation and type-appropriate ordering
34
+ */
35
+
36
+ const float64Array = new Float64Array(2);
37
+ const int32Array = new Int32Array(float64Array.buffer, 0, 4);
38
+ let nullTerminate = false;
39
+ let textEncoder;
40
+ try {
41
+ textEncoder = new TextEncoder();
42
+ } catch (error) {}
43
+
44
+ /*
45
+ * Convert arbitrary scalar values to buffer bytes with type preservation and type-appropriate ordering
46
+ */
47
+ export function writeKey(key, target, position, inSequence) {
48
+ let targetView = target.dataView;
49
+ if (!targetView) {
50
+ targetView = target.dataView = new DataView(target.buffer, target.byteOffset, ((target.byteLength + 3) >> 2) << 2);
51
+ }
52
+ switch (typeof key) {
53
+ case 'string':
54
+ let strLength = key.length;
55
+ let c1 = key.charCodeAt(0);
56
+ if (!(c1 >= 28)) {
57
+ // escape character
58
+ target[position++] = 27;
59
+ }
60
+ if (strLength < 0x40) {
61
+ let i, c2;
62
+ for (i = 0; i < strLength; i++) {
63
+ c1 = key.charCodeAt(i);
64
+ if (c1 <= 4) {
65
+ target[position++] = 4;
66
+ target[position++] = c1;
67
+ } else if (c1 < 0x80) {
68
+ target[position++] = c1;
69
+ } else if (c1 < 0x800) {
70
+ target[position++] = (c1 >> 6) | 0xc0;
71
+ target[position++] = (c1 & 0x3f) | 0x80;
72
+ } else if ((c1 & 0xfc00) === 0xd800 && ((c2 = key.charCodeAt(i + 1)) & 0xfc00) === 0xdc00) {
73
+ c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
74
+ i++;
75
+ target[position++] = (c1 >> 18) | 0xf0;
76
+ target[position++] = ((c1 >> 12) & 0x3f) | 0x80;
77
+ target[position++] = ((c1 >> 6) & 0x3f) | 0x80;
78
+ target[position++] = (c1 & 0x3f) | 0x80;
79
+ } else {
80
+ target[position++] = (c1 >> 12) | 0xe0;
81
+ target[position++] = ((c1 >> 6) & 0x3f) | 0x80;
82
+ target[position++] = (c1 & 0x3f) | 0x80;
83
+ }
84
+ }
85
+ } else {
86
+ if (target.utf8Write) {
87
+ position += target.utf8Write(key, position, target.byteLength - position);
88
+ } else {
89
+ position += textEncoder.encodeInto(key, target.subarray(position)).written;
90
+ }
91
+ if (position > target.length - 4) {
92
+ throw new RangeError('String does not fit in target buffer');
93
+ }
94
+ }
95
+ break;
96
+ case 'number':
97
+ float64Array[0] = key;
98
+ let lowInt = int32Array[0];
99
+ let highInt = int32Array[1];
100
+ let length;
101
+ if (key < 0) {
102
+ targetView.setInt32(position + 4, ~((lowInt >>> 4) | (highInt << 28)));
103
+ targetView.setInt32(position + 0, (highInt ^ 0x7fffffff) >>> 4);
104
+ targetView.setInt32(position + 8, ((lowInt & 0xf) ^ 0xf) << 4, true); // just always do the null termination here
105
+ return position + 9;
106
+ } else if (lowInt & 0xf || inSequence) {
107
+ length = 9;
108
+ } else if (lowInt & 0xfffff) {
109
+ length = 8;
110
+ } else if (lowInt || highInt & 0xf) {
111
+ length = 6;
112
+ } else {
113
+ length = 4;
114
+ }
115
+ // switching order to go to little endian
116
+ targetView.setInt32(position + 0, (highInt >>> 4) | 0x10000000);
117
+ targetView.setInt32(position + 4, (lowInt >>> 4) | (highInt << 28));
118
+ // if (length == 9 || nullTerminate)
119
+ targetView.setInt32(position + 8, (lowInt & 0xf) << 4, true);
120
+ return position + length;
121
+ case 'object':
122
+ if (key) {
123
+ if (Array.isArray(key)) {
124
+ for (let i = 0, l = key.length; i < l; i++) {
125
+ if (i > 0) {
126
+ target[position++] = 0;
127
+ }
128
+ position = writeKey(key[i], target, position, true);
129
+ }
130
+ break;
131
+ } else if (key instanceof Uint8Array) {
132
+ target.set(key, position);
133
+ position += key.length;
134
+ break;
135
+ } else {
136
+ throw new Error('Unable to serialize object as a key: ' + JSON.stringify(key));
137
+ }
138
+ } // null
139
+ else {
140
+ target[position++] = 0;
141
+ }
142
+ break;
143
+ case 'boolean':
144
+ targetView.setUint32(position++, key ? 7 : 6, true);
145
+ return position;
146
+ case 'bigint':
147
+ let asFloat = Number(key);
148
+ if (BigInt(asFloat) > key) {
149
+ float64Array[0] = asFloat;
150
+ if (asFloat > 0) {
151
+ if (int32Array[0]) {
152
+ int32Array[0]--;
153
+ } else {
154
+ int32Array[1]--;
155
+ int32Array[0] = 0xffffffff;
156
+ }
157
+ } else {
158
+ if (int32Array[0] < 0xffffffff) {
159
+ int32Array[0]++;
160
+ } else {
161
+ int32Array[1]++;
162
+ int32Array[0] = 0;
163
+ }
164
+ }
165
+ asFloat = float64Array[0];
166
+ }
167
+ let difference = key - BigInt(asFloat);
168
+ if (difference === 0n) {
169
+ return writeKey(asFloat, target, position, inSequence);
170
+ }
171
+ writeKey(asFloat, target, position, inSequence);
172
+ position += 9; // always increment by 9 if we are adding fractional bits
173
+ let exponent = BigInt(((int32Array[1] >> 20) & 0x7ff) - 1079);
174
+ let nextByte = difference >> exponent;
175
+ target[position - 1] |= Number(nextByte);
176
+ difference -= nextByte << exponent;
177
+ let first = true;
178
+ while (difference || first) {
179
+ first = false;
180
+ exponent -= 7n;
181
+ let nextByte = difference >> exponent;
182
+ target[position++] = Number(nextByte) | 0x80;
183
+ difference -= nextByte << exponent;
184
+ }
185
+ return position;
186
+ case 'undefined':
187
+ return position;
188
+ // undefined is interpreted as the absence of a key, signified by zero length
189
+ case 'symbol':
190
+ target[position++] = 2;
191
+ return writeKey(key.description, target, position, inSequence);
192
+ default:
193
+ throw new Error('Can not serialize key of type ' + typeof key);
194
+ }
195
+ if (nullTerminate && !inSequence) {
196
+ targetView.setUint32(position, 0);
197
+ }
198
+ return position;
199
+ }
200
+
201
+ let position;
202
+ export function readKey(buffer, start, end, inSequence) {
203
+ position = start;
204
+ let controlByte = buffer[position];
205
+ let value;
206
+ if (controlByte < 24) {
207
+ if (controlByte < 8) {
208
+ position++;
209
+ if (controlByte == 6) {
210
+ value = false;
211
+ } else if (controlByte == 7) {
212
+ value = true;
213
+ } else if (controlByte == 0) {
214
+ value = null;
215
+ } else if (controlByte == 2) {
216
+ value = Symbol.for(readStringSafely(buffer, end));
217
+ } else {
218
+ return Uint8Array.prototype.slice.call(buffer, start, end);
219
+ }
220
+ } else {
221
+ let dataView;
222
+ try {
223
+ dataView =
224
+ buffer.dataView ||
225
+ (buffer.dataView = new DataView(buffer.buffer, buffer.byteOffset, ((buffer.byteLength + 3) >> 2) << 2));
226
+ } catch (error) {
227
+ // if it is write at the end of the ArrayBuffer, we may need to retry with the exact remaining bytes
228
+ dataView =
229
+ buffer.dataView ||
230
+ (buffer.dataView = new DataView(
231
+ buffer.buffer,
232
+ buffer.byteOffset,
233
+ buffer.buffer.byteLength - buffer.byteOffset,
234
+ ));
235
+ }
236
+
237
+ let highInt = dataView.getInt32(position) << 4;
238
+ let size = end - position;
239
+ let lowInt;
240
+ if (size > 4) {
241
+ lowInt = dataView.getInt32(position + 4);
242
+ highInt |= lowInt >>> 28;
243
+ if (size <= 6) {
244
+ // clear the last bits
245
+ lowInt &= -0x10000;
246
+ }
247
+ lowInt = lowInt << 4;
248
+ if (size > 8) {
249
+ lowInt = lowInt | (buffer[position + 8] >> 4);
250
+ }
251
+ } else {
252
+ lowInt = 0;
253
+ }
254
+ if (controlByte < 16) {
255
+ // negative gets negated
256
+ highInt = highInt ^ 0x7fffffff;
257
+ lowInt = ~lowInt;
258
+ }
259
+ int32Array[1] = highInt;
260
+ int32Array[0] = lowInt;
261
+ value = float64Array[0];
262
+ position += 9;
263
+ if (size > 9 && buffer[position] > 0) {
264
+ // convert the float to bigint, and then we will add precision as we enumerate through the
265
+ // extra bytes
266
+ value = BigInt(value);
267
+ let exponent = (highInt >> 20) & 0x7ff;
268
+ let next_byte = buffer[position - 1] & 0xf;
269
+ value += BigInt(next_byte) << BigInt(exponent - 1079);
270
+ while ((next_byte = buffer[position]) > 0 && position++ < end) {
271
+ value += BigInt(next_byte & 0x7f) << BigInt((start - position) * 7 + exponent - 1016);
272
+ }
273
+ }
274
+ }
275
+ } else {
276
+ if (controlByte == 27) {
277
+ position++;
278
+ }
279
+ value = readStringSafely(buffer, end);
280
+ }
281
+ while (position < end) {
282
+ if (buffer[position] === 0) {
283
+ position++;
284
+ }
285
+ if (inSequence) {
286
+ encoder.position = position;
287
+ return value;
288
+ }
289
+ let nextValue = readKey(buffer, position, end, true);
290
+ if (value instanceof Array) {
291
+ value.push(nextValue);
292
+ } else {
293
+ value = [value, nextValue];
294
+ }
295
+ }
296
+ return value;
297
+ }
298
+ export const enableNullTermination = () => (nullTerminate = true);
299
+
300
+ export const encoder = {
301
+ writeKey,
302
+ readKey,
303
+ enableNullTermination,
304
+ };
305
+ let targetBuffer = [];
306
+ let targetPosition = 0;
307
+ const hasNodeBuffer = typeof Buffer !== 'undefined';
308
+ const ByteArrayAllocate = hasNodeBuffer ? Buffer.allocUnsafeSlow : Uint8Array;
309
+ export const toBufferKey = key => {
310
+ let newBuffer;
311
+ if (targetPosition + 100 > targetBuffer.length) {
312
+ targetBuffer = new ByteArrayAllocate(8192);
313
+ targetPosition = 0;
314
+ newBuffer = true;
315
+ }
316
+ try {
317
+ let result = targetBuffer.slice(targetPosition, (targetPosition = writeKey(key, targetBuffer, targetPosition)));
318
+ if (targetPosition > targetBuffer.length) {
319
+ if (newBuffer) {
320
+ throw new Error('Key is too large');
321
+ }
322
+ return toBufferKey(key);
323
+ }
324
+ return result;
325
+ } catch (error) {
326
+ if (newBuffer) {
327
+ throw error;
328
+ }
329
+ targetPosition = targetBuffer.length;
330
+ return toBufferKey(key);
331
+ }
332
+ };
333
+ export const fromBufferKey = sourceBuffer => {
334
+ return readKey(sourceBuffer, 0, sourceBuffer.length);
335
+ };
336
+ const fromCharCode = String.fromCharCode;
337
+
338
+ let pendingSurrogate;
339
+ function finishUtf8(byte1, src) {
340
+ if ((byte1 & 0xe0) === 0xc0) {
341
+ // 2 bytes
342
+ const byte2 = src[position++] & 0x3f;
343
+ return ((byte1 & 0x1f) << 6) | byte2;
344
+ } else if ((byte1 & 0xf0) === 0xe0) {
345
+ // 3 bytes
346
+ const byte2 = src[position++] & 0x3f;
347
+ const byte3 = src[position++] & 0x3f;
348
+ return ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3;
349
+ } else if ((byte1 & 0xf8) === 0xf0) {
350
+ // 4 bytes
351
+ if (pendingSurrogate) {
352
+ byte1 = pendingSurrogate;
353
+ pendingSurrogate = null;
354
+ position += 3;
355
+ return byte1;
356
+ }
357
+ const byte2 = src[position++] & 0x3f;
358
+ const byte3 = src[position++] & 0x3f;
359
+ const byte4 = src[position++] & 0x3f;
360
+ let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
361
+ if (unit > 0xffff) {
362
+ pendingSurrogate = 0xdc00 | (unit & 0x3ff);
363
+ unit = (((unit - 0x10000) >>> 10) & 0x3ff) | 0xd800;
364
+ position -= 4; // reset so we can return the next part of the surrogate pair
365
+ }
366
+ return unit;
367
+ } else {
368
+ return byte1;
369
+ }
370
+ }
371
+
372
+ // CSP PATCH BEGIN — replaces upstream's module-init dynamic-codegen with
373
+ // an interpreted equivalent. The original `makeStringBuilder()` produces
374
+ // a function string that unrolls 0x30 iterations of the loop below for
375
+ // perf; this version does the same work as a real loop, slower per call
376
+ // but CSP-safe (no module-init code generation from strings).
377
+ const readString = (function makeReadString() {
378
+ function readStr(source) {
379
+ const codes = [];
380
+ while (codes.length < 0x30) {
381
+ let v = source[position++];
382
+ if (v > 4) {
383
+ if (v >= 0x80) {
384
+ v = finishUtf8(v, source);
385
+ }
386
+ } else if (v === 4) {
387
+ v = source[position++];
388
+ } else {
389
+ return fromCharCode.apply(null, codes);
390
+ }
391
+ codes.push(v);
392
+ }
393
+ return fromCharCode.apply(null, codes) + readStr(source);
394
+ }
395
+ return readStr;
396
+ })();
397
+ // CSP PATCH END
398
+
399
+ function readStringSafely(source, end) {
400
+ if (source[end] > 0) {
401
+ let previous = source[end];
402
+ try {
403
+ // read string expects a null terminator, that is a 0 or undefined from reading past the end of the buffer, so we
404
+ // have to ensure that, but do so safely, restoring the buffer to its original state
405
+ source[end] = 0;
406
+ return readString(source);
407
+ } finally {
408
+ source[end] = previous;
409
+ }
410
+ } else {
411
+ return readString(source);
412
+ }
413
+ }
414
+ export function compareKeys(a, b) {
415
+ // compare with type consistency that matches binary comparison
416
+ if (typeof a == 'object') {
417
+ if (!a) {
418
+ return b == null ? 0 : -1;
419
+ }
420
+ if (a.compare) {
421
+ if (b == null) {
422
+ return 1;
423
+ } else if (b.compare) {
424
+ return a.compare(b);
425
+ } else {
426
+ return -1;
427
+ }
428
+ }
429
+ let arrayComparison;
430
+ if (b instanceof Array) {
431
+ let i = 0;
432
+ while ((arrayComparison = compareKeys(a[i], b[i])) == 0 && i <= a.length) {
433
+ i++;
434
+ }
435
+ return arrayComparison;
436
+ }
437
+ arrayComparison = compareKeys(a[0], b);
438
+ if (arrayComparison == 0 && a.length > 1) {
439
+ return 1;
440
+ }
441
+ return arrayComparison;
442
+ } else if (typeof a == typeof b) {
443
+ if (typeof a === 'symbol') {
444
+ a = Symbol.keyFor(a);
445
+ b = Symbol.keyFor(b);
446
+ }
447
+ return a < b ? -1 : a === b ? 0 : 1;
448
+ } else if (typeof b == 'object') {
449
+ if (b instanceof Array) {
450
+ return -compareKeys(b, a);
451
+ }
452
+ return 1;
453
+ } else {
454
+ return typeOrder[typeof a] < typeOrder[typeof b] ? -1 : 1;
455
+ }
456
+ }
457
+ const typeOrder = {
458
+ symbol: 0,
459
+ undefined: 1,
460
+ boolean: 2,
461
+ number: 3,
462
+ string: 4,
463
+ };
464
+ export const MINIMUM_KEY = null;
465
+ export const MAXIMUM_KEY = new Uint8Array([0xff]);