@dxos/util 0.8.4-main.84f28bd → 0.8.4-main.8baae0fced

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 (153) hide show
  1. package/LICENSE +102 -5
  2. package/dist/lib/browser/index.mjs +637 -228
  3. package/dist/lib/browser/index.mjs.map +4 -4
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/node-esm/index.mjs +637 -228
  6. package/dist/lib/node-esm/index.mjs.map +4 -4
  7. package/dist/lib/node-esm/meta.json +1 -1
  8. package/dist/types/src/array-to-hex.d.ts.map +1 -1
  9. package/dist/types/src/array.d.ts +3 -2
  10. package/dist/types/src/array.d.ts.map +1 -1
  11. package/dist/types/src/assume.d.ts.map +1 -1
  12. package/dist/types/src/binder.d.ts.map +1 -1
  13. package/dist/types/src/bitfield.d.ts.map +1 -1
  14. package/dist/types/src/browser-storage.d.ts +9 -0
  15. package/dist/types/src/browser-storage.d.ts.map +1 -0
  16. package/dist/types/src/callback-collection.d.ts.map +1 -1
  17. package/dist/types/src/callback.d.ts.map +1 -1
  18. package/dist/types/src/case.d.ts.map +1 -1
  19. package/dist/types/src/chunk-array.d.ts.map +1 -1
  20. package/dist/types/src/circular-buffer.d.ts +1 -0
  21. package/dist/types/src/circular-buffer.d.ts.map +1 -1
  22. package/dist/types/src/clear-undefined.d.ts.map +1 -1
  23. package/dist/types/src/complex.d.ts +15 -0
  24. package/dist/types/src/complex.d.ts.map +1 -1
  25. package/dist/types/src/composite-key.d.ts +10 -0
  26. package/dist/types/src/composite-key.d.ts.map +1 -0
  27. package/dist/types/src/composite-key.test.d.ts +2 -0
  28. package/dist/types/src/composite-key.test.d.ts.map +1 -0
  29. package/dist/types/src/deep.d.ts +0 -3
  30. package/dist/types/src/deep.d.ts.map +1 -1
  31. package/dist/types/src/defer-function.d.ts.map +1 -1
  32. package/dist/types/src/defer.d.ts +1 -1
  33. package/dist/types/src/defer.d.ts.map +1 -1
  34. package/dist/types/src/di-container.d.ts.map +1 -1
  35. package/dist/types/src/di-key.d.ts +7 -5
  36. package/dist/types/src/di-key.d.ts.map +1 -1
  37. package/dist/types/src/entry.d.ts.map +1 -1
  38. package/dist/types/src/error-format.d.ts +5 -0
  39. package/dist/types/src/error-format.d.ts.map +1 -0
  40. package/dist/types/src/filename.d.ts +9 -0
  41. package/dist/types/src/filename.d.ts.map +1 -0
  42. package/dist/types/src/for-each-async.d.ts.map +1 -1
  43. package/dist/types/src/human-hash.d.ts.map +1 -1
  44. package/dist/types/src/id.d.ts +30 -0
  45. package/dist/types/src/id.d.ts.map +1 -0
  46. package/dist/types/src/id.test.d.ts +2 -0
  47. package/dist/types/src/id.test.d.ts.map +1 -0
  48. package/dist/types/src/index.d.ts +8 -2
  49. package/dist/types/src/index.d.ts.map +1 -1
  50. package/dist/types/src/instance-id.d.ts.map +1 -1
  51. package/dist/types/src/interval.d.ts.map +1 -1
  52. package/dist/types/src/join-tables.d.ts.map +1 -1
  53. package/dist/types/src/json.d.ts +1 -1
  54. package/dist/types/src/json.d.ts.map +1 -1
  55. package/dist/types/src/map-values.d.ts.map +1 -1
  56. package/dist/types/src/map.d.ts.map +1 -1
  57. package/dist/types/src/object.d.ts +3 -0
  58. package/dist/types/src/object.d.ts.map +1 -1
  59. package/dist/types/src/order-keys.d.ts.map +1 -1
  60. package/dist/types/src/order.d.ts.map +1 -1
  61. package/dist/types/src/pick.d.ts.map +1 -1
  62. package/dist/types/src/platform.d.ts +5 -2
  63. package/dist/types/src/platform.d.ts.map +1 -1
  64. package/dist/types/src/position.d.ts +5 -5
  65. package/dist/types/src/position.d.ts.map +1 -1
  66. package/dist/types/src/random.d.ts.map +1 -1
  67. package/dist/types/src/range.d.ts.map +1 -1
  68. package/dist/types/src/reducers.d.ts.map +1 -1
  69. package/dist/types/src/remove-undefined-keys.d.ts.map +1 -1
  70. package/dist/types/src/retry.d.ts +32 -0
  71. package/dist/types/src/retry.d.ts.map +1 -0
  72. package/dist/types/src/safe-await.d.ts.map +1 -1
  73. package/dist/types/src/safe-instanceof.d.ts.map +1 -1
  74. package/dist/types/src/safe-parse.d.ts +7 -4
  75. package/dist/types/src/safe-parse.d.ts.map +1 -1
  76. package/dist/types/src/safe-stringify.d.ts +22 -0
  77. package/dist/types/src/safe-stringify.d.ts.map +1 -0
  78. package/dist/types/src/safe-stringify.test.d.ts +2 -0
  79. package/dist/types/src/safe-stringify.test.d.ts.map +1 -0
  80. package/dist/types/src/sliding-window-summary.d.ts.map +1 -1
  81. package/dist/types/src/sort.d.ts.map +1 -1
  82. package/dist/types/src/string.d.ts +8 -0
  83. package/dist/types/src/string.d.ts.map +1 -1
  84. package/dist/types/src/string.test.d.ts +2 -0
  85. package/dist/types/src/string.test.d.ts.map +1 -0
  86. package/dist/types/src/sum.d.ts.map +1 -1
  87. package/dist/types/src/throw-unhandled-error.d.ts.map +1 -1
  88. package/dist/types/src/to-fallback.d.ts +18 -4
  89. package/dist/types/src/to-fallback.d.ts.map +1 -1
  90. package/dist/types/src/tracer.d.ts.map +1 -1
  91. package/dist/types/src/tree.d.ts.map +1 -1
  92. package/dist/types/src/types.d.ts +24 -6
  93. package/dist/types/src/types.d.ts.map +1 -1
  94. package/dist/types/src/uint8array.d.ts +27 -0
  95. package/dist/types/src/uint8array.d.ts.map +1 -1
  96. package/dist/types/src/unit.d.ts +14 -0
  97. package/dist/types/src/unit.d.ts.map +1 -0
  98. package/dist/types/src/unit.test.d.ts +2 -0
  99. package/dist/types/src/unit.test.d.ts.map +1 -0
  100. package/dist/types/src/url.d.ts.map +1 -1
  101. package/dist/types/src/weak.d.ts +15 -0
  102. package/dist/types/src/weak.d.ts.map +1 -1
  103. package/dist/types/tsconfig.tsbuildinfo +1 -1
  104. package/package.json +15 -17
  105. package/src/array.test.ts +1 -1
  106. package/src/array.ts +9 -4
  107. package/src/assume.ts +0 -1
  108. package/src/binder.ts +2 -2
  109. package/src/browser-storage.ts +60 -0
  110. package/src/circular-buffer.test.ts +27 -1
  111. package/src/circular-buffer.ts +5 -0
  112. package/src/complex.test.ts +1 -1
  113. package/src/complex.ts +32 -0
  114. package/src/composite-key.test.ts +31 -0
  115. package/src/composite-key.ts +16 -0
  116. package/src/deep.ts +2 -6
  117. package/src/defer.ts +1 -1
  118. package/src/di-key.ts +10 -8
  119. package/src/error-format.ts +24 -0
  120. package/src/filename.ts +16 -0
  121. package/src/human-hash.test.ts +1 -1
  122. package/src/id.test.ts +109 -0
  123. package/src/id.ts +48 -0
  124. package/src/index.ts +8 -2
  125. package/src/json.ts +2 -7
  126. package/src/map-values.ts +6 -0
  127. package/src/object.ts +3 -0
  128. package/src/platform.ts +35 -3
  129. package/src/position.test.ts +39 -45
  130. package/src/position.ts +7 -11
  131. package/src/retry.ts +74 -0
  132. package/src/safe-parse.ts +29 -15
  133. package/src/safe-stringify.test.ts +96 -0
  134. package/src/safe-stringify.ts +153 -0
  135. package/src/sort.test.ts +1 -1
  136. package/src/string.test.ts +19 -0
  137. package/src/string.ts +40 -0
  138. package/src/to-fallback.ts +44 -160
  139. package/src/tree.test.ts +1 -1
  140. package/src/types.test.ts +11 -1
  141. package/src/types.ts +40 -12
  142. package/src/uint8array.test.ts +1 -1
  143. package/src/uint8array.ts +44 -0
  144. package/src/unit.test.ts +25 -0
  145. package/src/unit.ts +87 -0
  146. package/src/weak.test.ts +1 -1
  147. package/src/weak.ts +52 -14
  148. package/dist/types/src/explicit-resource-management-polyfill.d.ts +0 -1
  149. package/dist/types/src/explicit-resource-management-polyfill.d.ts.map +0 -1
  150. package/dist/types/src/first-two-chars.d.ts +0 -9
  151. package/dist/types/src/first-two-chars.d.ts.map +0 -1
  152. package/src/explicit-resource-management-polyfill.ts +0 -13
  153. package/src/first-two-chars.ts +0 -44
@@ -97,21 +97,28 @@ 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
113
121
  import { invariant } from "@dxos/invariant";
114
- var __dxlog_file = "/__w/dxos/dxos/packages/common/util/src/bitfield.ts";
115
122
  var BitField = class _BitField {
116
123
  static get(data, idx) {
117
124
  const bit = data[idx >> 3] >> 7 - idx % 8 & 1;
@@ -143,15 +150,7 @@ var BitField = class _BitField {
143
150
  return result;
144
151
  }
145
152
  static and(first, second) {
146
- invariant(first.length === second.length, "Bitfields must be of the same length", {
147
- F: __dxlog_file,
148
- L: 52,
149
- S: this,
150
- A: [
151
- "first.length === second.length",
152
- "'Bitfields must be of the same length'"
153
- ]
154
- });
153
+ invariant(first.length === second.length, "Bitfields must be of the same length");
155
154
  const result = new Uint8Array(first.length);
156
155
  for (let i = 0; i < first.length; i++) {
157
156
  result[i] = first[i] & second[i];
@@ -179,6 +178,49 @@ var BitField = class _BitField {
179
178
  }
180
179
  };
181
180
 
181
+ // src/browser-storage.ts
182
+ var clearIndexedDB = async () => {
183
+ const dbs = await indexedDB.databases();
184
+ const results = await Promise.allSettled(dbs.filter((db) => db.name != null).map((db) => new Promise((resolve, reject) => {
185
+ const request = indexedDB.deleteDatabase(db.name);
186
+ request.onsuccess = () => resolve();
187
+ request.onerror = () => reject(request.error);
188
+ request.onblocked = () => reject(new Error(`IndexedDB deletion blocked: ${db.name}`));
189
+ })));
190
+ const failures = results.filter((r) => r.status === "rejected");
191
+ if (failures.length > 0) {
192
+ throw new AggregateError(failures.map((r) => r.reason), "Failed to delete some IndexedDB databases");
193
+ }
194
+ };
195
+ var clearOPFS = async () => {
196
+ const root = await navigator.storage.getDirectory();
197
+ const errors = [];
198
+ for await (const [name] of root.entries()) {
199
+ try {
200
+ await root.removeEntry(name, {
201
+ recursive: true
202
+ });
203
+ } catch (err) {
204
+ errors.push(err);
205
+ }
206
+ }
207
+ if (errors.length > 0) {
208
+ throw new AggregateError(errors, "Failed to remove some OPFS entries");
209
+ }
210
+ };
211
+ var clearServiceWorkers = async () => {
212
+ const regs = await navigator.serviceWorker.getRegistrations();
213
+ for (const reg of regs) {
214
+ await reg.unregister();
215
+ }
216
+ };
217
+ var clearCaches = async () => {
218
+ const keys2 = await caches.keys();
219
+ for (const key of keys2) {
220
+ await caches.delete(key);
221
+ }
222
+ };
223
+
182
224
  // src/callback-collection.ts
183
225
  var CallbackCollection = class {
184
226
  #callbacks = [];
@@ -205,33 +247,17 @@ var CallbackCollection = class {
205
247
 
206
248
  // src/callback.ts
207
249
  import { invariant as invariant2 } from "@dxos/invariant";
208
- var __dxlog_file2 = "/__w/dxos/dxos/packages/common/util/src/callback.ts";
209
250
  var Callback = class {
251
+ _callback;
210
252
  call(...args) {
211
- invariant2(this._callback, "Callback not set", {
212
- F: __dxlog_file2,
213
- L: 20,
214
- S: this,
215
- A: [
216
- "this._callback",
217
- "'Callback not set'"
218
- ]
219
- });
253
+ invariant2(this._callback, "Callback not set");
220
254
  return this._callback(...args);
221
255
  }
222
256
  callIfSet(...args) {
223
257
  return this._callback?.(...args);
224
258
  }
225
259
  set(callback) {
226
- invariant2(!this._callback, "Callback already set", {
227
- F: __dxlog_file2,
228
- L: 29,
229
- S: this,
230
- A: [
231
- "!this._callback",
232
- "'Callback already set'"
233
- ]
234
- });
260
+ invariant2(!this._callback, "Callback already set");
235
261
  this._callback = callback;
236
262
  }
237
263
  isSet() {
@@ -299,20 +325,12 @@ var chunkArray = (array, size) => {
299
325
 
300
326
  // src/circular-buffer.ts
301
327
  import { invariant as invariant3 } from "@dxos/invariant";
302
- var __dxlog_file3 = "/__w/dxos/dxos/packages/common/util/src/circular-buffer.ts";
303
328
  var CircularBuffer = class {
329
+ _buffer;
330
+ _nextIndex = 0;
331
+ _elementCount = 0;
304
332
  constructor(size) {
305
- this._nextIndex = 0;
306
- this._elementCount = 0;
307
- invariant3(size >= 1, void 0, {
308
- F: __dxlog_file3,
309
- L: 13,
310
- S: this,
311
- A: [
312
- "size >= 1",
313
- ""
314
- ]
315
- });
333
+ invariant3(size >= 1);
316
334
  this._buffer = new Array(size);
317
335
  }
318
336
  push(element) {
@@ -325,6 +343,10 @@ var CircularBuffer = class {
325
343
  get elementCount() {
326
344
  return this._elementCount;
327
345
  }
346
+ clear() {
347
+ this._nextIndex = 0;
348
+ this._elementCount = 0;
349
+ }
328
350
  getLast() {
329
351
  if (this._elementCount === 0) {
330
352
  return void 0;
@@ -374,10 +396,11 @@ import { inspect } from "@dxos/node-std/util";
374
396
  import { inspectObject, raise } from "@dxos/debug";
375
397
  var MAX_SERIALIZATION_LENGTH = 10;
376
398
  var ComplexSet = class {
399
+ _projection;
400
+ _values = /* @__PURE__ */ new Map();
377
401
  // prettier-ignore
378
402
  constructor(_projection, values) {
379
403
  this._projection = _projection;
380
- this._values = /* @__PURE__ */ new Map();
381
404
  if (values) {
382
405
  for (const value of values) {
383
406
  this.add(value);
@@ -467,11 +490,12 @@ var makeSet = (projection) => {
467
490
  };
468
491
  };
469
492
  var ComplexMap = class _ComplexMap {
493
+ _keyProjection;
494
+ _keys = /* @__PURE__ */ new Map();
495
+ _values = /* @__PURE__ */ new Map();
470
496
  // prettier-ignore
471
497
  constructor(_keyProjection, entries2) {
472
498
  this._keyProjection = _keyProjection;
473
- this._keys = /* @__PURE__ */ new Map();
474
- this._values = /* @__PURE__ */ new Map();
475
499
  if (entries2) {
476
500
  for (const [key, value] of entries2) {
477
501
  this.set(key, value);
@@ -516,6 +540,36 @@ var ComplexMap = class _ComplexMap {
516
540
  this._values.set(primitive, value);
517
541
  return this;
518
542
  }
543
+ /**
544
+ * Returns the value for the given key if present, otherwise inserts and returns the default value.
545
+ * @param key - The key to look up or insert.
546
+ * @param defaultValue - The value to insert if the key is not present.
547
+ * @returns The existing or newly inserted value.
548
+ */
549
+ getOrInsert(key, defaultValue) {
550
+ const primitive = this._keyProjection(key);
551
+ if (this._values.has(primitive)) {
552
+ return this._values.get(primitive);
553
+ }
554
+ this.set(key, defaultValue);
555
+ return defaultValue;
556
+ }
557
+ /**
558
+ * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
559
+ * The callback is only invoked when the key is missing.
560
+ * @param key - The key to look up or insert.
561
+ * @param callbackfn - Function to compute the value if the key is not present.
562
+ * @returns The existing or newly computed value.
563
+ */
564
+ getOrInsertComputed(key, callbackfn) {
565
+ const primitive = this._keyProjection(key);
566
+ if (this._values.has(primitive)) {
567
+ return this._values.get(primitive);
568
+ }
569
+ const value = callbackfn(key);
570
+ this.set(key, value);
571
+ return value;
572
+ }
519
573
  get size() {
520
574
  return this._keys.size;
521
575
  }
@@ -555,21 +609,15 @@ var makeMap = (keyProjection) => class BoundComplexMap extends ComplexMap {
555
609
  }
556
610
  };
557
611
 
612
+ // src/composite-key.ts
613
+ var SEPARATOR = ":";
614
+ var compositeKey = (...parts) => parts.join(SEPARATOR);
615
+ var splitCompositeKey = (key) => key.split(SEPARATOR);
616
+
558
617
  // src/deep.ts
559
- import get from "lodash.get";
560
- import set from "lodash.set";
561
618
  import { invariant as invariant4 } from "@dxos/invariant";
562
- var __dxlog_file4 = "/__w/dxos/dxos/packages/common/util/src/deep.ts";
563
619
  var setDeep = (obj, path, value) => {
564
- invariant4(path.length > 0, void 0, {
565
- F: __dxlog_file4,
566
- L: 18,
567
- S: void 0,
568
- A: [
569
- "path.length > 0",
570
- ""
571
- ]
572
- });
620
+ invariant4(path.length > 0);
573
621
  let parent = obj;
574
622
  for (const key of path.slice(0, -1)) {
575
623
  if (parent[key] === void 0) {
@@ -592,13 +640,11 @@ var getDeep = (obj, path) => {
592
640
  // src/defer-function.ts
593
641
  var deferFunction = (fnProvider) => (...args) => fnProvider()(...args);
594
642
 
595
- // src/explicit-resource-management-polyfill.ts
596
- Symbol.dispose ??= Symbol("Symbol.dispose");
597
- Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
598
-
599
643
  // src/defer.ts
644
+ import "@hazae41/symbol-dispose-polyfill";
600
645
  var defer = (fn) => new DeferGuard(fn);
601
646
  var DeferGuard = class {
647
+ _fn;
602
648
  /**
603
649
  * @internal
604
650
  */
@@ -614,6 +660,7 @@ var DeferGuard = class {
614
660
  };
615
661
  var deferAsync = (fn) => new DeferAsyncGuard(fn);
616
662
  var DeferAsyncGuard = class {
663
+ _fn;
617
664
  /**
618
665
  * @internal
619
666
  */
@@ -628,6 +675,8 @@ var DeferAsyncGuard = class {
628
675
  // src/entry.ts
629
676
  var entry = (map, key) => new MapEntry(map, key);
630
677
  var MapEntry = class {
678
+ _map;
679
+ _key;
631
680
  /**
632
681
  * @internal
633
682
  */
@@ -653,33 +702,29 @@ var MapEntry = class {
653
702
  }
654
703
  };
655
704
 
656
- // src/first-two-chars.ts
657
- var renderableCharRegex = /^(?![\p{Control}\p{Mark}\p{Separator}\p{Surrogate}\p{Unassigned}\p{P}])[\p{L}\p{N}\p{S}\p{Emoji}]$/u;
658
- var getFirstTwoRenderableChars = (label) => {
659
- const characters = Array.from(label);
660
- const result = [
661
- "",
662
- ""
663
- ];
664
- let foundFirst = false;
665
- for (let i = 0; i < characters.length; i++) {
666
- const char = characters[i];
667
- if (renderableCharRegex.test(char)) {
668
- if (!foundFirst) {
669
- result[0] = char;
670
- foundFirst = true;
671
- } else {
672
- const textBetween = characters.slice(result[0].length, i).join("");
673
- if (/[^\p{L}\p{N}_]/u.test(textBetween)) {
674
- result[1] = char;
675
- break;
676
- }
677
- }
678
- }
679
- }
680
- return result;
705
+ // src/error-format.ts
706
+ var formatErrorWithCauses = (error) => {
707
+ const lines = [];
708
+ let current = error;
709
+ let level = 0;
710
+ while (current) {
711
+ const prefix = level === 0 ? "" : `Caused by: `;
712
+ lines.push(prefix + (current.stack ?? String(current)));
713
+ if (!(current.cause instanceof Error)) {
714
+ break;
715
+ }
716
+ current = current.cause;
717
+ level += 1;
718
+ }
719
+ return lines.join("\n\n");
681
720
  };
682
721
 
722
+ // src/filename.ts
723
+ var createFilename = ({ parts = [], ext, date = /* @__PURE__ */ new Date() }) => [
724
+ date.toISOString().replace(/[:.]/g, "-"),
725
+ ...parts
726
+ ].join("_") + (ext ? `.${ext}` : "");
727
+
683
728
  // src/for-each-async.ts
684
729
  var forEachAsync = (items, fn) => Promise.all(items.map(fn));
685
730
 
@@ -944,6 +989,7 @@ var DEFAULT_WORDLIST = [
944
989
  "zulu"
945
990
  ];
946
991
  var HumanHasher = class {
992
+ wordlist;
947
993
  /**
948
994
  * Transforms hex digests to human-readable strings.
949
995
  *
@@ -1014,6 +1060,19 @@ var humanize = (value) => {
1014
1060
  return hasher.humanize(value);
1015
1061
  };
1016
1062
 
1063
+ // src/id.ts
1064
+ var PART = /^[a-zA-Z][a-zA-Z0-9]{0,62}$/;
1065
+ var ID = /^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)$/;
1066
+ function id(strings, ...values) {
1067
+ const raw = strings.reduce((out, str, i) => out + str + (i < values.length ? String(values[i]) : ""), "");
1068
+ if (!ID.test(raw)) {
1069
+ throw new Error(`Invalid id (expected AT Protocol NSID): ${JSON.stringify(raw)}`);
1070
+ }
1071
+ return raw;
1072
+ }
1073
+ var isWellFormedId = (value) => ID.test(value);
1074
+ var isWellFormedIdPart = (value) => PART.test(value);
1075
+
1017
1076
  // src/map.ts
1018
1077
  var defaultMap = (map, key, def) => {
1019
1078
  let value = map.get(key);
@@ -1025,7 +1084,7 @@ var defaultMap = (map, key, def) => {
1025
1084
  };
1026
1085
 
1027
1086
  // src/instance-id.ts
1028
- var symbol = Symbol.for("dxos.instance-contexts");
1087
+ var symbol = /* @__PURE__ */ Symbol.for("dxos.instance-contexts");
1029
1088
  var instanceContexts = globalThis[symbol] ??= /* @__PURE__ */ new WeakMap();
1030
1089
  var getPrototypeSpecificInstanceId = (instance) => {
1031
1090
  const prototype = Object.getPrototypeOf(instance);
@@ -1033,12 +1092,12 @@ var getPrototypeSpecificInstanceId = (instance) => {
1033
1092
  nextId: 0,
1034
1093
  instanceIds: /* @__PURE__ */ new WeakMap()
1035
1094
  }));
1036
- let id = instanceCtx.instanceIds.get(instance);
1037
- if (id === void 0) {
1038
- id = instanceCtx.nextId++;
1039
- instanceCtx.instanceIds.set(instance, id);
1095
+ let id2 = instanceCtx.instanceIds.get(instance);
1096
+ if (id2 === void 0) {
1097
+ id2 = instanceCtx.nextId++;
1098
+ instanceCtx.instanceIds.set(instance, id2);
1040
1099
  }
1041
- return id;
1100
+ return id2;
1042
1101
  };
1043
1102
  var getDebugName = (instance) => {
1044
1103
  if (instance == null) {
@@ -1105,11 +1164,31 @@ var bufferToArray = (buffer) => {
1105
1164
  };
1106
1165
  var stringToArray = (string) => bufferToArray(Buffer.from(string, "hex"));
1107
1166
  var arrayToString = (array) => arrayToBuffer(array).toString("hex");
1167
+ var toUnpaddedBase64 = (bytes) => arrayToBuffer(bytes).toString("base64").replace(/=+$/, "");
1168
+ var encodeUint8ArrayToJson = (bytes) => ({
1169
+ "/": {
1170
+ bytes: toUnpaddedBase64(bytes)
1171
+ }
1172
+ });
1173
+ var isEncodedUint8Array = (value) => {
1174
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1175
+ return false;
1176
+ }
1177
+ if (Object.keys(value).length !== 1) {
1178
+ return false;
1179
+ }
1180
+ const inner = value["/"];
1181
+ if (typeof inner !== "object" || inner === null || Array.isArray(inner)) {
1182
+ return false;
1183
+ }
1184
+ return Object.keys(inner).length === 1 && typeof inner.bytes === "string";
1185
+ };
1186
+ var decodeUint8ArrayFromJson = (encoded) => bufferToArray(Buffer.from(encoded["/"].bytes, "base64"));
1108
1187
 
1109
1188
  // src/json.ts
1110
1189
  var MAX_DEPTH = 5;
1111
1190
  var LOG_MAX_DEPTH = 7;
1112
- function jsonReplacer(key, value) {
1191
+ var jsonReplacer = (key, value) => {
1113
1192
  if (value !== null && typeof value === "object" && typeof value[inspect2.custom] === "function") {
1114
1193
  return value[inspect2.custom]();
1115
1194
  }
@@ -1122,7 +1201,7 @@ function jsonReplacer(key, value) {
1122
1201
  }
1123
1202
  }
1124
1203
  return value;
1125
- }
1204
+ };
1126
1205
  var jsonify = (value, depth = 0, visitedObjects = /* @__PURE__ */ new WeakSet()) => {
1127
1206
  if (depth > MAX_DEPTH) {
1128
1207
  return null;
@@ -1209,31 +1288,10 @@ var deepMapValues = (value, fn) => {
1209
1288
  return new DeepMapper(fn).map(value);
1210
1289
  };
1211
1290
  var DeepMapper = class {
1291
+ _fn;
1292
+ _cyclic = /* @__PURE__ */ new Map();
1212
1293
  constructor(_fn) {
1213
1294
  this._fn = _fn;
1214
- this._cyclic = /* @__PURE__ */ new Map();
1215
- this._recurse = (value) => {
1216
- if (this._cyclic.has(value)) {
1217
- return this._cyclic.get(value);
1218
- }
1219
- if (Array.isArray(value)) {
1220
- const res = new Array(value.length);
1221
- this._cyclic.set(value, res);
1222
- for (let i = 0; i < value.length; i++) {
1223
- res[i] = this._map(value[i], i);
1224
- }
1225
- return res;
1226
- } else if (value !== null && typeof value === "object") {
1227
- const res = {};
1228
- this._cyclic.set(value, res);
1229
- for (const key in value) {
1230
- res[key] = this._map(value[key], key);
1231
- }
1232
- return res;
1233
- } else {
1234
- return value;
1235
- }
1236
- };
1237
1295
  }
1238
1296
  map(value) {
1239
1297
  return this._map(value, void 0);
@@ -1244,36 +1302,39 @@ var DeepMapper = class {
1244
1302
  }
1245
1303
  return this._fn(value, this._recurse, key);
1246
1304
  }
1305
+ _recurse = (value) => {
1306
+ if (this._cyclic.has(value)) {
1307
+ return this._cyclic.get(value);
1308
+ }
1309
+ if (Array.isArray(value)) {
1310
+ const res = new Array(value.length);
1311
+ this._cyclic.set(value, res);
1312
+ for (let i = 0; i < value.length; i++) {
1313
+ res[i] = this._map(value[i], i);
1314
+ }
1315
+ return res;
1316
+ } else if (ArrayBuffer.isView(value)) {
1317
+ return value;
1318
+ } else if (value !== null && typeof value === "object") {
1319
+ const res = {};
1320
+ this._cyclic.set(value, res);
1321
+ for (const key in value) {
1322
+ res[key] = this._map(value[key], key);
1323
+ }
1324
+ return res;
1325
+ } else {
1326
+ return value;
1327
+ }
1328
+ };
1247
1329
  };
1248
1330
  var deepMapValuesAsync = (value, fn) => {
1249
1331
  return new DeepMapperAsync(fn).map(value);
1250
1332
  };
1251
1333
  var DeepMapperAsync = class {
1334
+ _fn;
1335
+ _cyclic = /* @__PURE__ */ new Map();
1252
1336
  constructor(_fn) {
1253
1337
  this._fn = _fn;
1254
- this._cyclic = /* @__PURE__ */ new Map();
1255
- this._recurse = async (value) => {
1256
- if (this._cyclic.has(value)) {
1257
- return this._cyclic.get(value);
1258
- }
1259
- if (Array.isArray(value)) {
1260
- const res = new Array(value.length);
1261
- this._cyclic.set(value, res);
1262
- for (let i = 0; i < value.length; i++) {
1263
- res[i] = await this._map(value[i], i);
1264
- }
1265
- return res;
1266
- } else if (value !== null && typeof value === "object") {
1267
- const res = {};
1268
- this._cyclic.set(value, res);
1269
- for (const key in value) {
1270
- res[key] = await this._map(value[key], key);
1271
- }
1272
- return res;
1273
- } else {
1274
- return value;
1275
- }
1276
- };
1277
1338
  }
1278
1339
  map(value) {
1279
1340
  return this._map(value, void 0);
@@ -1284,6 +1345,30 @@ var DeepMapperAsync = class {
1284
1345
  }
1285
1346
  return this._fn(value, this._recurse, key);
1286
1347
  }
1348
+ _recurse = async (value) => {
1349
+ if (this._cyclic.has(value)) {
1350
+ return this._cyclic.get(value);
1351
+ }
1352
+ if (Array.isArray(value)) {
1353
+ const res = new Array(value.length);
1354
+ this._cyclic.set(value, res);
1355
+ for (let i = 0; i < value.length; i++) {
1356
+ res[i] = await this._map(value[i], i);
1357
+ }
1358
+ return res;
1359
+ } else if (ArrayBuffer.isView(value)) {
1360
+ return value;
1361
+ } else if (value !== null && typeof value === "object") {
1362
+ const res = {};
1363
+ this._cyclic.set(value, res);
1364
+ for (const key in value) {
1365
+ res[key] = await this._map(value[key], key);
1366
+ }
1367
+ return res;
1368
+ } else {
1369
+ return value;
1370
+ }
1371
+ };
1287
1372
  };
1288
1373
  var visitValues = (object, visitor) => {
1289
1374
  if (Array.isArray(object)) {
@@ -1317,27 +1402,27 @@ var orderKeys = (obj, order) => {
1317
1402
 
1318
1403
  // src/order.ts
1319
1404
  var inferObjectOrder = (objectMap, order = []) => {
1320
- const orderedObjects = order.reduce((acc, id) => {
1321
- if (id in objectMap) {
1322
- acc.objects.push(objectMap[id]);
1323
- acc.ids.add(id);
1405
+ const orderedObjects = order.reduce((acc, id2) => {
1406
+ if (id2 in objectMap) {
1407
+ acc.objects.push(objectMap[id2]);
1408
+ acc.ids.add(id2);
1324
1409
  }
1325
1410
  return acc;
1326
1411
  }, {
1327
1412
  objects: [],
1328
1413
  ids: /* @__PURE__ */ new Set()
1329
1414
  });
1330
- const { objects } = Object.keys(objectMap).reduce((acc, id) => {
1331
- if (!acc.ids.has(id)) {
1332
- acc.objects.push(objectMap[id]);
1415
+ const { objects } = Object.keys(objectMap).reduce((acc, id2) => {
1416
+ if (!acc.ids.has(id2)) {
1417
+ acc.objects.push(objectMap[id2]);
1333
1418
  }
1334
1419
  return acc;
1335
1420
  }, orderedObjects);
1336
1421
  return objects;
1337
1422
  };
1338
1423
  var inferRecordOrder = (objectMap, order = []) => {
1339
- return Object.assign(order.filter((id) => id in objectMap).reduce((acc, id) => {
1340
- acc[id] = null;
1424
+ return Object.assign(order.filter((id2) => id2 in objectMap).reduce((acc, id2) => {
1425
+ acc[id2] = null;
1341
1426
  return acc;
1342
1427
  }, {}), objectMap);
1343
1428
  };
@@ -1372,7 +1457,18 @@ var omit = (obj, keys2) => {
1372
1457
 
1373
1458
  // src/platform.ts
1374
1459
  var isNode = () => typeof process !== "undefined" && process.versions != null && process.versions.node != null;
1375
- var mobileAndTabletCheck = () => {
1460
+ var isBun = () => globalThis.Bun !== void 0;
1461
+ var isTauri = () => !!globalThis.__TAURI__;
1462
+ var isMobile = () => {
1463
+ let check = false;
1464
+ (function(a) {
1465
+ 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))) {
1466
+ check = true;
1467
+ }
1468
+ })(navigator.userAgent || navigator.vendor || window.opera);
1469
+ return check;
1470
+ };
1471
+ var isMobileOrTablet = () => {
1376
1472
  let check = false;
1377
1473
  ((a) => {
1378
1474
  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))) {
@@ -1394,7 +1490,7 @@ var iosCheck = () => {
1394
1490
  };
1395
1491
  var safariCheck = () => typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
1396
1492
  var getHostPlatform = () => {
1397
- if (!("navigator" in window)) {
1493
+ if (!("navigator" in globalThis)) {
1398
1494
  return "unknown";
1399
1495
  }
1400
1496
  const platform = (navigator.userAgentData?.platform || navigator.platform)?.toLowerCase();
@@ -1412,12 +1508,12 @@ var getHostPlatform = () => {
1412
1508
  };
1413
1509
 
1414
1510
  // src/position.ts
1415
- var byPosition = ({ position: a = "static" }, { position: b = "static" }) => {
1511
+ var byPosition = ({ position: a }, { position: b }) => {
1416
1512
  if (a === b) {
1417
1513
  return 0;
1418
- } else if (a === "hoist" || b === "fallback") {
1514
+ } else if (a === "first" || b === "last") {
1419
1515
  return -1;
1420
- } else if (b === "hoist" || a === "fallback") {
1516
+ } else if (b === "first" || a === "last") {
1421
1517
  return 1;
1422
1518
  } else {
1423
1519
  return 0;
@@ -1570,6 +1666,43 @@ var removeProperties = (root, condition) => {
1570
1666
  return result;
1571
1667
  };
1572
1668
 
1669
+ // src/retry.ts
1670
+ var DEFAULT_RETRY_OPTIONS = {
1671
+ count: 3,
1672
+ delayMs: 100,
1673
+ exponent: 2,
1674
+ retryOnError: async () => true,
1675
+ retryOnValue: async () => false
1676
+ };
1677
+ var retry = async (options, cb) => {
1678
+ const fullOptions = {
1679
+ ...DEFAULT_RETRY_OPTIONS,
1680
+ ...options
1681
+ };
1682
+ let numRetries = 0, currentDelay = fullOptions.delayMs;
1683
+ while (true) {
1684
+ let result;
1685
+ try {
1686
+ result = await cb();
1687
+ } catch (err) {
1688
+ if (numRetries > fullOptions.count || !await fullOptions.retryOnError(err)) {
1689
+ throw err;
1690
+ }
1691
+ await new Promise((resolve) => setTimeout(resolve, currentDelay));
1692
+ currentDelay *= fullOptions.exponent;
1693
+ numRetries++;
1694
+ continue;
1695
+ }
1696
+ if (!await fullOptions.retryOnValue(result)) {
1697
+ return result;
1698
+ }
1699
+ await new Promise((resolve) => setTimeout(resolve, currentDelay));
1700
+ currentDelay *= fullOptions.exponent;
1701
+ numRetries++;
1702
+ continue;
1703
+ }
1704
+ };
1705
+
1573
1706
  // src/safe-await.ts
1574
1707
  var safeAwaitAll = async (source, taskFactory, onError) => {
1575
1708
  const failedItems = [];
@@ -1589,7 +1722,7 @@ var safeAwaitAll = async (source, taskFactory, onError) => {
1589
1722
  };
1590
1723
 
1591
1724
  // src/safe-instanceof.ts
1592
- var instanceTag = Symbol("instanceTag");
1725
+ var instanceTag = /* @__PURE__ */ Symbol("instanceTag");
1593
1726
  var safeInstanceof = (tag) => (target) => {
1594
1727
  target.prototype[instanceTag] = tag;
1595
1728
  Object.defineProperty(target.prototype, Symbol.hasInstance, {
@@ -1601,48 +1734,139 @@ var safeInstanceof = (tag) => (target) => {
1601
1734
  };
1602
1735
 
1603
1736
  // src/safe-parse.ts
1604
- var safeParseInt = (value, defaultValue) => {
1737
+ function safeParseInt(str, defaultValue) {
1605
1738
  try {
1606
- const n = parseInt(value ?? "");
1607
- return isNaN(n) ? defaultValue : n;
1608
- } catch (err) {
1739
+ const value = parseInt(str ?? "");
1740
+ return isNaN(value) ? defaultValue : value;
1741
+ } catch {
1609
1742
  return defaultValue;
1610
1743
  }
1744
+ }
1745
+ function safeParseFloat(str, defaultValue) {
1746
+ try {
1747
+ const value = parseFloat(str ?? "");
1748
+ return isNaN(value) ? defaultValue : value;
1749
+ } catch {
1750
+ return defaultValue;
1751
+ }
1752
+ }
1753
+ var safeParseJson = (str, defaultValue) => {
1754
+ if (str && str.length > 0) {
1755
+ try {
1756
+ return JSON.parse(str);
1757
+ } catch {
1758
+ }
1759
+ }
1760
+ return defaultValue;
1611
1761
  };
1612
- var safeParseFloat = (str, defaultValue) => {
1762
+ var safeUrl = (str) => {
1613
1763
  try {
1614
- return parseFloat(str);
1764
+ return new URL(str ?? "");
1615
1765
  } catch {
1616
- return defaultValue ?? 0;
1766
+ return void 0;
1617
1767
  }
1618
1768
  };
1619
- var safeParseJson = (data, defaultValue) => {
1620
- if (data && data.length > 0) {
1769
+
1770
+ // src/safe-stringify.ts
1771
+ var SKIP = Object.freeze({});
1772
+ function safeStringify(obj, filter = defaultFilter, indent = 2) {
1773
+ const seen = /* @__PURE__ */ new WeakMap();
1774
+ function replacer(key, value) {
1621
1775
  try {
1622
- return JSON.parse(data);
1623
- } catch (err) {
1776
+ let path = key;
1777
+ if (!key) {
1778
+ path = "$";
1779
+ if (value != null && typeof value === "object") {
1780
+ seen.set(value, path);
1781
+ }
1782
+ return value;
1783
+ } else if (this) {
1784
+ const parentPath = seen.get(this);
1785
+ path = parentPath ? `${parentPath}.${key}` : key;
1786
+ }
1787
+ if (value == null) {
1788
+ return value;
1789
+ }
1790
+ if (typeof value === "function") {
1791
+ return void 0;
1792
+ }
1793
+ if (typeof value === "object" && Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value)) {
1794
+ return void 0;
1795
+ }
1796
+ if (typeof value === "object" && value !== null) {
1797
+ const exists = seen.get(value);
1798
+ if (exists) {
1799
+ return `[${path} => ${exists}]`;
1800
+ }
1801
+ seen.set(value, path);
1802
+ }
1803
+ if (filter) {
1804
+ const filteredValue = filter?.(key, value);
1805
+ if (filteredValue !== void 0) {
1806
+ return filteredValue === SKIP ? void 0 : filteredValue;
1807
+ }
1808
+ }
1809
+ return value;
1810
+ } catch (error) {
1811
+ return `ERROR: ${error.message}`;
1624
1812
  }
1625
1813
  }
1626
- return defaultValue;
1814
+ try {
1815
+ return JSON.stringify(obj, replacer, indent);
1816
+ } catch (error) {
1817
+ return `ERROR: ${error.message}`;
1818
+ }
1819
+ }
1820
+ var createReplacer = ({ omit: omit2, parse, maxDepth, maxArrayLen, maxStringLen } = {}) => {
1821
+ let currentDepth = 0;
1822
+ const depthMap = /* @__PURE__ */ new WeakMap();
1823
+ return function(key, value) {
1824
+ if (key === "") {
1825
+ currentDepth = 0;
1826
+ } else if (this && typeof this === "object") {
1827
+ const parentDepth = depthMap.get(this) ?? 0;
1828
+ currentDepth = parentDepth + 1;
1829
+ }
1830
+ if (typeof value === "function") {
1831
+ return SKIP;
1832
+ }
1833
+ if (maxArrayLen != null && Array.isArray(value) && value.length > maxArrayLen) {
1834
+ return `[length: ${value.length}]`;
1835
+ }
1836
+ if (value && typeof value === "object") {
1837
+ depthMap.set(value, currentDepth);
1838
+ if (maxDepth != null && currentDepth >= maxDepth) {
1839
+ return Array.isArray(value) ? `[{ length: ${value.length} }]` : `{ keys: ${Object.keys(value).length} }`;
1840
+ }
1841
+ }
1842
+ if (omit2?.includes(key)) {
1843
+ return SKIP;
1844
+ }
1845
+ if (parse?.includes(key) && typeof value === "string") {
1846
+ try {
1847
+ return JSON.parse(value);
1848
+ } catch {
1849
+ return value;
1850
+ }
1851
+ }
1852
+ if (maxStringLen != null && typeof value === "string" && value.length > maxStringLen) {
1853
+ return value.slice(0, maxStringLen) + "...";
1854
+ }
1855
+ return value;
1856
+ };
1627
1857
  };
1858
+ var defaultFilter = createReplacer();
1628
1859
 
1629
1860
  // src/sliding-window-summary.ts
1630
1861
  import { invariant as invariant5 } from "@dxos/invariant";
1631
- var __dxlog_file5 = "/__w/dxos/dxos/packages/common/util/src/sliding-window-summary.ts";
1632
1862
  var SlidingWindowSummary = class {
1863
+ _buffer;
1864
+ _sum = 0;
1865
+ _precision;
1633
1866
  constructor(options) {
1634
- this._sum = 0;
1635
1867
  this._buffer = new CircularBuffer(options.dataPoints);
1636
1868
  if (options.precision != null) {
1637
- invariant5(options.precision >= 0, void 0, {
1638
- F: __dxlog_file5,
1639
- L: 26,
1640
- S: this,
1641
- A: [
1642
- "options.precision >= 0",
1643
- ""
1644
- ]
1645
- });
1869
+ invariant5(options.precision >= 0);
1646
1870
  this._precision = Math.pow(10, options.precision);
1647
1871
  }
1648
1872
  }
@@ -1711,6 +1935,28 @@ var capitalize = (str) => {
1711
1935
  }
1712
1936
  return str.charAt(0).toUpperCase() + str.slice(1);
1713
1937
  };
1938
+ function trim(strings, ...values) {
1939
+ const raw = strings.reduce((out, str, i) => {
1940
+ out += str;
1941
+ if (i < values.length) {
1942
+ const match = str.match(/(^|\n)([ \t]*)$/);
1943
+ const baseIndent = match ? match[2] : "";
1944
+ const val = String(values[i]).replace(/\r?\n/g, "\n" + baseIndent);
1945
+ out += val;
1946
+ }
1947
+ return out;
1948
+ }, "");
1949
+ const lines = raw.split("\n");
1950
+ while (lines.length && !lines[0].trim()) {
1951
+ lines.shift();
1952
+ }
1953
+ while (lines.length && !lines[lines.length - 1].trim()) {
1954
+ lines.pop();
1955
+ }
1956
+ const minIndent = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^[ \t]*/)?.[0].length ?? 0));
1957
+ return lines.map((l) => l.slice(minIndent)).join("\n");
1958
+ }
1959
+ var kebabize = (str) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? "-" : "") + $.toLowerCase());
1714
1960
 
1715
1961
  // src/sum.ts
1716
1962
  var sum = (values) => values.reduce((a, b) => a + b, 0);
@@ -1724,18 +1970,6 @@ var throwUnhandledError = (error) => {
1724
1970
 
1725
1971
  // src/to-fallback.ts
1726
1972
  var idEmoji = [
1727
- // When changing this set, please check the result in a console or e.g. RunKit (https://runkit.com/thure/642214441dd6ae000855a8de)
1728
- // 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.
1729
- // This set was chosen from the characters in Unicode Emoji v15.0 based on the following criteria:
1730
- // – not people or isolated anthropomorphic faces
1731
- // – not flags
1732
- // – more concrete than abstract
1733
- // – less culturally specific
1734
- // – less easily confused with another emoji in the set
1735
- // – requires less special knowledge to identify
1736
- // – less likely to evoke negative feelings (no meat, no drugs, no weapons, etc)
1737
- // – less common as a signifier in UX
1738
- // NOTE that this is intentionally an array of strings because of the way emoji graphemes work.
1739
1973
  "\u{1F47B}",
1740
1974
  "\u{1F479}",
1741
1975
  "\u{1F47D}",
@@ -1871,17 +2105,18 @@ var idEmoji = [
1871
2105
  ];
1872
2106
  var idHue = [
1873
2107
  "red",
1874
- // 'orange' as const, /* More shades in these palettes are considered “ugly” */
2108
+ "orange",
1875
2109
  "amber",
1876
- // 'yellow' as const, /* More shades in these palettes are considered “ugly” */
2110
+ "yellow",
1877
2111
  "lime",
1878
2112
  "green",
1879
2113
  "emerald",
1880
2114
  "teal",
1881
2115
  "cyan",
1882
- // 'sky' as const, /* Omitted since it is quite similar to the primary accent palette */
1883
- // 'blue' as const, /* Omitted since it is quite similar to the primary accent palette */
1884
- // 'indigo' as const, /* Omitted since it is quite similar to the primary accent palette */
2116
+ // Omit colors similar to primary accent.
2117
+ // 'sky' as const,
2118
+ // 'blue' as const,
2119
+ // 'indigo' as const,
1885
2120
  "violet",
1886
2121
  "purple",
1887
2122
  "fuchsia",
@@ -1909,10 +2144,8 @@ var toFallback = (hash) => {
1909
2144
 
1910
2145
  // src/tracer.ts
1911
2146
  var Tracer = class {
1912
- constructor() {
1913
- this._events = /* @__PURE__ */ new Map();
1914
- this._recording = false;
1915
- }
2147
+ _events = /* @__PURE__ */ new Map();
2148
+ _recording = false;
1916
2149
  // TODO(burdon): Start/stop methods for recording data? By id?
1917
2150
  // Alternatively, enable subscriptions to track/compute series.
1918
2151
  // TODO(burdon): Hierarchical traces?
@@ -1922,8 +2155,8 @@ var Tracer = class {
1922
2155
  keys() {
1923
2156
  return Array.from(this._events.keys());
1924
2157
  }
1925
- get(id, filter) {
1926
- const events = this._events.get(id);
2158
+ get(id2, filter) {
2159
+ const events = this._events.get(id2);
1927
2160
  if (filter) {
1928
2161
  return events?.filter((event) => Object.entries(filter).every(([key, value]) => event?.value[key] === value));
1929
2162
  }
@@ -1940,11 +2173,11 @@ var Tracer = class {
1940
2173
  this._recording = false;
1941
2174
  return this;
1942
2175
  }
1943
- emit(id, value) {
1944
- this._post(this._createEvent(id, value));
2176
+ emit(id2, value) {
2177
+ this._post(this._createEvent(id2, value));
1945
2178
  }
1946
- mark(id, value) {
1947
- const event = this._createEvent(id, value);
2179
+ mark(id2, value) {
2180
+ const event = this._createEvent(id2, value);
1948
2181
  const start = performance.now();
1949
2182
  return {
1950
2183
  start,
@@ -1954,9 +2187,9 @@ var Tracer = class {
1954
2187
  }
1955
2188
  };
1956
2189
  }
1957
- _createEvent(id, value) {
2190
+ _createEvent(id2, value) {
1958
2191
  const event = {
1959
- id,
2192
+ id: id2,
1960
2193
  timestamp: Date.now()
1961
2194
  };
1962
2195
  if (value !== void 0) {
@@ -2013,7 +2246,7 @@ var stringifyTree = (node, ancestors = [], rows = []) => {
2013
2246
  };
2014
2247
 
2015
2248
  // src/types.ts
2016
- var isNotFalsy = (value) => !!value;
2249
+ var isTruthy = (value) => !!value;
2017
2250
  var isNonNullable = (value) => value != null;
2018
2251
  var doAsync = async (fn) => fn();
2019
2252
  var getProviderValue = (provider, arg) => {
@@ -2043,6 +2276,117 @@ var arrayMove = (array, from, to) => {
2043
2276
  array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
2044
2277
  return array;
2045
2278
  };
2279
+ function arraySwap(array, from, to) {
2280
+ const current = array[from];
2281
+ array[from] = array[to];
2282
+ array[to] = current;
2283
+ return array;
2284
+ }
2285
+
2286
+ // src/unit.ts
2287
+ var createFormat = (unit) => {
2288
+ return (n, precision = unit.precision ?? 0) => {
2289
+ const value = n / unit.quotient;
2290
+ const formattedValue = value.toLocaleString("en-US", {
2291
+ minimumFractionDigits: precision,
2292
+ maximumFractionDigits: precision
2293
+ });
2294
+ return {
2295
+ unit,
2296
+ value,
2297
+ formattedValue,
2298
+ toString: () => `${formattedValue}${unit.symbol}`
2299
+ };
2300
+ };
2301
+ };
2302
+ var MS_SECONDS = 1e3;
2303
+ var MS_MINUTES = 60 * MS_SECONDS;
2304
+ var MS_HOURS = 60 * MS_MINUTES;
2305
+ var Unit = {
2306
+ // General.
2307
+ Percent: createFormat({
2308
+ symbol: "%",
2309
+ quotient: 1 / 100,
2310
+ precision: 2
2311
+ }),
2312
+ Thousand: createFormat({
2313
+ symbol: "k",
2314
+ quotient: 1e3,
2315
+ precision: 2
2316
+ }),
2317
+ // Bytes (note KB vs KiB).
2318
+ Gigabyte: createFormat({
2319
+ symbol: "GB",
2320
+ quotient: 1e3 * 1e3 * 1e3,
2321
+ precision: 2
2322
+ }),
2323
+ Megabyte: createFormat({
2324
+ symbol: "MB",
2325
+ quotient: 1e3 * 1e3,
2326
+ precision: 2
2327
+ }),
2328
+ Kilobyte: createFormat({
2329
+ symbol: "KB",
2330
+ quotient: 1e3,
2331
+ precision: 2
2332
+ }),
2333
+ Byte: createFormat({
2334
+ symbol: "B",
2335
+ quotient: 1
2336
+ }),
2337
+ // Time.
2338
+ Hour: createFormat({
2339
+ symbol: "h",
2340
+ quotient: MS_HOURS
2341
+ }),
2342
+ Minute: createFormat({
2343
+ symbol: "m",
2344
+ quotient: MS_MINUTES
2345
+ }),
2346
+ Second: createFormat({
2347
+ symbol: "s",
2348
+ quotient: MS_SECONDS,
2349
+ precision: 1
2350
+ }),
2351
+ Millisecond: createFormat({
2352
+ symbol: "ms",
2353
+ quotient: 1
2354
+ }),
2355
+ Duration: (n) => {
2356
+ const hours = Math.floor(n / MS_HOURS);
2357
+ const minutes = Math.floor(n % MS_HOURS / MS_MINUTES);
2358
+ if (hours) {
2359
+ const formattedValue = minutes ? `${hours}h ${minutes}m` : `${hours}h`;
2360
+ return {
2361
+ unit: {
2362
+ symbol: "h",
2363
+ quotient: MS_HOURS
2364
+ },
2365
+ value: hours,
2366
+ formattedValue,
2367
+ toString: () => formattedValue
2368
+ };
2369
+ }
2370
+ if (minutes) {
2371
+ const seconds2 = (n - MS_MINUTES * minutes) / MS_SECONDS;
2372
+ const formattedValue = seconds2 ? `${minutes}m ${seconds2}s` : `${minutes}m`;
2373
+ return {
2374
+ unit: {
2375
+ symbol: "m",
2376
+ quotient: MS_MINUTES
2377
+ },
2378
+ value: minutes,
2379
+ formattedValue,
2380
+ toString: () => formattedValue
2381
+ };
2382
+ }
2383
+ const seconds = n >= MS_SECONDS;
2384
+ if (seconds) {
2385
+ return Unit.Second(n);
2386
+ }
2387
+ return Unit.Millisecond(n);
2388
+ }
2389
+ };
2046
2390
 
2047
2391
  // src/url.ts
2048
2392
  var createUrl = (url, search) => {
@@ -2055,16 +2399,20 @@ var createUrl = (url, search) => {
2055
2399
 
2056
2400
  // src/weak.ts
2057
2401
  var WeakDictionary = class {
2402
+ _internal = /* @__PURE__ */ new Map();
2403
+ _finalization = new FinalizationRegistry(({ key, ref }) => {
2404
+ if (this._internal.get(key) === ref) {
2405
+ this._internal.delete(key);
2406
+ }
2407
+ });
2058
2408
  constructor(entries2) {
2059
- this._internal = /* @__PURE__ */ new Map();
2060
- this._finalization = new FinalizationRegistry((cleanUpCallback) => {
2061
- cleanUpCallback();
2062
- });
2063
- this._internal = new Map(entries2?.map(([key, value]) => [
2064
- key,
2065
- new WeakRef(value)
2066
- ]));
2067
- entries2?.forEach(([key, value]) => this._register(key, value));
2409
+ if (entries2) {
2410
+ for (const [key, value] of entries2) {
2411
+ const ref = new WeakRef(value);
2412
+ this._internal.set(key, ref);
2413
+ this._register(key, value, ref);
2414
+ }
2415
+ }
2068
2416
  }
2069
2417
  *entries() {
2070
2418
  for (const [key, value] of this._internal) {
@@ -2104,10 +2452,45 @@ var WeakDictionary = class {
2104
2452
  return this._internal.get(key)?.deref();
2105
2453
  }
2106
2454
  set(key, value) {
2107
- this._internal.set(key, new WeakRef(value));
2108
- this._register(key, value);
2455
+ const previous = this._internal.get(key)?.deref();
2456
+ if (previous) {
2457
+ this._unregister(previous);
2458
+ }
2459
+ const ref = new WeakRef(value);
2460
+ this._internal.set(key, ref);
2461
+ this._register(key, value, ref);
2109
2462
  return this;
2110
2463
  }
2464
+ /**
2465
+ * Returns the value for the given key if present, otherwise inserts and returns the default value.
2466
+ * @param key - The key to look up or insert.
2467
+ * @param defaultValue - The value to insert if the key is not present.
2468
+ * @returns The existing or newly inserted value.
2469
+ */
2470
+ getOrInsert(key, defaultValue) {
2471
+ const existing = this.get(key);
2472
+ if (existing !== void 0) {
2473
+ return existing;
2474
+ }
2475
+ this.set(key, defaultValue);
2476
+ return defaultValue;
2477
+ }
2478
+ /**
2479
+ * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
2480
+ * The callback is only invoked when the key is missing.
2481
+ * @param key - The key to look up or insert.
2482
+ * @param callbackfn - Function to compute the value if the key is not present.
2483
+ * @returns The existing or newly computed value.
2484
+ */
2485
+ getOrInsertComputed(key, callbackfn) {
2486
+ const existing = this.get(key);
2487
+ if (existing !== void 0) {
2488
+ return existing;
2489
+ }
2490
+ const value = callbackfn(key);
2491
+ this.set(key, value);
2492
+ return value;
2493
+ }
2111
2494
  has(key) {
2112
2495
  return this._internal.has(key) && this._internal.get(key).deref() !== void 0;
2113
2496
  }
@@ -2138,9 +2521,10 @@ var WeakDictionary = class {
2138
2521
  }
2139
2522
  });
2140
2523
  }
2141
- _register(key, value) {
2142
- this._finalization.register(value, () => {
2143
- this._internal.delete(key);
2524
+ _register(key, value, ref) {
2525
+ this._finalization.register(value, {
2526
+ key,
2527
+ ref
2144
2528
  }, value);
2145
2529
  }
2146
2530
  _unregister(value) {
@@ -2156,11 +2540,14 @@ export {
2156
2540
  ComplexSet,
2157
2541
  HumanHasher,
2158
2542
  MapEntry,
2543
+ SKIP,
2159
2544
  SlidingWindowSummary,
2160
2545
  Tracer,
2546
+ Unit,
2161
2547
  WeakDictionary,
2162
2548
  accessBy,
2163
2549
  arrayMove,
2550
+ arraySwap,
2164
2551
  arrayToBuffer,
2165
2552
  arrayToHex,
2166
2553
  arrayToString,
@@ -2171,19 +2558,29 @@ export {
2171
2558
  capitalize,
2172
2559
  chunkArray,
2173
2560
  clamp,
2561
+ clearCaches,
2562
+ clearIndexedDB,
2563
+ clearOPFS,
2564
+ clearServiceWorkers,
2174
2565
  clearUndefined,
2566
+ coerceArray,
2175
2567
  compareMulti,
2176
2568
  compareObject,
2177
2569
  compareScalar,
2178
2570
  compareString,
2571
+ compositeKey,
2179
2572
  createBinder,
2180
2573
  createBucketReducer,
2574
+ createFilename,
2181
2575
  createGroupReducer,
2576
+ createReplacer,
2182
2577
  createSetDispatch,
2183
2578
  createUrl,
2184
2579
  decamelize,
2580
+ decodeUint8ArrayFromJson,
2185
2581
  deepMapValues,
2186
2582
  deepMapValuesAsync,
2583
+ defaultFilter,
2187
2584
  defaultMap,
2188
2585
  defer,
2189
2586
  deferAsync,
@@ -2191,16 +2588,16 @@ export {
2191
2588
  diff,
2192
2589
  distinctBy,
2193
2590
  doAsync,
2591
+ encodeUint8ArrayToJson,
2194
2592
  entries,
2195
2593
  entry,
2196
2594
  exponentialBackoffInterval,
2197
2595
  forEachAsync,
2198
- get,
2596
+ formatErrorWithCauses,
2199
2597
  getAsyncProviderValue,
2200
2598
  getDate,
2201
2599
  getDebugName,
2202
2600
  getDeep,
2203
- getFirstTwoRenderableChars,
2204
2601
  getHostPlatform,
2205
2602
  getPrototypeSpecificInstanceId,
2206
2603
  getProviderValue,
@@ -2209,6 +2606,7 @@ export {
2209
2606
  hexToHue,
2210
2607
  humanize,
2211
2608
  hyphenize,
2609
+ id,
2212
2610
  idEmoji,
2213
2611
  idHue,
2214
2612
  inferObjectOrder,
@@ -2216,14 +2614,22 @@ export {
2216
2614
  intersectBy,
2217
2615
  intersection,
2218
2616
  iosCheck,
2617
+ isBun,
2618
+ isEncodedUint8Array,
2619
+ isMobile,
2620
+ isMobileOrTablet,
2219
2621
  isNode,
2220
2622
  isNonNullable,
2221
- isNotFalsy,
2623
+ isTauri,
2624
+ isTruthy,
2625
+ isWellFormedId,
2626
+ isWellFormedIdPart,
2222
2627
  joinTables,
2223
2628
  jsonKeyReplacer,
2224
2629
  jsonReplacer,
2225
2630
  jsonify,
2226
2631
  jsonlogify,
2632
+ kebabize,
2227
2633
  keyToEmoji,
2228
2634
  keyToFallback,
2229
2635
  keyToHue,
@@ -2232,7 +2638,6 @@ export {
2232
2638
  makeSet,
2233
2639
  mapValues,
2234
2640
  median,
2235
- mobileAndTabletCheck,
2236
2641
  numericalValues,
2237
2642
  omit,
2238
2643
  orderKeys,
@@ -2248,15 +2653,18 @@ export {
2248
2653
  removeBy,
2249
2654
  removeProperties,
2250
2655
  removeUndefinedProperties,
2656
+ retry,
2251
2657
  safariCheck,
2252
2658
  safeAwaitAll,
2253
2659
  safeInstanceof,
2254
2660
  safeParseFloat,
2255
2661
  safeParseInt,
2256
2662
  safeParseJson,
2257
- set,
2663
+ safeStringify,
2664
+ safeUrl,
2258
2665
  setDeep,
2259
2666
  sortKeys,
2667
+ splitCompositeKey,
2260
2668
  stringToArray,
2261
2669
  stringifyTree,
2262
2670
  stripUndefined,
@@ -2266,6 +2674,7 @@ export {
2266
2674
  toFallback,
2267
2675
  toHue,
2268
2676
  tracer,
2677
+ trim,
2269
2678
  visitValues
2270
2679
  };
2271
2680
  //# sourceMappingURL=index.mjs.map