@aztec/kv-store 0.0.1-commit.fff30aa → 0.0.1-dev
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.
- package/dest/bench/shared_map_bench.d.ts +19 -0
- package/dest/bench/shared_map_bench.d.ts.map +1 -0
- package/dest/bench/shared_map_bench.js +91 -0
- package/dest/interfaces/array_test_suite.d.ts +1 -1
- package/dest/interfaces/array_test_suite.d.ts.map +1 -1
- package/dest/interfaces/array_test_suite.js +33 -34
- package/dest/interfaces/index.d.ts +2 -2
- package/dest/interfaces/index.d.ts.map +1 -1
- package/dest/interfaces/map_test_suite.d.ts +1 -1
- package/dest/interfaces/map_test_suite.d.ts.map +1 -1
- package/dest/interfaces/map_test_suite.js +32 -33
- package/dest/interfaces/multi_map_test_suite.d.ts +1 -1
- package/dest/interfaces/multi_map_test_suite.d.ts.map +1 -1
- package/dest/interfaces/multi_map_test_suite.js +68 -69
- package/dest/interfaces/set_test_suite.d.ts +1 -1
- package/dest/interfaces/set_test_suite.d.ts.map +1 -1
- package/dest/interfaces/set_test_suite.js +13 -14
- package/dest/interfaces/singleton_test_suite.d.ts +1 -1
- package/dest/interfaces/singleton_test_suite.d.ts.map +1 -1
- package/dest/interfaces/singleton_test_suite.js +6 -7
- package/dest/sqlite-opfs/array.d.ts +21 -0
- package/dest/sqlite-opfs/array.d.ts.map +1 -0
- package/dest/sqlite-opfs/array.js +128 -0
- package/dest/sqlite-opfs/errors.d.ts +27 -0
- package/dest/sqlite-opfs/errors.d.ts.map +1 -0
- package/dest/sqlite-opfs/errors.js +34 -0
- package/dest/sqlite-opfs/index.d.ts +16 -0
- package/dest/sqlite-opfs/index.d.ts.map +1 -0
- package/dest/sqlite-opfs/index.js +22 -0
- package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts +32 -0
- package/dest/sqlite-opfs/internal/ordered-binary-browser.d.ts.map +1 -0
- package/dest/sqlite-opfs/internal/ordered-binary-browser.js +448 -0
- package/dest/sqlite-opfs/map.d.ts +35 -0
- package/dest/sqlite-opfs/map.d.ts.map +1 -0
- package/dest/sqlite-opfs/map.js +163 -0
- package/dest/sqlite-opfs/messages.d.ts +66 -0
- package/dest/sqlite-opfs/messages.d.ts.map +1 -0
- package/dest/sqlite-opfs/messages.js +5 -0
- package/dest/sqlite-opfs/multi_map.d.ts +16 -0
- package/dest/sqlite-opfs/multi_map.d.ts.map +1 -0
- package/dest/sqlite-opfs/multi_map.js +67 -0
- package/dest/sqlite-opfs/set.d.ts +13 -0
- package/dest/sqlite-opfs/set.d.ts.map +1 -0
- package/dest/sqlite-opfs/set.js +19 -0
- package/dest/sqlite-opfs/singleton.d.ts +13 -0
- package/dest/sqlite-opfs/singleton.d.ts.map +1 -0
- package/dest/sqlite-opfs/singleton.js +48 -0
- package/dest/sqlite-opfs/store.d.ts +79 -0
- package/dest/sqlite-opfs/store.d.ts.map +1 -0
- package/dest/sqlite-opfs/store.js +281 -0
- package/dest/sqlite-opfs/worker.d.ts +2 -0
- package/dest/sqlite-opfs/worker.d.ts.map +1 -0
- package/dest/sqlite-opfs/worker.js +244 -0
- package/package.json +22 -19
- package/src/bench/shared_map_bench.ts +111 -0
- package/src/interfaces/array_test_suite.ts +33 -35
- package/src/interfaces/index.ts +1 -1
- package/src/interfaces/map_test_suite.ts +32 -34
- package/src/interfaces/multi_map_test_suite.ts +65 -67
- package/src/interfaces/set_test_suite.ts +13 -15
- package/src/interfaces/singleton_test_suite.ts +6 -8
- package/src/sqlite-opfs/array.ts +124 -0
- package/src/sqlite-opfs/errors.ts +44 -0
- package/src/sqlite-opfs/index.ts +39 -0
- package/src/sqlite-opfs/internal/ordered-binary-browser.js +465 -0
- package/src/sqlite-opfs/map.ts +163 -0
- package/src/sqlite-opfs/messages.ts +39 -0
- package/src/sqlite-opfs/multi_map.ts +74 -0
- package/src/sqlite-opfs/set.ts +29 -0
- package/src/sqlite-opfs/singleton.ts +48 -0
- package/src/sqlite-opfs/store.ts +296 -0
- package/src/sqlite-opfs/worker.ts +226 -0
|
@@ -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
|
+
|
|
3
|
+
import type { DataStoreConfig } from '../config.js';
|
|
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.l1Contracts?.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]);
|