plateaudb 0.1.0 → 0.2.0

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/README.md CHANGED
@@ -6,7 +6,7 @@ It keeps a compressed bitmap of row ids for each value of a field you declare, s
6
6
  filters on several fields (`team = 7 AND state IN (1, 2) ORDER BY updatedAt DESC LIMIT 50`) costs
7
7
  roughly the size of its result, not the size of the table.
8
8
 
9
- Status: 0.1.0, pre-1.0. Read [Known limits](#known-limits) before you put data in it that you
9
+ Status: 0.2.0, pre-1.0. Read [Known limits](#known-limits) before you put data in it that you
10
10
  cannot rebuild.
11
11
 
12
12
  ## Install
@@ -131,6 +131,49 @@ await plateau.whenLeader(); // resolves when this tab is the leader, e.g. to h
131
131
  const stop = db.observe("orders", ({ stores }) => render()); // after a commit in any tab
132
132
  ```
133
133
 
134
+ ## Where plateau cannot run: the IndexedDB fallback
135
+
136
+ Where the engine cannot run, `plateau` hands every call to the browser's own `indexedDB`, so code
137
+ written against it keeps working. It falls back when the browser has no OPFS
138
+ (`navigator.storage.getDirectory`), no `Worker` or no WebAssembly, or when the worker cannot start
139
+ the engine or open an OPFS sync access handle: a WebKit ephemeral session (Playwright's default
140
+ context) fails there with `UnknownError`, as do browsers without module workers,
141
+ `FileSystemSyncAccessHandle` or WebAssembly SIMD.
142
+
143
+ The backend is chosen once per page, at the first call that needs storage (`open`,
144
+ `deleteDatabase`, `databases`, `setMemoryBudget`, `memoryStats`), and never changes after that.
145
+ `open` still returns its request at once; the request fires its events when the choice is made.
146
+
147
+ ```js
148
+ plateau.backend; // "opfs" or "indexeddb"; undefined before the choice
149
+ const backend = await plateau.chooseBackend(); // chooses now if no call has yet
150
+ ```
151
+
152
+ To skip the check, start the runtime before the first call with the backend you want:
153
+ `startRuntime({ backend: "indexeddb" })` (always the browser's IndexedDB) or
154
+ `startRuntime({ backend: "opfs" })` (never fall back; opening fails where OPFS does). Every tab of
155
+ the origin should ask for the same one.
156
+
157
+ On the fallback:
158
+
159
+ - **Data is separate.** What one backend wrote is not visible on the other. A browser that gains
160
+ OPFS support later starts on an empty plateau database; the old data stays in its IndexedDB.
161
+ - The objects are the browser's own (`IDBDatabase`, `IDBObjectStore`, ...), with plateau's calls
162
+ added to them. `PlateauKeyRange` returns the browser's `IDBKeyRange`; create key ranges after the
163
+ first `open`, since a range made before the backend is chosen is plateau's own and the browser
164
+ does not take it.
165
+ - `createObjectStore(name, { columns })` works; the browser ignores `columns`, so a field of the
166
+ wrong kind is stored instead of throwing `DataError`.
167
+ - `store.query` returns what plateau's engine returns for the same records, read from the store
168
+ (an `eq` filter on a field with a `multiEntry` index reads only that index's records), so it
169
+ costs the size of the store, not of the result. It also runs on stores without `columns`;
170
+ `request.plan` is `scan` or `index:<name>`.
171
+ - `db.observe` calls back in every tab after a readwrite transaction that opened one of the
172
+ observed stores commits, whether or not it wrote to it.
173
+ - `db.compact()` and `plateau.setMemoryBudget()` do nothing; `plateau.memoryStats()` reports zeros
174
+ and the budget last set. `plateau.whenLeader()` works as on OPFS.
175
+ - `plateau.databases()` returns the browser's list.
176
+
134
177
  ## Memory budget
135
178
 
136
179
  The worker keeps the parts of each file it has read in memory up to a budget, and drops the least
@@ -153,21 +196,28 @@ so `memoryStats` reports the peak.
153
196
  Measured with Playwright on macOS: Chromium 158 and WebKit 27.2. Firefox is not measured
154
197
  (Playwright's Firefox did not launch on the test machine), so treat it as unknown.
155
198
 
156
- plateau needs OPFS with `FileSystemSyncAccessHandle` in a dedicated worker, module workers, and
157
- WebAssembly SIMD (Chrome 91+, Safari 16.4+, Firefox 89+ ship SIMD).
199
+ plateau's engine needs OPFS with `FileSystemSyncAccessHandle` in a dedicated worker, module
200
+ workers, and WebAssembly SIMD (Chrome 91+, Safari 16.4+, Firefox 89+ ship SIMD). Elsewhere it runs
201
+ on the browser's IndexedDB (see [the fallback](#where-plateau-cannot-run-the-indexeddb-fallback)).
158
202
 
159
- In a WebKit ephemeral session (Playwright's default, non-persistent context) opening a database
160
- fails with `UnknownError`; with a persistent profile it works. Private browsing modes are not
161
- measured.
203
+ In a WebKit ephemeral session (Playwright's default, non-persistent context) OPFS is not available,
204
+ so plateau runs on the fallback; with a persistent profile it runs on OPFS. Measured with
205
+ Playwright: on the fallback, 85 of 85 conformance tests pass in Chromium and WebKit, with OPFS,
206
+ `Worker` or WebAssembly removed, the WASM failing to compile, the worker failing to load, and in a
207
+ WebKit ephemeral context. Private browsing modes are not measured.
162
208
 
163
209
  ## Known limits
164
210
 
165
- - **Conformance: 84 of 85** WPT-style IndexedDB tests pass in Chromium and WebKit, against 85 of
166
- 85 for native IndexedDB. The one difference: a key stored as `-0` comes back as `0`.
167
- - **No fallback to native IndexedDB.** Where OPFS or its sync access handle is missing, plateau
168
- does not switch to `window.indexedDB` for you.
211
+ - **Conformance: 84 of 85** WPT-style IndexedDB tests pass in Chromium and WebKit on OPFS, against
212
+ 85 of 85 for native IndexedDB. The one difference: a key stored as `-0` comes back as `0`. On the
213
+ IndexedDB fallback all 85 pass.
214
+ - **The fallback's data is separate** from OPFS data, and its `store.query` scans the store (see
215
+ [the fallback](#where-plateau-cannot-run-the-indexeddb-fallback)).
216
+ - **First open:** the page's first call waits for the worker to check that it can open an OPFS
217
+ file before the database opens: about 1 ms more to the first open on a fresh page (medians of
218
+ 10 page loads: Chromium 10.2 ms against 9.6 ms without the check, WebKit 15.0 ms against 14.0 ms).
169
219
  - **Values:** `Blob`, `File`, `ImageData` and `Error` values throw `DataCloneError`.
170
- - `plateau.databases()` returns an empty list.
220
+ - `plateau.databases()` returns an empty list on OPFS.
171
221
  - **Start-up:** the first query on a fresh page load costs more than native IndexedDB, because the
172
222
  worker starts and the WASM compiles (measured through the API at 1M rows in Chromium: 8-13 ms
173
223
  against native 4-5 ms). Reopening and warm queries are faster than native.
@@ -0,0 +1,8 @@
1
+ export type Backend = "opfs" | "indexeddb";
2
+ /** The browser's IndexedDB as it was when plateau loaded, before an app could replace it. */
3
+ export declare const nativeIndexedDB: IDBFactory | undefined;
4
+ /** The backend, once chosen. */
5
+ export declare function chosenBackend(): Backend | undefined;
6
+ /** Chooses the backend if no call has yet, and resolves with it. Synchronous when nothing needs a
7
+ * probe (a requested backend, or something missing on the main thread). */
8
+ export declare function chooseBackend(): Promise<Backend>;
package/dist/facade.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type Backend } from "./backend";
1
2
  import { PlateauEvent, PlateauTarget, PlateauVersionChangeEvent } from "./events";
2
3
  import { PlateauKeyRange, type Key, type KeyPath, type WireRange } from "./key";
3
4
  import type { CursorHit, Direction, IndexDef, MemoryStats, Op, PutRow, StoreDef, TxReply } from "./protocol";
@@ -47,9 +48,19 @@ interface Observer {
47
48
  callback: (change: PlateauChange) => void;
48
49
  }
49
50
  export declare class PlateauFactory {
51
+ /** Which backend runs this page's databases: `"opfs"` (plateau's engine) or `"indexeddb"` (the
52
+ * browser's own, where the engine cannot run); undefined until the first call that needs storage
53
+ * chooses it. It never changes after that. */
54
+ get backend(): Backend | undefined;
55
+ /** Chooses the backend now if no call has yet, and resolves with it. */
56
+ chooseBackend(): Promise<Backend>;
50
57
  open(name: string, version?: number): PlateauOpenDBRequest;
51
58
  deleteDatabase(name: string): PlateauOpenDBRequest;
59
+ /** @internal */
60
+ private deleteHere;
52
61
  cmp(a: unknown, b: unknown): number;
62
+ /** On the IndexedDB fallback, the browser's list; plateau's engine does not list its databases yet
63
+ * and resolves with an empty list. */
53
64
  databases(): Promise<{
54
65
  name: string;
55
66
  version: number;
@@ -64,7 +75,8 @@ export declare class PlateauFactory {
64
75
  * less. */
65
76
  setMemoryBudget(bytes: number | null): Promise<void>;
66
77
  /** plateau's own: the runtime's WASM memory (its peak: WASM memory never shrinks), the budget,
67
- * the bytes loaded sections hold, and the file sizes of database `name` if it is open. */
78
+ * the bytes loaded sections hold, and the file sizes of database `name` if it is open. On the
79
+ * IndexedDB fallback there is no engine: zeros, and the budget last set. */
68
80
  memoryStats(name?: string): Promise<MemoryStats>;
69
81
  }
70
82
  export declare class PlateauDatabase extends PlateauTarget {
@@ -0,0 +1,3 @@
1
+ /** Adds plateau's calls to the connection and the upgrade transaction an open request delivers,
2
+ * before the app's listeners see them. */
3
+ export declare function instrumentOpen(r: IDBOpenDBRequest): void;
@@ -1139,7 +1139,12 @@ class Decoder {
1139
1139
  // src/host.worker.ts
1140
1140
  var memory = null;
1141
1141
  var markReady = () => {};
1142
- var wasmReady = new Promise((resolve) => markReady = resolve);
1142
+ var markFailed = () => {};
1143
+ var wasmReady = new Promise((resolve, reject) => {
1144
+ markReady = resolve;
1145
+ markFailed = reject;
1146
+ });
1147
+ wasmReady.catch(() => {});
1143
1148
  var encoder = new TextEncoder;
1144
1149
 
1145
1150
  class IdbError extends Error {
@@ -2120,8 +2125,24 @@ async function host(name) {
2120
2125
  await h.open();
2121
2126
  return h;
2122
2127
  }
2128
+ var probed = null;
2129
+ function probe() {
2130
+ probed ??= (async () => {
2131
+ await wasmReady;
2132
+ try {
2133
+ const access = await lockFile(await rootDir(), "probe");
2134
+ access.close();
2135
+ } catch (e) {
2136
+ throw new IdbError("NotSupportedError", `plateau: OPFS sync access is not available here: ${e?.name ?? ""} ${e?.message ?? String(e)}`.trim());
2137
+ }
2138
+ })();
2139
+ return probed;
2140
+ }
2123
2141
  async function call(m) {
2124
2142
  switch (m.t) {
2143
+ case "probe":
2144
+ await probe();
2145
+ return null;
2125
2146
  case "open": {
2126
2147
  const h = await host(m.db);
2127
2148
  if (h.closeTimer !== null)
@@ -2316,7 +2337,14 @@ function drain() {
2316
2337
  self.onmessage = (e) => {
2317
2338
  const m = e.data;
2318
2339
  if (m.t === "init") {
2319
- memory = initSync({ module: m.module }).memory;
2340
+ try {
2341
+ memory = initSync({ module: m.module }).memory;
2342
+ } catch (e) {
2343
+ const message = `plateau: the engine does not start here: ${e instanceof Error ? e.message : String(e)}`;
2344
+ markFailed(new IdbError("NotSupportedError", message));
2345
+ post({ t: "init", error: message });
2346
+ return;
2347
+ }
2320
2348
  setMemoryBudget(defaultBudget());
2321
2349
  markReady();
2322
2350
  post({ t: "init" });
package/dist/index.d.ts CHANGED
@@ -4,3 +4,4 @@ export { PlateauEvent, PlateauVersionChangeEvent } from "./events";
4
4
  export { startRuntime, runtime, type RuntimeOptions } from "./runtime";
5
5
  export { encodeValue, decodeValue } from "./value";
6
6
  export type { ColumnDecl, ColumnKind, MemoryStats } from "./protocol";
7
+ export type { Backend } from "./backend";
package/dist/index.js CHANGED
@@ -1,231 +1,3 @@
1
- // src/events.ts
2
- class PlateauEvent {
3
- type;
4
- bubbles;
5
- cancelable;
6
- isTrusted = true;
7
- target = null;
8
- currentTarget = null;
9
- eventPhase = 0;
10
- defaultPrevented = false;
11
- stopped = false;
12
- stoppedNow = false;
13
- constructor(type, init = {}) {
14
- this.type = type;
15
- this.bubbles = !!init.bubbles;
16
- this.cancelable = !!init.cancelable;
17
- }
18
- preventDefault() {
19
- if (this.cancelable)
20
- this.defaultPrevented = true;
21
- }
22
- stopPropagation() {
23
- this.stopped = true;
24
- }
25
- stopImmediatePropagation() {
26
- this.stopped = true;
27
- this.stoppedNow = true;
28
- }
29
- get timeStamp() {
30
- return performance.now();
31
- }
32
- get cancelBubble() {
33
- return this.stopped;
34
- }
35
- get returnValue() {
36
- return !this.defaultPrevented;
37
- }
38
- }
39
-
40
- class PlateauVersionChangeEvent extends PlateauEvent {
41
- oldVersion;
42
- newVersion;
43
- constructor(type, init = {}) {
44
- super(type);
45
- this.oldVersion = init.oldVersion ?? 0;
46
- this.newVersion = init.newVersion ?? null;
47
- }
48
- }
49
-
50
- class PlateauTarget {
51
- entries = null;
52
- slots = null;
53
- parentTarget() {
54
- return null;
55
- }
56
- addEventListener(type, fn, opts) {
57
- if (!fn)
58
- return;
59
- const capture = typeof opts === "boolean" ? opts : !!opts?.capture;
60
- const once = typeof opts === "object" && !!opts?.once;
61
- this.entries ??= [];
62
- if (this.entries.some((e) => !e.removed && e.type === type && e.fn === fn && e.capture === capture))
63
- return;
64
- this.entries.push({ type, capture, once, fn });
65
- }
66
- removeEventListener(type, fn, opts) {
67
- const capture = typeof opts === "boolean" ? opts : !!opts?.capture;
68
- if (!this.entries)
69
- return;
70
- const i = this.entries.findIndex((e) => !e.removed && e.type === type && e.fn === fn && e.capture === capture);
71
- if (i >= 0) {
72
- this.entries[i].removed = true;
73
- this.entries.splice(i, 1);
74
- }
75
- }
76
- getHandler(type) {
77
- return this.slots?.[type] ?? null;
78
- }
79
- setHandler(type, fn) {
80
- const f = typeof fn === "function" ? fn : null;
81
- this.entries ??= [];
82
- this.slots ??= {};
83
- if (f) {
84
- let has = false;
85
- for (const e of this.entries)
86
- if (e.slot === type)
87
- has = true;
88
- if (!has)
89
- this.entries.push({ type, capture: false, once: false, fn: null, slot: type });
90
- } else {
91
- const i = this.entries.findIndex((e) => e.slot === type);
92
- if (i >= 0) {
93
- this.entries[i].removed = true;
94
- this.entries.splice(i, 1);
95
- }
96
- }
97
- this.slots[type] = f;
98
- }
99
- hasListeners() {
100
- return this.entries !== null && this.entries.length > 0;
101
- }
102
- listensOnPath(type, bubbles) {
103
- const entries = this.entries;
104
- if (entries === null)
105
- return false;
106
- for (const e of entries)
107
- if (e.type === type && (bubbles || e.capture))
108
- return true;
109
- return false;
110
- }
111
- dispatchEvent(e) {
112
- dispatch(this, e);
113
- return !e.defaultPrevented;
114
- }
115
- invoke(e, phase, out) {
116
- const entries = this.entries;
117
- if (entries === null || entries.length === 0)
118
- return;
119
- let only = null;
120
- let matches = 0;
121
- for (const x of entries) {
122
- if (x.type === e.type) {
123
- matches++;
124
- only = x;
125
- }
126
- }
127
- if (matches === 0)
128
- return;
129
- if (matches !== 1)
130
- only = null;
131
- if (only !== null && only.slot !== undefined && phase !== "capture") {
132
- const fn = this.slots[only.slot];
133
- if (fn) {
134
- try {
135
- fn.call(this, e);
136
- } catch (err) {
137
- out.threw = true;
138
- report(err);
139
- }
140
- }
141
- return;
142
- }
143
- const list = entries.filter((x) => x.type === e.type && (phase === "target" || x.capture === (phase === "capture")));
144
- for (const x of list) {
145
- if (x.removed)
146
- continue;
147
- if (x.once)
148
- this.removeEventListener(x.type, x.fn, x.capture);
149
- const fn = x.slot ? this.slots[x.slot] : x.fn;
150
- if (!fn)
151
- continue;
152
- try {
153
- if (typeof fn === "function")
154
- fn.call(this, e);
155
- else
156
- fn.handleEvent(e);
157
- } catch (err) {
158
- out.threw = true;
159
- report(err);
160
- }
161
- if (e.stoppedNow)
162
- break;
163
- }
164
- }
165
- }
166
- function report(err) {
167
- const g = globalThis;
168
- if (g.reportError)
169
- g.reportError(err);
170
- else
171
- setTimeout(() => {
172
- throw err;
173
- });
174
- }
175
- function dispatch(target, e) {
176
- const p1 = target.parentTarget();
177
- const p2 = p1 === null ? null : p1.parentTarget();
178
- if ((p2 === null || p2.parentTarget() === null) && (p1 === null || !p1.listensOnPath(e.type, e.bubbles)) && (p2 === null || !p2.listensOnPath(e.type, e.bubbles))) {
179
- const out = { threw: false };
180
- e.target = target;
181
- e.eventPhase = 2;
182
- e.currentTarget = target;
183
- target.invoke(e, "target", out);
184
- e.eventPhase = 0;
185
- e.currentTarget = null;
186
- return out;
187
- }
188
- const path = [];
189
- for (let t = target.parentTarget();t; t = t.parentTarget())
190
- path.push(t);
191
- const out = { threw: false };
192
- e.target = target;
193
- e.eventPhase = 1;
194
- for (let i = path.length - 1;i >= 0 && !e.stopped; i--) {
195
- e.currentTarget = path[i];
196
- path[i].invoke(e, "capture", out);
197
- }
198
- if (!e.stopped) {
199
- e.eventPhase = 2;
200
- e.currentTarget = target;
201
- target.invoke(e, "target", out);
202
- }
203
- if (e.bubbles) {
204
- e.eventPhase = 3;
205
- for (let i = 0;i < path.length && !e.stopped; i++) {
206
- e.currentTarget = path[i];
207
- path[i].invoke(e, "bubble", out);
208
- }
209
- }
210
- e.eventPhase = 0;
211
- e.currentTarget = null;
212
- return out;
213
- }
214
- function handlers(cls, types) {
215
- for (const type of types) {
216
- Object.defineProperty(cls.prototype, `on${type}`, {
217
- get() {
218
- return this.getHandler(type);
219
- },
220
- set(fn) {
221
- this.setHandler(type, fn);
222
- },
223
- configurable: true,
224
- enumerable: true
225
- });
226
- }
227
- }
228
-
229
1
  // src/key.ts
230
2
  var NUMBER = 16;
231
3
  var DATE = 32;
@@ -464,6 +236,11 @@ function canInjectKey(value, path) {
464
236
  }
465
237
  return v !== null && typeof v === "object";
466
238
  }
239
+ var nativeRanges = false;
240
+ function useNativeKeyRanges() {
241
+ nativeRanges = typeof IDBKeyRange !== "undefined";
242
+ }
243
+
467
244
  class PlateauKeyRange {
468
245
  lo;
469
246
  hi;
@@ -482,16 +259,24 @@ class PlateauKeyRange {
482
259
  return this.hi === undefined ? undefined : decodeKey(this.hi);
483
260
  }
484
261
  static only(value) {
262
+ if (nativeRanges)
263
+ return IDBKeyRange.only(value);
485
264
  const k = requireKey(value);
486
265
  return new PlateauKeyRange(k, k, false, false);
487
266
  }
488
267
  static lowerBound(lower, open = false) {
268
+ if (nativeRanges)
269
+ return IDBKeyRange.lowerBound(lower, open);
489
270
  return new PlateauKeyRange(requireKey(lower), undefined, !!open, true);
490
271
  }
491
272
  static upperBound(upper, open = false) {
273
+ if (nativeRanges)
274
+ return IDBKeyRange.upperBound(upper, open);
492
275
  return new PlateauKeyRange(undefined, requireKey(upper), true, !!open);
493
276
  }
494
277
  static bound(lower, upper, lowerOpen = false, upperOpen = false) {
278
+ if (nativeRanges)
279
+ return IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen);
495
280
  const lo = requireKey(lower);
496
281
  const hi = requireKey(upper);
497
282
  if (lo > hi || lo === hi && (lowerOpen || upperOpen))
@@ -681,7 +466,10 @@ class Runtime {
681
466
  nextTx = 1;
682
467
  tab;
683
468
  leading;
469
+ requested;
470
+ dead = null;
684
471
  becameLeader;
472
+ started = false;
685
473
  calls = new Map;
686
474
  nextCall = 1;
687
475
  held = [];
@@ -704,7 +492,11 @@ class Runtime {
704
492
  constructor(o = {}) {
705
493
  this.leading = new Promise((resolve) => this.becameLeader = resolve);
706
494
  this.tab = typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
707
- this.startWorker(o);
495
+ this.requested = o.backend ?? "auto";
496
+ if (this.requested === "indexeddb")
497
+ this.stop("plateau: this page uses the browser's IndexedDB");
498
+ else
499
+ this.startWorker(o);
708
500
  const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;
709
501
  if (!locks || typeof BroadcastChannel === "undefined") {
710
502
  this.lead();
@@ -728,6 +520,23 @@ class Runtime {
728
520
  return forever();
729
521
  });
730
522
  }
523
+ stop(message) {
524
+ if (this.dead)
525
+ return;
526
+ this.dead = new DOMException(message, "NotSupportedError");
527
+ this.worker?.terminate();
528
+ this.worker = null;
529
+ if (this.role !== "leader")
530
+ return;
531
+ for (const [id, c] of this.calls) {
532
+ this.calls.delete(id);
533
+ c.reject(this.dead);
534
+ }
535
+ for (const [id, reply] of this.relayed) {
536
+ this.relayed.delete(id);
537
+ reply({ t: "call", id, ok: false, name: this.dead.name, message: this.dead.message });
538
+ }
539
+ }
731
540
  call(m) {
732
541
  const id = this.nextCall++;
733
542
  return new Promise((resolve, reject) => {
@@ -786,14 +595,30 @@ class Runtime {
786
595
  return out;
787
596
  }
788
597
  startWorker(o) {
789
- const worker = o.worker ?? new Worker(new URL("./host.worker.js", import.meta.url), { type: "module" });
790
- if (!o.worker) {
791
- const compiled = WebAssembly.compileStreaming(fetch(WASM_URL)).catch(async () => WebAssembly.compile(await (await fetch(WASM_URL)).arrayBuffer()));
792
- compiled.then((module) => worker.postMessage({ t: "init", module }));
598
+ let worker;
599
+ try {
600
+ worker = o.worker ?? new Worker(new URL("./host.worker.js", import.meta.url), { type: "module" });
601
+ if (!o.worker) {
602
+ const compiled = WebAssembly.compileStreaming(fetch(WASM_URL)).catch(async () => WebAssembly.compile(await (await fetch(WASM_URL)).arrayBuffer()));
603
+ compiled.then((module) => worker.postMessage({ t: "init", module }), (e) => this.stop(`plateau: the engine's WebAssembly does not compile here: ${e?.message ?? String(e)}`));
604
+ }
605
+ } catch (e) {
606
+ this.stop(`plateau: the engine's worker does not start here: ${e?.message ?? String(e)}`);
607
+ return;
793
608
  }
609
+ this.started = !!o.worker;
610
+ worker.addEventListener("error", (e) => {
611
+ if (!this.started && this.worker === worker)
612
+ this.stop(`plateau: the engine's worker failed to load: ${e.message ?? ""}`.trim());
613
+ });
794
614
  worker.addEventListener("message", (e) => {
795
615
  const m = e.data;
796
- if (m.t === "call") {
616
+ if (m.t === "init") {
617
+ if (m.error)
618
+ this.stop(m.error);
619
+ else
620
+ this.started = true;
621
+ } else if (m.t === "call") {
797
622
  const r = this.relayed.get(m.id);
798
623
  if (r) {
799
624
  this.relayed.delete(m.id);
@@ -806,7 +631,13 @@ class Runtime {
806
631
  this.worker = worker;
807
632
  }
808
633
  send(m, transfer = []) {
809
- if (this.role === "leader") {
634
+ if (this.role === "leader" && this.dead) {
635
+ const dead = this.dead;
636
+ if (m.t !== "tx")
637
+ queueMicrotask(() => this.settle({ t: "call", id: m.id, ok: false, name: dead.name, message: dead.message }));
638
+ else if (m.begin)
639
+ queueMicrotask(() => this.txs.get(m.tx)?._onReply({ t: "tx", tx: m.tx, res: [], errs: [], end: { ok: false, name: "UnknownError", message: dead.message } }));
640
+ } else if (this.role === "leader") {
810
641
  this.worker.postMessage(m, transfer);
811
642
  } else if (this.role === "follower") {
812
643
  if (m.t === "tx") {
@@ -875,7 +706,7 @@ class Runtime {
875
706
  this.leaderTab = this.tab;
876
707
  this.role = "leader";
877
708
  this.becameLeader();
878
- if (!this.worker)
709
+ if (!this.worker && !this.dead)
879
710
  this.startWorker({});
880
711
  this.hub?.postMessage({ t: "leader", tab: this.tab });
881
712
  this.flush();
@@ -1019,6 +850,10 @@ class Runtime {
1019
850
  const f = this.followers.get(from);
1020
851
  if (!f)
1021
852
  return;
853
+ if (this.dead) {
854
+ f.port.postMessage({ t: "call", id: m.id, ok: false, name: this.dead.name, message: this.dead.message });
855
+ return;
856
+ }
1022
857
  const id = this.nextCall++;
1023
858
  if (m.t === "close")
1024
859
  count(f.conns, m.db, -1);
@@ -1038,6 +873,11 @@ class Runtime {
1038
873
  const f = this.followers.get(from);
1039
874
  if (!f)
1040
875
  return;
876
+ if (this.dead) {
877
+ if (m.begin)
878
+ f.port.postMessage({ t: "tx", tx: m.tx, res: [], errs: [], end: { ok: false, name: "UnknownError", message: this.dead.message } });
879
+ return;
880
+ }
1041
881
  let p = f.txs.get(m.tx);
1042
882
  if (!p) {
1043
883
  if (!m.begin)
@@ -1096,7 +936,7 @@ class Runtime {
1096
936
  p.kill();
1097
937
  for (const [db, n] of f.conns)
1098
938
  for (let i = 0;i < n; i++)
1099
- this.worker.postMessage({ t: "close", db, id: this.nextCall++ });
939
+ this.worker?.postMessage({ t: "close", db, id: this.nextCall++ });
1100
940
  for (const [key, release] of this.slotHolds) {
1101
941
  if (!key.startsWith(`${tab}:`))
1102
942
  continue;
@@ -1113,6 +953,9 @@ class Runtime {
1113
953
  }
1114
954
  }
1115
955
  var current = null;
956
+ function currentRuntime() {
957
+ return current;
958
+ }
1116
959
  function runtime(o) {
1117
960
  current ??= new Runtime(o);
1118
961
  return current;
@@ -1121,12 +964,519 @@ function startRuntime(o) {
1121
964
  return runtime(o);
1122
965
  }
1123
966
 
1124
- // src/value.ts
1125
- var TAGS = new Set(["$u", "$n", "$bi", "$d", "$re", "$bo", "$no", "$so", "$ab", "$ta", "$sa", "$m", "$set", "$r"]);
1126
- var VIEWS = {
1127
- Int8Array,
1128
- Uint8Array,
1129
- Uint8ClampedArray,
967
+ // src/backend.ts
968
+ var nativeIndexedDB = typeof indexedDB !== "undefined" ? indexedDB : undefined;
969
+ var chosen;
970
+ var choice = null;
971
+ function chosenBackend() {
972
+ return chosen;
973
+ }
974
+ function missing() {
975
+ if (typeof Worker !== "function")
976
+ return "no Worker";
977
+ if (typeof WebAssembly !== "object" || typeof WebAssembly.compile !== "function")
978
+ return "no WebAssembly";
979
+ const storage = typeof navigator !== "undefined" ? navigator.storage : undefined;
980
+ if (typeof storage?.getDirectory !== "function")
981
+ return "no OPFS (navigator.storage.getDirectory)";
982
+ return null;
983
+ }
984
+ function choose(b, why) {
985
+ chosen = b;
986
+ if (b === "indexeddb") {
987
+ useNativeKeyRanges();
988
+ runtime().stop(`plateau: this page uses the browser's IndexedDB${why ? ` (${why})` : ""}`);
989
+ }
990
+ return b;
991
+ }
992
+ function chooseBackend() {
993
+ if (choice)
994
+ return choice;
995
+ const requested = currentRuntime()?.requested ?? "auto";
996
+ if (!nativeIndexedDB || requested === "opfs")
997
+ choice = Promise.resolve(choose("opfs"));
998
+ else if (requested === "indexeddb")
999
+ choice = Promise.resolve(choose("indexeddb"));
1000
+ else {
1001
+ const why = missing();
1002
+ const rt = runtime(why ? { backend: "indexeddb" } : undefined);
1003
+ if (why)
1004
+ choice = Promise.resolve(choose("indexeddb", why));
1005
+ else
1006
+ choice = rt.call({ t: "probe" }).then(() => choose("opfs"), (e) => choose("indexeddb", e?.message));
1007
+ }
1008
+ return choice;
1009
+ }
1010
+
1011
+ // src/events.ts
1012
+ class PlateauEvent {
1013
+ type;
1014
+ bubbles;
1015
+ cancelable;
1016
+ isTrusted = true;
1017
+ target = null;
1018
+ currentTarget = null;
1019
+ eventPhase = 0;
1020
+ defaultPrevented = false;
1021
+ stopped = false;
1022
+ stoppedNow = false;
1023
+ constructor(type, init = {}) {
1024
+ this.type = type;
1025
+ this.bubbles = !!init.bubbles;
1026
+ this.cancelable = !!init.cancelable;
1027
+ }
1028
+ preventDefault() {
1029
+ if (this.cancelable)
1030
+ this.defaultPrevented = true;
1031
+ }
1032
+ stopPropagation() {
1033
+ this.stopped = true;
1034
+ }
1035
+ stopImmediatePropagation() {
1036
+ this.stopped = true;
1037
+ this.stoppedNow = true;
1038
+ }
1039
+ get timeStamp() {
1040
+ return performance.now();
1041
+ }
1042
+ get cancelBubble() {
1043
+ return this.stopped;
1044
+ }
1045
+ get returnValue() {
1046
+ return !this.defaultPrevented;
1047
+ }
1048
+ }
1049
+
1050
+ class PlateauVersionChangeEvent extends PlateauEvent {
1051
+ oldVersion;
1052
+ newVersion;
1053
+ constructor(type, init = {}) {
1054
+ super(type);
1055
+ this.oldVersion = init.oldVersion ?? 0;
1056
+ this.newVersion = init.newVersion ?? null;
1057
+ }
1058
+ }
1059
+
1060
+ class PlateauTarget {
1061
+ entries = null;
1062
+ slots = null;
1063
+ parentTarget() {
1064
+ return null;
1065
+ }
1066
+ addEventListener(type, fn, opts) {
1067
+ if (!fn)
1068
+ return;
1069
+ const capture = typeof opts === "boolean" ? opts : !!opts?.capture;
1070
+ const once = typeof opts === "object" && !!opts?.once;
1071
+ this.entries ??= [];
1072
+ if (this.entries.some((e) => !e.removed && e.type === type && e.fn === fn && e.capture === capture))
1073
+ return;
1074
+ this.entries.push({ type, capture, once, fn });
1075
+ }
1076
+ removeEventListener(type, fn, opts) {
1077
+ const capture = typeof opts === "boolean" ? opts : !!opts?.capture;
1078
+ if (!this.entries)
1079
+ return;
1080
+ const i = this.entries.findIndex((e) => !e.removed && e.type === type && e.fn === fn && e.capture === capture);
1081
+ if (i >= 0) {
1082
+ this.entries[i].removed = true;
1083
+ this.entries.splice(i, 1);
1084
+ }
1085
+ }
1086
+ getHandler(type) {
1087
+ return this.slots?.[type] ?? null;
1088
+ }
1089
+ setHandler(type, fn) {
1090
+ const f = typeof fn === "function" ? fn : null;
1091
+ this.entries ??= [];
1092
+ this.slots ??= {};
1093
+ if (f) {
1094
+ let has = false;
1095
+ for (const e of this.entries)
1096
+ if (e.slot === type)
1097
+ has = true;
1098
+ if (!has)
1099
+ this.entries.push({ type, capture: false, once: false, fn: null, slot: type });
1100
+ } else {
1101
+ const i = this.entries.findIndex((e) => e.slot === type);
1102
+ if (i >= 0) {
1103
+ this.entries[i].removed = true;
1104
+ this.entries.splice(i, 1);
1105
+ }
1106
+ }
1107
+ this.slots[type] = f;
1108
+ }
1109
+ hasListeners() {
1110
+ return this.entries !== null && this.entries.length > 0;
1111
+ }
1112
+ listensOnPath(type, bubbles) {
1113
+ const entries = this.entries;
1114
+ if (entries === null)
1115
+ return false;
1116
+ for (const e of entries)
1117
+ if (e.type === type && (bubbles || e.capture))
1118
+ return true;
1119
+ return false;
1120
+ }
1121
+ dispatchEvent(e) {
1122
+ dispatch(this, e);
1123
+ return !e.defaultPrevented;
1124
+ }
1125
+ invoke(e, phase, out) {
1126
+ const entries = this.entries;
1127
+ if (entries === null || entries.length === 0)
1128
+ return;
1129
+ let only = null;
1130
+ let matches = 0;
1131
+ for (const x of entries) {
1132
+ if (x.type === e.type) {
1133
+ matches++;
1134
+ only = x;
1135
+ }
1136
+ }
1137
+ if (matches === 0)
1138
+ return;
1139
+ if (matches !== 1)
1140
+ only = null;
1141
+ if (only !== null && only.slot !== undefined && phase !== "capture") {
1142
+ const fn = this.slots[only.slot];
1143
+ if (fn) {
1144
+ try {
1145
+ fn.call(this, e);
1146
+ } catch (err) {
1147
+ out.threw = true;
1148
+ report(err);
1149
+ }
1150
+ }
1151
+ return;
1152
+ }
1153
+ const list = entries.filter((x) => x.type === e.type && (phase === "target" || x.capture === (phase === "capture")));
1154
+ for (const x of list) {
1155
+ if (x.removed)
1156
+ continue;
1157
+ if (x.once)
1158
+ this.removeEventListener(x.type, x.fn, x.capture);
1159
+ const fn = x.slot ? this.slots[x.slot] : x.fn;
1160
+ if (!fn)
1161
+ continue;
1162
+ try {
1163
+ if (typeof fn === "function")
1164
+ fn.call(this, e);
1165
+ else
1166
+ fn.handleEvent(e);
1167
+ } catch (err) {
1168
+ out.threw = true;
1169
+ report(err);
1170
+ }
1171
+ if (e.stoppedNow)
1172
+ break;
1173
+ }
1174
+ }
1175
+ }
1176
+ function report(err) {
1177
+ const g = globalThis;
1178
+ if (g.reportError)
1179
+ g.reportError(err);
1180
+ else
1181
+ setTimeout(() => {
1182
+ throw err;
1183
+ });
1184
+ }
1185
+ function dispatch(target, e) {
1186
+ const p1 = target.parentTarget();
1187
+ const p2 = p1 === null ? null : p1.parentTarget();
1188
+ if ((p2 === null || p2.parentTarget() === null) && (p1 === null || !p1.listensOnPath(e.type, e.bubbles)) && (p2 === null || !p2.listensOnPath(e.type, e.bubbles))) {
1189
+ const out = { threw: false };
1190
+ e.target = target;
1191
+ e.eventPhase = 2;
1192
+ e.currentTarget = target;
1193
+ target.invoke(e, "target", out);
1194
+ e.eventPhase = 0;
1195
+ e.currentTarget = null;
1196
+ return out;
1197
+ }
1198
+ const path = [];
1199
+ for (let t = target.parentTarget();t; t = t.parentTarget())
1200
+ path.push(t);
1201
+ const out = { threw: false };
1202
+ e.target = target;
1203
+ e.eventPhase = 1;
1204
+ for (let i = path.length - 1;i >= 0 && !e.stopped; i--) {
1205
+ e.currentTarget = path[i];
1206
+ path[i].invoke(e, "capture", out);
1207
+ }
1208
+ if (!e.stopped) {
1209
+ e.eventPhase = 2;
1210
+ e.currentTarget = target;
1211
+ target.invoke(e, "target", out);
1212
+ }
1213
+ if (e.bubbles) {
1214
+ e.eventPhase = 3;
1215
+ for (let i = 0;i < path.length && !e.stopped; i++) {
1216
+ e.currentTarget = path[i];
1217
+ path[i].invoke(e, "bubble", out);
1218
+ }
1219
+ }
1220
+ e.eventPhase = 0;
1221
+ e.currentTarget = null;
1222
+ return out;
1223
+ }
1224
+ function handlers(cls, types) {
1225
+ for (const type of types) {
1226
+ Object.defineProperty(cls.prototype, `on${type}`, {
1227
+ get() {
1228
+ return this.getHandler(type);
1229
+ },
1230
+ set(fn) {
1231
+ this.setHandler(type, fn);
1232
+ },
1233
+ configurable: true,
1234
+ enumerable: true
1235
+ });
1236
+ }
1237
+ }
1238
+
1239
+ // src/fallback.ts
1240
+ var CHANNEL = "plateau/fallback/changed";
1241
+ var instrumented = new WeakSet;
1242
+ var closed = new WeakSet;
1243
+ var observed = new Map;
1244
+ var channel;
1245
+ function hub() {
1246
+ if (channel === undefined) {
1247
+ channel = typeof BroadcastChannel === "function" ? new BroadcastChannel(CHANNEL) : null;
1248
+ if (channel)
1249
+ channel.onmessage = (e) => notify(e.data.db, e.data.stores);
1250
+ }
1251
+ return channel;
1252
+ }
1253
+ function notify(name, stores) {
1254
+ for (const observers of observed.get(name)?.values() ?? []) {
1255
+ for (const o of observers) {
1256
+ const hit = stores.filter((s) => o.stores.has(s));
1257
+ if (!hit.length)
1258
+ continue;
1259
+ try {
1260
+ o.callback({ stores: hit });
1261
+ } catch (e) {
1262
+ reportError(e);
1263
+ }
1264
+ }
1265
+ }
1266
+ }
1267
+ function forget(db) {
1268
+ closed.add(db);
1269
+ const m = observed.get(db.name);
1270
+ m?.delete(db);
1271
+ if (m && !m.size)
1272
+ observed.delete(db.name);
1273
+ }
1274
+ function own(target, name, value) {
1275
+ Object.defineProperty(target, name, { value, configurable: true, writable: true, enumerable: false });
1276
+ }
1277
+ var protoCache = null;
1278
+ var protos = () => ({
1279
+ transaction: IDBDatabase.prototype.transaction,
1280
+ createObjectStore: IDBDatabase.prototype.createObjectStore,
1281
+ close: IDBDatabase.prototype.close,
1282
+ objectStore: IDBTransaction.prototype.objectStore,
1283
+ getAll: IDBObjectStore.prototype.getAll,
1284
+ getAllKeys: IDBObjectStore.prototype.getAllKeys,
1285
+ index: IDBObjectStore.prototype.index,
1286
+ result: Object.getOwnPropertyDescriptor(IDBRequest.prototype, "result").get
1287
+ });
1288
+ var proto = () => protoCache ??= protos();
1289
+ function instrumentDb(db) {
1290
+ if (instrumented.has(db))
1291
+ return;
1292
+ instrumented.add(db);
1293
+ own(db, "transaction", function(...args) {
1294
+ const tx = proto().transaction.apply(this, args);
1295
+ instrumentTx(tx);
1296
+ return tx;
1297
+ });
1298
+ own(db, "createObjectStore", function(...args) {
1299
+ const s = proto().createObjectStore.apply(this, args);
1300
+ instrumentStore(s);
1301
+ return s;
1302
+ });
1303
+ own(db, "close", function() {
1304
+ forget(this);
1305
+ proto().close.call(this);
1306
+ });
1307
+ own(db, "observe", function(stores, callback) {
1308
+ if (closed.has(this))
1309
+ throw new DOMException("The connection is closed.", "InvalidStateError");
1310
+ if (typeof callback !== "function")
1311
+ throw new TypeError("plateau: observe needs a callback.");
1312
+ hub();
1313
+ const o = { stores: new Set(typeof stores === "string" ? [stores] : [...stores].map(String)), callback };
1314
+ let m = observed.get(this.name);
1315
+ if (!m)
1316
+ observed.set(this.name, m = new Map);
1317
+ let set = m.get(this);
1318
+ if (!set)
1319
+ m.set(this, set = new Set);
1320
+ set.add(o);
1321
+ return () => {
1322
+ set.delete(o);
1323
+ };
1324
+ });
1325
+ own(db, "compact", async function() {
1326
+ if (closed.has(this))
1327
+ throw new DOMException("The connection is closed.", "InvalidStateError");
1328
+ });
1329
+ db.addEventListener("close", () => forget(db));
1330
+ }
1331
+ function instrumentTx(tx) {
1332
+ if (instrumented.has(tx))
1333
+ return;
1334
+ instrumented.add(tx);
1335
+ const opened = new Set;
1336
+ own(tx, "objectStore", function(name) {
1337
+ const s = proto().objectStore.call(this, name);
1338
+ instrumentStore(s);
1339
+ opened.add(s.name);
1340
+ return s;
1341
+ });
1342
+ if (tx.mode !== "readwrite")
1343
+ return;
1344
+ tx.addEventListener("complete", () => {
1345
+ if (!opened.size)
1346
+ return;
1347
+ const stores = [...opened];
1348
+ const name = tx.db.name;
1349
+ notify(name, stores);
1350
+ hub()?.postMessage({ db: name, stores });
1351
+ });
1352
+ }
1353
+ function instrumentStore(s) {
1354
+ if (instrumented.has(s))
1355
+ return;
1356
+ instrumented.add(s);
1357
+ own(s, "query", function(q) {
1358
+ return query(this, q);
1359
+ });
1360
+ }
1361
+ function instrumentOpen(r) {
1362
+ r.addEventListener("upgradeneeded", () => {
1363
+ instrumentDb(r.result);
1364
+ if (r.transaction)
1365
+ instrumentTx(r.transaction);
1366
+ });
1367
+ r.addEventListener("success", () => {
1368
+ const db = proto().result.call(r);
1369
+ if (db instanceof IDBDatabase)
1370
+ instrumentDb(db);
1371
+ });
1372
+ }
1373
+ function test(f) {
1374
+ let one;
1375
+ switch (f.op) {
1376
+ case "eq": {
1377
+ const v = Number(f.value);
1378
+ one = (x) => x === v;
1379
+ break;
1380
+ }
1381
+ case "in": {
1382
+ const set = new Set((f.values ?? []).map(Number));
1383
+ one = (x) => set.has(x);
1384
+ break;
1385
+ }
1386
+ case "range": {
1387
+ const { gt, gte, lt, lte } = f;
1388
+ if ([gt, gte, lt, lte].some((b) => b !== undefined && b !== null && Number.isNaN(Number(b))))
1389
+ return () => false;
1390
+ const has = (b) => b !== undefined && b !== null;
1391
+ one = (x) => (!has(gt) || x > gt) && (!has(gte) || x >= gte) && (!has(lt) || x < lt) && (!has(lte) || x <= lte);
1392
+ break;
1393
+ }
1394
+ default:
1395
+ throw new TypeError(`plateau: unknown query op ${String(f.op)}.`);
1396
+ }
1397
+ return (x) => {
1398
+ if (typeof x === "number")
1399
+ return !Number.isNaN(x) && one(x);
1400
+ if (Array.isArray(x))
1401
+ return x.some((y) => typeof y === "number" && one(y));
1402
+ return false;
1403
+ };
1404
+ }
1405
+ function field(v, name) {
1406
+ return v !== null && typeof v === "object" ? v[name] : undefined;
1407
+ }
1408
+ function run(q, keys, values, tests) {
1409
+ let rows = [];
1410
+ for (let i = 0;i < values.length; i++)
1411
+ if (tests.every(([f, t]) => t(field(values[i], f))))
1412
+ rows.push(i);
1413
+ if (q.count)
1414
+ return rows.length;
1415
+ const o = q.orderBy;
1416
+ if (o) {
1417
+ const dir = o.desc ? -1 : 1;
1418
+ const at = (i) => {
1419
+ const x = field(values[i], o.field);
1420
+ return typeof x === "number" && !Number.isNaN(x) ? x : null;
1421
+ };
1422
+ rows = rows.sort((a, b) => {
1423
+ const x = at(a);
1424
+ const y = at(b);
1425
+ if (x === null || y === null)
1426
+ return x === y ? cmp(keys[a], keys[b]) : x === null ? 1 : -1;
1427
+ return dir * (x - y || cmp(keys[a], keys[b]));
1428
+ });
1429
+ }
1430
+ if (q.limit !== undefined && q.limit !== null)
1431
+ rows = rows.slice(0, Math.max(0, Math.floor(Number(q.limit))));
1432
+ return rows.map((i) => values[i]);
1433
+ }
1434
+ function query(s, q) {
1435
+ if (q === null || typeof q !== "object")
1436
+ throw new TypeError("plateau: query takes an object.");
1437
+ const where = q.where ?? [];
1438
+ if (!Array.isArray(where))
1439
+ throw new TypeError("plateau: query's where must be an array.");
1440
+ const tests = where.map((f) => [String(f.field), test(f)]);
1441
+ let source = s;
1442
+ let range;
1443
+ let plan = "scan";
1444
+ for (const f of where) {
1445
+ if (f.op !== "eq" || typeof f.value !== "number" || Number.isNaN(f.value))
1446
+ continue;
1447
+ const idx = [...s.indexNames].map((n) => proto().index.call(s, n)).find((i) => i.keyPath === f.field && i.multiEntry);
1448
+ if (!idx)
1449
+ continue;
1450
+ source = idx;
1451
+ range = f.value;
1452
+ plan = `index:${idx.name}`;
1453
+ break;
1454
+ }
1455
+ const keysReq = source instanceof IDBIndex ? source.getAllKeys(range) : proto().getAllKeys.call(s);
1456
+ const valuesReq = source instanceof IDBIndex ? source.getAll(range) : proto().getAll.call(s);
1457
+ let keys = [];
1458
+ let out;
1459
+ keysReq.addEventListener("success", () => keys = keysReq.result);
1460
+ valuesReq.addEventListener("success", () => {
1461
+ out = run(q, keys, proto().result.call(valuesReq), tests);
1462
+ });
1463
+ Object.defineProperty(valuesReq, "result", {
1464
+ configurable: true,
1465
+ get() {
1466
+ proto().result.call(valuesReq);
1467
+ return out;
1468
+ }
1469
+ });
1470
+ own(valuesReq, "plan", plan);
1471
+ return valuesReq;
1472
+ }
1473
+
1474
+ // src/value.ts
1475
+ var TAGS = new Set(["$u", "$n", "$bi", "$d", "$re", "$bo", "$no", "$so", "$ab", "$ta", "$sa", "$m", "$set", "$r"]);
1476
+ var VIEWS = {
1477
+ Int8Array,
1478
+ Uint8Array,
1479
+ Uint8ClampedArray,
1130
1480
  Int16Array,
1131
1481
  Uint16Array,
1132
1482
  Int32Array,
@@ -1519,17 +1869,81 @@ function finishRequest(req, result, error) {
1519
1869
  req._error = error;
1520
1870
  }
1521
1871
 
1872
+ class BridgedRequest extends PlateauOpenDBRequest {
1873
+ parentTarget() {
1874
+ return null;
1875
+ }
1876
+ }
1877
+ function bridge(req, nat) {
1878
+ const b = req;
1879
+ Object.setPrototypeOf(b, BridgedRequest.prototype);
1880
+ const settle = () => {
1881
+ b._done = true;
1882
+ b._result = nat.result;
1883
+ b._error = nat.error;
1884
+ };
1885
+ nat.addEventListener("upgradeneeded", (e) => {
1886
+ settle();
1887
+ b.transaction = nat.transaction;
1888
+ const out = dispatch(b, new PlateauVersionChangeEvent("upgradeneeded", { oldVersion: e.oldVersion, newVersion: e.newVersion }));
1889
+ if (out.threw)
1890
+ nat.transaction?.abort();
1891
+ });
1892
+ nat.addEventListener("blocked", (e) => {
1893
+ dispatch(b, new PlateauVersionChangeEvent("blocked", { oldVersion: e.oldVersion, newVersion: e.newVersion }));
1894
+ });
1895
+ nat.addEventListener("success", (e) => {
1896
+ settle();
1897
+ b.transaction = null;
1898
+ const v = e;
1899
+ dispatch(b, v.oldVersion === undefined ? new PlateauEvent("success") : new PlateauVersionChangeEvent("success", { oldVersion: v.oldVersion, newVersion: v.newVersion }));
1900
+ });
1901
+ nat.addEventListener("error", () => {
1902
+ settle();
1903
+ b.transaction = null;
1904
+ dispatch(b, new PlateauEvent("error", { bubbles: true, cancelable: true }));
1905
+ });
1906
+ }
1907
+ function nativeOpen(name, version) {
1908
+ const r = version === undefined ? nativeIndexedDB.open(name) : nativeIndexedDB.open(name, version);
1909
+ instrumentOpen(r);
1910
+ return r;
1911
+ }
1912
+ var fallbackBudget = null;
1913
+
1522
1914
  class PlateauFactory {
1915
+ get backend() {
1916
+ return chosenBackend();
1917
+ }
1918
+ chooseBackend() {
1919
+ return chooseBackend();
1920
+ }
1523
1921
  open(name, version) {
1524
1922
  const n = String(name);
1525
1923
  const v = toVersion(version);
1924
+ const b = chosenBackend() ?? (void chooseBackend(), chosenBackend());
1925
+ if (b === "indexeddb")
1926
+ return nativeOpen(n, v);
1526
1927
  const req = new PlateauOpenDBRequest;
1527
- enqueue(n, () => openDatabase(req, n, v));
1928
+ if (b === "opfs")
1929
+ enqueue(n, () => openDatabase(req, n, v));
1930
+ else
1931
+ chooseBackend().then((b) => b === "opfs" ? enqueue(n, () => openDatabase(req, n, v)) : bridge(req, nativeOpen(n, v)));
1528
1932
  return req;
1529
1933
  }
1530
1934
  deleteDatabase(name) {
1531
1935
  const n = String(name);
1936
+ const b = chosenBackend() ?? (void chooseBackend(), chosenBackend());
1937
+ if (b === "indexeddb")
1938
+ return nativeIndexedDB.deleteDatabase(n);
1532
1939
  const req = new PlateauOpenDBRequest;
1940
+ if (b === "opfs")
1941
+ this.deleteHere(req, n);
1942
+ else
1943
+ chooseBackend().then((b) => b === "opfs" ? this.deleteHere(req, n) : bridge(req, nativeIndexedDB.deleteDatabase(n)));
1944
+ return req;
1945
+ }
1946
+ deleteHere(req, n) {
1533
1947
  enqueue(n, async () => {
1534
1948
  await new Promise((r) => afterTask(r));
1535
1949
  await closeOthers(n, null, null, null, req);
@@ -1544,12 +1958,14 @@ class PlateauFactory {
1544
1958
  finishRequest(req, undefined, null);
1545
1959
  dispatch(req, new PlateauVersionChangeEvent("success", { oldVersion: old, newVersion: null }));
1546
1960
  });
1547
- return req;
1548
1961
  }
1549
1962
  cmp(a, b) {
1550
1963
  return cmp(a, b);
1551
1964
  }
1552
1965
  async databases() {
1966
+ if (await chooseBackend() === "indexeddb" && typeof nativeIndexedDB.databases === "function") {
1967
+ return await nativeIndexedDB.databases();
1968
+ }
1553
1969
  return [];
1554
1970
  }
1555
1971
  whenLeader() {
@@ -1558,9 +1974,15 @@ class PlateauFactory {
1558
1974
  async setMemoryBudget(bytes) {
1559
1975
  if (bytes !== null && !(bytes > 0))
1560
1976
  throw new TypeError("plateau: the memory budget must be a positive number of bytes, or null.");
1977
+ if (await chooseBackend() === "indexeddb") {
1978
+ fallbackBudget = bytes;
1979
+ return;
1980
+ }
1561
1981
  await runtime().call({ t: "budget", bytes });
1562
1982
  }
1563
- memoryStats(name) {
1983
+ async memoryStats(name) {
1984
+ if (await chooseBackend() === "indexeddb")
1985
+ return { wasmMemoryBytes: 0, budgetBytes: fallbackBudget ?? Infinity, cachedBytes: 0 };
1564
1986
  return runtime().call(name === undefined ? { t: "stats" } : { t: "stats", db: String(name) });
1565
1987
  }
1566
1988
  }
package/dist/key.d.ts CHANGED
@@ -41,6 +41,10 @@ export interface WireRange {
41
41
  loOpen: boolean;
42
42
  hiOpen: boolean;
43
43
  }
44
+ /** @internal From now on `PlateauKeyRange`'s factories return the browser's `IDBKeyRange`: the page
45
+ * runs on the browser's IndexedDB, which takes no other range. */
46
+ export declare function useNativeKeyRanges(): void;
47
+ /** On the IndexedDB fallback, the factories return the browser's own `IDBKeyRange`. */
44
48
  export declare class PlateauKeyRange {
45
49
  /** @internal */ readonly lo: string | undefined;
46
50
  /** @internal */ readonly hi: string | undefined;
@@ -210,6 +210,11 @@ export type CallMessage = {
210
210
  t: "compact";
211
211
  id: number;
212
212
  db: string;
213
+ }
214
+ /** Checks that the worker runs the engine on OPFS; fails where it cannot. */
215
+ | {
216
+ t: "probe";
217
+ id: number;
213
218
  };
214
219
  /** A call message without its id, per variant. */
215
220
  export type CallRequest = CallMessage extends infer M ? (M extends CallMessage ? Omit<M, "id"> : never) : never;
package/dist/runtime.d.ts CHANGED
@@ -4,6 +4,9 @@ export interface RuntimeOptions {
4
4
  worker?: Worker;
5
5
  /** Resolves when that worker has its WASM (it replied to `init`). */
6
6
  initialized?: Promise<unknown>;
7
+ /** Which backend this page uses: `auto` (the default) picks OPFS where the engine runs there and
8
+ * the browser's own IndexedDB elsewhere; `opfs` and `indexeddb` skip the check. */
9
+ backend?: "auto" | "opfs" | "indexeddb";
7
10
  }
8
11
  /** Once versionchange has fired at a tab's connections: whether one is still open without a close
9
12
  * pending, and their version (0 when none is open). */
@@ -36,7 +39,14 @@ export declare class Runtime {
36
39
  readonly tab: string;
37
40
  /** Resolves when this tab becomes the leader (at once for a single tab); never rejects. */
38
41
  readonly leading: Promise<void>;
42
+ /** The backend the page asked for (`startRuntime({ backend })`). */
43
+ readonly requested: "auto" | "opfs" | "indexeddb";
44
+ /** Set when this tab cannot run the engine (its worker failed to start, or the page uses the
45
+ * browser's IndexedDB): calls fail with it, here and from the tabs this one leads. */
46
+ dead: DOMException | null;
39
47
  private becameLeader;
48
+ /** Whether the worker answered `init` (or was handed over started). */
49
+ private started;
40
50
  private calls;
41
51
  private nextCall;
42
52
  /** Messages sent while no leader is known, in order. */
@@ -65,6 +75,9 @@ export declare class Runtime {
65
75
  private slotHolds;
66
76
  private fanouts;
67
77
  constructor(o?: RuntimeOptions);
78
+ /** This tab does not run the engine: stops its worker; calls fail from now on, and a tab this one
79
+ * leads gets the same failure, so it picks the same backend. */
80
+ stop(message: string): void;
68
81
  call<T>(m: CallRequest): Promise<T>;
69
82
  post(m: TxMessage, transfer?: Transferable[]): void;
70
83
  /** A transaction of this tab finished. */
@@ -107,6 +120,8 @@ export declare class Runtime {
107
120
  /** A follower closed: roll back its transactions, close its connections, free what it held. */
108
121
  private followerGone;
109
122
  }
123
+ /** The page's runtime if it has started. */
124
+ export declare function currentRuntime(): Runtime | null;
110
125
  /** The page's runtime, started on first call. */
111
126
  export declare function runtime(o?: RuntimeOptions): Runtime;
112
127
  /** Starts the runtime now, as an app does by importing the library at start-up; `o` attaches it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plateaudb",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "A browser database on OPFS with an IndexedDB-compatible API, written in Rust and compiled to WebAssembly; multi-key query time stays near-flat as rows grow",
6
6
  "license": "MIT",