@dxos/util 0.8.4-main.406dc2a → 0.8.4-main.422d1c7879

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.
Files changed (78) hide show
  1. package/dist/lib/browser/index.mjs +602 -457
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +602 -457
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/array.d.ts +3 -2
  8. package/dist/types/src/array.d.ts.map +1 -1
  9. package/dist/types/src/browser-storage.d.ts +9 -0
  10. package/dist/types/src/browser-storage.d.ts.map +1 -0
  11. package/dist/types/src/circular-buffer.d.ts +1 -0
  12. package/dist/types/src/circular-buffer.d.ts.map +1 -1
  13. package/dist/types/src/complex.d.ts +15 -0
  14. package/dist/types/src/complex.d.ts.map +1 -1
  15. package/dist/types/src/composite-key.d.ts +10 -0
  16. package/dist/types/src/composite-key.d.ts.map +1 -0
  17. package/dist/types/src/composite-key.test.d.ts +2 -0
  18. package/dist/types/src/composite-key.test.d.ts.map +1 -0
  19. package/dist/types/src/deep.d.ts +0 -3
  20. package/dist/types/src/deep.d.ts.map +1 -1
  21. package/dist/types/src/defer.d.ts +1 -1
  22. package/dist/types/src/defer.d.ts.map +1 -1
  23. package/dist/types/src/di-key.d.ts +7 -5
  24. package/dist/types/src/di-key.d.ts.map +1 -1
  25. package/dist/types/src/error-format.d.ts +5 -0
  26. package/dist/types/src/error-format.d.ts.map +1 -0
  27. package/dist/types/src/filename.d.ts +9 -0
  28. package/dist/types/src/filename.d.ts.map +1 -0
  29. package/dist/types/src/index.d.ts +6 -0
  30. package/dist/types/src/index.d.ts.map +1 -1
  31. package/dist/types/src/platform.d.ts +4 -1
  32. package/dist/types/src/platform.d.ts.map +1 -1
  33. package/dist/types/src/retry.d.ts +32 -0
  34. package/dist/types/src/retry.d.ts.map +1 -0
  35. package/dist/types/src/safe-parse.d.ts +7 -4
  36. package/dist/types/src/safe-parse.d.ts.map +1 -1
  37. package/dist/types/src/safe-stringify.d.ts +22 -0
  38. package/dist/types/src/safe-stringify.d.ts.map +1 -0
  39. package/dist/types/src/safe-stringify.test.d.ts +2 -0
  40. package/dist/types/src/safe-stringify.test.d.ts.map +1 -0
  41. package/dist/types/src/to-fallback.d.ts +18 -4
  42. package/dist/types/src/to-fallback.d.ts.map +1 -1
  43. package/dist/types/src/types.d.ts +23 -5
  44. package/dist/types/src/types.d.ts.map +1 -1
  45. package/dist/types/src/unit.d.ts +12 -13
  46. package/dist/types/src/unit.d.ts.map +1 -1
  47. package/dist/types/src/weak.d.ts +15 -0
  48. package/dist/types/src/weak.d.ts.map +1 -1
  49. package/dist/types/tsconfig.tsbuildinfo +1 -1
  50. package/package.json +12 -14
  51. package/src/array.ts +9 -2
  52. package/src/binder.ts +2 -2
  53. package/src/browser-storage.ts +60 -0
  54. package/src/circular-buffer.test.ts +26 -0
  55. package/src/circular-buffer.ts +5 -0
  56. package/src/complex.ts +32 -0
  57. package/src/composite-key.test.ts +31 -0
  58. package/src/composite-key.ts +16 -0
  59. package/src/deep.ts +2 -6
  60. package/src/defer.ts +1 -1
  61. package/src/di-key.ts +10 -8
  62. package/src/error-format.ts +22 -0
  63. package/src/filename.ts +16 -0
  64. package/src/index.ts +6 -0
  65. package/src/platform.ts +35 -3
  66. package/src/retry.ts +74 -0
  67. package/src/safe-parse.ts +27 -16
  68. package/src/safe-stringify.test.ts +96 -0
  69. package/src/safe-stringify.ts +153 -0
  70. package/src/to-fallback.ts +39 -156
  71. package/src/types.test.ts +11 -1
  72. package/src/types.ts +39 -12
  73. package/src/unit.test.ts +1 -1
  74. package/src/unit.ts +59 -28
  75. package/src/weak.ts +52 -14
  76. package/dist/types/src/explicit-resource-management-polyfill.d.ts +0 -1
  77. package/dist/types/src/explicit-resource-management-polyfill.d.ts.map +0 -1
  78. package/src/explicit-resource-management-polyfill.ts +0 -13
@@ -97,16 +97,24 @@ var intersectBy = (arrays, selector) => {
97
97
  return lookups.every((lookup) => lookup.has(key));
98
98
  });
99
99
  };
100
+ var coerceArray = (arr) => {
101
+ if (arr === void 0) {
102
+ return [];
103
+ }
104
+ return Array.isArray(arr) ? arr : [
105
+ arr
106
+ ];
107
+ };
100
108
 
101
109
  // src/assume.ts
102
110
  function assumeType(value) {
103
111
  }
104
112
 
105
113
  // src/binder.ts
106
- import util from "@dxos/node-std/util";
114
+ import { promisify } from "@dxos/node-std/util";
107
115
  var createBinder = (obj) => ({
108
116
  fn: (fn) => fn.bind(obj),
109
- async: (fn) => util.promisify(fn.bind(obj))
117
+ async: (fn) => promisify(fn.bind(obj))
110
118
  });
111
119
 
112
120
  // src/bitfield.ts
@@ -179,93 +187,78 @@ var BitField = class _BitField {
179
187
  }
180
188
  };
181
189
 
182
- // src/callback-collection.ts
183
- function _check_private_redeclaration(obj, privateCollection) {
184
- if (privateCollection.has(obj)) {
185
- throw new TypeError("Cannot initialize the same private elements twice on an object");
190
+ // src/browser-storage.ts
191
+ var clearIndexedDB = async () => {
192
+ const dbs = await indexedDB.databases();
193
+ const results = await Promise.allSettled(dbs.filter((db) => db.name != null).map((db) => new Promise((resolve, reject) => {
194
+ const request = indexedDB.deleteDatabase(db.name);
195
+ request.onsuccess = () => resolve();
196
+ request.onerror = () => reject(request.error);
197
+ request.onblocked = () => reject(new Error(`IndexedDB deletion blocked: ${db.name}`));
198
+ })));
199
+ const failures = results.filter((r) => r.status === "rejected");
200
+ if (failures.length > 0) {
201
+ throw new AggregateError(failures.map((r) => r.reason), "Failed to delete some IndexedDB databases");
202
+ }
203
+ };
204
+ var clearOPFS = async () => {
205
+ const root = await navigator.storage.getDirectory();
206
+ const errors = [];
207
+ for await (const [name] of root.entries()) {
208
+ try {
209
+ await root.removeEntry(name, {
210
+ recursive: true
211
+ });
212
+ } catch (err) {
213
+ errors.push(err);
214
+ }
186
215
  }
187
- }
188
- function _class_apply_descriptor_get(receiver, descriptor) {
189
- if (descriptor.get) {
190
- return descriptor.get.call(receiver);
216
+ if (errors.length > 0) {
217
+ throw new AggregateError(errors, "Failed to remove some OPFS entries");
191
218
  }
192
- return descriptor.value;
193
- }
194
- function _class_apply_descriptor_set(receiver, descriptor, value) {
195
- if (descriptor.set) {
196
- descriptor.set.call(receiver, value);
197
- } else {
198
- if (!descriptor.writable) {
199
- throw new TypeError("attempted to set read only private field");
200
- }
201
- descriptor.value = value;
219
+ };
220
+ var clearServiceWorkers = async () => {
221
+ const regs = await navigator.serviceWorker.getRegistrations();
222
+ for (const reg of regs) {
223
+ await reg.unregister();
202
224
  }
203
- }
204
- function _class_extract_field_descriptor(receiver, privateMap, action) {
205
- if (!privateMap.has(receiver)) {
206
- throw new TypeError("attempted to " + action + " private field on non-instance");
225
+ };
226
+ var clearCaches = async () => {
227
+ const keys2 = await caches.keys();
228
+ for (const key of keys2) {
229
+ await caches.delete(key);
207
230
  }
208
- return privateMap.get(receiver);
209
- }
210
- function _class_private_field_get(receiver, privateMap) {
211
- var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
212
- return _class_apply_descriptor_get(receiver, descriptor);
213
- }
214
- function _class_private_field_init(obj, privateMap, value) {
215
- _check_private_redeclaration(obj, privateMap);
216
- privateMap.set(obj, value);
217
- }
218
- function _class_private_field_set(receiver, privateMap, value) {
219
- var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
220
- _class_apply_descriptor_set(receiver, descriptor, value);
221
- return value;
222
- }
223
- var _callbacks = /* @__PURE__ */ new WeakMap();
231
+ };
232
+
233
+ // src/callback-collection.ts
224
234
  var CallbackCollection = class {
235
+ #callbacks = [];
225
236
  append(callback) {
226
- _class_private_field_get(this, _callbacks).push(callback);
237
+ this.#callbacks.push(callback);
227
238
  }
228
239
  prepend(callback) {
229
- _class_private_field_get(this, _callbacks).unshift(callback);
240
+ this.#callbacks.unshift(callback);
230
241
  }
231
242
  remove(callback) {
232
- _class_private_field_set(this, _callbacks, _class_private_field_get(this, _callbacks).filter((c) => c !== callback));
243
+ this.#callbacks = this.#callbacks.filter((c) => c !== callback);
233
244
  }
234
245
  callParallel(...args) {
235
- return Promise.all(_class_private_field_get(this, _callbacks).map((callback) => callback(...args)));
246
+ return Promise.all(this.#callbacks.map((callback) => callback(...args)));
236
247
  }
237
248
  async callSerial(...args) {
238
249
  const results = [];
239
- for (const callback of _class_private_field_get(this, _callbacks)) {
250
+ for (const callback of this.#callbacks) {
240
251
  results.push(await callback(...args));
241
252
  }
242
253
  return results;
243
254
  }
244
- constructor() {
245
- _class_private_field_init(this, _callbacks, {
246
- writable: true,
247
- value: []
248
- });
249
- }
250
255
  };
251
256
 
252
257
  // src/callback.ts
253
258
  import { invariant as invariant2 } from "@dxos/invariant";
254
- function _define_property(obj, key, value) {
255
- if (key in obj) {
256
- Object.defineProperty(obj, key, {
257
- value,
258
- enumerable: true,
259
- configurable: true,
260
- writable: true
261
- });
262
- } else {
263
- obj[key] = value;
264
- }
265
- return obj;
266
- }
267
259
  var __dxlog_file2 = "/__w/dxos/dxos/packages/common/util/src/callback.ts";
268
260
  var Callback = class {
261
+ _callback;
269
262
  call(...args) {
270
263
  invariant2(this._callback, "Callback not set", {
271
264
  F: __dxlog_file2,
@@ -296,9 +289,6 @@ var Callback = class {
296
289
  isSet() {
297
290
  return !!this._callback;
298
291
  }
299
- constructor() {
300
- _define_property(this, "_callback", void 0);
301
- }
302
292
  };
303
293
  var createSetDispatch = ({ handlers }) => {
304
294
  return new Proxy({
@@ -361,21 +351,23 @@ var chunkArray = (array, size) => {
361
351
 
362
352
  // src/circular-buffer.ts
363
353
  import { invariant as invariant3 } from "@dxos/invariant";
364
- function _define_property2(obj, key, value) {
365
- if (key in obj) {
366
- Object.defineProperty(obj, key, {
367
- value,
368
- enumerable: true,
369
- configurable: true,
370
- writable: true
371
- });
372
- } else {
373
- obj[key] = value;
374
- }
375
- return obj;
376
- }
377
354
  var __dxlog_file3 = "/__w/dxos/dxos/packages/common/util/src/circular-buffer.ts";
378
355
  var CircularBuffer = class {
356
+ _buffer;
357
+ _nextIndex = 0;
358
+ _elementCount = 0;
359
+ constructor(size) {
360
+ invariant3(size >= 1, void 0, {
361
+ F: __dxlog_file3,
362
+ L: 13,
363
+ S: this,
364
+ A: [
365
+ "size >= 1",
366
+ ""
367
+ ]
368
+ });
369
+ this._buffer = new Array(size);
370
+ }
379
371
  push(element) {
380
372
  const evicted = this._elementCount === this._buffer.length ? this._buffer[this._nextIndex] : void 0;
381
373
  this._buffer[this._nextIndex] = element;
@@ -386,6 +378,10 @@ var CircularBuffer = class {
386
378
  get elementCount() {
387
379
  return this._elementCount;
388
380
  }
381
+ clear() {
382
+ this._nextIndex = 0;
383
+ this._elementCount = 0;
384
+ }
389
385
  getLast() {
390
386
  if (this._elementCount === 0) {
391
387
  return void 0;
@@ -415,21 +411,6 @@ var CircularBuffer = class {
415
411
  yield this._buffer[i];
416
412
  }
417
413
  }
418
- constructor(size) {
419
- _define_property2(this, "_buffer", void 0);
420
- _define_property2(this, "_nextIndex", 0);
421
- _define_property2(this, "_elementCount", 0);
422
- invariant3(size >= 1, void 0, {
423
- F: __dxlog_file3,
424
- L: 13,
425
- S: this,
426
- A: [
427
- "size >= 1",
428
- ""
429
- ]
430
- });
431
- this._buffer = new Array(size);
432
- }
433
414
  };
434
415
 
435
416
  // src/clear-undefined.ts
@@ -448,22 +429,19 @@ var clearUndefined = (obj) => {
448
429
  // src/complex.ts
449
430
  import { inspect } from "@dxos/node-std/util";
450
431
  import { inspectObject, raise } from "@dxos/debug";
451
- function _define_property3(obj, key, value) {
452
- if (key in obj) {
453
- Object.defineProperty(obj, key, {
454
- value,
455
- enumerable: true,
456
- configurable: true,
457
- writable: true
458
- });
459
- } else {
460
- obj[key] = value;
461
- }
462
- return obj;
463
- }
464
432
  var MAX_SERIALIZATION_LENGTH = 10;
465
- var _inspect_custom = inspect.custom;
466
433
  var ComplexSet = class {
434
+ _projection;
435
+ _values = /* @__PURE__ */ new Map();
436
+ // prettier-ignore
437
+ constructor(_projection, values) {
438
+ this._projection = _projection;
439
+ if (values) {
440
+ for (const value of values) {
441
+ this.add(value);
442
+ }
443
+ }
444
+ }
467
445
  toString() {
468
446
  return inspectObject(this);
469
447
  }
@@ -472,7 +450,7 @@ var ComplexSet = class {
472
450
  size: this._values.size
473
451
  } : Array.from(this._values.values());
474
452
  }
475
- [_inspect_custom]() {
453
+ [inspect.custom]() {
476
454
  return inspectObject(this);
477
455
  }
478
456
  add(value) {
@@ -538,18 +516,6 @@ var ComplexSet = class {
538
516
  isDisjointFrom(other) {
539
517
  throw new Error("Method not implemented.");
540
518
  }
541
- // prettier-ignore
542
- constructor(_projection, values) {
543
- _define_property3(this, "_projection", void 0);
544
- _define_property3(this, "_values", void 0);
545
- this._projection = _projection;
546
- this._values = /* @__PURE__ */ new Map();
547
- if (values) {
548
- for (const value of values) {
549
- this.add(value);
550
- }
551
- }
552
- }
553
519
  };
554
520
  var makeSet = (projection) => {
555
521
  return class BoundComplexSet extends ComplexSet {
@@ -558,8 +524,19 @@ var makeSet = (projection) => {
558
524
  }
559
525
  };
560
526
  };
561
- var _inspect_custom1 = inspect.custom;
562
527
  var ComplexMap = class _ComplexMap {
528
+ _keyProjection;
529
+ _keys = /* @__PURE__ */ new Map();
530
+ _values = /* @__PURE__ */ new Map();
531
+ // prettier-ignore
532
+ constructor(_keyProjection, entries2) {
533
+ this._keyProjection = _keyProjection;
534
+ if (entries2) {
535
+ for (const [key, value] of entries2) {
536
+ this.set(key, value);
537
+ }
538
+ }
539
+ }
563
540
  toString() {
564
541
  return inspectObject(this);
565
542
  }
@@ -568,7 +545,7 @@ var ComplexMap = class _ComplexMap {
568
545
  size: this._values.size
569
546
  } : Array.from(this._values.values());
570
547
  }
571
- [_inspect_custom1]() {
548
+ [inspect.custom]() {
572
549
  return inspectObject(this);
573
550
  }
574
551
  clear() {
@@ -598,6 +575,36 @@ var ComplexMap = class _ComplexMap {
598
575
  this._values.set(primitive, value);
599
576
  return this;
600
577
  }
578
+ /**
579
+ * Returns the value for the given key if present, otherwise inserts and returns the default value.
580
+ * @param key - The key to look up or insert.
581
+ * @param defaultValue - The value to insert if the key is not present.
582
+ * @returns The existing or newly inserted value.
583
+ */
584
+ getOrInsert(key, defaultValue) {
585
+ const primitive = this._keyProjection(key);
586
+ if (this._values.has(primitive)) {
587
+ return this._values.get(primitive);
588
+ }
589
+ this.set(key, defaultValue);
590
+ return defaultValue;
591
+ }
592
+ /**
593
+ * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
594
+ * The callback is only invoked when the key is missing.
595
+ * @param key - The key to look up or insert.
596
+ * @param callbackfn - Function to compute the value if the key is not present.
597
+ * @returns The existing or newly computed value.
598
+ */
599
+ getOrInsertComputed(key, callbackfn) {
600
+ const primitive = this._keyProjection(key);
601
+ if (this._values.has(primitive)) {
602
+ return this._values.get(primitive);
603
+ }
604
+ const value = callbackfn(key);
605
+ this.set(key, value);
606
+ return value;
607
+ }
601
608
  get size() {
602
609
  return this._keys.size;
603
610
  }
@@ -630,39 +637,25 @@ var ComplexMap = class _ComplexMap {
630
637
  get [Symbol.toStringTag]() {
631
638
  return "ComplexMap";
632
639
  }
633
- // prettier-ignore
634
- constructor(_keyProjection, entries2) {
635
- _define_property3(this, "_keyProjection", void 0);
636
- _define_property3(this, "_keys", void 0);
637
- _define_property3(this, "_values", void 0);
638
- this._keyProjection = _keyProjection;
639
- this._keys = /* @__PURE__ */ new Map();
640
- this._values = /* @__PURE__ */ new Map();
641
- if (entries2) {
642
- for (const [key, value] of entries2) {
643
- this.set(key, value);
644
- }
645
- }
646
- }
647
640
  };
648
- var makeMap = (keyProjection) => {
649
- class BoundComplexMap extends ComplexMap {
650
- constructor(entries2) {
651
- super(keyProjection, entries2);
652
- }
641
+ var makeMap = (keyProjection) => class BoundComplexMap extends ComplexMap {
642
+ constructor(entries2) {
643
+ super(keyProjection, entries2);
653
644
  }
654
- return BoundComplexMap;
655
645
  };
656
646
 
647
+ // src/composite-key.ts
648
+ var SEPARATOR = ":";
649
+ var compositeKey = (...parts) => parts.join(SEPARATOR);
650
+ var splitCompositeKey = (key) => key.split(SEPARATOR);
651
+
657
652
  // src/deep.ts
658
- import get from "lodash.get";
659
- import set from "lodash.set";
660
653
  import { invariant as invariant4 } from "@dxos/invariant";
661
654
  var __dxlog_file4 = "/__w/dxos/dxos/packages/common/util/src/deep.ts";
662
655
  var setDeep = (obj, path, value) => {
663
656
  invariant4(path.length > 0, void 0, {
664
657
  F: __dxlog_file4,
665
- L: 18,
658
+ L: 12,
666
659
  S: void 0,
667
660
  A: [
668
661
  "path.length > 0",
@@ -691,72 +684,51 @@ var getDeep = (obj, path) => {
691
684
  // src/defer-function.ts
692
685
  var deferFunction = (fnProvider) => (...args) => fnProvider()(...args);
693
686
 
694
- // src/explicit-resource-management-polyfill.ts
695
- var _Symbol;
696
- var _Symbol1;
697
- (_Symbol = Symbol).dispose ?? (_Symbol.dispose = Symbol("Symbol.dispose"));
698
- (_Symbol1 = Symbol).asyncDispose ?? (_Symbol1.asyncDispose = Symbol("Symbol.asyncDispose"));
699
-
700
687
  // src/defer.ts
701
- function _define_property4(obj, key, value) {
702
- if (key in obj) {
703
- Object.defineProperty(obj, key, {
704
- value,
705
- enumerable: true,
706
- configurable: true,
707
- writable: true
708
- });
709
- } else {
710
- obj[key] = value;
711
- }
712
- return obj;
713
- }
688
+ import "@hazae41/symbol-dispose-polyfill";
714
689
  var defer = (fn) => new DeferGuard(fn);
715
690
  var DeferGuard = class {
716
- [Symbol.dispose]() {
717
- const result = this._fn();
718
- if (result instanceof Promise) {
719
- throw new Error("Async functions in defer are not supported. Use deferAsync instead.");
720
- }
721
- }
691
+ _fn;
722
692
  /**
723
693
  * @internal
724
694
  */
725
695
  constructor(_fn) {
726
- _define_property4(this, "_fn", void 0);
727
696
  this._fn = _fn;
728
697
  }
698
+ [Symbol.dispose]() {
699
+ const result = this._fn();
700
+ if (result instanceof Promise) {
701
+ throw new Error("Async functions in defer are not supported. Use deferAsync instead.");
702
+ }
703
+ }
729
704
  };
730
705
  var deferAsync = (fn) => new DeferAsyncGuard(fn);
731
706
  var DeferAsyncGuard = class {
732
- async [Symbol.asyncDispose]() {
733
- await this._fn();
734
- }
707
+ _fn;
735
708
  /**
736
709
  * @internal
737
710
  */
738
711
  constructor(_fn) {
739
- _define_property4(this, "_fn", void 0);
740
712
  this._fn = _fn;
741
713
  }
714
+ async [Symbol.asyncDispose]() {
715
+ await this._fn();
716
+ }
742
717
  };
743
718
 
744
719
  // src/entry.ts
745
- function _define_property5(obj, key, value) {
746
- if (key in obj) {
747
- Object.defineProperty(obj, key, {
748
- value,
749
- enumerable: true,
750
- configurable: true,
751
- writable: true
752
- });
753
- } else {
754
- obj[key] = value;
755
- }
756
- return obj;
757
- }
758
720
  var entry = (map, key) => new MapEntry(map, key);
759
721
  var MapEntry = class {
722
+ _map;
723
+ _key;
724
+ /**
725
+ * @internal
726
+ */
727
+ // prettier-ignore
728
+ constructor(_map, _key) {
729
+ this._map = _map;
730
+ this._key = _key;
731
+ }
760
732
  get key() {
761
733
  return this._key;
762
734
  }
@@ -772,36 +744,34 @@ var MapEntry = class {
772
744
  deep(key) {
773
745
  return entry(this.value, key);
774
746
  }
775
- /**
776
- * @internal
777
- */
778
- // prettier-ignore
779
- constructor(_map, _key) {
780
- _define_property5(this, "_map", void 0);
781
- _define_property5(this, "_key", void 0);
782
- this._map = _map;
783
- this._key = _key;
784
- }
785
747
  };
786
748
 
749
+ // src/error-format.ts
750
+ var formatErrorWithCauses = (error) => {
751
+ const lines = [];
752
+ let current = error;
753
+ let level = 0;
754
+ while (current) {
755
+ const prefix = level === 0 ? "" : `Caused by: `;
756
+ lines.push(prefix + (current.stack ?? String(current)));
757
+ if (!(current.cause instanceof Error)) break;
758
+ current = current.cause;
759
+ level += 1;
760
+ }
761
+ return lines.join("\n\n");
762
+ };
763
+
764
+ // src/filename.ts
765
+ var createFilename = ({ parts = [], ext, date = /* @__PURE__ */ new Date() }) => [
766
+ date.toISOString().replace(/[:.]/g, "-"),
767
+ ...parts
768
+ ].join("_") + (ext ? `.${ext}` : "");
769
+
787
770
  // src/for-each-async.ts
788
771
  var forEachAsync = (items, fn) => Promise.all(items.map(fn));
789
772
 
790
773
  // src/human-hash.ts
791
774
  import { PublicKey } from "@dxos/keys";
792
- function _define_property6(obj, key, value) {
793
- if (key in obj) {
794
- Object.defineProperty(obj, key, {
795
- value,
796
- enumerable: true,
797
- configurable: true,
798
- writable: true
799
- });
800
- } else {
801
- obj[key] = value;
802
- }
803
- return obj;
804
- }
805
775
  var DEFAULT_WORDLIST = [
806
776
  "ack",
807
777
  "alabama",
@@ -1061,6 +1031,27 @@ var DEFAULT_WORDLIST = [
1061
1031
  "zulu"
1062
1032
  ];
1063
1033
  var HumanHasher = class {
1034
+ wordlist;
1035
+ /**
1036
+ * Transforms hex digests to human-readable strings.
1037
+ *
1038
+ * The format of these strings will look something like:
1039
+ * `victor-bacon-zulu-lima`. The output is obtained by compressing the input
1040
+ * digest to a fixed number of bytes, then mapping those bytes to one of 256
1041
+ * words. A default wordlist is provided, but you can override this if you
1042
+ * prefer.
1043
+ * As long as you use the same wordlist, the output will be consistent (i.e.
1044
+ * the same digest will always render the same representation).
1045
+ *
1046
+ * @param wordlist A list of exactly 256 words to choose from
1047
+ */
1048
+ constructor(wordlist = DEFAULT_WORDLIST) {
1049
+ this.wordlist = wordlist;
1050
+ if (wordlist.length !== 256) {
1051
+ throw new Error("Wordlist must have exactly 256 items");
1052
+ }
1053
+ this.wordlist = wordlist;
1054
+ }
1064
1055
  /**
1065
1056
  * Humanize a given hexadecimal digest.
1066
1057
  *
@@ -1100,27 +1091,6 @@ var HumanHasher = class {
1100
1091
  const checksums = segments.map((x) => x.reduce((acc, curr) => acc ^ curr));
1101
1092
  return checksums;
1102
1093
  }
1103
- /**
1104
- * Transforms hex digests to human-readable strings.
1105
- *
1106
- * The format of these strings will look something like:
1107
- * `victor-bacon-zulu-lima`. The output is obtained by compressing the input
1108
- * digest to a fixed number of bytes, then mapping those bytes to one of 256
1109
- * words. A default wordlist is provided, but you can override this if you
1110
- * prefer.
1111
- * As long as you use the same wordlist, the output will be consistent (i.e.
1112
- * the same digest will always render the same representation).
1113
- *
1114
- * @param wordlist A list of exactly 256 words to choose from
1115
- */
1116
- constructor(wordlist = DEFAULT_WORDLIST) {
1117
- _define_property6(this, "wordlist", void 0);
1118
- this.wordlist = wordlist;
1119
- if (wordlist.length !== 256) {
1120
- throw new Error("Wordlist must have exactly 256 items");
1121
- }
1122
- this.wordlist = wordlist;
1123
- }
1124
1094
  };
1125
1095
  var hasher = new HumanHasher();
1126
1096
  var humanize = (value) => {
@@ -1143,10 +1113,8 @@ var defaultMap = (map, key, def) => {
1143
1113
  };
1144
1114
 
1145
1115
  // src/instance-id.ts
1146
- var _globalThis;
1147
- var _symbol;
1148
- var symbol = Symbol.for("dxos.instance-contexts");
1149
- var instanceContexts = (_globalThis = globalThis)[_symbol = symbol] ?? (_globalThis[_symbol] = /* @__PURE__ */ new WeakMap());
1116
+ var symbol = /* @__PURE__ */ Symbol.for("dxos.instance-contexts");
1117
+ var instanceContexts = globalThis[symbol] ??= /* @__PURE__ */ new WeakMap();
1150
1118
  var getPrototypeSpecificInstanceId = (instance) => {
1151
1119
  const prototype = Object.getPrototypeOf(instance);
1152
1120
  const instanceCtx = defaultMap(instanceContexts, prototype, () => ({
@@ -1318,19 +1286,6 @@ var jsonKeyReplacer = (options = {}) => (key, value) => {
1318
1286
  };
1319
1287
 
1320
1288
  // src/map-values.ts
1321
- function _define_property7(obj, key, value) {
1322
- if (key in obj) {
1323
- Object.defineProperty(obj, key, {
1324
- value,
1325
- enumerable: true,
1326
- configurable: true,
1327
- writable: true
1328
- });
1329
- } else {
1330
- obj[key] = value;
1331
- }
1332
- return obj;
1333
- }
1334
1289
  var mapValues = (obj, fn) => {
1335
1290
  const result = {};
1336
1291
  Object.keys(obj).forEach((key) => {
@@ -1342,6 +1297,11 @@ var deepMapValues = (value, fn) => {
1342
1297
  return new DeepMapper(fn).map(value);
1343
1298
  };
1344
1299
  var DeepMapper = class {
1300
+ _fn;
1301
+ _cyclic = /* @__PURE__ */ new Map();
1302
+ constructor(_fn) {
1303
+ this._fn = _fn;
1304
+ }
1345
1305
  map(value) {
1346
1306
  return this._map(value, void 0);
1347
1307
  }
@@ -1351,40 +1311,38 @@ var DeepMapper = class {
1351
1311
  }
1352
1312
  return this._fn(value, this._recurse, key);
1353
1313
  }
1354
- constructor(_fn) {
1355
- _define_property7(this, "_fn", void 0);
1356
- _define_property7(this, "_cyclic", void 0);
1357
- _define_property7(this, "_recurse", void 0);
1358
- this._fn = _fn;
1359
- this._cyclic = /* @__PURE__ */ new Map();
1360
- this._recurse = (value) => {
1361
- if (this._cyclic.has(value)) {
1362
- return this._cyclic.get(value);
1314
+ _recurse = (value) => {
1315
+ if (this._cyclic.has(value)) {
1316
+ return this._cyclic.get(value);
1317
+ }
1318
+ if (Array.isArray(value)) {
1319
+ const res = new Array(value.length);
1320
+ this._cyclic.set(value, res);
1321
+ for (let i = 0; i < value.length; i++) {
1322
+ res[i] = this._map(value[i], i);
1363
1323
  }
1364
- if (Array.isArray(value)) {
1365
- const res = new Array(value.length);
1366
- this._cyclic.set(value, res);
1367
- for (let i = 0; i < value.length; i++) {
1368
- res[i] = this._map(value[i], i);
1369
- }
1370
- return res;
1371
- } else if (value !== null && typeof value === "object") {
1372
- const res = {};
1373
- this._cyclic.set(value, res);
1374
- for (const key in value) {
1375
- res[key] = this._map(value[key], key);
1376
- }
1377
- return res;
1378
- } else {
1379
- return value;
1324
+ return res;
1325
+ } else if (value !== null && typeof value === "object") {
1326
+ const res = {};
1327
+ this._cyclic.set(value, res);
1328
+ for (const key in value) {
1329
+ res[key] = this._map(value[key], key);
1380
1330
  }
1381
- };
1382
- }
1331
+ return res;
1332
+ } else {
1333
+ return value;
1334
+ }
1335
+ };
1383
1336
  };
1384
1337
  var deepMapValuesAsync = (value, fn) => {
1385
1338
  return new DeepMapperAsync(fn).map(value);
1386
1339
  };
1387
1340
  var DeepMapperAsync = class {
1341
+ _fn;
1342
+ _cyclic = /* @__PURE__ */ new Map();
1343
+ constructor(_fn) {
1344
+ this._fn = _fn;
1345
+ }
1388
1346
  map(value) {
1389
1347
  return this._map(value, void 0);
1390
1348
  }
@@ -1394,35 +1352,28 @@ var DeepMapperAsync = class {
1394
1352
  }
1395
1353
  return this._fn(value, this._recurse, key);
1396
1354
  }
1397
- constructor(_fn) {
1398
- _define_property7(this, "_fn", void 0);
1399
- _define_property7(this, "_cyclic", void 0);
1400
- _define_property7(this, "_recurse", void 0);
1401
- this._fn = _fn;
1402
- this._cyclic = /* @__PURE__ */ new Map();
1403
- this._recurse = async (value) => {
1404
- if (this._cyclic.has(value)) {
1405
- return this._cyclic.get(value);
1355
+ _recurse = async (value) => {
1356
+ if (this._cyclic.has(value)) {
1357
+ return this._cyclic.get(value);
1358
+ }
1359
+ if (Array.isArray(value)) {
1360
+ const res = new Array(value.length);
1361
+ this._cyclic.set(value, res);
1362
+ for (let i = 0; i < value.length; i++) {
1363
+ res[i] = await this._map(value[i], i);
1406
1364
  }
1407
- if (Array.isArray(value)) {
1408
- const res = new Array(value.length);
1409
- this._cyclic.set(value, res);
1410
- for (let i = 0; i < value.length; i++) {
1411
- res[i] = await this._map(value[i], i);
1412
- }
1413
- return res;
1414
- } else if (value !== null && typeof value === "object") {
1415
- const res = {};
1416
- this._cyclic.set(value, res);
1417
- for (const key in value) {
1418
- res[key] = await this._map(value[key], key);
1419
- }
1420
- return res;
1421
- } else {
1422
- return value;
1365
+ return res;
1366
+ } else if (value !== null && typeof value === "object") {
1367
+ const res = {};
1368
+ this._cyclic.set(value, res);
1369
+ for (const key in value) {
1370
+ res[key] = await this._map(value[key], key);
1423
1371
  }
1424
- };
1425
- }
1372
+ return res;
1373
+ } else {
1374
+ return value;
1375
+ }
1376
+ };
1426
1377
  };
1427
1378
  var visitValues = (object, visitor) => {
1428
1379
  if (Array.isArray(object)) {
@@ -1511,7 +1462,18 @@ var omit = (obj, keys2) => {
1511
1462
 
1512
1463
  // src/platform.ts
1513
1464
  var isNode = () => typeof process !== "undefined" && process.versions != null && process.versions.node != null;
1514
- var mobileAndTabletCheck = () => {
1465
+ var isBun = () => globalThis.Bun !== void 0;
1466
+ var isTauri = () => !!globalThis.__TAURI__;
1467
+ var isMobile = () => {
1468
+ let check = false;
1469
+ (function(a) {
1470
+ if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
1471
+ check = true;
1472
+ }
1473
+ })(navigator.userAgent || navigator.vendor || window.opera);
1474
+ return check;
1475
+ };
1476
+ var isMobileOrTablet = () => {
1515
1477
  let check = false;
1516
1478
  ((a) => {
1517
1479
  if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
@@ -1533,7 +1495,7 @@ var iosCheck = () => {
1533
1495
  };
1534
1496
  var safariCheck = () => typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
1535
1497
  var getHostPlatform = () => {
1536
- if (!("navigator" in window)) {
1498
+ if (!("navigator" in globalThis)) {
1537
1499
  return "unknown";
1538
1500
  }
1539
1501
  const platform = (navigator.userAgentData?.platform || navigator.platform)?.toLowerCase();
@@ -1709,6 +1671,43 @@ var removeProperties = (root, condition) => {
1709
1671
  return result;
1710
1672
  };
1711
1673
 
1674
+ // src/retry.ts
1675
+ var DEFAULT_RETRY_OPTIONS = {
1676
+ count: 3,
1677
+ delayMs: 100,
1678
+ exponent: 2,
1679
+ retryOnError: async () => true,
1680
+ retryOnValue: async () => false
1681
+ };
1682
+ var retry = async (options, cb) => {
1683
+ const fullOptions = {
1684
+ ...DEFAULT_RETRY_OPTIONS,
1685
+ ...options
1686
+ };
1687
+ let numRetries = 0, currentDelay = fullOptions.delayMs;
1688
+ while (true) {
1689
+ let result;
1690
+ try {
1691
+ result = await cb();
1692
+ } catch (err) {
1693
+ if (numRetries > fullOptions.count || !await fullOptions.retryOnError(err)) {
1694
+ throw err;
1695
+ }
1696
+ await new Promise((resolve) => setTimeout(resolve, currentDelay));
1697
+ currentDelay *= fullOptions.exponent;
1698
+ numRetries++;
1699
+ continue;
1700
+ }
1701
+ if (!await fullOptions.retryOnValue(result)) {
1702
+ return result;
1703
+ }
1704
+ await new Promise((resolve) => setTimeout(resolve, currentDelay));
1705
+ currentDelay *= fullOptions.exponent;
1706
+ numRetries++;
1707
+ continue;
1708
+ }
1709
+ };
1710
+
1712
1711
  // src/safe-await.ts
1713
1712
  var safeAwaitAll = async (source, taskFactory, onError) => {
1714
1713
  const failedItems = [];
@@ -1728,7 +1727,7 @@ var safeAwaitAll = async (source, taskFactory, onError) => {
1728
1727
  };
1729
1728
 
1730
1729
  // src/safe-instanceof.ts
1731
- var instanceTag = Symbol("instanceTag");
1730
+ var instanceTag = /* @__PURE__ */ Symbol("instanceTag");
1732
1731
  var safeInstanceof = (tag) => (target) => {
1733
1732
  target.prototype[instanceTag] = tag;
1734
1733
  Object.defineProperty(target.prototype, Symbol.hasInstance, {
@@ -1740,48 +1739,151 @@ var safeInstanceof = (tag) => (target) => {
1740
1739
  };
1741
1740
 
1742
1741
  // src/safe-parse.ts
1743
- var safeParseInt = (value, defaultValue) => {
1742
+ function safeParseInt(str, defaultValue) {
1744
1743
  try {
1745
- const n = parseInt(value ?? "");
1746
- return isNaN(n) ? defaultValue : n;
1744
+ const value = parseInt(str ?? "");
1745
+ return isNaN(value) ? defaultValue : value;
1747
1746
  } catch {
1748
1747
  return defaultValue;
1749
1748
  }
1750
- };
1751
- var safeParseFloat = (str, defaultValue) => {
1749
+ }
1750
+ function safeParseFloat(str, defaultValue) {
1752
1751
  try {
1753
- return parseFloat(str);
1752
+ const value = parseFloat(str ?? "");
1753
+ return isNaN(value) ? defaultValue : value;
1754
1754
  } catch {
1755
- return defaultValue ?? 0;
1755
+ return defaultValue;
1756
1756
  }
1757
- };
1758
- var safeParseJson = (data, defaultValue) => {
1759
- if (data && data.length > 0) {
1757
+ }
1758
+ var safeParseJson = (str, defaultValue) => {
1759
+ if (str && str.length > 0) {
1760
1760
  try {
1761
- return JSON.parse(data);
1761
+ return JSON.parse(str);
1762
1762
  } catch {
1763
1763
  }
1764
1764
  }
1765
1765
  return defaultValue;
1766
1766
  };
1767
+ var safeUrl = (str) => {
1768
+ try {
1769
+ return new URL(str ?? "");
1770
+ } catch {
1771
+ return void 0;
1772
+ }
1773
+ };
1767
1774
 
1768
- // src/sliding-window-summary.ts
1769
- import { invariant as invariant5 } from "@dxos/invariant";
1770
- function _define_property8(obj, key, value) {
1771
- if (key in obj) {
1772
- Object.defineProperty(obj, key, {
1773
- value,
1774
- enumerable: true,
1775
- configurable: true,
1776
- writable: true
1777
- });
1778
- } else {
1779
- obj[key] = value;
1775
+ // src/safe-stringify.ts
1776
+ var SKIP = Object.freeze({});
1777
+ function safeStringify(obj, filter = defaultFilter, indent = 2) {
1778
+ const seen = /* @__PURE__ */ new WeakMap();
1779
+ function replacer(key, value) {
1780
+ try {
1781
+ let path = key;
1782
+ if (!key) {
1783
+ path = "$";
1784
+ if (value != null && typeof value === "object") {
1785
+ seen.set(value, path);
1786
+ }
1787
+ return value;
1788
+ } else if (this) {
1789
+ const parentPath = seen.get(this);
1790
+ path = parentPath ? `${parentPath}.${key}` : key;
1791
+ }
1792
+ if (value == null) {
1793
+ return value;
1794
+ }
1795
+ if (typeof value === "function") {
1796
+ return void 0;
1797
+ }
1798
+ if (typeof value === "object" && Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value)) {
1799
+ return void 0;
1800
+ }
1801
+ if (typeof value === "object" && value !== null) {
1802
+ const exists = seen.get(value);
1803
+ if (exists) {
1804
+ return `[${path} => ${exists}]`;
1805
+ }
1806
+ seen.set(value, path);
1807
+ }
1808
+ if (filter) {
1809
+ const filteredValue = filter?.(key, value);
1810
+ if (filteredValue !== void 0) {
1811
+ return filteredValue === SKIP ? void 0 : filteredValue;
1812
+ }
1813
+ }
1814
+ return value;
1815
+ } catch (error) {
1816
+ return `ERROR: ${error.message}`;
1817
+ }
1818
+ }
1819
+ try {
1820
+ return JSON.stringify(obj, replacer, indent);
1821
+ } catch (error) {
1822
+ return `ERROR: ${error.message}`;
1780
1823
  }
1781
- return obj;
1782
1824
  }
1825
+ var createReplacer = ({ omit: omit2, parse, maxDepth, maxArrayLen, maxStringLen } = {}) => {
1826
+ let currentDepth = 0;
1827
+ const depthMap = /* @__PURE__ */ new WeakMap();
1828
+ return function(key, value) {
1829
+ if (key === "") {
1830
+ currentDepth = 0;
1831
+ } else if (this && typeof this === "object") {
1832
+ const parentDepth = depthMap.get(this) ?? 0;
1833
+ currentDepth = parentDepth + 1;
1834
+ }
1835
+ if (typeof value === "function") {
1836
+ return SKIP;
1837
+ }
1838
+ if (maxArrayLen != null && Array.isArray(value) && value.length > maxArrayLen) {
1839
+ return `[length: ${value.length}]`;
1840
+ }
1841
+ if (value && typeof value === "object") {
1842
+ depthMap.set(value, currentDepth);
1843
+ if (maxDepth != null && currentDepth >= maxDepth) {
1844
+ return Array.isArray(value) ? `[{ length: ${value.length} }]` : `{ keys: ${Object.keys(value).length} }`;
1845
+ }
1846
+ }
1847
+ if (omit2?.includes(key)) {
1848
+ return SKIP;
1849
+ }
1850
+ if (parse?.includes(key) && typeof value === "string") {
1851
+ try {
1852
+ return JSON.parse(value);
1853
+ } catch {
1854
+ return value;
1855
+ }
1856
+ }
1857
+ if (maxStringLen != null && typeof value === "string" && value.length > maxStringLen) {
1858
+ return value.slice(0, maxStringLen) + "...";
1859
+ }
1860
+ return value;
1861
+ };
1862
+ };
1863
+ var defaultFilter = createReplacer();
1864
+
1865
+ // src/sliding-window-summary.ts
1866
+ import { invariant as invariant5 } from "@dxos/invariant";
1783
1867
  var __dxlog_file5 = "/__w/dxos/dxos/packages/common/util/src/sliding-window-summary.ts";
1784
1868
  var SlidingWindowSummary = class {
1869
+ _buffer;
1870
+ _sum = 0;
1871
+ _precision;
1872
+ constructor(options) {
1873
+ this._buffer = new CircularBuffer(options.dataPoints);
1874
+ if (options.precision != null) {
1875
+ invariant5(options.precision >= 0, void 0, {
1876
+ F: __dxlog_file5,
1877
+ L: 26,
1878
+ S: this,
1879
+ A: [
1880
+ "options.precision >= 0",
1881
+ ""
1882
+ ]
1883
+ });
1884
+ this._precision = Math.pow(10, options.precision);
1885
+ }
1886
+ }
1785
1887
  record(value) {
1786
1888
  const evicted = this._buffer.push(value);
1787
1889
  this._sum += value - (evicted ?? 0);
@@ -1816,24 +1918,6 @@ var SlidingWindowSummary = class {
1816
1918
  }
1817
1919
  return Math.round(value * this._precision) / this._precision;
1818
1920
  }
1819
- constructor(options) {
1820
- _define_property8(this, "_buffer", void 0);
1821
- _define_property8(this, "_sum", 0);
1822
- _define_property8(this, "_precision", void 0);
1823
- this._buffer = new CircularBuffer(options.dataPoints);
1824
- if (options.precision != null) {
1825
- invariant5(options.precision >= 0, void 0, {
1826
- F: __dxlog_file5,
1827
- L: 26,
1828
- S: this,
1829
- A: [
1830
- "options.precision >= 0",
1831
- ""
1832
- ]
1833
- });
1834
- this._precision = Math.pow(10, options.precision);
1835
- }
1836
- }
1837
1921
  };
1838
1922
 
1839
1923
  // src/sort.ts
@@ -1896,18 +1980,6 @@ var throwUnhandledError = (error) => {
1896
1980
 
1897
1981
  // src/to-fallback.ts
1898
1982
  var idEmoji = [
1899
- // When changing this set, please check the result in a console or e.g. RunKit (https://runkit.com/thure/642214441dd6ae000855a8de)
1900
- // Emoji sometimes use a combination of code points, and some code points aren't visible on their own, so by adding or deleting you may unintentionally create non-visible items.
1901
- // This set was chosen from the characters in Unicode Emoji v15.0 based on the following criteria:
1902
- // – not people or isolated anthropomorphic faces
1903
- // – not flags
1904
- // – more concrete than abstract
1905
- // – less culturally specific
1906
- // – less easily confused with another emoji in the set
1907
- // – requires less special knowledge to identify
1908
- // – less likely to evoke negative feelings (no meat, no drugs, no weapons, etc)
1909
- // – less common as a signifier in UX
1910
- // NOTE that this is intentionally an array of strings because of the way emoji graphemes work.
1911
1983
  "\u{1F47B}",
1912
1984
  "\u{1F479}",
1913
1985
  "\u{1F47D}",
@@ -2043,17 +2115,18 @@ var idEmoji = [
2043
2115
  ];
2044
2116
  var idHue = [
2045
2117
  "red",
2046
- // 'orange' as const, /* More shades in these palettes are considered “ugly” */
2118
+ "orange",
2047
2119
  "amber",
2048
- // 'yellow' as const, /* More shades in these palettes are considered “ugly” */
2120
+ "yellow",
2049
2121
  "lime",
2050
2122
  "green",
2051
2123
  "emerald",
2052
2124
  "teal",
2053
2125
  "cyan",
2054
- // 'sky' as const, /* Omitted since it is quite similar to the primary accent palette */
2055
- // 'blue' as const, /* Omitted since it is quite similar to the primary accent palette */
2056
- // 'indigo' as const, /* Omitted since it is quite similar to the primary accent palette */
2126
+ // Omit colors similar to primary accent.
2127
+ // 'sky' as const,
2128
+ // 'blue' as const,
2129
+ // 'indigo' as const,
2057
2130
  "violet",
2058
2131
  "purple",
2059
2132
  "fuchsia",
@@ -2080,20 +2153,9 @@ var toFallback = (hash) => {
2080
2153
  };
2081
2154
 
2082
2155
  // src/tracer.ts
2083
- function _define_property9(obj, key, value) {
2084
- if (key in obj) {
2085
- Object.defineProperty(obj, key, {
2086
- value,
2087
- enumerable: true,
2088
- configurable: true,
2089
- writable: true
2090
- });
2091
- } else {
2092
- obj[key] = value;
2093
- }
2094
- return obj;
2095
- }
2096
2156
  var Tracer = class {
2157
+ _events = /* @__PURE__ */ new Map();
2158
+ _recording = false;
2097
2159
  // TODO(burdon): Start/stop methods for recording data? By id?
2098
2160
  // Alternatively, enable subscriptions to track/compute series.
2099
2161
  // TODO(burdon): Hierarchical traces?
@@ -2150,10 +2212,6 @@ var Tracer = class {
2150
2212
  defaultMap(this._events, event.id, []).push(event);
2151
2213
  }
2152
2214
  }
2153
- constructor() {
2154
- _define_property9(this, "_events", /* @__PURE__ */ new Map());
2155
- _define_property9(this, "_recording", false);
2156
- }
2157
2215
  };
2158
2216
  var tracer = new Tracer();
2159
2217
 
@@ -2228,69 +2286,112 @@ var arrayMove = (array, from, to) => {
2228
2286
  array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
2229
2287
  return array;
2230
2288
  };
2289
+ function arraySwap(array, from, to) {
2290
+ const current = array[from];
2291
+ array[from] = array[to];
2292
+ array[to] = current;
2293
+ return array;
2294
+ }
2231
2295
 
2232
2296
  // src/unit.ts
2233
- var Formatter = (unit) => {
2234
- return (n, precision = 2) => {
2297
+ var createFormat = (unit) => {
2298
+ return (n, precision = unit.precision ?? 0) => {
2235
2299
  const value = n / unit.quotient;
2236
- return `${value.toFixed(precision)}${unit.symbol}`;
2300
+ return {
2301
+ unit,
2302
+ value,
2303
+ formattedValue: value.toFixed(precision),
2304
+ toString: () => `${value.toFixed(precision)}${unit.symbol}`
2305
+ };
2237
2306
  };
2238
2307
  };
2308
+ var MS_SECONDS = 1e3;
2309
+ var MS_MINUTES = 60 * MS_SECONDS;
2310
+ var MS_HOURS = 60 * MS_MINUTES;
2239
2311
  var Unit = {
2240
- // ms.
2241
- Hour: Formatter({
2312
+ // General.
2313
+ Percent: createFormat({
2314
+ symbol: "%",
2315
+ quotient: 1 / 100,
2316
+ precision: 2
2317
+ }),
2318
+ Thousand: createFormat({
2319
+ symbol: "k",
2320
+ quotient: 1e3,
2321
+ precision: 2
2322
+ }),
2323
+ // Bytes (note KB vs KiB).
2324
+ Gigabyte: createFormat({
2325
+ symbol: "GB",
2326
+ quotient: 1e3 * 1e3 * 1e3,
2327
+ precision: 2
2328
+ }),
2329
+ Megabyte: createFormat({
2330
+ symbol: "MB",
2331
+ quotient: 1e3 * 1e3,
2332
+ precision: 2
2333
+ }),
2334
+ Kilobyte: createFormat({
2335
+ symbol: "KB",
2336
+ quotient: 1e3,
2337
+ precision: 2
2338
+ }),
2339
+ Byte: createFormat({
2340
+ symbol: "B",
2341
+ quotient: 1
2342
+ }),
2343
+ // Time.
2344
+ Hour: createFormat({
2242
2345
  symbol: "h",
2243
- quotient: 60 * 60 * 1e3
2346
+ quotient: MS_HOURS
2244
2347
  }),
2245
- Minute: Formatter({
2348
+ Minute: createFormat({
2246
2349
  symbol: "m",
2247
- quotient: 60 * 1e3
2350
+ quotient: MS_MINUTES
2248
2351
  }),
2249
- Second: Formatter({
2352
+ Second: createFormat({
2250
2353
  symbol: "s",
2251
- quotient: 1e3
2354
+ quotient: MS_SECONDS,
2355
+ precision: 1
2252
2356
  }),
2253
- Millisecond: Formatter({
2357
+ Millisecond: createFormat({
2254
2358
  symbol: "ms",
2255
2359
  quotient: 1
2256
2360
  }),
2257
2361
  Duration: (n) => {
2258
- const hours = Math.floor(n / (60 * 60 * 1e3));
2259
- const minutes = Math.floor(n % (60 * 60 * 1e3) / (60 * 1e3));
2362
+ const hours = Math.floor(n / MS_HOURS);
2363
+ const minutes = Math.floor(n % MS_HOURS / MS_MINUTES);
2260
2364
  if (hours) {
2261
- return minutes ? `${hours}h ${minutes}m` : `${hours}h`;
2365
+ const formattedValue = minutes ? `${hours}h ${minutes}m` : `${hours}h`;
2366
+ return {
2367
+ unit: {
2368
+ symbol: "h",
2369
+ quotient: MS_HOURS
2370
+ },
2371
+ value: hours,
2372
+ formattedValue,
2373
+ toString: () => formattedValue
2374
+ };
2262
2375
  }
2263
- const seconds = Math.floor(n % (60 * 1e3) / 1e3);
2264
2376
  if (minutes) {
2265
- return seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;
2377
+ const seconds2 = (n - MS_MINUTES * minutes) / MS_SECONDS;
2378
+ const formattedValue = seconds2 ? `${minutes}m ${seconds2}s` : `${minutes}m`;
2379
+ return {
2380
+ unit: {
2381
+ symbol: "m",
2382
+ quotient: MS_MINUTES
2383
+ },
2384
+ value: minutes,
2385
+ formattedValue,
2386
+ toString: () => formattedValue
2387
+ };
2266
2388
  }
2389
+ const seconds = n >= MS_SECONDS;
2267
2390
  if (seconds) {
2268
- return `${(n / 1e3).toFixed(1)}s`;
2391
+ return Unit.Second(n);
2269
2392
  }
2270
- return `${n}ms`;
2271
- },
2272
- // bytes (note KB via KiB).
2273
- Gigabyte: Formatter({
2274
- symbol: "GB",
2275
- quotient: 1e3 * 1e3 * 1e3
2276
- }),
2277
- Megabyte: Formatter({
2278
- symbol: "MB",
2279
- quotient: 1e3 * 1e3
2280
- }),
2281
- Kilobyte: Formatter({
2282
- symbol: "KB",
2283
- quotient: 1e3
2284
- }),
2285
- // general.
2286
- Thousand: Formatter({
2287
- symbol: "k",
2288
- quotient: 1e3
2289
- }),
2290
- Percent: Formatter({
2291
- symbol: "%",
2292
- quotient: 1 / 100
2293
- })
2393
+ return Unit.Millisecond(n);
2394
+ }
2294
2395
  };
2295
2396
 
2296
2397
  // src/url.ts
@@ -2303,20 +2404,22 @@ var createUrl = (url, search) => {
2303
2404
  };
2304
2405
 
2305
2406
  // src/weak.ts
2306
- function _define_property10(obj, key, value) {
2307
- if (key in obj) {
2308
- Object.defineProperty(obj, key, {
2309
- value,
2310
- enumerable: true,
2311
- configurable: true,
2312
- writable: true
2313
- });
2314
- } else {
2315
- obj[key] = value;
2316
- }
2317
- return obj;
2318
- }
2319
2407
  var WeakDictionary = class {
2408
+ _internal = /* @__PURE__ */ new Map();
2409
+ _finalization = new FinalizationRegistry(({ key, ref }) => {
2410
+ if (this._internal.get(key) === ref) {
2411
+ this._internal.delete(key);
2412
+ }
2413
+ });
2414
+ constructor(entries2) {
2415
+ if (entries2) {
2416
+ for (const [key, value] of entries2) {
2417
+ const ref = new WeakRef(value);
2418
+ this._internal.set(key, ref);
2419
+ this._register(key, value, ref);
2420
+ }
2421
+ }
2422
+ }
2320
2423
  *entries() {
2321
2424
  for (const [key, value] of this._internal) {
2322
2425
  yield [
@@ -2355,10 +2458,45 @@ var WeakDictionary = class {
2355
2458
  return this._internal.get(key)?.deref();
2356
2459
  }
2357
2460
  set(key, value) {
2358
- this._internal.set(key, new WeakRef(value));
2359
- this._register(key, value);
2461
+ const previous = this._internal.get(key)?.deref();
2462
+ if (previous) {
2463
+ this._unregister(previous);
2464
+ }
2465
+ const ref = new WeakRef(value);
2466
+ this._internal.set(key, ref);
2467
+ this._register(key, value, ref);
2360
2468
  return this;
2361
2469
  }
2470
+ /**
2471
+ * Returns the value for the given key if present, otherwise inserts and returns the default value.
2472
+ * @param key - The key to look up or insert.
2473
+ * @param defaultValue - The value to insert if the key is not present.
2474
+ * @returns The existing or newly inserted value.
2475
+ */
2476
+ getOrInsert(key, defaultValue) {
2477
+ const existing = this.get(key);
2478
+ if (existing !== void 0) {
2479
+ return existing;
2480
+ }
2481
+ this.set(key, defaultValue);
2482
+ return defaultValue;
2483
+ }
2484
+ /**
2485
+ * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
2486
+ * The callback is only invoked when the key is missing.
2487
+ * @param key - The key to look up or insert.
2488
+ * @param callbackfn - Function to compute the value if the key is not present.
2489
+ * @returns The existing or newly computed value.
2490
+ */
2491
+ getOrInsertComputed(key, callbackfn) {
2492
+ const existing = this.get(key);
2493
+ if (existing !== void 0) {
2494
+ return existing;
2495
+ }
2496
+ const value = callbackfn(key);
2497
+ this.set(key, value);
2498
+ return value;
2499
+ }
2362
2500
  has(key) {
2363
2501
  return this._internal.has(key) && this._internal.get(key).deref() !== void 0;
2364
2502
  }
@@ -2389,25 +2527,15 @@ var WeakDictionary = class {
2389
2527
  }
2390
2528
  });
2391
2529
  }
2392
- _register(key, value) {
2393
- this._finalization.register(value, () => {
2394
- this._internal.delete(key);
2530
+ _register(key, value, ref) {
2531
+ this._finalization.register(value, {
2532
+ key,
2533
+ ref
2395
2534
  }, value);
2396
2535
  }
2397
2536
  _unregister(value) {
2398
2537
  this._finalization.unregister(value);
2399
2538
  }
2400
- constructor(entries2) {
2401
- _define_property10(this, "_internal", /* @__PURE__ */ new Map());
2402
- _define_property10(this, "_finalization", new FinalizationRegistry((cleanUpCallback) => {
2403
- cleanUpCallback();
2404
- }));
2405
- this._internal = new Map(entries2?.map(([key, value]) => [
2406
- key,
2407
- new WeakRef(value)
2408
- ]));
2409
- entries2?.forEach(([key, value]) => this._register(key, value));
2410
- }
2411
2539
  };
2412
2540
  export {
2413
2541
  BitField,
@@ -2418,12 +2546,14 @@ export {
2418
2546
  ComplexSet,
2419
2547
  HumanHasher,
2420
2548
  MapEntry,
2549
+ SKIP,
2421
2550
  SlidingWindowSummary,
2422
2551
  Tracer,
2423
2552
  Unit,
2424
2553
  WeakDictionary,
2425
2554
  accessBy,
2426
2555
  arrayMove,
2556
+ arraySwap,
2427
2557
  arrayToBuffer,
2428
2558
  arrayToHex,
2429
2559
  arrayToString,
@@ -2434,19 +2564,28 @@ export {
2434
2564
  capitalize,
2435
2565
  chunkArray,
2436
2566
  clamp,
2567
+ clearCaches,
2568
+ clearIndexedDB,
2569
+ clearOPFS,
2570
+ clearServiceWorkers,
2437
2571
  clearUndefined,
2572
+ coerceArray,
2438
2573
  compareMulti,
2439
2574
  compareObject,
2440
2575
  compareScalar,
2441
2576
  compareString,
2577
+ compositeKey,
2442
2578
  createBinder,
2443
2579
  createBucketReducer,
2580
+ createFilename,
2444
2581
  createGroupReducer,
2582
+ createReplacer,
2445
2583
  createSetDispatch,
2446
2584
  createUrl,
2447
2585
  decamelize,
2448
2586
  deepMapValues,
2449
2587
  deepMapValuesAsync,
2588
+ defaultFilter,
2450
2589
  defaultMap,
2451
2590
  defer,
2452
2591
  deferAsync,
@@ -2458,7 +2597,7 @@ export {
2458
2597
  entry,
2459
2598
  exponentialBackoffInterval,
2460
2599
  forEachAsync,
2461
- get,
2600
+ formatErrorWithCauses,
2462
2601
  getAsyncProviderValue,
2463
2602
  getDate,
2464
2603
  getDebugName,
@@ -2478,8 +2617,12 @@ export {
2478
2617
  intersectBy,
2479
2618
  intersection,
2480
2619
  iosCheck,
2620
+ isBun,
2621
+ isMobile,
2622
+ isMobileOrTablet,
2481
2623
  isNode,
2482
2624
  isNonNullable,
2625
+ isTauri,
2483
2626
  isTruthy,
2484
2627
  joinTables,
2485
2628
  jsonKeyReplacer,
@@ -2495,7 +2638,6 @@ export {
2495
2638
  makeSet,
2496
2639
  mapValues,
2497
2640
  median,
2498
- mobileAndTabletCheck,
2499
2641
  numericalValues,
2500
2642
  omit,
2501
2643
  orderKeys,
@@ -2511,15 +2653,18 @@ export {
2511
2653
  removeBy,
2512
2654
  removeProperties,
2513
2655
  removeUndefinedProperties,
2656
+ retry,
2514
2657
  safariCheck,
2515
2658
  safeAwaitAll,
2516
2659
  safeInstanceof,
2517
2660
  safeParseFloat,
2518
2661
  safeParseInt,
2519
2662
  safeParseJson,
2520
- set,
2663
+ safeStringify,
2664
+ safeUrl,
2521
2665
  setDeep,
2522
2666
  sortKeys,
2667
+ splitCompositeKey,
2523
2668
  stringToArray,
2524
2669
  stringifyTree,
2525
2670
  stripUndefined,