@vite-hub/device 0.0.0-stage → 0.3.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,686 @@
1
+ import { defineErrors } from "@vite-hub/runtime";
2
+ //#region src/errors.ts
3
+ const deviceErrors = /*#__PURE__*/ defineErrors({
4
+ docs: "https://vitehub.dev/docs/device/diagnostics",
5
+ codes: {
6
+ DEVICE_ALREADY_OPEN: {
7
+ why: ({ version, open }) => `\`openDevice()\` was called with the version ${JSON.stringify(version)}, and the device is already open with the version ${JSON.stringify(open)}.`,
8
+ fix: "Call `openDevice()` once, before `app.mount()`, with one `version` for the build."
9
+ },
10
+ DEVICE_FETCH_FAILED: {
11
+ why: ({ url, status }) => `GET ${url} answered ${status}. \`useStoredFetch()\` keeps what the read shows, and the device does not store the answer.`,
12
+ fix: "Check that the route answers 2xx with JSON for this request. For a 401, sign the person in again. For another error, read the server log of the route."
13
+ },
14
+ DEVICE_INVALID_ACCOUNT: {
15
+ why: ({ account }) => `\`setDeviceAccount()\` got ${account}. It takes the id of the signed-in account, or \`null\` after a sign-out.`,
16
+ fix: "Pass the user id from your session as a string, such as `setDeviceAccount(session.user.id)`, or `null` when no one is signed in."
17
+ },
18
+ DEVICE_INVALID_KEY: {
19
+ why: ({ key }) => `\`useStoredData()\` got the key ${key}. A key must be a string that is not empty.`,
20
+ fix: "Give each read a key that names its data, such as `'projects'` or `` `project:${id}` ``."
21
+ },
22
+ DEVICE_INVALID_MAX_AGE: {
23
+ why: ({ maxAge }) => `\`maxAge\` is ${maxAge}. It must be a number of milliseconds that is 0 or more.`,
24
+ fix: "Set `maxAge` in milliseconds, such as `24 * 60 * 60 * 1000` for one day, or remove it to keep the default of 7 days."
25
+ },
26
+ DEVICE_NOT_OPEN: {
27
+ why: "`useStoredData()` keeps the answer in memory only, because the app did not call `openDevice()`. A reload shows the default, not the stored copy.",
28
+ fix: "Call `await openDevice()` before `app.mount()`. In an app that the server renders, call `openDevice()` after the app mounts."
29
+ },
30
+ DEVICE_STORAGE_FAILED: {
31
+ why: ({ action }) => `IndexedDB failed to ${action}. The stored copies on the device can be out of date.`,
32
+ fix: "Call the function again. If it fails again, ask the user to clear the site data in the browser settings. The browser console has the IndexedDB error as the cause."
33
+ },
34
+ DEVICE_VALUE_NOT_JSON: {
35
+ why: ({ key }) => `The loader of \`${key}\` returned a value that JSON cannot store, so the device does not keep it.`,
36
+ fix: "Return plain data from the loader: objects, arrays, strings, numbers, booleans, and null. Turn a `Date` into a string and a `Map` into an object."
37
+ },
38
+ DEVICE_VALUE_TOO_LARGE: {
39
+ why: ({ key, bytes, limit }) => `The answer of \`${key}\` has ${bytes} bytes as JSON. The device keeps at most ${limit} bytes, so it does not keep this answer.`,
40
+ fix: "Store less: load one page of a list, or only the fields that the first screen shows."
41
+ }
42
+ }
43
+ });
44
+ /** Prints a diagnostic that does not stop the read, with the lower-level error when it has one. */
45
+ function warn(error) {
46
+ const message = `[vitehub] ${error.code}: ${error.why} ${error.fix ?? ""}`.trim();
47
+ if (error.cause === void 0) console.warn(message);
48
+ else console.warn(message, error.cause);
49
+ }
50
+ //#endregion
51
+ //#region src/indexeddb.ts
52
+ const databaseName = "vitehub-device";
53
+ const format = 3;
54
+ const metaKey = "device";
55
+ const ageIndex = "age";
56
+ const channelName = "vitehub-device";
57
+ function done(transaction) {
58
+ return new Promise((resolve, reject) => {
59
+ transaction.oncomplete = () => resolve();
60
+ transaction.onabort = () => reject(transaction.error ?? new DOMException("The IndexedDB transaction was aborted.", "AbortError"));
61
+ transaction.onerror = () => reject(transaction.error ?? new DOMException("The IndexedDB transaction failed.", "UnknownError"));
62
+ });
63
+ }
64
+ /**
65
+ * Opens the IndexedDB storage. It rejects when the browser has no IndexedDB or refuses it, such as a sandboxed frame or
66
+ * some private windows. `indexedDB.open()` can throw at once, and the promise turns that into a rejection.
67
+ */
68
+ function openIndexedDB() {
69
+ return new Promise((resolve, reject) => {
70
+ const request = indexedDB.open(databaseName, format);
71
+ request.onupgradeneeded = () => {
72
+ const database = request.result;
73
+ for (const name of Array.from(database.objectStoreNames)) database.deleteObjectStore(name);
74
+ database.createObjectStore("meta");
75
+ database.createObjectStore("entries", { keyPath: "key" }).createIndex(ageIndex, [
76
+ "storedAt",
77
+ "bytes",
78
+ "expiresAt"
79
+ ]);
80
+ };
81
+ request.onsuccess = () => {
82
+ const database = request.result;
83
+ database.onversionchange = () => database.close();
84
+ resolve(indexedDBStorage(database));
85
+ };
86
+ request.onerror = () => reject(request.error);
87
+ });
88
+ }
89
+ /**
90
+ * Deletes the entries that expired at `now`, then the oldest entries of every tab until the entries hold at most
91
+ * `maxBytes`. Runs inside the write, so it picks from what the disk holds, not from what a tab remembers.
92
+ */
93
+ function trim(entries, maxBytes, now) {
94
+ const rows = [];
95
+ let total = 0;
96
+ const cursor = entries.index(ageIndex).openKeyCursor();
97
+ cursor.onsuccess = () => {
98
+ const row = cursor.result;
99
+ if (row) {
100
+ const [, bytes, expiresAt] = row.key;
101
+ if (expiresAt <= now) entries.delete(row.primaryKey);
102
+ else {
103
+ rows.push({
104
+ key: row.primaryKey,
105
+ bytes
106
+ });
107
+ total += bytes;
108
+ }
109
+ return row.continue();
110
+ }
111
+ for (const { key, bytes } of rows) {
112
+ if (total <= maxBytes) return;
113
+ entries.delete(key);
114
+ total -= bytes;
115
+ }
116
+ };
117
+ }
118
+ function indexedDBStorage(database) {
119
+ return {
120
+ async read() {
121
+ const transaction = database.transaction(["meta", "entries"], "readonly");
122
+ const meta = transaction.objectStore("meta").get(metaKey);
123
+ const entries = transaction.objectStore("entries").getAll();
124
+ await done(transaction);
125
+ return {
126
+ meta: meta.result,
127
+ entries: entries.result
128
+ };
129
+ },
130
+ async reset(meta, expected) {
131
+ const transaction = database.transaction(["meta", "entries"], "readwrite");
132
+ const metas = transaction.objectStore("meta");
133
+ const current = metas.get(metaKey);
134
+ let found;
135
+ current.onsuccess = () => {
136
+ found = current.result;
137
+ if (found?.generation !== expected) return;
138
+ transaction.objectStore("entries").clear();
139
+ metas.put(meta, metaKey);
140
+ };
141
+ await done(transaction);
142
+ return found;
143
+ },
144
+ async write(meta, { puts, deletes, maxBytes, now }) {
145
+ const transaction = database.transaction(["meta", "entries"], "readwrite");
146
+ const entries = transaction.objectStore("entries");
147
+ const current = transaction.objectStore("meta").get(metaKey);
148
+ let found;
149
+ current.onsuccess = () => {
150
+ found = current.result;
151
+ if (found?.generation !== meta.generation || found.account !== meta.account || found.version !== meta.version) return;
152
+ for (const key of deletes) entries.delete(key);
153
+ for (const entry of puts) entries.put(entry);
154
+ trim(entries, maxBytes, now);
155
+ };
156
+ await done(transaction);
157
+ return found;
158
+ },
159
+ async clear(generation) {
160
+ const transaction = database.transaction(["meta", "entries"], "readwrite");
161
+ transaction.objectStore("entries").clear();
162
+ const metas = transaction.objectStore("meta");
163
+ const current = metas.get(metaKey);
164
+ let next;
165
+ current.onsuccess = () => {
166
+ const found = current.result;
167
+ if (!found) return;
168
+ next = {
169
+ ...found,
170
+ generation
171
+ };
172
+ metas.put(next, metaKey);
173
+ };
174
+ await done(transaction);
175
+ return next;
176
+ },
177
+ close: () => database.close()
178
+ };
179
+ }
180
+ function isMeta(value) {
181
+ if (!value || typeof value !== "object") return false;
182
+ const account = Reflect.get(value, "account");
183
+ return (account === null || typeof account === "string") && typeof Reflect.get(value, "version") === "string" && typeof Reflect.get(value, "generation") === "string";
184
+ }
185
+ function isDeviceMessage(value) {
186
+ if (!value || typeof value !== "object") return false;
187
+ const meta = Reflect.get(value, "meta");
188
+ if (meta !== void 0 && !isMeta(meta)) return false;
189
+ const type = Reflect.get(value, "type");
190
+ if (type === "clear") return true;
191
+ const account = Reflect.get(value, "account");
192
+ return type === "account" && (account === null || typeof account === "string");
193
+ }
194
+ /** The tabs of the browser, through a BroadcastChannel. Without one, each tab works alone. */
195
+ function browserChannel() {
196
+ if (typeof BroadcastChannel !== "function") return {
197
+ post: () => void 0,
198
+ receive: () => () => void 0
199
+ };
200
+ const channel = new BroadcastChannel(channelName);
201
+ return {
202
+ post: (message) => channel.postMessage(message),
203
+ receive(listener) {
204
+ const onMessage = (event) => {
205
+ if (isDeviceMessage(event.data)) listener(event.data);
206
+ };
207
+ channel.addEventListener("message", onMessage);
208
+ return () => channel.removeEventListener("message", onMessage);
209
+ }
210
+ };
211
+ }
212
+ //#endregion
213
+ //#region src/device.ts
214
+ /** The device keeps at most 5 MB of JSON. `openDevice()` reads all of it before the app mounts. */
215
+ const maxDeviceBytes = 5242880;
216
+ /** `openDevice()` waits at most 1 second for IndexedDB, so a slow or stuck browser does not stop the app. */
217
+ const openTimeout = 1e3;
218
+ const encoder = /*#__PURE__*/ new TextEncoder();
219
+ const ok = [void 0, void 0];
220
+ function describe(value) {
221
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
222
+ }
223
+ function checkAccount(account) {
224
+ if (account !== null && (typeof account !== "string" || account === "")) throw deviceErrors.DEVICE_INVALID_ACCOUNT({ account: describe(account) });
225
+ }
226
+ function checkKey(key) {
227
+ if (typeof key !== "string" || key === "") throw deviceErrors.DEVICE_INVALID_KEY({ key: describe(key) });
228
+ return key;
229
+ }
230
+ function checkMaxAge(maxAge) {
231
+ if (typeof maxAge !== "number" || Number.isNaN(maxAge) || maxAge < 0) throw deviceErrors.DEVICE_INVALID_MAX_AGE({ maxAge: describe(maxAge) });
232
+ return maxAge;
233
+ }
234
+ /** A random id for a new generation of the disk. */
235
+ function newGeneration() {
236
+ return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(8)), (byte) => byte.toString(16).padStart(2, "0")).join("");
237
+ }
238
+ function createDevice(options) {
239
+ const now = options.now ?? (() => Date.now());
240
+ const maxBytes = options.maxBytes ?? maxDeviceBytes;
241
+ /** The copies that new reads of this tab show: the copies of the disk, and the answers that the device stores. */
242
+ const entries = /* @__PURE__ */ new Map();
243
+ /** The changes for the disk: a copy to put, or `undefined` to delete the key. */
244
+ const pending = /* @__PURE__ */ new Map();
245
+ const listeners = /* @__PURE__ */ new Set();
246
+ const warned = /* @__PURE__ */ new Set();
247
+ let storage;
248
+ let opening;
249
+ /** `true` once `open()` finished, so `setAccount()` can name the account at once. */
250
+ let opened = false;
251
+ /** `true` when the device opened without a disk, so nothing waits to be written. */
252
+ let diskless = false;
253
+ let version = "";
254
+ /**
255
+ * The meta that this tab expects on the disk. A change of this tab sets it in the queue, after its disk operation, so
256
+ * it follows the order of the operations. A message of another tab sets it at once.
257
+ */
258
+ let meta;
259
+ /**
260
+ * `true` once this tab saw the disk in the version of its build. When the disk shows another version for the same
261
+ * account after that, a newer build opened in another tab, and this tab leaves the disk to it.
262
+ */
263
+ let versionSeen = false;
264
+ /** The account that this page named. `undefined` before it calls `setAccount()`, or after another tab named another account. */
265
+ let named;
266
+ /** The account of the latest `setAccount()` call, also while the device opens. */
267
+ let requested;
268
+ /**
269
+ * Changes when the page names an account, and when the copies and the answers in memory stop being valid. The device
270
+ * stores an answer only when its loader call started in the current epoch, after the page named an account.
271
+ */
272
+ let epoch = 0;
273
+ let queue = Promise.resolve();
274
+ let flushQueued = false;
275
+ const stopReceiving = options.channel.receive(receive);
276
+ function warnOnce(id, error) {
277
+ if (warned.has(id)) return;
278
+ warned.add(id);
279
+ warn(error);
280
+ }
281
+ function emit(event) {
282
+ if (event.type === "load" && !event.keys.length) return;
283
+ for (const listener of listeners) listener(event);
284
+ }
285
+ /** Runs disk operations, and the changes of `meta` that come with them, one after another in the order of the calls. */
286
+ function enqueue(task) {
287
+ const run = queue.then(task);
288
+ queue = run.catch(() => void 0);
289
+ return run;
290
+ }
291
+ function persisting() {
292
+ return storage !== void 0 && typeof named === "string" && meta?.account === named && meta.version === version;
293
+ }
294
+ function backgroundFailure(cause) {
295
+ warnOnce("storage", deviceErrors.DEVICE_STORAGE_FAILED({
296
+ action: "store a copy",
297
+ cause
298
+ }));
299
+ }
300
+ /** Forgets every copy and answer in memory, and tells the reads to start over. */
301
+ function invalidate() {
302
+ epoch++;
303
+ entries.clear();
304
+ pending.clear();
305
+ emit({ type: "reset" });
306
+ }
307
+ /** Sets the meta that this tab expects on the disk. */
308
+ function setMeta(next) {
309
+ meta = next;
310
+ if (next?.version === version) versionSeen = true;
311
+ }
312
+ /** Writes `change` when the disk still has the generation `expected`. Runs in the queue. */
313
+ async function persist(target, expected, change) {
314
+ const found = await target.write(expected, change);
315
+ if (found?.generation === expected.generation || meta !== expected) return;
316
+ adopt(found);
317
+ }
318
+ /**
319
+ * Takes the meta that the disk has, after another tab changed the disk and this tab missed its message. Everything of
320
+ * this tab is old. After another account, this tab stores again only after it names an account.
321
+ */
322
+ function adopt(found) {
323
+ setMeta(found);
324
+ if (found?.account !== named) named = void 0;
325
+ invalidate();
326
+ }
327
+ /** Writes the pending changes in one write, after the operations that are already queued. */
328
+ function flush() {
329
+ if (flushQueued || !pending.size) return;
330
+ flushQueued = true;
331
+ enqueue(async () => {
332
+ flushQueued = false;
333
+ const target = storage;
334
+ const expected = meta;
335
+ if (!target || !expected || !persisting()) return;
336
+ const change = {
337
+ puts: [],
338
+ deletes: [],
339
+ maxBytes,
340
+ now: now()
341
+ };
342
+ for (const [key, entry] of pending) if (entry) change.puts.push(entry);
343
+ else change.deletes.push(key);
344
+ pending.clear();
345
+ await persist(target, expected, change);
346
+ }).catch(backgroundFailure);
347
+ }
348
+ /** Deletes the expired copies on the disk, and the oldest ones over the cap. The disk picks them in its transaction. */
349
+ function trim() {
350
+ enqueue(async () => {
351
+ if (storage && meta) await persist(storage, meta, {
352
+ puts: [],
353
+ deletes: [],
354
+ maxBytes,
355
+ now: now()
356
+ });
357
+ }).catch(backgroundFailure);
358
+ }
359
+ /** Drops the oldest copies in the memory of this tab until it is under the size cap. The disk keeps its own cap. */
360
+ function evict(keep) {
361
+ let total = 0;
362
+ for (const entry of entries.values()) total += entry.bytes;
363
+ for (const entry of [...entries.values()].sort((a, b) => a.storedAt - b.storedAt)) {
364
+ if (total <= maxBytes) return;
365
+ if (entry.key === keep) continue;
366
+ entries.delete(entry.key);
367
+ total -= entry.bytes;
368
+ }
369
+ }
370
+ function receive(message) {
371
+ if (message.type === "account" && !message.meta && message.account === named) return;
372
+ if (message.type === "account" && message.account !== named) named = void 0;
373
+ if (message.meta) return adopt(message.meta);
374
+ invalidate();
375
+ }
376
+ async function connect() {
377
+ let opened;
378
+ try {
379
+ opened = await options.openStorage();
380
+ return {
381
+ storage: opened,
382
+ ...await opened.read()
383
+ };
384
+ } catch {
385
+ opened?.close();
386
+ return;
387
+ }
388
+ }
389
+ async function load() {
390
+ try {
391
+ await connectAndTake();
392
+ } finally {
393
+ opened = true;
394
+ }
395
+ }
396
+ async function connectAndTake() {
397
+ const started = epoch;
398
+ let timer;
399
+ const connecting = connect();
400
+ const found = await Promise.race([connecting, new Promise((resolve) => {
401
+ timer = setTimeout(resolve, options.openTimeout ?? openTimeout, void 0);
402
+ })]);
403
+ clearTimeout(timer);
404
+ if (!found) {
405
+ diskless = true;
406
+ pending.clear();
407
+ connecting.then((late) => late?.storage.close());
408
+ return;
409
+ }
410
+ storage = found.storage;
411
+ if (epoch === started) take(found.meta, found.entries);
412
+ else if (!meta) setMeta(found.meta);
413
+ const fromPage = named !== void 0;
414
+ const account = fromPage ? named : meta?.account;
415
+ if (account === void 0) return;
416
+ const since = epoch;
417
+ enqueue(async () => epoch === since ? ensure(account, false, fromPage) : ok).then(([error]) => error && warnOnce("storage", error));
418
+ }
419
+ /** Takes the copies that the disk had when the device opened. */
420
+ function take(found, stored) {
421
+ setMeta(found);
422
+ if (!found || found.version !== version || found.account === null || requested !== void 0 && requested !== found.account) return;
423
+ const time = now();
424
+ const loaded = [];
425
+ let expired = false;
426
+ let total = 0;
427
+ for (const entry of stored) {
428
+ if (entry.expiresAt <= time) {
429
+ expired = true;
430
+ continue;
431
+ }
432
+ total += entry.bytes;
433
+ if (!entries.has(entry.key)) {
434
+ entries.set(entry.key, {
435
+ ...entry,
436
+ account: found.account
437
+ });
438
+ loaded.push(entry.key);
439
+ }
440
+ }
441
+ evict();
442
+ if (expired || total > maxBytes) trim();
443
+ emit({
444
+ type: "load",
445
+ keys: loaded.filter((key) => entries.has(key))
446
+ });
447
+ }
448
+ /**
449
+ * Brings the disk to `account` in the version of this build. When the disk holds another account or version, every copy
450
+ * goes and the disk gets a new generation, and the other tabs hear of it. Runs in the queue. In this tab it is not a
451
+ * reset: the tab raised the epoch when it named the account, and holds no copy of another account or version.
452
+ *
453
+ * One naming, one reset attempt. The reset applies only on the generation that this tab knew when the task started.
454
+ * On any other generation, the tab takes the disk as it is and does not write the meta again until the page names an
455
+ * account.
456
+ */
457
+ async function ensure(account, announce, fromPage) {
458
+ if (fromPage && named !== account) return ok;
459
+ const target = storage;
460
+ if (!target) {
461
+ if (announce) options.channel.post({
462
+ type: "account",
463
+ account,
464
+ meta: void 0
465
+ });
466
+ return ok;
467
+ }
468
+ if (meta?.account === account && meta.version !== version && versionSeen) return ok;
469
+ if (meta?.account !== account || meta.version !== version) {
470
+ const expected = meta;
471
+ const next = {
472
+ account,
473
+ version,
474
+ generation: newGeneration()
475
+ };
476
+ let found;
477
+ try {
478
+ found = await target.reset(next, expected?.generation);
479
+ } catch (cause) {
480
+ options.channel.post({
481
+ type: "account",
482
+ account,
483
+ meta: void 0
484
+ });
485
+ return [deviceErrors.DEVICE_STORAGE_FAILED({
486
+ action: "delete the copies of the previous account",
487
+ cause
488
+ }), void 0];
489
+ }
490
+ if (found?.generation !== expected?.generation) {
491
+ if (meta === expected) adopt(found);
492
+ return ok;
493
+ }
494
+ setMeta(next);
495
+ options.channel.post({
496
+ type: "account",
497
+ account,
498
+ meta: next
499
+ });
500
+ }
501
+ flush();
502
+ return ok;
503
+ }
504
+ /** Names `account` in memory, at once, so that loader calls that started before it are never stored. */
505
+ function name(account) {
506
+ const previous = named;
507
+ named = account;
508
+ if (previous !== void 0 || [...entries.values()].some((entry) => entry.account !== account)) return invalidate();
509
+ if (account === null) return invalidate();
510
+ epoch++;
511
+ emit({ type: "named" });
512
+ }
513
+ async function setAccount(account) {
514
+ checkAccount(account);
515
+ requested = account;
516
+ if (opening && !opened) await opening;
517
+ if (requested !== account) return ok;
518
+ const changed = account !== named;
519
+ if (changed) name(account);
520
+ return enqueue(() => ensure(account, changed, true));
521
+ }
522
+ async function clear() {
523
+ if (opening) await opening;
524
+ invalidate();
525
+ return enqueue(async () => {
526
+ const target = storage;
527
+ if (!target) {
528
+ options.channel.post({
529
+ type: "clear",
530
+ meta: void 0
531
+ });
532
+ return ok;
533
+ }
534
+ try {
535
+ setMeta(await target.clear(newGeneration()));
536
+ options.channel.post({
537
+ type: "clear",
538
+ meta
539
+ });
540
+ return ok;
541
+ } catch (cause) {
542
+ options.channel.post({
543
+ type: "clear",
544
+ meta: void 0
545
+ });
546
+ return [deviceErrors.DEVICE_STORAGE_FAILED({
547
+ action: "delete the stored copies",
548
+ cause
549
+ }), void 0];
550
+ }
551
+ });
552
+ }
553
+ function write(key, value, maxAge, since) {
554
+ if (!opening) warnOnce("open", deviceErrors.DEVICE_NOT_OPEN());
555
+ if (since !== epoch || typeof named !== "string") return;
556
+ store(key, value, maxAge, named);
557
+ }
558
+ function claim(key, value, maxAge, since, account) {
559
+ checkAccount(account);
560
+ if (!opening) warnOnce("open", deviceErrors.DEVICE_NOT_OPEN());
561
+ if (since !== epoch || opening && !opened) return false;
562
+ const naming = account !== named;
563
+ if (naming) {
564
+ requested = account;
565
+ name(account);
566
+ if (epoch !== since + 1 || named !== account) return false;
567
+ }
568
+ enqueue(() => ensure(account, naming, true)).then(([error]) => error && warnOnce("storage", error));
569
+ if (typeof account === "string") store(key, value, maxAge, account);
570
+ return true;
571
+ }
572
+ /** Keeps `value` as the copy of `key` for `account`, in memory and on the disk. */
573
+ function store(key, value, maxAge, account) {
574
+ let json;
575
+ try {
576
+ json = JSON.stringify(value);
577
+ } catch (cause) {
578
+ warnOnce(`json:${key}`, deviceErrors.DEVICE_VALUE_NOT_JSON({
579
+ key,
580
+ cause
581
+ }));
582
+ json = void 0;
583
+ }
584
+ const bytes = json === void 0 ? 0 : encoder.encode(json).byteLength;
585
+ if (json !== void 0 && bytes > maxBytes) {
586
+ warnOnce(`size:${key}`, deviceErrors.DEVICE_VALUE_TOO_LARGE({
587
+ key,
588
+ bytes,
589
+ limit: maxBytes
590
+ }));
591
+ json = void 0;
592
+ }
593
+ if (json === void 0) {
594
+ entries.delete(key);
595
+ if (!diskless) pending.set(key, void 0);
596
+ return flush();
597
+ }
598
+ const time = now();
599
+ const entry = {
600
+ key,
601
+ json,
602
+ storedAt: time,
603
+ expiresAt: time + maxAge,
604
+ bytes
605
+ };
606
+ entries.set(key, {
607
+ ...entry,
608
+ account
609
+ });
610
+ if (!diskless) pending.set(key, entry);
611
+ evict(key);
612
+ flush();
613
+ }
614
+ return {
615
+ open(openOptions = {}) {
616
+ const wanted = openOptions.version ?? "";
617
+ if (opening) {
618
+ if (wanted !== version) throw deviceErrors.DEVICE_ALREADY_OPEN({
619
+ version: wanted,
620
+ open: version
621
+ });
622
+ return opening;
623
+ }
624
+ version = wanted;
625
+ versionSeen = false;
626
+ opening = load();
627
+ return opening;
628
+ },
629
+ named: () => named !== void 0,
630
+ setAccount,
631
+ clear,
632
+ inspect: () => ({
633
+ account: named !== void 0 ? named : meta?.account ?? null,
634
+ persisted: persisting(),
635
+ storage: storage ? "indexeddb" : "memory",
636
+ entries: [...entries.values()].map((entry) => ({
637
+ key: entry.key,
638
+ storedAt: new Date(entry.storedAt),
639
+ bytes: entry.bytes
640
+ })).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0)
641
+ }),
642
+ epoch: () => epoch,
643
+ read(key, maxAge) {
644
+ const entry = entries.get(key);
645
+ if (!entry || now() - entry.storedAt > maxAge) return void 0;
646
+ return {
647
+ value: JSON.parse(entry.json),
648
+ storedAt: entry.storedAt
649
+ };
650
+ },
651
+ write,
652
+ claim,
653
+ whenOpen: async () => {
654
+ if (opening) await opening;
655
+ },
656
+ loading: () => opening !== void 0 && !opened,
657
+ subscribe(listener) {
658
+ listeners.add(listener);
659
+ return () => listeners.delete(listener);
660
+ },
661
+ settled: async () => {
662
+ if (opening) await opening;
663
+ for (let current = queue;; current = queue) {
664
+ await current;
665
+ if (current === queue) return;
666
+ }
667
+ },
668
+ close() {
669
+ stopReceiving();
670
+ listeners.clear();
671
+ storage?.close();
672
+ }
673
+ };
674
+ }
675
+ let browserDevice;
676
+ /** The device of this browser tab. `undefined` on the server, where nothing is stored. */
677
+ function currentDevice() {
678
+ if (typeof document === "undefined") return void 0;
679
+ browserDevice ??= createDevice({
680
+ openStorage: openIndexedDB,
681
+ channel: browserChannel()
682
+ });
683
+ return browserDevice;
684
+ }
685
+ //#endregion
686
+ export { deviceErrors as a, currentDevice as i, checkKey as n, checkMaxAge as r, checkAccount as t };