@dxos/util 0.8.4-main.f9ba587 → 0.8.4-main.fcfe5033a5

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 (102) hide show
  1. package/dist/lib/browser/index.mjs +508 -146
  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 +508 -146
  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/assume.d.ts.map +1 -1
  10. package/dist/types/src/circular-buffer.d.ts +1 -0
  11. package/dist/types/src/circular-buffer.d.ts.map +1 -1
  12. package/dist/types/src/complex.d.ts +15 -0
  13. package/dist/types/src/complex.d.ts.map +1 -1
  14. package/dist/types/src/composite-key.d.ts +10 -0
  15. package/dist/types/src/composite-key.d.ts.map +1 -0
  16. package/dist/types/src/composite-key.test.d.ts +2 -0
  17. package/dist/types/src/composite-key.test.d.ts.map +1 -0
  18. package/dist/types/src/deep.d.ts +0 -3
  19. package/dist/types/src/deep.d.ts.map +1 -1
  20. package/dist/types/src/defer.d.ts +1 -1
  21. package/dist/types/src/defer.d.ts.map +1 -1
  22. package/dist/types/src/di-key.d.ts +7 -5
  23. package/dist/types/src/di-key.d.ts.map +1 -1
  24. package/dist/types/src/error-format.d.ts +5 -0
  25. package/dist/types/src/error-format.d.ts.map +1 -0
  26. package/dist/types/src/filename.d.ts +9 -0
  27. package/dist/types/src/filename.d.ts.map +1 -0
  28. package/dist/types/src/index.d.ts +6 -2
  29. package/dist/types/src/index.d.ts.map +1 -1
  30. package/dist/types/src/json.d.ts +1 -1
  31. package/dist/types/src/json.d.ts.map +1 -1
  32. package/dist/types/src/object.d.ts +3 -0
  33. package/dist/types/src/object.d.ts.map +1 -1
  34. package/dist/types/src/platform.d.ts +4 -1
  35. package/dist/types/src/platform.d.ts.map +1 -1
  36. package/dist/types/src/retry.d.ts +32 -0
  37. package/dist/types/src/retry.d.ts.map +1 -0
  38. package/dist/types/src/safe-parse.d.ts +7 -4
  39. package/dist/types/src/safe-parse.d.ts.map +1 -1
  40. package/dist/types/src/safe-stringify.d.ts +22 -0
  41. package/dist/types/src/safe-stringify.d.ts.map +1 -0
  42. package/dist/types/src/safe-stringify.test.d.ts +2 -0
  43. package/dist/types/src/safe-stringify.test.d.ts.map +1 -0
  44. package/dist/types/src/string.d.ts +8 -0
  45. package/dist/types/src/string.d.ts.map +1 -1
  46. package/dist/types/src/string.test.d.ts +2 -0
  47. package/dist/types/src/string.test.d.ts.map +1 -0
  48. package/dist/types/src/to-fallback.d.ts +18 -4
  49. package/dist/types/src/to-fallback.d.ts.map +1 -1
  50. package/dist/types/src/types.d.ts +24 -6
  51. package/dist/types/src/types.d.ts.map +1 -1
  52. package/dist/types/src/unit.d.ts +14 -0
  53. package/dist/types/src/unit.d.ts.map +1 -0
  54. package/dist/types/src/unit.test.d.ts +2 -0
  55. package/dist/types/src/unit.test.d.ts.map +1 -0
  56. package/dist/types/src/weak.d.ts +15 -0
  57. package/dist/types/src/weak.d.ts.map +1 -1
  58. package/dist/types/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +14 -13
  60. package/src/array.test.ts +1 -1
  61. package/src/array.ts +9 -4
  62. package/src/assume.ts +0 -1
  63. package/src/binder.ts +2 -2
  64. package/src/circular-buffer.test.ts +27 -1
  65. package/src/circular-buffer.ts +5 -0
  66. package/src/complex.test.ts +1 -1
  67. package/src/complex.ts +32 -0
  68. package/src/composite-key.test.ts +31 -0
  69. package/src/composite-key.ts +16 -0
  70. package/src/deep.ts +2 -6
  71. package/src/defer.ts +1 -1
  72. package/src/di-key.ts +10 -8
  73. package/src/error-format.ts +22 -0
  74. package/src/filename.ts +16 -0
  75. package/src/human-hash.test.ts +1 -1
  76. package/src/index.ts +6 -2
  77. package/src/json.ts +2 -7
  78. package/src/object.ts +3 -0
  79. package/src/platform.ts +35 -3
  80. package/src/position.test.ts +2 -2
  81. package/src/retry.ts +74 -0
  82. package/src/safe-parse.ts +29 -15
  83. package/src/safe-stringify.test.ts +96 -0
  84. package/src/safe-stringify.ts +153 -0
  85. package/src/sort.test.ts +1 -1
  86. package/src/string.test.ts +19 -0
  87. package/src/string.ts +36 -0
  88. package/src/to-fallback.ts +44 -160
  89. package/src/tree.test.ts +1 -1
  90. package/src/types.test.ts +11 -1
  91. package/src/types.ts +40 -12
  92. package/src/uint8array.test.ts +1 -1
  93. package/src/unit.test.ts +25 -0
  94. package/src/unit.ts +83 -0
  95. package/src/weak.test.ts +1 -1
  96. package/src/weak.ts +52 -14
  97. package/dist/types/src/explicit-resource-management-polyfill.d.ts +0 -1
  98. package/dist/types/src/explicit-resource-management-polyfill.d.ts.map +0 -1
  99. package/dist/types/src/first-two-chars.d.ts +0 -9
  100. package/dist/types/src/first-two-chars.d.ts.map +0 -1
  101. package/src/explicit-resource-management-polyfill.ts +0 -13
  102. package/src/first-two-chars.ts +0 -44
package/src/types.ts CHANGED
@@ -10,15 +10,33 @@ export type MaybeProvider<T, V = void> = T | ((arg: V) => T);
10
10
 
11
11
  export type MaybePromise<T> = T | Promise<T>;
12
12
 
13
- export type GuardedType<T> = T extends (value: any) => value is infer R ? R : never;
14
-
15
- export type DeepReadonly<T> = {
16
- readonly [P in keyof T]: T[P] extends Record<string, any>
17
- ? DeepReadonly<T[P]>
18
- : T[P] extends Array<infer U>
19
- ? ReadonlyArray<DeepReadonly<U>>
20
- : T[P];
21
- };
13
+ export type GuardedType<T> = T extends ((value: any) => value is infer R) ? R : never;
14
+
15
+ /**
16
+ * Removes readonly modifiers from top-level properties of T.
17
+ * Also converts readonly arrays at the top level to mutable arrays.
18
+ * For nested properties, mutability depends on the schema definition.
19
+ */
20
+ export type ToMutable<T> = T extends object
21
+ ? { -readonly [K in keyof T]: T[K] extends readonly (infer U)[] ? U[] : T[K] }
22
+ : T;
23
+
24
+ export type Intersection<Types extends readonly unknown[]> = Types extends [infer First, ...infer Rest]
25
+ ? First & Intersection<Rest>
26
+ : unknown;
27
+
28
+ /**
29
+ * Recursively makes all properties of T readonly.
30
+ * Primitives (including branded types like `string & { __brand: true }`) are returned as-is.
31
+ * Arrays become ReadonlyArrays with deeply readonly elements.
32
+ */
33
+ export type DeepReadonly<T> = T extends string | number | boolean | bigint | symbol | null | undefined
34
+ ? T // Primitives (including branded primitives) stay as-is.
35
+ : T extends Array<infer U>
36
+ ? ReadonlyArray<DeepReadonly<U>>
37
+ : T extends object
38
+ ? { readonly [P in keyof T]: DeepReadonly<T[P]> }
39
+ : T;
22
40
 
23
41
  export type DeepWriteable<T> = { -readonly [K in keyof T]: T[K] extends object ? DeepWriteable<T[K]> : T[K] };
24
42
 
@@ -48,7 +66,7 @@ export type Falsy = false | 0 | '' | null | undefined;
48
66
  * NOTE: To filter by type:
49
67
  * items.filter((item: any): item is RangeSet<Decoration> => item instanceof RangeSet)
50
68
  */
51
- export const isNotFalsy = <T>(value: T): value is Exclude<T, Falsy> => !!value;
69
+ export const isTruthy = <T>(value: T): value is Exclude<T, Falsy> => !!value;
52
70
  export const isNonNullable = <T>(value: T | null | undefined): value is T => value != null;
53
71
 
54
72
  // TODO(burdon): Replace use of setTimeout everywhere?
@@ -104,9 +122,19 @@ export const sortKeys = <T extends object>(obj: T): T =>
104
122
  }, {} as T);
105
123
 
106
124
  /**
107
- * Swap position of element within array.
125
+ * Move element within array.
108
126
  */
109
- export const arrayMove = <T>(array: T[], from: number, to: number): Array<T> => {
127
+ export const arrayMove = <T>(array: T[], from: number, to: number): T[] => {
110
128
  array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
111
129
  return array;
112
130
  };
131
+
132
+ /**
133
+ * Swap position of element within array.
134
+ */
135
+ export function arraySwap<T>(array: T[], from: number, to: number): T[] {
136
+ const current = array[from];
137
+ array[from] = array[to];
138
+ array[to] = current;
139
+ return array;
140
+ }
@@ -2,7 +2,7 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { test, expect, describe } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { arrayToBuffer, arrayToString, bufferToArray, stringToArray } from './uint8array';
8
8
 
@@ -0,0 +1,25 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, it } from 'vitest';
6
+
7
+ import { Unit } from './unit';
8
+
9
+ describe('url', () => {
10
+ it('duration', ({ expect }) => {
11
+ const tests: [number, string][] = [
12
+ [0, '0ms'],
13
+ [1, '1ms'],
14
+ [1_000, '1.0s'],
15
+ [2_887, '2.9s'],
16
+ [1_000 * 60, '1m'],
17
+ [1_000 * 60 + 1_000 * 5, '1m 5s'],
18
+ [1_000 * 60 * 60 + 1_000 * 60 * 5, '1h 5m'],
19
+ ];
20
+
21
+ tests.forEach(([input, output]) => {
22
+ expect(Unit.Duration(input).toString(), input.toString()).toBe(output);
23
+ });
24
+ });
25
+ });
package/src/unit.ts ADDED
@@ -0,0 +1,83 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export type Unit = {
6
+ symbol: string;
7
+ quotient: number;
8
+ precision?: number;
9
+ };
10
+
11
+ export type UnitValue<T> = {
12
+ unit: Unit;
13
+ value: number;
14
+ formattedValue: T;
15
+ toString: () => string;
16
+ };
17
+
18
+ export type UnitFormat<T = any> = (n: number, precision?: number) => UnitValue<T>;
19
+
20
+ const createFormat = (unit: Unit): UnitFormat<string> => {
21
+ return (n: number, precision = unit.precision ?? 0) => {
22
+ const value = n / unit.quotient;
23
+ return {
24
+ unit,
25
+ value,
26
+ formattedValue: value.toFixed(precision),
27
+ toString: () => `${value.toFixed(precision)}${unit.symbol}`,
28
+ };
29
+ };
30
+ };
31
+
32
+ const MS_SECONDS = 1_000;
33
+ const MS_MINUTES = 60 * MS_SECONDS;
34
+ const MS_HOURS = 60 * MS_MINUTES;
35
+
36
+ export const Unit: Record<string, UnitFormat> = {
37
+ // General.
38
+ Percent: createFormat({ symbol: '%', quotient: 1 / 100, precision: 2 }),
39
+ Thousand: createFormat({ symbol: 'k', quotient: 1_000, precision: 2 }),
40
+
41
+ // Bytes (note KB vs KiB).
42
+ Gigabyte: createFormat({ symbol: 'GB', quotient: 1_000 * 1_000 * 1_000, precision: 2 }),
43
+ Megabyte: createFormat({ symbol: 'MB', quotient: 1_000 * 1_000, precision: 2 }),
44
+ Kilobyte: createFormat({ symbol: 'KB', quotient: 1_000, precision: 2 }),
45
+ Byte: createFormat({ symbol: 'B', quotient: 1 }),
46
+
47
+ // Time.
48
+ Hour: createFormat({ symbol: 'h', quotient: MS_HOURS }),
49
+ Minute: createFormat({ symbol: 'm', quotient: MS_MINUTES }),
50
+ Second: createFormat({ symbol: 's', quotient: MS_SECONDS, precision: 1 }),
51
+ Millisecond: createFormat({ symbol: 'ms', quotient: 1 }),
52
+ Duration: (n: number) => {
53
+ const hours = Math.floor(n / MS_HOURS);
54
+ const minutes = Math.floor((n % MS_HOURS) / MS_MINUTES);
55
+ if (hours) {
56
+ const formattedValue = minutes ? `${hours}h ${minutes}m` : `${hours}h`;
57
+ return {
58
+ unit: { symbol: 'h', quotient: MS_HOURS },
59
+ value: hours,
60
+ formattedValue,
61
+ toString: () => formattedValue,
62
+ };
63
+ }
64
+
65
+ if (minutes) {
66
+ const seconds = (n - MS_MINUTES * minutes) / MS_SECONDS;
67
+ const formattedValue = seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;
68
+ return {
69
+ unit: { symbol: 'm', quotient: MS_MINUTES },
70
+ value: minutes,
71
+ formattedValue,
72
+ toString: () => formattedValue,
73
+ };
74
+ }
75
+
76
+ const seconds = n >= MS_SECONDS;
77
+ if (seconds) {
78
+ return Unit.Second(n);
79
+ }
80
+
81
+ return Unit.Millisecond(n);
82
+ },
83
+ } as const;
package/src/weak.test.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { test, expect, describe } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { WeakDictionary } from './weak';
8
8
 
package/src/weak.ts CHANGED
@@ -7,13 +7,20 @@
7
7
  */
8
8
  export class WeakDictionary<K, V extends object> implements Map<K, V> {
9
9
  private readonly _internal = new Map<K, WeakRef<V>>();
10
- private readonly _finalization = new FinalizationRegistry((cleanUpCallback: () => void) => {
11
- cleanUpCallback();
10
+ private readonly _finalization = new FinalizationRegistry<{ key: K; ref: WeakRef<V> }>(({ key, ref }) => {
11
+ if (this._internal.get(key) === ref) {
12
+ this._internal.delete(key);
13
+ }
12
14
  });
13
15
 
14
16
  constructor(entries?: [K, V][]) {
15
- this._internal = new Map(entries?.map(([key, value]) => [key, new WeakRef(value)]));
16
- entries?.forEach(([key, value]) => this._register(key, value));
17
+ if (entries) {
18
+ for (const [key, value] of entries) {
19
+ const ref = new WeakRef(value);
20
+ this._internal.set(key, ref);
21
+ this._register(key, value, ref);
22
+ }
23
+ }
17
24
  }
18
25
 
19
26
  *entries(): SetIterator<[K, V]> {
@@ -55,11 +62,48 @@ export class WeakDictionary<K, V extends object> implements Map<K, V> {
55
62
  }
56
63
 
57
64
  set(key: K, value: V): this {
58
- this._internal.set(key, new WeakRef(value));
59
- this._register(key, value);
65
+ const previous = this._internal.get(key)?.deref();
66
+ if (previous) {
67
+ this._unregister(previous);
68
+ }
69
+ const ref = new WeakRef(value);
70
+ this._internal.set(key, ref);
71
+ this._register(key, value, ref);
60
72
  return this;
61
73
  }
62
74
 
75
+ /**
76
+ * Returns the value for the given key if present, otherwise inserts and returns the default value.
77
+ * @param key - The key to look up or insert.
78
+ * @param defaultValue - The value to insert if the key is not present.
79
+ * @returns The existing or newly inserted value.
80
+ */
81
+ getOrInsert(key: K, defaultValue: V): V {
82
+ const existing = this.get(key);
83
+ if (existing !== undefined) {
84
+ return existing;
85
+ }
86
+ this.set(key, defaultValue);
87
+ return defaultValue;
88
+ }
89
+
90
+ /**
91
+ * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
92
+ * The callback is only invoked when the key is missing.
93
+ * @param key - The key to look up or insert.
94
+ * @param callbackfn - Function to compute the value if the key is not present.
95
+ * @returns The existing or newly computed value.
96
+ */
97
+ getOrInsertComputed(key: K, callbackfn: (key: K) => V): V {
98
+ const existing = this.get(key);
99
+ if (existing !== undefined) {
100
+ return existing;
101
+ }
102
+ const value = callbackfn(key);
103
+ this.set(key, value);
104
+ return value;
105
+ }
106
+
63
107
  has(key: K): boolean {
64
108
  return this._internal.has(key) && this._internal.get(key)!.deref() !== undefined;
65
109
  }
@@ -96,14 +140,8 @@ export class WeakDictionary<K, V extends object> implements Map<K, V> {
96
140
  });
97
141
  }
98
142
 
99
- private _register(key: K, value: V): void {
100
- this._finalization.register(
101
- value,
102
- () => {
103
- this._internal.delete(key);
104
- },
105
- value,
106
- );
143
+ private _register(key: K, value: V, ref: WeakRef<V>): void {
144
+ this._finalization.register(value, { key, ref }, value);
107
145
  }
108
146
 
109
147
  private _unregister(value: V): void {
@@ -1 +0,0 @@
1
- //# sourceMappingURL=explicit-resource-management-polyfill.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"explicit-resource-management-polyfill.d.ts","sourceRoot":"","sources":["../../../src/explicit-resource-management-polyfill.ts"],"names":[],"mappings":""}
@@ -1,9 +0,0 @@
1
- /**
2
- * Returns the first two renderable characters from a string that are separated by non-word characters.
3
- * Handles Unicode characters correctly.
4
- *
5
- * @param {string} label - The input string to process
6
- * @returns {[string, string]} Array containing the two characters, or empty strings if not found
7
- */
8
- export declare const getFirstTwoRenderableChars: (label: string) => string[];
9
- //# sourceMappingURL=first-two-chars.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"first-two-chars.d.ts","sourceRoot":"","sources":["../../../src/first-two-chars.ts"],"names":[],"mappings":"AASA;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,GAAI,OAAO,MAAM,aA2BvD,CAAC"}
@@ -1,13 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html
6
-
7
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
8
- // @ts-ignore
9
- Symbol.dispose ??= Symbol('Symbol.dispose');
10
-
11
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
12
- // @ts-ignore
13
- Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
@@ -1,44 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- // Regular expression to match renderable characters
6
- // Excludes control characters, combining marks, and other non-renderable characters. Also excludes punctuation.
7
- const renderableCharRegex =
8
- /^(?![\p{Control}\p{Mark}\p{Separator}\p{Surrogate}\p{Unassigned}\p{P}])[\p{L}\p{N}\p{S}\p{Emoji}]$/u;
9
-
10
- /**
11
- * Returns the first two renderable characters from a string that are separated by non-word characters.
12
- * Handles Unicode characters correctly.
13
- *
14
- * @param {string} label - The input string to process
15
- * @returns {[string, string]} Array containing the two characters, or empty strings if not found
16
- */
17
- export const getFirstTwoRenderableChars = (label: string) => {
18
- // Convert string to array of Unicode characters
19
- const characters = Array.from(label);
20
-
21
- // Keep track of found renderable characters
22
- const result = ['', ''];
23
- let foundFirst = false;
24
-
25
- for (let i = 0; i < characters.length; i++) {
26
- const char = characters[i];
27
-
28
- if (renderableCharRegex.test(char)) {
29
- if (!foundFirst) {
30
- result[0] = char;
31
- foundFirst = true;
32
- } else {
33
- // Check if there's at least one non-word character between the first and current char
34
- const textBetween = characters.slice(result[0].length, i).join('');
35
- if (/[^\p{L}\p{N}_]/u.test(textBetween)) {
36
- result[1] = char;
37
- break;
38
- }
39
- }
40
- }
41
- }
42
-
43
- return result;
44
- };