toastflow-core 1.1.4 → 1.1.5

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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/util.ts +18 -7
package/package.json CHANGED
@@ -8,7 +8,7 @@
8
8
  "url": "https://github.com/adrianjanocko/toastflow.git",
9
9
  "directory": "packages/core"
10
10
  },
11
- "version": "1.1.4",
11
+ "version": "1.1.5",
12
12
  "main": "src/index.ts",
13
13
  "module": "src/index.ts",
14
14
  "types": "src/index.ts",
package/src/util.ts CHANGED
@@ -2,22 +2,33 @@
2
2
  * Generate a UUID v4 using `crypto.randomUUID` when available; otherwise fall back
3
3
  * to the classic template with random nibbles (uses `crypto.getRandomValues` when possible).
4
4
  */
5
+ type CryptoLike = {
6
+ randomUUID?: () => string;
7
+ getRandomValues?: (arr: Uint8Array) => Uint8Array;
8
+ };
9
+
5
10
  export function generateUuid(): string {
6
- const cryptoSource: Crypto | undefined =
7
- typeof crypto !== "undefined" ? (crypto as Crypto) : undefined;
11
+ const cryptoApi: CryptoLike | undefined = (globalThis as any)?.crypto;
8
12
 
9
- if (typeof cryptoSource?.randomUUID === "function") {
13
+ if (typeof cryptoApi?.randomUUID === "function") {
10
14
  try {
11
- return cryptoSource.randomUUID();
15
+ return cryptoApi.randomUUID();
12
16
  } catch {
13
17
  // ignore and use fallback
14
18
  }
15
19
  }
16
20
 
21
+ function randomNibble(): number {
22
+ if (typeof cryptoApi?.getRandomValues === "function") {
23
+ const bytes = new Uint8Array(1);
24
+ cryptoApi.getRandomValues(bytes);
25
+ return (bytes[0] ?? 0) & 0xf;
26
+ }
27
+ return Math.floor(Math.random() * 16);
28
+ }
29
+
17
30
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
18
- const rand = cryptoSource?.getRandomValues
19
- ? cryptoSource.getRandomValues(new Uint8Array(1))[0] & 0xf
20
- : Math.floor(Math.random() * 16);
31
+ const rand = randomNibble();
21
32
  const value = c === "x" ? rand : (rand & 0x3) | 0x8;
22
33
  return value.toString(16);
23
34
  });