@silkui/core 0.1.12 → 0.1.13

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,975 @@
1
+ // IndexedDB over memory, for apps that keep caches and keys in it: databases, versions and
2
+ // upgrades, object stores with key paths and generators, indexes (compound and multiEntry),
3
+ // key ranges, cursors, and transactions that commit once their requests are done or undo
4
+ // their writes on abort. On the full runtime a database is saved to a file (with `node:v8`
5
+ // serialization) after each transaction that wrote; values that cannot be serialized keep
6
+ // the database in memory only. Requests run in microtasks, so promise code between requests
7
+ // keeps a transaction alive as browsers do.
8
+
9
+ import { storageDirectory } from "./storage.js";
10
+
11
+ const DOMError = (name, message) => {
12
+ const DOMExceptionClass = globalThis.DOMException;
13
+ if (typeof DOMExceptionClass === "function") return new DOMExceptionClass(message, name);
14
+ const error = new Error(message);
15
+ error.name = name;
16
+ return error;
17
+ };
18
+
19
+ // Keys, as the spec orders them: numbers, then dates, strings, binary and arrays.
20
+ function keyType(key) {
21
+ if (typeof key === "number") return Number.isNaN(key) ? null : 1;
22
+ if (key instanceof Date) return Number.isNaN(key.getTime()) ? null : 2;
23
+ if (typeof key === "string") return 3;
24
+ if (key instanceof ArrayBuffer || ArrayBuffer.isView(key)) return 4;
25
+ if (Array.isArray(key)) return 5;
26
+ return null;
27
+ }
28
+
29
+ function validKey(key) {
30
+ const type = keyType(key);
31
+ if (type === null) return false;
32
+ if (type === 5) return key.every(validKey);
33
+ return true;
34
+ }
35
+
36
+ function checkKey(key) {
37
+ if (!validKey(key)) throw DOMError("DataError", "the value is not a valid key");
38
+ return key;
39
+ }
40
+
41
+ function bytesOf(key) {
42
+ return key instanceof ArrayBuffer ? new Uint8Array(key) : new Uint8Array(key.buffer, key.byteOffset, key.byteLength);
43
+ }
44
+
45
+ export function cmp(a, b) {
46
+ const ta = keyType(a);
47
+ const tb = keyType(b);
48
+ if (ta !== tb) return ta < tb ? -1 : 1;
49
+ switch (ta) {
50
+ case 1: return a === b ? 0 : a < b ? -1 : 1;
51
+ case 2: return cmp(a.getTime(), b.getTime());
52
+ case 3: return a === b ? 0 : a < b ? -1 : 1;
53
+ case 4: {
54
+ const x = bytesOf(a);
55
+ const y = bytesOf(b);
56
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
57
+ return cmp(x.length, y.length);
58
+ }
59
+ case 5: {
60
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
61
+ const order = cmp(a[i], b[i]);
62
+ if (order !== 0) return order;
63
+ }
64
+ return cmp(a.length, b.length);
65
+ }
66
+ }
67
+ return 0;
68
+ }
69
+
70
+ function copyKey(key) {
71
+ if (Array.isArray(key)) return key.map(copyKey);
72
+ if (key instanceof Date) return new Date(key.getTime());
73
+ if (key instanceof ArrayBuffer || ArrayBuffer.isView(key)) return bytesOf(key).slice().buffer;
74
+ return key;
75
+ }
76
+
77
+ function clone(value) {
78
+ if (typeof structuredClone === "function") {
79
+ try {
80
+ return structuredClone(value);
81
+ } catch (error) {
82
+ throw DOMError("DataCloneError", String(error?.message ?? error));
83
+ }
84
+ }
85
+ return value;
86
+ }
87
+
88
+ function valueAtPath(value, path) {
89
+ if (Array.isArray(path)) {
90
+ const keys = [];
91
+ for (const part of path) {
92
+ const key = valueAtPath(value, part);
93
+ if (key === undefined) return undefined;
94
+ keys.push(key);
95
+ }
96
+ return keys;
97
+ }
98
+ if (path === "") return value;
99
+ let at = value;
100
+ for (const part of path.split(".")) {
101
+ if (at === null || at === undefined || typeof at !== "object" && typeof at !== "string") return undefined;
102
+ if (typeof at === "string" && part === "length") at = at.length;
103
+ else if (!(part in Object(at))) return undefined;
104
+ else at = at[part];
105
+ }
106
+ return at;
107
+ }
108
+
109
+ function setAtPath(value, path, key) {
110
+ const parts = path.split(".");
111
+ let at = value;
112
+ for (const part of parts.slice(0, -1)) {
113
+ if (at[part] === undefined) at[part] = {};
114
+ at = at[part];
115
+ }
116
+ at[parts[parts.length - 1]] = key;
117
+ }
118
+
119
+ export class IDBKeyRange {
120
+ constructor(lower, upper, lowerOpen, upperOpen) {
121
+ this.lower = lower;
122
+ this.upper = upper;
123
+ this.lowerOpen = !!lowerOpen;
124
+ this.upperOpen = !!upperOpen;
125
+ }
126
+ static only(value) { checkKey(value); return new IDBKeyRange(value, value, false, false); }
127
+ static lowerBound(lower, open) { checkKey(lower); return new IDBKeyRange(lower, undefined, open, true); }
128
+ static upperBound(upper, open) { checkKey(upper); return new IDBKeyRange(undefined, upper, true, open); }
129
+ static bound(lower, upper, lowerOpen, upperOpen) {
130
+ checkKey(lower);
131
+ checkKey(upper);
132
+ if (cmp(lower, upper) > 0 || (cmp(lower, upper) === 0 && (lowerOpen || upperOpen))) throw DOMError("DataError", "the range's lower bound is above its upper bound");
133
+ return new IDBKeyRange(lower, upper, lowerOpen, upperOpen);
134
+ }
135
+ includes(key) {
136
+ checkKey(key);
137
+ if (this.lower !== undefined) {
138
+ const order = cmp(key, this.lower);
139
+ if (order < 0 || (order === 0 && this.lowerOpen)) return false;
140
+ }
141
+ if (this.upper !== undefined) {
142
+ const order = cmp(key, this.upper);
143
+ if (order > 0 || (order === 0 && this.upperOpen)) return false;
144
+ }
145
+ return true;
146
+ }
147
+ }
148
+
149
+ function rangeOf(query) {
150
+ if (query === undefined || query === null) return null;
151
+ if (query instanceof IDBKeyRange) return query;
152
+ return IDBKeyRange.only(checkKey(query));
153
+ }
154
+
155
+ // A small event target: listeners, `on<type>` handlers, and the event's target fields.
156
+ class Target {
157
+ #listeners = new Map();
158
+ addEventListener(type, listener, options) {
159
+ if (!listener) return;
160
+ let list = this.#listeners.get(type);
161
+ if (!list) this.#listeners.set(type, (list = []));
162
+ if (!list.some((entry) => entry.listener === listener)) list.push({ listener, once: !!options?.once });
163
+ }
164
+ removeEventListener(type, listener) {
165
+ const list = this.#listeners.get(type);
166
+ const index = list?.findIndex((entry) => entry.listener === listener) ?? -1;
167
+ if (index >= 0) list.splice(index, 1);
168
+ }
169
+ dispatchEvent(event) {
170
+ event.target ??= this;
171
+ event.currentTarget = this;
172
+ for (const entry of (this.#listeners.get(event.type) ?? []).slice()) {
173
+ if (entry.once) this.removeEventListener(event.type, entry.listener);
174
+ call(entry.listener, this, event);
175
+ if (event._stopped) break;
176
+ }
177
+ const handler = this["on" + event.type];
178
+ if (typeof handler === "function" && !event._stopped) call(handler, this, event);
179
+ return !event.defaultPrevented;
180
+ }
181
+ }
182
+
183
+ function call(listener, self, event) {
184
+ try {
185
+ if (typeof listener === "function") listener.call(self, event);
186
+ else listener.handleEvent(event);
187
+ } catch (error) {
188
+ event._threw = true;
189
+ globalThis.reportError?.(error) ?? console.error(error);
190
+ }
191
+ }
192
+
193
+ class IDBEvent {
194
+ constructor(type, fields = {}) {
195
+ this.type = type;
196
+ this.target = null;
197
+ this.currentTarget = null;
198
+ this.defaultPrevented = false;
199
+ this._stopped = false;
200
+ this.bubbles = type === "error";
201
+ this.cancelable = type === "error";
202
+ this.timeStamp = Date.now();
203
+ Object.assign(this, fields);
204
+ }
205
+ preventDefault() { if (this.cancelable) this.defaultPrevented = true; }
206
+ stopPropagation() { this._stopped = true; }
207
+ stopImmediatePropagation() { this._stopped = true; }
208
+ }
209
+
210
+ export class IDBVersionChangeEvent extends IDBEvent {
211
+ constructor(type, init = {}) {
212
+ super(type, { oldVersion: init.oldVersion ?? 0, newVersion: init.newVersion ?? null });
213
+ }
214
+ }
215
+
216
+ export class IDBRequest extends Target {
217
+ constructor(source, transaction) {
218
+ super();
219
+ this.source = source;
220
+ this.transaction = transaction;
221
+ this.readyState = "pending";
222
+ this.onsuccess = null;
223
+ this.onerror = null;
224
+ this._result = undefined;
225
+ this._error = null;
226
+ }
227
+ get result() {
228
+ if (this.readyState !== "done") throw DOMError("InvalidStateError", "the request is not done");
229
+ return this._result;
230
+ }
231
+ get error() {
232
+ if (this.readyState !== "done") throw DOMError("InvalidStateError", "the request is not done");
233
+ return this._error;
234
+ }
235
+ }
236
+
237
+ export class IDBOpenDBRequest extends IDBRequest {
238
+ constructor() {
239
+ super(null, null);
240
+ this.onupgradeneeded = null;
241
+ this.onblocked = null;
242
+ }
243
+ }
244
+
245
+ function names(list) {
246
+ const sorted = [...list].sort();
247
+ return Object.assign(sorted, {
248
+ contains: (name) => sorted.includes(name),
249
+ item: (index) => sorted[index] ?? null,
250
+ });
251
+ }
252
+
253
+ // Stored data. A store keeps its records sorted by key.
254
+ class StoreData {
255
+ constructor(name, keyPath, autoIncrement) {
256
+ this.name = name;
257
+ this.keyPath = keyPath;
258
+ this.autoIncrement = autoIncrement;
259
+ this.current = 1;
260
+ this.records = [];
261
+ this.indexes = new Map();
262
+ }
263
+ find(key) {
264
+ let low = 0;
265
+ let high = this.records.length;
266
+ while (low < high) {
267
+ const middle = (low + high) >>> 1;
268
+ if (cmp(this.records[middle].key, key) < 0) low = middle + 1;
269
+ else high = middle;
270
+ }
271
+ return low;
272
+ }
273
+ get(key) {
274
+ const at = this.find(key);
275
+ const record = this.records[at];
276
+ return record && cmp(record.key, key) === 0 ? record : null;
277
+ }
278
+ inRange(range) {
279
+ if (!range) return this.records;
280
+ return this.records.filter((record) => range.includes(record.key));
281
+ }
282
+ }
283
+
284
+ class DatabaseData {
285
+ constructor(name) {
286
+ this.name = name;
287
+ this.version = 0;
288
+ this.stores = new Map();
289
+ this.connections = new Set();
290
+ }
291
+ }
292
+
293
+ const databases = new Map();
294
+ let loaded = false;
295
+
296
+ // Saving to files, on a runtime with node:fs and node:v8.
297
+ const fs = globalThis.process?.getBuiltinModule?.("node:fs");
298
+ const v8 = globalThis.process?.getBuiltinModule?.("node:v8");
299
+ const directory = fs && v8 ? storageDirectory()?.concat("/indexeddb") : null;
300
+
301
+ function fileOf(name) {
302
+ return directory + "/" + encodeURIComponent(name) + ".idb";
303
+ }
304
+
305
+ function loadAll() {
306
+ if (loaded) return;
307
+ loaded = true;
308
+ if (!directory) return;
309
+ let entries = [];
310
+ try {
311
+ entries = fs.readdirSync(directory).filter((entry) => entry.endsWith(".idb"));
312
+ } catch {
313
+ return;
314
+ }
315
+ for (const entry of entries) {
316
+ try {
317
+ const saved = v8.deserialize(fs.readFileSync(directory + "/" + entry));
318
+ const data = new DatabaseData(saved.name);
319
+ data.version = saved.version;
320
+ for (const store of saved.stores) {
321
+ const storeData = new StoreData(store.name, store.keyPath, store.autoIncrement);
322
+ storeData.current = store.current;
323
+ storeData.records = store.records;
324
+ for (const index of store.indexes) storeData.indexes.set(index.name, index);
325
+ data.stores.set(store.name, storeData);
326
+ }
327
+ databases.set(data.name, data);
328
+ } catch (error) {
329
+ console.warn("indexedDB: could not read " + entry + ": " + error.message);
330
+ }
331
+ }
332
+ }
333
+
334
+ const unsaveable = new Set();
335
+ function save(data) {
336
+ if (!directory) return;
337
+ try {
338
+ const bytes = v8.serialize({
339
+ name: data.name,
340
+ version: data.version,
341
+ stores: [...data.stores.values()].map((store) => ({
342
+ name: store.name,
343
+ keyPath: store.keyPath,
344
+ autoIncrement: store.autoIncrement,
345
+ current: store.current,
346
+ records: store.records,
347
+ indexes: [...store.indexes.values()],
348
+ })),
349
+ });
350
+ fs.mkdirSync(directory, { recursive: true });
351
+ fs.writeFileSync(fileOf(data.name) + ".tmp", bytes);
352
+ fs.renameSync(fileOf(data.name) + ".tmp", fileOf(data.name));
353
+ unsaveable.delete(data.name);
354
+ } catch (error) {
355
+ if (!unsaveable.has(data.name)) console.warn("indexedDB: '" + data.name + "' stays in memory: " + error.message);
356
+ unsaveable.add(data.name);
357
+ }
358
+ }
359
+
360
+ function remove(name) {
361
+ if (!directory) return;
362
+ try {
363
+ fs.rmSync(fileOf(name), { force: true });
364
+ } catch {}
365
+ }
366
+
367
+ export class IDBDatabase extends Target {
368
+ constructor(data) {
369
+ super();
370
+ this._data = data;
371
+ this._closed = false;
372
+ this._upgrade = null;
373
+ this.onabort = null;
374
+ this.onclose = null;
375
+ this.onerror = null;
376
+ this.onversionchange = null;
377
+ }
378
+ get name() { return this._data.name; }
379
+ get version() { return this._data.version; }
380
+ get objectStoreNames() { return names(this._data.stores.keys()); }
381
+
382
+ transaction(storeNames, mode = "readonly") {
383
+ if (this._closed) throw DOMError("InvalidStateError", "the database connection is closed");
384
+ if (this._upgrade?._active) throw DOMError("InvalidStateError", "a version change transaction is running");
385
+ const list = typeof storeNames === "string" ? [storeNames] : [...storeNames];
386
+ if (list.length === 0) throw DOMError("InvalidAccessError", "a transaction needs a store");
387
+ for (const name of list) if (!this._data.stores.has(name)) throw DOMError("NotFoundError", "no object store named '" + name + "'");
388
+ if (mode !== "readonly" && mode !== "readwrite") throw new TypeError("a transaction's mode is readonly or readwrite");
389
+ return new IDBTransaction(this, list, mode);
390
+ }
391
+
392
+ createObjectStore(name, options = {}) {
393
+ const upgrade = this._needsUpgrade();
394
+ name = String(name);
395
+ if (this._data.stores.has(name)) throw DOMError("ConstraintError", "an object store named '" + name + "' exists");
396
+ const keyPath = options.keyPath ?? null;
397
+ const autoIncrement = !!options.autoIncrement;
398
+ if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) throw DOMError("InvalidAccessError", "a key generator needs a key path of one name");
399
+ const store = new StoreData(name, keyPath, autoIncrement);
400
+ this._data.stores.set(name, store);
401
+ upgrade._undo.push(() => this._data.stores.delete(name));
402
+ upgrade._names.push(name);
403
+ return upgrade.objectStore(name);
404
+ }
405
+
406
+ deleteObjectStore(name) {
407
+ const upgrade = this._needsUpgrade();
408
+ const store = this._data.stores.get(name);
409
+ if (!store) throw DOMError("NotFoundError", "no object store named '" + name + "'");
410
+ this._data.stores.delete(name);
411
+ upgrade._undo.push(() => this._data.stores.set(name, store));
412
+ }
413
+
414
+ _needsUpgrade() {
415
+ if (!this._upgrade?._active) throw DOMError("InvalidStateError", "object stores change only in a version change transaction");
416
+ return this._upgrade;
417
+ }
418
+
419
+ close() {
420
+ if (this._closed) return;
421
+ this._closed = true;
422
+ this._data.connections.delete(this);
423
+ }
424
+ }
425
+
426
+ export class IDBTransaction extends Target {
427
+ constructor(db, storeNames, mode) {
428
+ super();
429
+ this.db = db;
430
+ this.mode = mode;
431
+ this.durability = "default";
432
+ this.error = null;
433
+ this.oncomplete = null;
434
+ this.onerror = null;
435
+ this.onabort = null;
436
+ this._names = storeNames;
437
+ this._requests = [];
438
+ this._undo = [];
439
+ this._active = true;
440
+ this._finished = false;
441
+ this._wrote = false;
442
+ this._running = false;
443
+ this._stores = new Map();
444
+ schedule(this);
445
+ }
446
+ get objectStoreNames() { return names(this._names); }
447
+
448
+ objectStore(name) {
449
+ if (this._finished) throw DOMError("InvalidStateError", "the transaction has finished");
450
+ if (!this._names.includes(name)) throw DOMError("NotFoundError", "the transaction does not cover '" + name + "'");
451
+ let store = this._stores.get(name);
452
+ if (!store) this._stores.set(name, (store = new IDBObjectStore(this, this.db._data.stores.get(name))));
453
+ return store;
454
+ }
455
+
456
+ abort() {
457
+ if (this._finished) throw DOMError("InvalidStateError", "the transaction has finished");
458
+ this._abort(DOMError("AbortError", "the transaction was aborted"), true);
459
+ }
460
+
461
+ commit() {
462
+ if (this._finished) throw DOMError("InvalidStateError", "the transaction has finished");
463
+ this._commitAsked = true;
464
+ }
465
+
466
+ _request(source, operation) {
467
+ if (this._finished || !this._active) throw DOMError("TransactionInactiveError", "the transaction is not active");
468
+ const request = new IDBRequest(source, this);
469
+ this._requests.push({ request, operation });
470
+ schedule(this);
471
+ return request;
472
+ }
473
+
474
+ _write(undo) {
475
+ if (this.mode === "readonly") throw DOMError("ReadOnlyError", "the transaction is read only");
476
+ this._wrote = true;
477
+ this._undo.push(undo);
478
+ }
479
+
480
+ _abort(error, explicit) {
481
+ if (this._finished) return;
482
+ this._finished = true;
483
+ this._active = false;
484
+ this.error = explicit ? null : error;
485
+ for (let i = this._undo.length - 1; i >= 0; i--) this._undo[i]();
486
+ this._undo = [];
487
+ for (const { request } of this._requests.splice(0)) {
488
+ request.readyState = "done";
489
+ request._error = DOMError("AbortError", "the transaction was aborted");
490
+ request.dispatchEvent(new IDBEvent("error"));
491
+ }
492
+ queueMicrotask(() => {
493
+ const event = new IDBEvent("abort", { target: this });
494
+ this.dispatchEvent(event);
495
+ this.db.dispatchEvent(Object.assign(new IDBEvent("abort"), { target: this }));
496
+ this._done?.(false);
497
+ });
498
+ }
499
+
500
+ _complete() {
501
+ this._finished = true;
502
+ this._active = false;
503
+ if (this._wrote || this.mode === "versionchange") save(this.db._data);
504
+ this.dispatchEvent(new IDBEvent("complete"));
505
+ this._done?.(true);
506
+ }
507
+ }
508
+
509
+ // A transaction runs its requests in order, in microtasks, and commits once a task passes
510
+ // with none left.
511
+ function schedule(transaction) {
512
+ if (transaction._running) return;
513
+ transaction._running = true;
514
+ queueMicrotask(() => run(transaction));
515
+ }
516
+
517
+ function run(transaction) {
518
+ transaction._running = false;
519
+ while (transaction._requests.length && !transaction._finished) {
520
+ const { request, operation } = transaction._requests.shift();
521
+ let result;
522
+ let error = null;
523
+ try {
524
+ result = operation();
525
+ } catch (thrown) {
526
+ error = thrown;
527
+ }
528
+ request.readyState = "done";
529
+ if (error) {
530
+ request._error = error;
531
+ const event = new IDBEvent("error");
532
+ request.dispatchEvent(event);
533
+ if (!event._stopped) {
534
+ event.currentTarget = null;
535
+ transaction.dispatchEvent(event);
536
+ if (!event._stopped) transaction.db.dispatchEvent(event);
537
+ }
538
+ if (!event.defaultPrevented || event._threw) transaction._abort(error, false);
539
+ } else {
540
+ request._result = result;
541
+ const event = new IDBEvent("success");
542
+ request.dispatchEvent(event);
543
+ if (event._threw) transaction._abort(DOMError("AbortError", "a success listener threw"), false);
544
+ }
545
+ }
546
+ if (transaction._finished) return;
547
+ // Requests queued by promise code after this one keep the transaction going.
548
+ setTimeout(() => {
549
+ if (transaction._finished) return;
550
+ if (transaction._requests.length) return run(transaction);
551
+ transaction._complete();
552
+ }, 0);
553
+ }
554
+
555
+ export class IDBObjectStore {
556
+ constructor(transaction, data) {
557
+ this.transaction = transaction;
558
+ this._data = data;
559
+ }
560
+ get name() { return this._data.name; }
561
+ get keyPath() { return this._data.keyPath; }
562
+ get autoIncrement() { return this._data.autoIncrement; }
563
+ get indexNames() { return names(this._data.indexes.keys()); }
564
+
565
+ put(value, key) { return this._store(value, key, false); }
566
+ add(value, key) { return this._store(value, key, true); }
567
+
568
+ _store(value, key, add) {
569
+ const store = this._data;
570
+ const transaction = this.transaction;
571
+ if (transaction.mode === "readonly") throw DOMError("ReadOnlyError", "the transaction is read only");
572
+ if (store.keyPath !== null && key !== undefined) throw DOMError("DataError", "a store with a key path takes no key");
573
+ if (store.keyPath === null && !store.autoIncrement && key === undefined) throw DOMError("DataError", "the store needs a key");
574
+ const copy = clone(value);
575
+ if (key !== undefined) checkKey(key);
576
+ let inline = store.keyPath !== null ? valueAtPath(copy, store.keyPath) : undefined;
577
+ if (store.keyPath !== null && inline !== undefined) checkKey(inline);
578
+ if (store.keyPath !== null && inline === undefined && !store.autoIncrement) throw DOMError("DataError", "the value has no key at the store's key path");
579
+ return transaction._request(this, () => {
580
+ let primary = key ?? inline;
581
+ if (primary === undefined) {
582
+ primary = store.current++;
583
+ if (store.keyPath !== null) setAtPath(copy, store.keyPath, primary);
584
+ const current = store.current - 1;
585
+ transaction._write(() => { if (store.current === current + 1) store.current = current; });
586
+ } else if (store.autoIncrement && typeof primary === "number" && primary >= store.current) {
587
+ const before = store.current;
588
+ store.current = Math.floor(primary) + 1;
589
+ transaction._write(() => { store.current = before; });
590
+ }
591
+ primary = copyKey(primary);
592
+ const at = store.find(primary);
593
+ const existing = store.records[at];
594
+ const same = existing && cmp(existing.key, primary) === 0;
595
+ if (same && add) throw DOMError("ConstraintError", "a record with the key exists");
596
+ for (const index of store.indexes.values()) {
597
+ if (!index.unique) continue;
598
+ for (const indexKey of indexKeys(index, copy)) {
599
+ const clash = store.records.find((record) => cmp(record.key, primary) !== 0 && indexKeys(index, record.value).some((other) => cmp(other, indexKey) === 0));
600
+ if (clash) throw DOMError("ConstraintError", "the index '" + index.name + "' is unique");
601
+ }
602
+ }
603
+ const record = { key: primary, value: copy };
604
+ if (same) {
605
+ store.records[at] = record;
606
+ transaction._write(() => { store.records[store.find(primary)] = existing; });
607
+ } else {
608
+ store.records.splice(at, 0, record);
609
+ transaction._write(() => store.records.splice(store.find(primary), 1));
610
+ }
611
+ return copyKey(primary);
612
+ });
613
+ }
614
+
615
+ delete(query) {
616
+ const store = this._data;
617
+ const transaction = this.transaction;
618
+ if (transaction.mode === "readonly") throw DOMError("ReadOnlyError", "the transaction is read only");
619
+ const range = rangeOf(query);
620
+ return transaction._request(this, () => {
621
+ const kept = [];
622
+ const removed = [];
623
+ for (const record of store.records) (range.includes(record.key) ? removed : kept).push(record);
624
+ if (removed.length) {
625
+ const before = store.records;
626
+ store.records = kept;
627
+ transaction._write(() => { store.records = before; });
628
+ }
629
+ return undefined;
630
+ });
631
+ }
632
+
633
+ clear() {
634
+ const store = this._data;
635
+ const transaction = this.transaction;
636
+ if (transaction.mode === "readonly") throw DOMError("ReadOnlyError", "the transaction is read only");
637
+ return transaction._request(this, () => {
638
+ const before = store.records;
639
+ store.records = [];
640
+ transaction._write(() => { store.records = before; });
641
+ return undefined;
642
+ });
643
+ }
644
+
645
+ get(query) {
646
+ const range = rangeOf(query);
647
+ return this.transaction._request(this, () => {
648
+ const record = this._data.inRange(range)[0];
649
+ return record ? clone(record.value) : undefined;
650
+ });
651
+ }
652
+
653
+ getKey(query) {
654
+ const range = rangeOf(query);
655
+ return this.transaction._request(this, () => copyKey(this._data.inRange(range)[0]?.key));
656
+ }
657
+
658
+ getAll(query, count) {
659
+ const range = rangeOf(query);
660
+ return this.transaction._request(this, () => limit(this._data.inRange(range), count).map((record) => clone(record.value)));
661
+ }
662
+
663
+ getAllKeys(query, count) {
664
+ const range = rangeOf(query);
665
+ return this.transaction._request(this, () => limit(this._data.inRange(range), count).map((record) => copyKey(record.key)));
666
+ }
667
+
668
+ count(query) {
669
+ const range = rangeOf(query);
670
+ return this.transaction._request(this, () => this._data.inRange(range).length);
671
+ }
672
+
673
+ openCursor(query, direction = "next") {
674
+ return openCursor(this, () => this._data.inRange(rangeOf(query)).map((record) => ({ key: record.key, primaryKey: record.key, record })), direction, true);
675
+ }
676
+
677
+ openKeyCursor(query, direction = "next") {
678
+ return openCursor(this, () => this._data.inRange(rangeOf(query)).map((record) => ({ key: record.key, primaryKey: record.key, record })), direction, false);
679
+ }
680
+
681
+ index(name) {
682
+ const index = this._data.indexes.get(name);
683
+ if (!index) throw DOMError("NotFoundError", "no index named '" + name + "'");
684
+ return new IDBIndex(this, index);
685
+ }
686
+
687
+ createIndex(name, keyPath, options = {}) {
688
+ const upgrade = this.transaction.db._needsUpgrade();
689
+ if (this._data.indexes.has(name)) throw DOMError("ConstraintError", "an index named '" + name + "' exists");
690
+ const index = { name: String(name), keyPath, unique: !!options.unique, multiEntry: !!options.multiEntry };
691
+ this._data.indexes.set(index.name, index);
692
+ upgrade._undo.push(() => this._data.indexes.delete(index.name));
693
+ return new IDBIndex(this, index);
694
+ }
695
+
696
+ deleteIndex(name) {
697
+ const upgrade = this.transaction.db._needsUpgrade();
698
+ const index = this._data.indexes.get(name);
699
+ if (!index) throw DOMError("NotFoundError", "no index named '" + name + "'");
700
+ this._data.indexes.delete(name);
701
+ upgrade._undo.push(() => this._data.indexes.set(name, index));
702
+ }
703
+ }
704
+
705
+ function limit(records, count) {
706
+ return count === undefined || count === 0 ? records : records.slice(0, count >>> 0);
707
+ }
708
+
709
+ function indexKeys(index, value) {
710
+ const key = valueAtPath(value, index.keyPath);
711
+ if (key === undefined) return [];
712
+ if (index.multiEntry && Array.isArray(key)) {
713
+ const keys = [];
714
+ for (const each of key) if (validKey(each) && !keys.some((other) => cmp(other, each) === 0)) keys.push(each);
715
+ return keys;
716
+ }
717
+ return validKey(key) ? [key] : [];
718
+ }
719
+
720
+ export class IDBIndex {
721
+ constructor(store, data) {
722
+ this.objectStore = store;
723
+ this._data = data;
724
+ }
725
+ get name() { return this._data.name; }
726
+ get keyPath() { return this._data.keyPath; }
727
+ get unique() { return this._data.unique; }
728
+ get multiEntry() { return this._data.multiEntry; }
729
+
730
+ _entries(query) {
731
+ const range = rangeOf(query);
732
+ const entries = [];
733
+ for (const record of this.objectStore._data.records) {
734
+ for (const key of indexKeys(this._data, record.value)) {
735
+ if (!range || range.includes(key)) entries.push({ key, primaryKey: record.key, record });
736
+ }
737
+ }
738
+ return entries.sort((a, b) => cmp(a.key, b.key) || cmp(a.primaryKey, b.primaryKey));
739
+ }
740
+
741
+ get(query) {
742
+ return this.objectStore.transaction._request(this, () => {
743
+ const entry = this._entries(query)[0];
744
+ return entry ? clone(entry.record.value) : undefined;
745
+ });
746
+ }
747
+ getKey(query) {
748
+ return this.objectStore.transaction._request(this, () => copyKey(this._entries(query)[0]?.primaryKey));
749
+ }
750
+ getAll(query, count) {
751
+ return this.objectStore.transaction._request(this, () => limit(this._entries(query), count).map((entry) => clone(entry.record.value)));
752
+ }
753
+ getAllKeys(query, count) {
754
+ return this.objectStore.transaction._request(this, () => limit(this._entries(query), count).map((entry) => copyKey(entry.primaryKey)));
755
+ }
756
+ count(query) {
757
+ return this.objectStore.transaction._request(this, () => this._entries(query).length);
758
+ }
759
+ openCursor(query, direction = "next") {
760
+ return openCursor(this, () => this._entries(query), direction, true);
761
+ }
762
+ openKeyCursor(query, direction = "next") {
763
+ return openCursor(this, () => this._entries(query), direction, false);
764
+ }
765
+ }
766
+
767
+ export class IDBCursor {
768
+ constructor(source, request, entries, direction) {
769
+ this.source = source;
770
+ this.request = request;
771
+ this.direction = direction;
772
+ this._entries = entries;
773
+ this._at = -1;
774
+ this._entry = null;
775
+ }
776
+ get key() { return copyKey(this._entry?.key); }
777
+ get primaryKey() { return copyKey(this._entry?.primaryKey); }
778
+
779
+ _store() {
780
+ return this.source instanceof IDBIndex ? this.source.objectStore : this.source;
781
+ }
782
+
783
+ _advance(count, until) {
784
+ const transaction = this._store().transaction;
785
+ const request = this.request;
786
+ request.readyState = "pending";
787
+ transaction._requests.push({
788
+ request,
789
+ operation: () => {
790
+ let left = count;
791
+ while (++this._at < this._entries.length) {
792
+ const entry = this._entries[this._at];
793
+ // A record deleted since the cursor opened is skipped.
794
+ if (!this._store()._data.get(entry.primaryKey)) continue;
795
+ if (until !== undefined && cmp(entry.key, until) * (this.direction.startsWith("prev") ? -1 : 1) < 0) continue;
796
+ if (--left > 0) continue;
797
+ this._entry = entry;
798
+ return this;
799
+ }
800
+ this._entry = null;
801
+ return null;
802
+ },
803
+ });
804
+ schedule(transaction);
805
+ }
806
+
807
+ continue(key) {
808
+ if (key !== undefined) checkKey(key);
809
+ this._advance(1, key);
810
+ }
811
+ advance(count) {
812
+ if (!(count > 0)) throw new TypeError("advance takes a count above 0");
813
+ this._advance(count >>> 0);
814
+ }
815
+ continuePrimaryKey(key, primaryKey) {
816
+ checkKey(key);
817
+ checkKey(primaryKey);
818
+ const transaction = this._store().transaction;
819
+ this.request.readyState = "pending";
820
+ transaction._requests.push({
821
+ request: this.request,
822
+ operation: () => {
823
+ while (++this._at < this._entries.length) {
824
+ const entry = this._entries[this._at];
825
+ const order = cmp(entry.key, key) || cmp(entry.primaryKey, primaryKey);
826
+ if ((this.direction.startsWith("prev") ? -order : order) < 0) continue;
827
+ this._entry = entry;
828
+ return this;
829
+ }
830
+ this._entry = null;
831
+ return null;
832
+ },
833
+ });
834
+ schedule(transaction);
835
+ }
836
+ update(value) {
837
+ const store = this._store();
838
+ if (store.keyPath !== null) return store.put(value);
839
+ return store.put(value, this._entry.primaryKey);
840
+ }
841
+ delete() {
842
+ return this._store().delete(this._entry.primaryKey);
843
+ }
844
+ }
845
+
846
+ export class IDBCursorWithValue extends IDBCursor {
847
+ get value() {
848
+ return this._entry ? clone(this._entry.record.value) : undefined;
849
+ }
850
+ }
851
+
852
+ function openCursor(source, list, direction, withValue) {
853
+ const store = source instanceof IDBIndex ? source.objectStore : source;
854
+ const transaction = store.transaction;
855
+ const request = transaction._request(source, () => {
856
+ let entries = list();
857
+ if (direction.startsWith("prev")) entries = entries.reverse();
858
+ if (direction.endsWith("unique")) entries = entries.filter((entry, i) => i === 0 || cmp(entry.key, entries[i - 1].key) !== 0);
859
+ cursor._entries = entries;
860
+ cursor._at = -1;
861
+ return cursor._step();
862
+ });
863
+ const cursor = new (withValue ? IDBCursorWithValue : IDBCursor)(source, request, [], direction);
864
+ cursor._step = () => {
865
+ while (++cursor._at < cursor._entries.length) {
866
+ const entry = cursor._entries[cursor._at];
867
+ if (!store._data.get(entry.primaryKey)) continue;
868
+ cursor._entry = entry;
869
+ return cursor;
870
+ }
871
+ cursor._entry = null;
872
+ return null;
873
+ };
874
+ return request;
875
+ }
876
+
877
+ export class IDBFactory {
878
+ open(name, version) {
879
+ if (version !== undefined && (!Number.isInteger(Number(version)) || Number(version) < 1)) throw new TypeError("a database version is a whole number above 0");
880
+ name = String(name);
881
+ const request = new IDBOpenDBRequest();
882
+ setTimeout(() => openDatabase(request, name, version === undefined ? undefined : Number(version)), 0);
883
+ return request;
884
+ }
885
+
886
+ deleteDatabase(name) {
887
+ name = String(name);
888
+ const request = new IDBOpenDBRequest();
889
+ setTimeout(() => {
890
+ loadAll();
891
+ const data = databases.get(name);
892
+ const oldVersion = data?.version ?? 0;
893
+ if (data) for (const connection of [...data.connections]) connection.dispatchEvent(new IDBVersionChangeEvent("versionchange", { oldVersion, newVersion: null }));
894
+ databases.delete(name);
895
+ remove(name);
896
+ request.readyState = "done";
897
+ request._result = undefined;
898
+ request.dispatchEvent(new IDBVersionChangeEvent("success", { oldVersion, newVersion: null }));
899
+ }, 0);
900
+ return request;
901
+ }
902
+
903
+ databases() {
904
+ loadAll();
905
+ return Promise.resolve([...databases.values()].map((data) => ({ name: data.name, version: data.version })));
906
+ }
907
+
908
+ cmp(a, b) {
909
+ return cmp(checkKey(a), checkKey(b));
910
+ }
911
+ }
912
+
913
+ function openDatabase(request, name, version) {
914
+ loadAll();
915
+ let data = databases.get(name);
916
+ if (!data) databases.set(name, (data = new DatabaseData(name)));
917
+ const oldVersion = data.version;
918
+ const newVersion = version ?? (oldVersion || 1);
919
+ if (newVersion < oldVersion) {
920
+ request.readyState = "done";
921
+ request._error = DOMError("VersionError", "the database is at version " + oldVersion);
922
+ request.dispatchEvent(new IDBEvent("error"));
923
+ return;
924
+ }
925
+ const db = new IDBDatabase(data);
926
+ const succeed = () => {
927
+ data.connections.add(db);
928
+ request.readyState = "done";
929
+ request._result = db;
930
+ request.transaction = null;
931
+ request.dispatchEvent(new IDBEvent("success"));
932
+ };
933
+ if (newVersion === oldVersion) return succeed();
934
+ for (const connection of [...data.connections]) {
935
+ connection.dispatchEvent(new IDBVersionChangeEvent("versionchange", { oldVersion, newVersion }));
936
+ }
937
+ const upgrade = new IDBTransaction(db, [...data.stores.keys()], "versionchange");
938
+ db._upgrade = upgrade;
939
+ data.version = newVersion;
940
+ upgrade._undo.push(() => { data.version = oldVersion; });
941
+ request.readyState = "done";
942
+ request._result = db;
943
+ request.transaction = upgrade;
944
+ upgrade._done = (committed) => {
945
+ db._upgrade = null;
946
+ request.transaction = null;
947
+ if (committed) succeed();
948
+ else {
949
+ if (oldVersion === 0 && data.stores.size === 0) databases.delete(name);
950
+ request._result = undefined;
951
+ request._error = DOMError("AbortError", "the version change transaction was aborted");
952
+ request.dispatchEvent(new IDBEvent("error"));
953
+ }
954
+ };
955
+ const event = new IDBVersionChangeEvent("upgradeneeded", { oldVersion, newVersion });
956
+ request.dispatchEvent(event);
957
+ if (event._threw) upgrade._abort(DOMError("AbortError", "an upgradeneeded listener threw"), false);
958
+ }
959
+
960
+ export function indexedDBModule() {
961
+ return {
962
+ indexedDB: new IDBFactory(),
963
+ IDBFactory,
964
+ IDBDatabase,
965
+ IDBTransaction,
966
+ IDBObjectStore,
967
+ IDBIndex,
968
+ IDBRequest,
969
+ IDBOpenDBRequest,
970
+ IDBKeyRange,
971
+ IDBCursor,
972
+ IDBCursorWithValue,
973
+ IDBVersionChangeEvent,
974
+ };
975
+ }