@anizoptera/uuid-slug 0.2.0 → 0.3.0

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 (95) hide show
  1. package/README.md +381 -27
  2. package/dist/alphabet.d.ts +21 -0
  3. package/dist/alphabet.d.ts.map +1 -0
  4. package/dist/alphabet.js +132 -0
  5. package/dist/alphabet.js.map +1 -0
  6. package/dist/base64url.d.ts +20 -0
  7. package/dist/base64url.d.ts.map +1 -0
  8. package/dist/base64url.js +33 -0
  9. package/dist/base64url.js.map +1 -0
  10. package/dist/codec.d.ts +17 -0
  11. package/dist/codec.d.ts.map +1 -0
  12. package/dist/codec.js +192 -0
  13. package/dist/codec.js.map +1 -0
  14. package/dist/errors.d.ts +16 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +80 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/feistel.js +105 -0
  19. package/dist/feistel.js.map +1 -0
  20. package/dist/index.d.ts +11 -168
  21. package/dist/index.js +10 -649
  22. package/dist/keyless.d.ts +31 -0
  23. package/dist/keyless.d.ts.map +1 -0
  24. package/dist/keyless.js +93 -0
  25. package/dist/keyless.js.map +1 -0
  26. package/dist/legacy-mask.js +55 -0
  27. package/dist/legacy-mask.js.map +1 -0
  28. package/dist/mask.js +108 -0
  29. package/dist/mask.js.map +1 -0
  30. package/dist/migration.js +66 -0
  31. package/dist/migration.js.map +1 -0
  32. package/dist/node/alphabet.js +130 -0
  33. package/dist/node/base64url.js +31 -0
  34. package/dist/node/codec.js +190 -0
  35. package/dist/node/errors.js +78 -0
  36. package/dist/node/feistel.js +103 -0
  37. package/dist/node/index.js +10 -647
  38. package/dist/node/keyless.js +91 -0
  39. package/dist/node/legacy-mask.js +53 -0
  40. package/dist/node/mask.js +106 -0
  41. package/dist/node/migration.js +64 -0
  42. package/dist/node/runtime/node.js +33 -0
  43. package/dist/node/runtime/pool.js +53 -0
  44. package/dist/node/schema.js +214 -0
  45. package/dist/node/siphash.js +106 -0
  46. package/dist/node/uuid.js +226 -0
  47. package/dist/node/v7.js +185 -0
  48. package/dist/node/yield.js +20 -0
  49. package/dist/runtime/pool.js +55 -0
  50. package/dist/runtime/pool.js.map +1 -0
  51. package/dist/runtime/web.js +39 -0
  52. package/dist/runtime/web.js.map +1 -0
  53. package/dist/schema.d.ts +20 -0
  54. package/dist/schema.d.ts.map +1 -0
  55. package/dist/schema.js +216 -0
  56. package/dist/schema.js.map +1 -0
  57. package/dist/siphash.js +108 -0
  58. package/dist/siphash.js.map +1 -0
  59. package/dist/types.d.ts +255 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/uuid.d.ts +78 -0
  62. package/dist/uuid.d.ts.map +1 -0
  63. package/dist/uuid.js +228 -0
  64. package/dist/uuid.js.map +1 -0
  65. package/dist/v7.d.ts +12 -0
  66. package/dist/v7.d.ts.map +1 -0
  67. package/dist/v7.js +187 -0
  68. package/dist/v7.js.map +1 -0
  69. package/dist/yield.js +22 -0
  70. package/dist/yield.js.map +1 -0
  71. package/package.json +8 -12
  72. package/src/alphabet.ts +187 -0
  73. package/src/base64url.ts +28 -63
  74. package/src/codec.ts +227 -125
  75. package/src/errors.ts +83 -9
  76. package/src/feistel.ts +128 -0
  77. package/src/index.ts +52 -26
  78. package/src/keyless.ts +136 -0
  79. package/src/legacy-mask.ts +25 -0
  80. package/src/mask.ts +129 -67
  81. package/src/migration.ts +104 -0
  82. package/src/runtime/bun.ts +49 -24
  83. package/src/runtime/node.ts +33 -15
  84. package/src/runtime/pool.ts +62 -0
  85. package/src/runtime/types.ts +42 -5
  86. package/src/runtime/web.ts +37 -9
  87. package/src/schema.ts +274 -97
  88. package/src/siphash.ts +127 -0
  89. package/src/types.ts +221 -37
  90. package/src/uuid.ts +189 -50
  91. package/src/v7.ts +217 -45
  92. package/src/yield.ts +22 -0
  93. package/dist/index.d.ts.map +0 -1
  94. package/dist/index.js.map +0 -1
  95. package/dist/web/index.js +0 -648
@@ -0,0 +1,104 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { BASE32HEX, BASE64URL, decodeInto, encode } from "./alphabet";
4
+ import { UuidSlugError } from "./errors";
5
+ import { decodeOriginalMask } from "./legacy-mask";
6
+ import { decodeMaskedCandidates } from "./mask";
7
+ import type {
8
+ MaskSchema,
9
+ MigrationFormat,
10
+ UuidSlugMigration,
11
+ UuidSlugMigrationOptions,
12
+ UuidString,
13
+ UuidV7String,
14
+ } from "./types";
15
+ import { formatUuid } from "./uuid";
16
+
17
+ /** Read old IDs with the codec's keys and sentinels; never change how new IDs are written. */
18
+ export function createMigration(
19
+ schemas: readonly MaskSchema[],
20
+ sentinels: ReadonlyMap<string, { uuid: UuidV7String }>,
21
+ options: UuidSlugMigrationOptions = {},
22
+ ): UuidSlugMigration {
23
+ const original = options.original === true;
24
+ const plain = options.plain === true;
25
+
26
+ function read(slug: string, format: MigrationFormat | undefined, firstOnly: boolean) {
27
+ if (
28
+ (format !== undefined &&
29
+ format !== "current" &&
30
+ format !== "original" &&
31
+ format !== "plain") ||
32
+ (format === "original" && !original) ||
33
+ (format === "plain" && !plain)
34
+ )
35
+ return new UuidSlugError(
36
+ "invalid_uuid_slug",
37
+ "Enable the requested format when creating the migration reader.",
38
+ );
39
+
40
+ const sentinel = sentinels.get(slug);
41
+ if (sentinel) return [sentinel.uuid];
42
+ const useCurrent = format === undefined || format === "current";
43
+ const useOriginal = original && (format === undefined || format === "original");
44
+ const usePlain = plain && (format === undefined || format === "plain");
45
+ const bytes = new Uint8Array(16);
46
+ // Original readers ignored the four trailing bits. Keep those aliases confined to migration.
47
+ const base32 = slug.length === 26 && usePlain;
48
+ const tail = decodeInto(slug, base32 ? BASE32HEX : BASE64URL, bytes, 0, 16, base32 ? 0 : 4);
49
+ if (tail instanceof Error) return tail;
50
+ // A base64 alias differs only in its final four bits; reuse the validated text instead of
51
+ // encoding all sixteen bytes again. Base32 input still needs the sentinel's base64 spelling.
52
+ const reserved =
53
+ (useOriginal || usePlain) &&
54
+ sentinels.get(
55
+ base32
56
+ ? encode(bytes, BASE64URL)
57
+ : tail === 0
58
+ ? slug
59
+ : slug.slice(0, 21) + BASE64URL.chars[((bytes[15] as number) & 3) << 4],
60
+ );
61
+ if (reserved && firstOnly) return [reserved.uuid];
62
+ const candidates: UuidString[] = reserved ? [reserved.uuid] : [];
63
+ function add(value: Uint8Array) {
64
+ const uuid = formatUuid(value);
65
+ if (uuid instanceof Error) return uuid;
66
+ if (!candidates.includes(uuid)) candidates.push(uuid);
67
+ return undefined;
68
+ }
69
+ if (useCurrent && !base32) {
70
+ const matches = decodeMaskedCandidates(bytes, tail, schemas, firstOnly, candidates);
71
+ if (matches instanceof Error) return matches;
72
+ if (firstOnly && candidates.length) return candidates;
73
+ }
74
+ // Legacy aliases reserve the raw identity, but their check bits can also encode a current ID.
75
+ if (reserved) return candidates;
76
+ if (useOriginal && slug.length === 22) {
77
+ const match = decodeOriginalMask(bytes);
78
+ if (match instanceof Error) return match;
79
+ if (match) {
80
+ const failed = add(match);
81
+ if (failed) return failed;
82
+ if (firstOnly) return candidates;
83
+ }
84
+ }
85
+ if (usePlain) {
86
+ const failed = add(bytes);
87
+ if (failed) return failed;
88
+ }
89
+ return candidates;
90
+ }
91
+
92
+ return {
93
+ decode(slug, format) {
94
+ const result = read(slug, format, true);
95
+ return result instanceof Error
96
+ ? result
97
+ : (result[0] ??
98
+ new UuidSlugError("invalid_uuid_slug", "Slug does not match an enabled format."));
99
+ },
100
+ candidates(slug, format) {
101
+ return read(slug, format, false);
102
+ },
103
+ };
104
+ }
@@ -1,33 +1,58 @@
1
- import { UuidRuntimeError } from "../errors";
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
2
3
  import { runtime as webRuntime } from "./web";
3
4
  import type { Runtime } from "./types";
5
+ import type { UuidV7String, UuidV7Slug } from "../types";
4
6
 
5
- type BunUuid = {
6
- randomUUIDv7(format?: "base64url" | "buffer" | "hex"): string | Uint8Array;
7
- };
8
-
9
- function bunObject(): BunUuid {
10
- const candidate = globalThis as typeof globalThis & { Bun?: BunUuid };
11
- if (!candidate.Bun?.randomUUIDv7) throw new UuidRuntimeError("Bun.randomUUIDv7 is unavailable.");
12
- return candidate.Bun;
7
+ /**
8
+ * `Bun.randomUUIDv7(encoding, timestamp)` honours the timestamp for every encoding, which is why
9
+ * this runtime can supply `uuidV7At` and Node cannot.
10
+ */
11
+ interface BunUuid {
12
+ (format: "hex", timestamp?: number): UuidV7String;
13
+ (format: "base64url", timestamp?: number): UuidV7Slug;
14
+ (format: "buffer", timestamp?: number): Uint8Array;
13
15
  }
14
16
 
15
- const bunRuntime: Runtime = {
16
- fillRandom: webRuntime.fillRandom,
17
- uuidV7() {
18
- return bunObject().randomUUIDv7("hex") as string;
19
- },
20
- uuidV7Bytes(out?: Uint8Array, offset = 0) {
21
- const bytes = bunObject().randomUUIDv7("buffer") as Uint8Array;
22
- if (!out) return bytes;
23
- out.set(bytes, offset);
24
- return out;
25
- },
26
- uuidV7Slug() {
27
- return bunObject().randomUUIDv7("base64url") as string;
28
- },
29
- };
17
+ /**
18
+ * Probed once at module load, not per call. This module is only ever selected by the `bun`
19
+ * export condition, so the global is there; what can differ is the version, and a Bun old
20
+ * enough to lack `randomUUIDv7` should degrade to the portable generator rather than throw
21
+ * from a method that claims to exist. `Runtime.uuidV7` and friends are optional so that
22
+ * absence is representable — a method that exists but throws makes the caller catch and fall
23
+ * back on every single call instead.
24
+ */
25
+ const bun = (globalThis as { Bun?: { randomUUIDv7?: BunUuid } }).Bun;
26
+ const nativeUuidV7 = bun?.randomUUIDv7?.bind(bun);
27
+
28
+ const bunRuntime: Runtime = { fillRandom: webRuntime.fillRandom };
30
29
 
31
30
  if (webRuntime.uuidV4) bunRuntime.uuidV4 = webRuntime.uuidV4;
32
31
 
32
+ /** Shared by the timestamped and untimestamped byte paths; see the copy note inside. */
33
+ const toOwnBytes = (bytes: Uint8Array, out?: Uint8Array, offset = 0) => {
34
+ // Bun hands back a node `Buffer`, which IS a Uint8Array and so satisfies the declared return
35
+ // type while behaving differently in ways nothing catches: `Buffer.toString("hex")` yields hex,
36
+ // `Uint8Array.toString("hex")` ignores the argument and yields "1,159,242,…", and
37
+ // `JSON.stringify` emits `{"type":"Buffer","data":[…]}` against `{"0":1,…}`. Code written and
38
+ // tested on Bun would silently produce different bytes on Node. Copying 16 bytes costs less
39
+ // than the generation it follows and makes the return type mean one thing everywhere; a view
40
+ // would share Bun's ArrayBuffer and tie this to its allocator.
41
+ if (!out) return new Uint8Array(bytes);
42
+ out.set(bytes, offset);
43
+ return out;
44
+ };
45
+
46
+ if (nativeUuidV7) {
47
+ bunRuntime.uuidV7 = () => nativeUuidV7("hex");
48
+ bunRuntime.uuidV7Slug = () => nativeUuidV7("base64url");
49
+ bunRuntime.uuidV7At = (timestamp: number) => nativeUuidV7("hex", timestamp);
50
+ bunRuntime.uuidV7BytesAt = (timestamp: number, out?: Uint8Array, offset = 0) =>
51
+ toOwnBytes(nativeUuidV7("buffer", timestamp), out, offset);
52
+ bunRuntime.uuidV7Bytes = (out?: Uint8Array, offset = 0) => {
53
+ const bytes = nativeUuidV7("buffer");
54
+ return toOwnBytes(bytes, out, offset);
55
+ };
56
+ }
57
+
33
58
  export const runtime = bunRuntime;
@@ -1,23 +1,41 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import crypto from "node:crypto";
2
- import { UuidRuntimeError } from "../errors";
4
+ import { pooledFill } from "./pool";
3
5
  import type { Runtime } from "./types";
4
6
 
5
- type NodeCryptoWithV7 = {
6
- randomUUIDv7?: () => string;
7
- };
8
-
9
- const cryptoWithV7 = crypto as typeof crypto & NodeCryptoWithV7;
7
+ /**
8
+ * Node grew `crypto.randomUUIDv7` in 26.6.0, so on every earlier release this is `undefined`
9
+ * and the capability is simply absent. Probed once here rather than inside the method:
10
+ * `Runtime.uuidV7` is optional precisely so a consumer can branch on its presence, and a
11
+ * method that exists but always throws defeats that — the caller reaches for it, catches, and
12
+ * falls back on EVERY call. Measured 2026-08-11 on Node 24.15.0, that throw cost 64% of v7
13
+ * throughput (400k against 1.11M ops/s).
14
+ */
15
+ // Cast to a NARROW shape, never `typeof crypto & {...}`. `@types/node` is pinned ahead of the
16
+ // runtime in `.tool-versions` and declares `randomUUIDv7` unconditionally, so intersecting keeps it
17
+ // non-optional and the guard below reads as always-true to the compiler — the type would license a
18
+ // refactor that drops the check and breaks every Node under 26.6, where the value is `undefined`.
19
+ // A narrow cast is the only spelling that makes the optionality the code relies on visible.
20
+ const nativeUuidV7: (() => string) | undefined = (crypto as { randomUUIDv7?: () => string })
21
+ .randomUUIDv7;
10
22
 
11
- export const runtime: Runtime = {
12
- fillRandom(bytes) {
13
- bytes.set(crypto.randomBytes(bytes.length));
14
- },
23
+ const nodeRuntime: Runtime = {
24
+ /**
25
+ * `randomFillSync` writes into the buffer it is given. `randomBytes` would allocate a fresh
26
+ * `Buffer` per call and copy out of it, leaving a second, unzeroed copy of the random
27
+ * material on the heap for the collector to get to whenever it does. Measured 14% faster
28
+ * as well, but the copy is the reason. Pooled because the per-call cost dominates at 16
29
+ * bytes; see `pool.ts`.
30
+ */
31
+ fillRandom: pooledFill((into) => {
32
+ crypto.randomFillSync(into);
33
+ }),
15
34
  uuidV4() {
16
35
  return crypto.randomUUID();
17
36
  },
18
- uuidV7() {
19
- if (!cryptoWithV7.randomUUIDv7)
20
- throw new UuidRuntimeError("Node crypto.randomUUIDv7 is unavailable.");
21
- return cryptoWithV7.randomUUIDv7();
22
- },
23
37
  };
38
+
39
+ if (nativeUuidV7) nodeRuntime.uuidV7 = () => nativeUuidV7.call(crypto);
40
+
41
+ export const runtime = nodeRuntime;
@@ -0,0 +1,62 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /**
4
+ * Draws cryptographic randomness a page at a time instead of per id.
5
+ *
6
+ * The underlying primitives cost far more per call than per byte, and a v7 id needs only 16
7
+ * bytes, so per-id draws spend nearly all of their time on call overhead. Measured 2026-08-11
8
+ * filling 16 bytes: 1.94M/s (Node 24) and 4.85M/s (Bun) drawing directly, against 38.9M/s and
9
+ * 77.9M/s from an 8 KiB pool — 20x and 16x. Node's own `randomUUID` batches for the same reason,
10
+ * which is why `crypto.randomUUID` measures 8.9M/s against 1.5M/s with its cache disabled.
11
+ *
12
+ * 8 KiB is the knee: 64 KiB gains nothing further on Node and measured slightly worse on Bun,
13
+ * while holding eight times as much unissued material in memory.
14
+ *
15
+ * The source is unchanged — this batches the same CSPRNG, it does not replace or stretch it.
16
+ */
17
+ const POOL_BYTES = 8192;
18
+
19
+ /**
20
+ * Wraps a direct random-fill primitive in a pool.
21
+ *
22
+ * Consumed bytes are zeroed as they are handed out. Batching is what creates the need: without
23
+ * a pool, material for an id is gone once used, whereas a live 8 KiB buffer would otherwise
24
+ * retain the random half of up to 512 already-issued ids, so a heap dump would expose ids the
25
+ * process had already handed out. Zeroing restores the property batching would remove; the cost
26
+ * is one write per byte already being copied.
27
+ *
28
+ * Each module instance owns its pool, so worker threads never share one. This is safe under
29
+ * Node's process model because a new process gets a fresh heap; it would NOT be safe under a
30
+ * POSIX `fork` that copies the heap, where parent and child would issue identical bytes.
31
+ */
32
+ export function pooledFill(
33
+ fill: (into: Uint8Array<ArrayBuffer>) => void,
34
+ ): (bytes: Uint8Array<ArrayBuffer>) => void {
35
+ const pool = new Uint8Array(POOL_BYTES);
36
+ // STARTS EMPTY, and must. Pre-filling here would move the first call's syscall off the hot path,
37
+ // which looks like a free win and is the one change that breaks heap-snapshot safety: a snapshot
38
+ // taken at import time (V8 or JavaScriptCore startup snapshots, and the serverless platforms
39
+ // built on them) would capture drawn randomness, and every process restored from it would issue
40
+ // the SAME identifiers. Nothing else would notice — the bytes stay perfectly random within any
41
+ // one process, so every other case in this suite passes. `test/entropy.test.ts` gates it by
42
+ // importing the package under the instrument and requiring that no source was touched.
43
+ let offset = POOL_BYTES;
44
+ return (bytes) => {
45
+ const { length } = bytes;
46
+ // A request larger than the pool would refill for a single use; serve it directly instead.
47
+ if (length > POOL_BYTES) {
48
+ fill(bytes);
49
+ return;
50
+ }
51
+ if (offset + length > POOL_BYTES) {
52
+ fill(pool);
53
+ offset = 0;
54
+ }
55
+ // Copy and erase in one pass; `subarray` plus `set` would allocate a view per call.
56
+ for (let i = 0; i < length; i += 1) {
57
+ bytes[i] = pool[offset + i] as number;
58
+ pool[offset + i] = 0;
59
+ }
60
+ offset += length;
61
+ };
62
+ }
@@ -1,12 +1,49 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { UuidV4String, UuidV7Slug, UuidV7String } from "../types";
4
+
1
5
  export interface Runtime {
2
6
  /**
3
7
  * The buffer is pinned to a plain `ArrayBuffer` because Web Crypto's `getRandomValues`
4
8
  * rejects a `SharedArrayBuffer` view at runtime, and the unparameterised `Uint8Array`
5
9
  * admits one. Narrowing here makes that refusal unrepresentable instead of a throw.
6
10
  */
7
- fillRandom(bytes: Uint8Array<ArrayBuffer>): void;
8
- uuidV4?(): string;
9
- uuidV7?(): string;
10
- uuidV7Bytes?(out?: Uint8Array, offset?: number): Uint8Array;
11
- uuidV7Slug?(): string;
11
+ fillRandom(this: void, bytes: Uint8Array<ArrayBuffer>): void;
12
+ /**
13
+ * `this: void` throughout, because these are read off the adapter and stored (a generator keeps
14
+ * `runtime.fillRandom`; the codec keeps `runtime.uuidV7Slug`). An implementation that reached
15
+ * for `this` would work when called through the object and break once detached, which the
16
+ * annotation turns into a compile error at the adapter instead.
17
+ */
18
+ /**
19
+ * BRANDED rather than `string`, which is load-bearing. These values are returned straight out of
20
+ * the codec's own branded signatures, and `Brand`'s marker property is optional, so a bare
21
+ * `string` satisfies every one of them: typed loosely, the native fast paths widened silently
22
+ * while the portable fallbacks beside them needed a visible cast, and only the fallbacks were
23
+ * ever checked. Measured 2026-08-12 — `uuidV7Slug` returned `string | UuidSlug`, which collapses
24
+ * to `string`, so `codec.uuidV7Slug()` promised a `UuidV7Slug` the compiler never examined.
25
+ *
26
+ * No adapter asserts the brand, and none has to — that optional marker means the platform's
27
+ * plain `string` already satisfies it, which is exactly why the loose typing was invisible. The
28
+ * work is done by the DECLARATION here: it makes every CALLER of the hook see the branded type,
29
+ * so a hook returning the wrong shape is a compile error at the call site rather than a silent
30
+ * widening. Nothing in the type system can catch the shape itself, where `nativeUuidV7("hex")`
31
+ * and `nativeUuidV7("base64url")` sit one literal apart and produce completely different
32
+ * strings — so both runners pin the actual shapes by execution instead.
33
+ */
34
+ uuidV4?(this: void): UuidV4String;
35
+ uuidV7?(this: void): UuidV7String;
36
+ uuidV7Bytes?(this: void, out?: Uint8Array, offset?: number): Uint8Array;
37
+ uuidV7Slug?(this: void): UuidV7Slug;
38
+ /**
39
+ * Generate at a caller-supplied millisecond. SEPARATE from `uuidV7` on purpose, because
40
+ * accepting a timestamp is a capability a native generator has independently of generating at
41
+ * all, and getting that wrong is silent: Node's `crypto.randomUUIDv7` takes an options object
42
+ * and IGNORES an unknown key, so passing a timestamp through it returns the current time with
43
+ * no error anywhere. Defined only where the platform provably honours the value — measured
44
+ * 2026-08-11, `Bun.randomUUIDv7("hex", 1577836800000)` yields the 2020 prefix `016f5e66e800`.
45
+ * Left undefined otherwise, which routes the call to the portable generator.
46
+ */
47
+ uuidV7At?(this: void, timestamp: number): UuidV7String;
48
+ uuidV7BytesAt?(this: void, timestamp: number, out?: Uint8Array, offset?: number): Uint8Array;
12
49
  }
@@ -1,6 +1,13 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import { UuidRuntimeError } from "../errors";
4
+ import { pooledFill } from "./pool";
2
5
  import type { Runtime } from "./types";
3
6
 
7
+ /**
8
+ * Resolve Web Crypto per draw so instrumentation installed after import can observe the source.
9
+ * Binding it at module load would bypass `test/instrument.ts` and hide those calls from the gate.
10
+ */
4
11
  function cryptoObject(): Crypto {
5
12
  const value = globalThis.crypto;
6
13
  if (!value?.getRandomValues)
@@ -8,13 +15,34 @@ function cryptoObject(): Crypto {
8
15
  return value;
9
16
  }
10
17
 
11
- export const runtime: Runtime = {
12
- fillRandom(bytes) {
13
- cryptoObject().getRandomValues(bytes);
14
- },
15
- uuidV4() {
16
- const crypto = cryptoObject();
17
- if (!crypto.randomUUID) throw new UuidRuntimeError("Web Crypto randomUUID is unavailable.");
18
- return crypto.randomUUID();
19
- },
18
+ const runtimeCapabilities: Runtime = {
19
+ /**
20
+ * Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per
21
+ * byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.
22
+ */
23
+ fillRandom: pooledFill((into) => {
24
+ cryptoObject().getRandomValues(into);
25
+ }),
20
26
  };
27
+
28
+ /**
29
+ * `randomUUID` is probed ONCE here and the method left undefined when it is absent — the rule
30
+ * `runtime/node.ts` already follows and the reason `Runtime`'s methods are optional.
31
+ *
32
+ * It is not the same capability as `getRandomValues`, and a browser can have one without the
33
+ * other: `crypto.randomUUID` is restricted to secure contexts, `getRandomValues` is not. Defined
34
+ * unconditionally with a throw inside, `uuidV4()` was the only one of four entry points that
35
+ * failed on such a page — `uuidV4Slug`, `uuidV4Bytes` and `uuidV7` all answered, because they
36
+ * reach the byte generator rather than this method. Leaving it undefined routes `uuidV4` to that
37
+ * same generator, so the four agree.
38
+ */
39
+ /*
40
+ * Probed through `Partial<Crypto>` because the DOM lib declares `randomUUID` as always present,
41
+ * so the plain condition is "always true" to the compiler (TS2774) while being false on any
42
+ * insecure page. The cast states the divergence rather than suppressing it: the types describe a
43
+ * secure context, the check describes every context.
44
+ */
45
+ if ((globalThis.crypto as Partial<Crypto> | undefined)?.randomUUID)
46
+ runtimeCapabilities.uuidV4 = () => cryptoObject().randomUUID();
47
+
48
+ export const runtime: Runtime = runtimeCapabilities;