@dxos/util 0.3.11-main.fbbdc2a → 0.3.11-main.fc97a54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/util",
3
- "version": "0.3.11-main.fbbdc2a",
3
+ "version": "0.3.11-main.fc97a54",
4
4
  "description": "Temporary bucket for misc functions, which should graduate into separate packages.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -16,13 +16,13 @@
16
16
  "src"
17
17
  ],
18
18
  "dependencies": {
19
- "@dxos/debug": "0.3.11-main.fbbdc2a",
20
- "@dxos/invariant": "0.3.11-main.fbbdc2a",
21
- "@dxos/keys": "0.3.11-main.fbbdc2a",
22
- "@dxos/node-std": "0.3.11-main.fbbdc2a"
19
+ "@dxos/debug": "0.3.11-main.fc97a54",
20
+ "@dxos/keys": "0.3.11-main.fc97a54",
21
+ "@dxos/invariant": "0.3.11-main.fc97a54",
22
+ "@dxos/node-std": "0.3.11-main.fc97a54"
23
23
  },
24
24
  "devDependencies": {
25
- "@dxos/crypto": "0.3.11-main.fbbdc2a"
25
+ "@dxos/crypto": "0.3.11-main.fc97a54"
26
26
  },
27
27
  "publishConfig": {
28
28
  "access": "public"
@@ -0,0 +1,37 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+
7
+ import { describe, test } from '@dxos/test';
8
+
9
+ import { defer, deferAsync } from './defer';
10
+
11
+ describe('defer', () => {
12
+ test('defer', () => {
13
+ const events: string[] = [];
14
+
15
+ {
16
+ using _ = defer(() => events.push('1'));
17
+ events.push('2');
18
+ }
19
+
20
+ expect(events).to.deep.eq(['2', '1']);
21
+ });
22
+
23
+ test('deferAsync', async () => {
24
+ const events: string[] = [];
25
+
26
+ {
27
+ await using _ = deferAsync(async () => {
28
+ await new Promise((resolve) => setTimeout(resolve, 5));
29
+ events.push('1');
30
+ });
31
+ events.push('2');
32
+ }
33
+ events.push('3');
34
+
35
+ expect(events).to.deep.eq(['2', '1', '3']);
36
+ });
37
+ });
package/src/defer.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Run function on scope exit.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * {
7
+ * using _ = defer(() => console.log('exiting'));
8
+ *
9
+ * ...
10
+ * }
11
+ */
12
+ //
13
+ // Copyright 2024 DXOS.org
14
+ //
15
+
16
+ export const defer = (fn: () => void): Disposable => new DeferGuard(fn);
17
+
18
+ class DeferGuard {
19
+ /**
20
+ * @internal
21
+ */
22
+ constructor(private readonly _fn: () => void) {}
23
+
24
+ [Symbol.dispose]() {
25
+ const result = this._fn();
26
+ if ((result as any) instanceof Promise) {
27
+ throw new Error('Async functions in defer are not supported. Use deferAsync instead.');
28
+ }
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Run async function on scope exit.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * {
38
+ * await using _ = deferAsync(async () => console.log('exiting'));
39
+ *
40
+ * ...
41
+ * }
42
+ */
43
+ export const deferAsync = (fn: () => Promise<void>): AsyncDisposable => new DeferAsyncGuard(fn);
44
+
45
+ class DeferAsyncGuard implements AsyncDisposable {
46
+ /**
47
+ * @internal
48
+ */
49
+ constructor(private readonly _fn: () => Promise<void>) {}
50
+
51
+ async [Symbol.asyncDispose]() {
52
+ await this._fn();
53
+ }
54
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ export * from './random';
18
18
  export * from './range';
19
19
  export * from './reducers';
20
20
  export * from './safe-instanceof';
21
+ export * from './safe-parse-json';
21
22
  export * from './sort';
22
23
  export * from './tracer';
23
24
  export * from './types';
@@ -26,3 +27,5 @@ export * from './instance-id';
26
27
  export * from './sum';
27
28
  export * from './for-each-async';
28
29
  export * from './weak';
30
+ export * from './map-values';
31
+ export * from './defer';
@@ -0,0 +1,11 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export const mapValues = <T, U>(obj: Record<string, T>, fn: (value: T, key: string) => U): Record<string, U> => {
6
+ const result: Record<string, U> = {};
7
+ Object.keys(obj).forEach((key) => {
8
+ result[key] = fn(obj[key], key);
9
+ });
10
+ return result;
11
+ };
package/src/platform.ts CHANGED
@@ -28,3 +28,29 @@ export const iosCheck = () => {
28
28
  // From https://stackoverflow.com/a/23522755/2804332
29
29
  export const safariCheck = () =>
30
30
  typeof navigator !== 'undefined' && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
31
+
32
+ /**
33
+ * Retrieve the host platform in a best-effort way with normalized output.
34
+ */
35
+ // From https://flaming.codes/posts/how-to-determine-os-in-browser.
36
+ export const getHostPlatform = () => {
37
+ if (!('navigator' in window)) {
38
+ return 'unknown';
39
+ }
40
+
41
+ // Use the modern 'web hints' provied by
42
+ // 'userAgentData' if available, else use
43
+ // the deprecated 'platform' as fallback.
44
+ const platform = ((navigator as any).userAgentData?.platform || navigator.platform)?.toLowerCase();
45
+ if (platform.startsWith('win')) {
46
+ return 'windows';
47
+ } else if (platform.startsWith('mac')) {
48
+ return 'macos';
49
+ } else if (platform.startsWith('ipad') || platform.startsWith('iphone') || platform.startsWith('ipod')) {
50
+ return 'ios';
51
+ } else if (platform.startsWith('linux')) {
52
+ return 'linux';
53
+ } else {
54
+ return 'unknown';
55
+ }
56
+ };
@@ -0,0 +1,15 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export const safeParseJson: {
6
+ <T extends object>(data: string | undefined | null, defaultValue: T): T;
7
+ <T extends object>(data: string | undefined | null): T | undefined;
8
+ } = <T extends object>(data: string | undefined | null, defaultValue?: T) => {
9
+ if (data) {
10
+ try {
11
+ return JSON.parse(data);
12
+ } catch (err) {}
13
+ }
14
+ return defaultValue;
15
+ };
package/src/types.ts CHANGED
@@ -2,23 +2,12 @@
2
2
  // Copyright 2020 DXOS.org
3
3
  //
4
4
 
5
- export const boolGuard = <T>(value: T | null | undefined): value is T => Boolean(value);
6
-
7
5
  export type AsyncCallback<T> = (param: T) => Promise<void>;
8
6
 
9
7
  export type Provider<T> = () => T;
10
8
 
11
9
  export type MaybePromise<T> = T | Promise<T>;
12
10
 
13
- export const isNotNullOrUndefined = <T>(x: T): x is Exclude<T, null | undefined> => x != null;
14
-
15
- /**
16
- * Use with filter chaining instead of filter(Boolean) to preserve type.
17
- * NOTE: To filter by type:
18
- * items.filter((item: any): item is RangeSet<Decoration> => item instanceof RangeSet)
19
- */
20
- export const nonNullable = <T>(value: T): value is NonNullable<T> => value !== null && value !== undefined;
21
-
22
11
  /**
23
12
  * All types that evaluate to false when cast to a boolean.
24
13
  */
@@ -29,6 +18,17 @@ export type Falsy = false | 0 | '' | null | undefined;
29
18
  */
30
19
  export type MaybeFunction<T> = T | (() => T);
31
20
 
21
+ /**
22
+ * Use with filter chaining instead of filter(Boolean) to preserve type.
23
+ * NOTE: To filter by type:
24
+ * items.filter((item: any): item is RangeSet<Decoration> => item instanceof RangeSet)
25
+ */
26
+ // TODO(burdon): Reconcile names.
27
+ export const isNotFalsy = <T>(value: T): value is Exclude<T, Falsy> => !!value;
28
+ export const nonNullable = <T>(value: T): value is NonNullable<T> => value !== null && value !== undefined;
29
+ export const isNotNullOrUndefined = <T>(value: T): value is Exclude<T, null | undefined> => value != null;
30
+ export const boolGuard = <T>(value: T | null | undefined): value is T => Boolean(value);
31
+
32
32
  /**
33
33
  * Get value from a provider.
34
34
  */