@reddb-io/browser 0.0.0-stage → 0.1.0-alpha.1

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.
@@ -0,0 +1,497 @@
1
+ /* @ts-self-types="./reddb_wasm.d.ts" */
2
+
3
+ /**
4
+ * Canonical `.rdb` artifact I/O. The worker owns and closes the underlying
5
+ * exclusive access handle; freeing this wrapper never unlocks it early.
6
+ */
7
+ export class BrowserArtifact {
8
+ static __wrap(ptr) {
9
+ const obj = Object.create(BrowserArtifact.prototype);
10
+ obj.__wbg_ptr = ptr;
11
+ BrowserArtifactFinalization.register(obj, obj.__wbg_ptr, obj);
12
+ return obj;
13
+ }
14
+ __destroy_into_raw() {
15
+ const ptr = this.__wbg_ptr;
16
+ this.__wbg_ptr = 0;
17
+ BrowserArtifactFinalization.unregister(this);
18
+ return ptr;
19
+ }
20
+ free() {
21
+ const ptr = this.__destroy_into_raw();
22
+ wasm.__wbg_browserartifact_free(ptr, 0);
23
+ }
24
+ /**
25
+ * @param {Array<any>} payloads
26
+ */
27
+ append(payloads) {
28
+ const ret = wasm.browserartifact_append(this.__wbg_ptr, payloads);
29
+ if (ret[1]) {
30
+ throw takeFromExternrefTable0(ret[0]);
31
+ }
32
+ }
33
+ /**
34
+ * @param {Uint8Array} snapshot
35
+ * @param {number} min_wal_bytes
36
+ */
37
+ checkpoint(snapshot, min_wal_bytes) {
38
+ const ptr0 = passArray8ToWasm0(snapshot, wasm.__wbindgen_malloc);
39
+ const len0 = WASM_VECTOR_LEN;
40
+ const ret = wasm.browserartifact_checkpoint(this.__wbg_ptr, ptr0, len0, min_wal_bytes);
41
+ if (ret[1]) {
42
+ throw takeFromExternrefTable0(ret[0]);
43
+ }
44
+ }
45
+ /**
46
+ * @param {any} handle
47
+ * @param {string} name
48
+ * @param {number} created_at_unix_ms
49
+ * @returns {BrowserArtifact}
50
+ */
51
+ static create(handle, name, created_at_unix_ms) {
52
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
53
+ const len0 = WASM_VECTOR_LEN;
54
+ const ret = wasm.browserartifact_create(handle, ptr0, len0, created_at_unix_ms);
55
+ if (ret[2]) {
56
+ throw takeFromExternrefTable0(ret[1]);
57
+ }
58
+ return BrowserArtifact.__wrap(ret[0]);
59
+ }
60
+ /**
61
+ * String-valued counters preserve all u64 bits across JavaScript.
62
+ * @returns {string}
63
+ */
64
+ generation() {
65
+ let deferred2_0;
66
+ let deferred2_1;
67
+ try {
68
+ const ret = wasm.browserartifact_generation(this.__wbg_ptr);
69
+ var ptr1 = ret[0];
70
+ var len1 = ret[1];
71
+ if (ret[3]) {
72
+ ptr1 = 0; len1 = 0;
73
+ throw takeFromExternrefTable0(ret[2]);
74
+ }
75
+ deferred2_0 = ptr1;
76
+ deferred2_1 = len1;
77
+ return getStringFromWasm0(ptr1, len1);
78
+ } finally {
79
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
80
+ }
81
+ }
82
+ /**
83
+ * @param {any} handle
84
+ * @param {string} name
85
+ * @returns {BrowserArtifact}
86
+ */
87
+ static open(handle, name) {
88
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
89
+ const len0 = WASM_VECTOR_LEN;
90
+ const ret = wasm.browserartifact_open(handle, ptr0, len0);
91
+ if (ret[2]) {
92
+ throw takeFromExternrefTable0(ret[1]);
93
+ }
94
+ return BrowserArtifact.__wrap(ret[0]);
95
+ }
96
+ /**
97
+ * @returns {Uint8Array | undefined}
98
+ */
99
+ readSnapshot() {
100
+ const ret = wasm.browserartifact_readSnapshot(this.__wbg_ptr);
101
+ if (ret[3]) {
102
+ throw takeFromExternrefTable0(ret[2]);
103
+ }
104
+ let v1;
105
+ if (ret[0] !== 0) {
106
+ v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
107
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
108
+ }
109
+ return v1;
110
+ }
111
+ /**
112
+ * @returns {Array<any>}
113
+ */
114
+ readWal() {
115
+ const ret = wasm.browserartifact_readWal(this.__wbg_ptr);
116
+ if (ret[2]) {
117
+ throw takeFromExternrefTable0(ret[1]);
118
+ }
119
+ return takeFromExternrefTable0(ret[0]);
120
+ }
121
+ }
122
+ if (Symbol.dispose) BrowserArtifact.prototype[Symbol.dispose] = BrowserArtifact.prototype.free;
123
+
124
+ /**
125
+ * Experimental storage-free execution, using the native scalar evaluator.
126
+ * @param {string} sql
127
+ * @returns {any}
128
+ */
129
+ export function executeScalar(sql) {
130
+ const ptr0 = passStringToWasm0(sql, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
131
+ const len0 = WASM_VECTOR_LEN;
132
+ const ret = wasm.executeScalar(ptr0, len0);
133
+ if (ret[2]) {
134
+ throw takeFromExternrefTable0(ret[1]);
135
+ }
136
+ return takeFromExternrefTable0(ret[0]);
137
+ }
138
+
139
+ /**
140
+ * Contract shared by the JS worker and foreign-language browser adapters.
141
+ * @returns {any}
142
+ */
143
+ export function runtimeInfo() {
144
+ const ret = wasm.runtimeInfo();
145
+ if (ret[2]) {
146
+ throw takeFromExternrefTable0(ret[1]);
147
+ }
148
+ return takeFromExternrefTable0(ret[0]);
149
+ }
150
+
151
+ /**
152
+ * @param {string} sql
153
+ */
154
+ export function validateQuery(sql) {
155
+ const ptr0 = passStringToWasm0(sql, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
156
+ const len0 = WASM_VECTOR_LEN;
157
+ const ret = wasm.validateQuery(ptr0, len0);
158
+ if (ret[1]) {
159
+ throw takeFromExternrefTable0(ret[0]);
160
+ }
161
+ }
162
+ function __wbg_get_imports() {
163
+ const import0 = {
164
+ __proto__: null,
165
+ __wbg___wbindgen_string_get_965592073e5d848c: function(arg0, arg1) {
166
+ const obj = arg1;
167
+ const ret = typeof(obj) === 'string' ? obj : undefined;
168
+ var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
169
+ var len1 = WASM_VECTOR_LEN;
170
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
171
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
172
+ },
173
+ __wbg___wbindgen_throw_9c75d47bf9e7731e: function(arg0, arg1) {
174
+ throw new Error(getStringFromWasm0(arg0, arg1));
175
+ },
176
+ __wbg_flush_8a925e51a05f983d: function() { return handleError(function (arg0) {
177
+ arg0.flush();
178
+ }, arguments); },
179
+ __wbg_getSize_ef1f7ad2400c4958: function() { return handleError(function (arg0) {
180
+ const ret = arg0.getSize();
181
+ return ret;
182
+ }, arguments); },
183
+ __wbg_get_unchecked_be562b1421656321: function(arg0, arg1) {
184
+ const ret = arg0[arg1 >>> 0];
185
+ return ret;
186
+ },
187
+ __wbg_instanceof_Error_5e21755e9d9cbee5: function(arg0) {
188
+ let result;
189
+ try {
190
+ result = arg0 instanceof Error;
191
+ } catch (_) {
192
+ result = false;
193
+ }
194
+ const ret = result;
195
+ return ret;
196
+ },
197
+ __wbg_instanceof_Uint8Array_57d77acd50e4c44d: function(arg0) {
198
+ let result;
199
+ try {
200
+ result = arg0 instanceof Uint8Array;
201
+ } catch (_) {
202
+ result = false;
203
+ }
204
+ const ret = result;
205
+ return ret;
206
+ },
207
+ __wbg_length_0a6ce016dc1460b0: function(arg0) {
208
+ const ret = arg0.length;
209
+ return ret;
210
+ },
211
+ __wbg_length_ba3c032602efe310: function(arg0) {
212
+ const ret = arg0.length;
213
+ return ret;
214
+ },
215
+ __wbg_message_d5628ca19de920d3: function(arg0) {
216
+ const ret = arg0.message;
217
+ return ret;
218
+ },
219
+ __wbg_new_3baa8d9866155c79: function() {
220
+ const ret = new Array();
221
+ return ret;
222
+ },
223
+ __wbg_new_c9ea13ea803a692e: function(arg0, arg1) {
224
+ const ret = new Error(getStringFromWasm0(arg0, arg1));
225
+ return ret;
226
+ },
227
+ __wbg_new_from_slice_5a173c243af2e823: function(arg0, arg1) {
228
+ const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
229
+ return ret;
230
+ },
231
+ __wbg_parse_342d5616e14beccc: function() { return handleError(function (arg0, arg1) {
232
+ const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
233
+ return ret;
234
+ }, arguments); },
235
+ __wbg_prototypesetcall_fd4050e806e1d519: function(arg0, arg1, arg2) {
236
+ Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);
237
+ },
238
+ __wbg_push_60a5366c0bb22a7d: function(arg0, arg1) {
239
+ const ret = arg0.push(arg1);
240
+ return ret;
241
+ },
242
+ __wbg_readAt_38b95ee3bea009e0: function() { return handleError(function (arg0, arg1, arg2, arg3) {
243
+ const ret = arg0.readAt(getArrayU8FromWasm0(arg1, arg2), arg3);
244
+ return ret;
245
+ }, arguments); },
246
+ __wbg_set_5337f8ac82364a3f: function() { return handleError(function (arg0, arg1, arg2) {
247
+ const ret = Reflect.set(arg0, arg1, arg2);
248
+ return ret;
249
+ }, arguments); },
250
+ __wbg_truncate_d9e55b46e14f9493: function() { return handleError(function (arg0, arg1) {
251
+ arg0.truncate(arg1);
252
+ }, arguments); },
253
+ __wbg_writeAt_1aacc9360d02366e: function() { return handleError(function (arg0, arg1, arg2, arg3) {
254
+ const ret = arg0.writeAt(getArrayU8FromWasm0(arg1, arg2), arg3);
255
+ return ret;
256
+ }, arguments); },
257
+ __wbindgen_cast_0000000000000001: function(arg0, arg1) {
258
+ // Cast intrinsic for `Ref(String) -> Externref`.
259
+ const ret = getStringFromWasm0(arg0, arg1);
260
+ return ret;
261
+ },
262
+ __wbindgen_init_externref_table: function() {
263
+ const table = wasm.__wbindgen_externrefs;
264
+ const offset = table.grow(4);
265
+ table.set(0, undefined);
266
+ table.set(offset + 0, undefined);
267
+ table.set(offset + 1, null);
268
+ table.set(offset + 2, true);
269
+ table.set(offset + 3, false);
270
+ },
271
+ };
272
+ return {
273
+ __proto__: null,
274
+ "./reddb_wasm_bg.js": import0,
275
+ };
276
+ }
277
+
278
+ const BrowserArtifactFinalization = (typeof FinalizationRegistry === 'undefined')
279
+ ? { register: () => {}, unregister: () => {} }
280
+ : new FinalizationRegistry(ptr => wasm.__wbg_browserartifact_free(ptr, 1));
281
+
282
+ function addToExternrefTable0(obj) {
283
+ const idx = wasm.__externref_table_alloc();
284
+ wasm.__wbindgen_externrefs.set(idx, obj);
285
+ return idx;
286
+ }
287
+
288
+ function getArrayU8FromWasm0(ptr, len) {
289
+ ptr = ptr >>> 0;
290
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
291
+ }
292
+
293
+ let cachedDataViewMemory0 = null;
294
+ function getDataViewMemory0() {
295
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
296
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
297
+ }
298
+ return cachedDataViewMemory0;
299
+ }
300
+
301
+ function getStringFromWasm0(ptr, len) {
302
+ return decodeText(ptr >>> 0, len);
303
+ }
304
+
305
+ let cachedUint8ArrayMemory0 = null;
306
+ function getUint8ArrayMemory0() {
307
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
308
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
309
+ }
310
+ return cachedUint8ArrayMemory0;
311
+ }
312
+
313
+ function handleError(f, args) {
314
+ try {
315
+ return f.apply(this, args);
316
+ } catch (e) {
317
+ const idx = addToExternrefTable0(e);
318
+ wasm.__wbindgen_exn_store(idx);
319
+ }
320
+ }
321
+
322
+ function isLikeNone(x) {
323
+ return x === undefined || x === null;
324
+ }
325
+
326
+ function passArray8ToWasm0(arg, malloc) {
327
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
328
+ getUint8ArrayMemory0().set(arg, ptr / 1);
329
+ WASM_VECTOR_LEN = arg.length;
330
+ return ptr;
331
+ }
332
+
333
+ function passStringToWasm0(arg, malloc, realloc) {
334
+ if (realloc === undefined) {
335
+ const buf = cachedTextEncoder.encode(arg);
336
+ const ptr = malloc(buf.length, 1) >>> 0;
337
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
338
+ WASM_VECTOR_LEN = buf.length;
339
+ return ptr;
340
+ }
341
+
342
+ let len = arg.length;
343
+ let ptr = malloc(len, 1) >>> 0;
344
+
345
+ const mem = getUint8ArrayMemory0();
346
+
347
+ let offset = 0;
348
+
349
+ for (; offset < len; offset++) {
350
+ const code = arg.charCodeAt(offset);
351
+ if (code > 0x7F) break;
352
+ mem[ptr + offset] = code;
353
+ }
354
+ if (offset !== len) {
355
+ if (offset !== 0) {
356
+ arg = arg.slice(offset);
357
+ }
358
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
359
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
360
+ const ret = cachedTextEncoder.encodeInto(arg, view);
361
+
362
+ offset += ret.written;
363
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
364
+ }
365
+
366
+ WASM_VECTOR_LEN = offset;
367
+ return ptr;
368
+ }
369
+
370
+ function takeFromExternrefTable0(idx) {
371
+ const value = wasm.__wbindgen_externrefs.get(idx);
372
+ wasm.__externref_table_dealloc(idx);
373
+ return value;
374
+ }
375
+
376
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
377
+ cachedTextDecoder.decode();
378
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
379
+ let numBytesDecoded = 0;
380
+ function decodeText(ptr, len) {
381
+ numBytesDecoded += len;
382
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
383
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
384
+ cachedTextDecoder.decode();
385
+ numBytesDecoded = len;
386
+ }
387
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
388
+ }
389
+
390
+ const cachedTextEncoder = new TextEncoder();
391
+
392
+ if (!('encodeInto' in cachedTextEncoder)) {
393
+ cachedTextEncoder.encodeInto = function (arg, view) {
394
+ const buf = cachedTextEncoder.encode(arg);
395
+ view.set(buf);
396
+ return {
397
+ read: arg.length,
398
+ written: buf.length
399
+ };
400
+ };
401
+ }
402
+
403
+ let WASM_VECTOR_LEN = 0;
404
+
405
+ let wasmModule, wasmInstance, wasm;
406
+ function __wbg_finalize_init(instance, module) {
407
+ wasmInstance = instance;
408
+ wasm = instance.exports;
409
+ wasmModule = module;
410
+ cachedDataViewMemory0 = null;
411
+ cachedUint8ArrayMemory0 = null;
412
+ wasm.__wbindgen_start();
413
+ return wasm;
414
+ }
415
+
416
+ async function __wbg_load(module, imports) {
417
+ if (typeof Response === 'function' && module instanceof Response) {
418
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
419
+ try {
420
+ return await WebAssembly.instantiateStreaming(module, imports);
421
+ } catch (e) {
422
+ const validResponse = module.ok && expectedResponseType(module.type);
423
+
424
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
425
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
426
+
427
+ } else { throw e; }
428
+ }
429
+ }
430
+
431
+ const bytes = await module.arrayBuffer();
432
+ return await WebAssembly.instantiate(bytes, imports);
433
+ } else {
434
+ const instance = await WebAssembly.instantiate(module, imports);
435
+
436
+ if (instance instanceof WebAssembly.Instance) {
437
+ return { instance, module };
438
+ } else {
439
+ return instance;
440
+ }
441
+ }
442
+
443
+ function expectedResponseType(type) {
444
+ switch (type) {
445
+ case 'basic': case 'cors': case 'default': return true;
446
+ }
447
+ return false;
448
+ }
449
+ }
450
+
451
+ function initSync(module) {
452
+ if (wasm !== undefined) return wasm;
453
+
454
+
455
+ if (module !== undefined) {
456
+ if (Object.getPrototypeOf(module) === Object.prototype) {
457
+ ({module} = module)
458
+ } else {
459
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
460
+ }
461
+ }
462
+
463
+ const imports = __wbg_get_imports();
464
+ if (!(module instanceof WebAssembly.Module)) {
465
+ module = new WebAssembly.Module(module);
466
+ }
467
+ const instance = new WebAssembly.Instance(module, imports);
468
+ return __wbg_finalize_init(instance, module);
469
+ }
470
+
471
+ async function __wbg_init(module_or_path) {
472
+ if (wasm !== undefined) return wasm;
473
+
474
+
475
+ if (module_or_path !== undefined) {
476
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
477
+ ({module_or_path} = module_or_path)
478
+ } else {
479
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
480
+ }
481
+ }
482
+
483
+ if (module_or_path === undefined) {
484
+ module_or_path = new URL('reddb_wasm_bg.wasm', import.meta.url);
485
+ }
486
+ const imports = __wbg_get_imports();
487
+
488
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
489
+ module_or_path = fetch(module_or_path);
490
+ }
491
+
492
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
493
+
494
+ return __wbg_finalize_init(instance, module);
495
+ }
496
+
497
+ export { initSync, __wbg_init as default };
Binary file
@@ -0,0 +1,30 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const __wbg_browserartifact_free: (a: number, b: number) => void;
5
+ export const browserartifact_append: (a: number, b: any) => [number, number];
6
+ export const browserartifact_checkpoint: (a: number, b: number, c: number, d: number) => [number, number];
7
+ export const browserartifact_create: (a: any, b: number, c: number, d: number) => [number, number, number];
8
+ export const browserartifact_generation: (a: number) => [number, number, number, number];
9
+ export const browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
10
+ export const browserartifact_readSnapshot: (a: number) => [number, number, number, number];
11
+ export const browserartifact_readWal: (a: number) => [number, number, number];
12
+ export const executeScalar: (a: number, b: number) => [number, number, number];
13
+ export const runtimeInfo: () => [number, number, number];
14
+ export const validateQuery: (a: number, b: number) => [number, number];
15
+ export const rust_zstd_wasm_shim_calloc: (a: number, b: number) => number;
16
+ export const rust_zstd_wasm_shim_free: (a: number) => void;
17
+ export const rust_zstd_wasm_shim_malloc: (a: number) => number;
18
+ export const rust_zstd_wasm_shim_memcmp: (a: number, b: number, c: number) => number;
19
+ export const rust_zstd_wasm_shim_memcpy: (a: number, b: number, c: number) => number;
20
+ export const rust_zstd_wasm_shim_memmove: (a: number, b: number, c: number) => number;
21
+ export const rust_zstd_wasm_shim_memset: (a: number, b: number, c: number) => number;
22
+ export const rust_zstd_wasm_shim_qsort: (a: number, b: number, c: number, d: number) => void;
23
+ export const __wbindgen_malloc: (a: number, b: number) => number;
24
+ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
25
+ export const __wbindgen_exn_store: (a: number) => void;
26
+ export const __externref_table_alloc: () => number;
27
+ export const __wbindgen_externrefs: WebAssembly.Table;
28
+ export const __externref_table_dealloc: (a: number) => void;
29
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
30
+ export const __wbindgen_start: () => void;
package/src/worker.js ADDED
@@ -0,0 +1,127 @@
1
+ import init, * as wasm from './wasm/reddb_wasm.js'
2
+ import { RUNTIME_ABI_VERSION, VALUE_ENCODING } from './protocol.js'
3
+
4
+ let artifact
5
+ let access
6
+ let release
7
+ let ownership
8
+ let queue = Promise.resolve()
9
+ let initialized
10
+
11
+ function initialize() {
12
+ return initialized ??= (async () => {
13
+ await init()
14
+ if (typeof wasm.runtimeInfo !== 'function') throw error('VERSION_MISMATCH', 'WASM runtime metadata is missing')
15
+ let info
16
+ try { info = wasm.runtimeInfo() }
17
+ catch { throw error('VERSION_MISMATCH', 'WASM binary does not expose the expected runtime ABI') }
18
+ if (info.abiVersion !== RUNTIME_ABI_VERSION || info.valueEncoding !== VALUE_ENCODING) {
19
+ throw error('VERSION_MISMATCH', 'WASM runtime ABI does not match this worker')
20
+ }
21
+ return info
22
+ })()
23
+ }
24
+
25
+ function error(code, message) {
26
+ return Object.assign(new Error(message), { code })
27
+ }
28
+
29
+ function synchronous(value) {
30
+ if (value && typeof value.then === 'function') {
31
+ value.catch(() => {})
32
+ throw error('STORAGE_UNSUPPORTED', 'This browser implements asynchronous OPFS access; synchronous access is required')
33
+ }
34
+ return value
35
+ }
36
+
37
+ async function open(name) {
38
+ await initialize()
39
+ await new Promise((resolve, reject) => {
40
+ ownership = navigator.locks.request(`reddb-browser:${name}`, { ifAvailable: true }, async (lock) => {
41
+ if (!lock) throw error('FILE_BUSY', 'This artifact is already open in another worker or tab')
42
+ try {
43
+ const root = await navigator.storage.getDirectory()
44
+ const directory = await root.getDirectoryHandle('reddb-browser', { create: true })
45
+ const file = await directory.getFileHandle(`${name}.rdb`, { create: true })
46
+ if (typeof file.createSyncAccessHandle !== 'function') {
47
+ throw error('STORAGE_UNSUPPORTED', 'This browser does not support synchronous OPFS access in a dedicated worker')
48
+ }
49
+ access = await file.createSyncAccessHandle()
50
+ const fileIo = {
51
+ readAt: (buffer, offset) => synchronous(access.read(buffer, { at: offset })),
52
+ writeAt: (buffer, offset) => synchronous(access.write(buffer, { at: offset })),
53
+ getSize: () => synchronous(access.getSize()),
54
+ truncate: (size) => synchronous(access.truncate(size)),
55
+ flush: () => synchronous(access.flush()),
56
+ }
57
+ artifact = fileIo.getSize() === 0
58
+ ? wasm.BrowserArtifact.create(fileIo, name, Date.now())
59
+ : wasm.BrowserArtifact.open(fileIo, name)
60
+ const lifetime = new Promise((resolveRelease) => { release = resolveRelease })
61
+ resolve()
62
+ await lifetime
63
+ } catch (failure) {
64
+ reject(failure)
65
+ throw failure
66
+ } finally {
67
+ artifact?.free()
68
+ artifact = undefined
69
+ if (access) synchronous(access.close())
70
+ access = undefined
71
+ }
72
+ })
73
+ // Observe early lock/open failures, including ifAvailable returning null.
74
+ ownership.catch(reject)
75
+ })
76
+ }
77
+
78
+ function bytes(value) {
79
+ if (!(value instanceof Uint8Array)) throw error('INVALID_ARGUMENT', 'Expected a Uint8Array')
80
+ return value
81
+ }
82
+
83
+ async function execute(method, params) {
84
+ if (method === 'initialize' || method === 'info') return initialize()
85
+ if (method === 'open') return open(params.name)
86
+ if (method === 'validateQuery' || method === 'executeScalar') {
87
+ await initialize()
88
+ if (typeof params.sql !== 'string') throw error('INVALID_ARGUMENT', 'Expected an RQL string')
89
+ return method === 'validateQuery' ? wasm.validateQuery(params.sql) : wasm.executeScalar(params.sql)
90
+ }
91
+ if (!artifact) throw error('CLOSED', 'The artifact is not open')
92
+ switch (method) {
93
+ case 'generation': return artifact.generation()
94
+ case 'readWal': return artifact.readWal()
95
+ case 'readSnapshot': return artifact.readSnapshot()
96
+ case 'append':
97
+ if (!Array.isArray(params.payloads)) throw error('INVALID_ARGUMENT', 'Expected an array of WAL payloads')
98
+ return artifact.append(params.payloads.map(bytes))
99
+ case 'checkpoint':
100
+ if (!Number.isInteger(params.minWalBytes) || params.minWalBytes < 0 || params.minWalBytes > 0xffffffff) {
101
+ throw error('INVALID_ARGUMENT', 'WAL capacity must be an unsigned 32-bit integer')
102
+ }
103
+ return artifact.checkpoint(bytes(params.snapshot), params.minWalBytes)
104
+ case 'close':
105
+ release()
106
+ await ownership
107
+ return
108
+ default: throw error('INVALID_ARGUMENT', `Unknown artifact operation: ${method}`)
109
+ }
110
+ }
111
+
112
+ self.onmessage = ({ data }) => {
113
+ const { id, method, params = {} } = data ?? {}
114
+ if (data?.abiVersion !== RUNTIME_ABI_VERSION) {
115
+ self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, error: { code: 'VERSION_MISMATCH', message: 'SDK runtime ABI does not match this worker' } })
116
+ return
117
+ }
118
+ // Opening is asynchronous; all following operations wait for ownership.
119
+ queue = queue.then(async () => {
120
+ try {
121
+ const result = await execute(method, params)
122
+ self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, result })
123
+ } catch (failure) {
124
+ self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, error: { code: failure.code || 'ARTIFACT_ERROR', message: failure.message || String(failure) } })
125
+ }
126
+ })
127
+ }