@anizoptera/uuid-slug 0.3.0 → 0.5.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 (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +373 -324
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +15 -8
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
@@ -1,58 +1,39 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { runtime as webRuntime } from "./web";
4
- import type { Runtime } from "./types";
5
- import type { UuidV7String, UuidV7Slug } from "../types";
3
+ import { Buffer } from "node:buffer";
4
+ import { BASE64URL_NAME } from "../base64url-name.ts";
5
+ import { bufferLatin1Scratch, runtime as portableRuntime } from "./portable.ts";
6
+ import type { Runtime } from "./types.ts";
6
7
 
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;
15
- }
16
-
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 };
29
-
30
- if (webRuntime.uuidV4) bunRuntime.uuidV4 = webRuntime.uuidV4;
8
+ export { encodeUtf8 } from "./portable.ts";
31
9
 
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;
10
+ const bunRuntime: Runtime = {
11
+ fillRandom: portableRuntime.fillRandom,
12
+ latin1Scratch: bufferLatin1Scratch(Buffer),
44
13
  };
45
14
 
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
- };
15
+ // Direct Node-compatible generation avoids Web Crypto's receiver binding on Bun. Probe once;
16
+ // absence keeps the existing Web Crypto path. Compare complete calls and module retention when
17
+ // Bun's native methods change; a faster kernel alone does not justify another static import.
18
+ const nativeUuidV4 = (
19
+ process as {
20
+ getBuiltinModule?: (name: string) => { randomUUID?: () => string } | undefined;
21
+ }
22
+ ).getBuiltinModule?.("node:crypto")?.randomUUID;
23
+ if (typeof nativeUuidV4 === "function") bunRuntime.uuidV4 = nativeUuidV4;
24
+ else if (globalThis.crypto.randomUUID)
25
+ bunRuntime.uuidV4 = globalThis.crypto.randomUUID.bind(globalThis.crypto);
26
+
27
+ // Native UUIDv7 can advance logical time during counter overflow; defaults do not forbid that.
28
+ // Select it only when complete-call gains preserve configured-call speed and resource efficiency.
29
+ // Explicit generators keep their clock controls; bench/decisions.md owns drift and cost evidence.
30
+ const nativeUuidV7 = (globalThis as { Bun?: { randomUUIDv7?: (encoding?: "base64url") => string } })
31
+ .Bun?.randomUUIDv7;
32
+ if (typeof nativeUuidV7 === "function") {
33
+ bunRuntime.uuidV7 = nativeUuidV7;
34
+ // Native slug output avoids portable byte generation and a second string construction.
35
+ // Other alphabets and configured clocks keep their existing implementation.
36
+ bunRuntime.uuidV7Slug = () => nativeUuidV7(BASE64URL_NAME);
56
37
  }
57
38
 
58
39
  export const runtime = bunRuntime;
@@ -1,41 +1,60 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
3
  import crypto from "node:crypto";
4
- import { pooledFill } from "./pool";
5
- import type { Runtime } from "./types";
4
+ import { Buffer } from "node:buffer";
5
+ import { pooledFill } from "./pool.ts";
6
+ import type { Runtime } from "./types.ts";
7
+
8
+ const JITLESS_FLAG = "--jitless";
9
+ const JIT_ENABLED_FLAG = "--no-jitless";
10
+ let jitless: boolean | undefined;
11
+ // NODE_OPTIONS is applied before command-line flags; the final explicit setting wins. Keep this
12
+ // startup-only so bounds and generation share the selection without probing each identifier.
13
+ // Quoted option words remain whole: a filename containing a flag is not a flag.
14
+ for (let index = process.execArgv.length - 1; index >= 0; index -= 1) {
15
+ const flag = process.execArgv[index];
16
+ if (flag === JITLESS_FLAG || flag === JIT_ENABLED_FLAG) {
17
+ jitless = flag === JITLESS_FLAG;
18
+ break;
19
+ }
20
+ }
21
+
22
+ // CLI overrides settle the answer without parsing the environment. Ordinary imports allocate no
23
+ // token array; quoted environment words need tokenization only when a mode flag could be present.
24
+ const nodeOptions = jitless === undefined ? process.env.NODE_OPTIONS : undefined;
25
+ if (nodeOptions?.includes("jitless")) {
26
+ const words = nodeOptions.match(/(?:[^\s"\\]|\\.|"(?:[^"\\]|\\.)*")+/g);
27
+ for (let index = (words?.length ?? 0) - 1; index >= 0; index -= 1) {
28
+ const flag = words?.[index]?.replace(/"|\\(?=.)/g, "");
29
+ if (flag === JITLESS_FLAG || flag === JIT_ENABLED_FLAG) {
30
+ jitless = flag === JITLESS_FLAG;
31
+ break;
32
+ }
33
+ }
34
+ }
6
35
 
7
36
  /**
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).
37
+ * Node's native UTF-8 encoder materially reduces string-seed construction; the portable adapter
38
+ * remains the compatibility boundary. bench/decisions.md owns the measured runtime scope.
14
39
  */
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;
40
+ export const encodeUtf8 = /* @__NO_SIDE_EFFECTS__ */ (text: string): Uint8Array =>
41
+ Buffer.from(text, "utf8");
22
42
 
23
43
  const nodeRuntime: Runtime = {
24
44
  /**
25
45
  * `randomFillSync` writes into the buffer it is given. `randomBytes` would allocate a fresh
26
46
  * `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`.
47
+ * material on the heap for the collector to get to whenever it does. Pooled because the
48
+ * per-call cost dominates at 16 bytes; see `pool.ts`.
30
49
  */
31
- fillRandom: pooledFill((into) => {
50
+ fillRandom: /*#__PURE__*/ pooledFill((into) => {
32
51
  crypto.randomFillSync(into);
52
+ return undefined;
33
53
  }),
34
- uuidV4() {
35
- return crypto.randomUUID();
36
- },
54
+ // Pooled formatting wins with the JIT; native text wins without it. Missing native capability
55
+ // stays undefined so the generator uses its tested portable fallback. Remeasure both modes
56
+ // after Node changes; bench/decisions.md owns the compared calls and resource limits.
57
+ ...(jitless ? { jitless: true, uuidV4: crypto.randomUUID } : {}),
37
58
  };
38
59
 
39
- if (nativeUuidV7) nodeRuntime.uuidV7 = () => nativeUuidV7.call(crypto);
40
-
41
60
  export const runtime = nodeRuntime;
@@ -1,20 +1,17 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
+ import { randomFailure } from "../errors.ts";
4
+ import type { UuidSlugError } from "../errors.ts";
5
+
3
6
  /**
4
7
  * Draws cryptographic randomness a page at a time instead of per id.
5
8
  *
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.
9
+ * Randomness calls cost more than copying the 16 bytes an identifier needs. The bounded pool
10
+ * amortizes that call without retaining more unissued material than needed.
14
11
  *
15
12
  * The source is unchanged — this batches the same CSPRNG, it does not replace or stretch it.
16
13
  */
17
- const POOL_BYTES = 8192;
14
+ export const POOL_BYTES = 8192;
18
15
 
19
16
  /**
20
17
  * Wraps a direct random-fill primitive in a pool.
@@ -29,34 +26,65 @@ const POOL_BYTES = 8192;
29
26
  * Node's process model because a new process gets a fresh heap; it would NOT be safe under a
30
27
  * POSIX `fork` that copies the heap, where parent and child would issue identical bytes.
31
28
  */
29
+ /*#__NO_SIDE_EFFECTS__*/
32
30
  export function pooledFill(
33
- fill: (into: Uint8Array<ArrayBuffer>) => void,
34
- ): (bytes: Uint8Array<ArrayBuffer>) => void {
35
- const pool = new Uint8Array(POOL_BYTES);
31
+ fill: (into: Uint8Array<ArrayBuffer>) => unknown,
32
+ ): (bytes: Uint8Array<ArrayBuffer>) => undefined | UuidSlugError {
33
+ let pool: Uint8Array<ArrayBuffer> | undefined;
36
34
  // STARTS EMPTY, and must. Pre-filling here would move the first call's syscall off the hot path,
37
35
  // which looks like a free win and is the one change that breaks heap-snapshot safety: a snapshot
38
36
  // taken at import time (V8 or JavaScriptCore startup snapshots, and the serverless platforms
39
37
  // built on them) would capture drawn randomness, and every process restored from it would issue
40
38
  // 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
39
+ // one process, so every other case in this suite passes. `__test__/entropy.test.ts` gates it by
42
40
  // importing the package under the instrument and requiring that no source was touched.
43
41
  let offset = POOL_BYTES;
44
42
  return (bytes) => {
45
43
  const { length } = bytes;
46
44
  // A request larger than the pool would refill for a single use; serve it directly instead.
47
45
  if (length > POOL_BYTES) {
48
- fill(bytes);
49
- return;
46
+ return randomFailure(fill(bytes));
50
47
  }
51
- if (offset + length > POOL_BYTES) {
52
- fill(pool);
48
+ if (pool === undefined || offset + length > POOL_BYTES) {
49
+ pool ??= new Uint8Array(POOL_BYTES);
50
+ const failed = randomFailure(fill(pool));
51
+ if (failed) return failed;
53
52
  offset = 0;
54
53
  }
55
54
  // 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
- }
55
+ // Continuation draws need four bytes. Fixed stores avoid their loop without another view
56
+ // or retained buffer. Owned draws use four-byte blocks, reusing each source offset rather
57
+ // than repeating its arithmetic. Blocks keep the body smaller than fully expanded stores;
58
+ // other lengths keep the indexed loop. Complete-call comparisons in bench/decisions.md
59
+ // decide this shape, not copy-only timing. Remeasure if draw widths
60
+ // or the runtime's typed-array handling change.
61
+ if (length === 4) {
62
+ bytes[0] = pool[offset + 0] as number;
63
+ pool[offset + 0] = 0;
64
+ bytes[1] = pool[offset + 1] as number;
65
+ pool[offset + 1] = 0;
66
+ bytes[2] = pool[offset + 2] as number;
67
+ pool[offset + 2] = 0;
68
+ bytes[3] = pool[offset + 3] as number;
69
+ pool[offset + 3] = 0;
70
+ } else if (length === 16) {
71
+ for (let i = 0; i < 16; i += 4) {
72
+ const sourceOffset = offset + i;
73
+ bytes[i] = pool[sourceOffset] as number;
74
+ pool[sourceOffset] = 0;
75
+ bytes[i + 1] = pool[sourceOffset + 1] as number;
76
+ pool[sourceOffset + 1] = 0;
77
+ bytes[i + 2] = pool[sourceOffset + 2] as number;
78
+ pool[sourceOffset + 2] = 0;
79
+ bytes[i + 3] = pool[sourceOffset + 3] as number;
80
+ pool[sourceOffset + 3] = 0;
81
+ }
82
+ } else
83
+ for (let i = 0; i < length; i += 1) {
84
+ bytes[i] = pool[offset + i] as number;
85
+ pool[offset + i] = 0;
86
+ }
60
87
  offset += length;
88
+ return undefined;
61
89
  };
62
90
  }
@@ -0,0 +1,68 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { RNG_UNAVAILABLE, UuidSlugError } from "../errors.ts";
4
+ import { pooledFill } from "./pool.ts";
5
+ import type { Latin1Scratch, Runtime } from "./types.ts";
6
+
7
+ let utf8Encoder: TextEncoder | undefined;
8
+ const nativeToHex = (Uint8Array.prototype as { toHex?: () => string }).toHex;
9
+
10
+ /** Create the shared encoder only when mask construction needs it; generation imports this adapter too. */
11
+ export const encodeUtf8 = (text: string): Uint8Array =>
12
+ (utf8Encoder ??= new TextEncoder()).encode(text);
13
+
14
+ const runtimeCapabilities: Runtime = {
15
+ /**
16
+ * Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per
17
+ * byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.
18
+ */
19
+ fillRandom: /*#__PURE__*/ pooledFill((into) => {
20
+ // Resolve per draw so instrumentation installed after import observes the source.
21
+ const crypto = globalThis.crypto;
22
+ if (!crypto?.getRandomValues)
23
+ return new UuidSlugError(RNG_UNAVAILABLE, "Web Crypto getRandomValues is unavailable.");
24
+ crypto.getRandomValues(into);
25
+ return undefined;
26
+ }),
27
+ };
28
+
29
+ // WebKit's fixed formatter slowed unrelated successful calls in mixed comparisons. Native hex
30
+ // did not reproduce a repeated loss while other engines retain their fixed writers. This identity
31
+ // selects cost only; absent hex support still uses the portable writer. Remeasure after browser
32
+ // changes (bench/decisions.md); the shared ASCII decoder also slowed slug output.
33
+ if (
34
+ typeof navigator !== "undefined" &&
35
+ navigator.vendor === "Apple Computer, Inc." &&
36
+ typeof nativeToHex === "function"
37
+ )
38
+ runtimeCapabilities.uuidHex = (bytes) => nativeToHex.call(bytes);
39
+
40
+ type Latin1Buffer = Uint8Array & {
41
+ toString(encoding: "latin1", start: number, end: number): string;
42
+ };
43
+ type HostBuffer = { alloc(size: number): Latin1Buffer } | undefined;
44
+
45
+ /** Build scratch text through a Node-compatible `Buffer` constructor. */
46
+ export function bufferLatin1Scratch(hostBuffer: NonNullable<HostBuffer>) {
47
+ return (length: number): Latin1Scratch => {
48
+ const bytes = hostBuffer.alloc(length);
49
+ return { bytes, text: () => bytes.toString("latin1", 0, length) };
50
+ };
51
+ }
52
+
53
+ // Deno's Web Crypto UUID method is faster than the portable formatter; Chromium's is slower.
54
+ // Runtime identity decides only this measured performance split—the entropy and UUID contracts
55
+ // are the same, and both paths remain covered by the shared runtime corpus.
56
+ if (typeof (globalThis as { Deno?: unknown }).Deno !== "undefined") {
57
+ if (globalThis.crypto?.randomUUID)
58
+ runtimeCapabilities.uuidV4 = globalThis.crypto.randomUUID.bind(globalThis.crypto);
59
+ }
60
+
61
+ /**
62
+ * Browser `randomUUID` is intentionally not selected. Chromium measured it about five times
63
+ * slower than this package's pooled byte generator and formatter, while insecure contexts can
64
+ * expose `getRandomValues` without `randomUUID`. Leaving the shortcut absent gives every browser
65
+ * context the faster common path. Reconsider when another browser engine or Chromium release
66
+ * overturns the complete public-route measurement.
67
+ */
68
+ export const runtime: Runtime = runtimeCapabilities;
@@ -1,49 +1,37 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import type { UuidV4String, UuidV7Slug, UuidV7String } from "../types";
3
+ import type { UuidSlugError } from "../errors.ts";
4
4
 
5
5
  export interface Runtime {
6
+ /** Node has disabled executable JavaScript code generation for this process. */
7
+ readonly jitless?: true;
6
8
  /**
7
9
  * The buffer is pinned to a plain `ArrayBuffer` because Web Crypto's `getRandomValues`
8
10
  * rejects a `SharedArrayBuffer` view at runtime, and the unparameterised `Uint8Array`
9
11
  * admits one. Narrowing here makes that refusal unrepresentable instead of a throw.
10
12
  */
11
- fillRandom(this: void, bytes: Uint8Array<ArrayBuffer>): void;
13
+ fillRandom(this: void, bytes: Uint8Array<ArrayBuffer>): undefined | UuidSlugError;
12
14
  /**
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.
15
+ * Hooks are detached from the adapter, so `this: void` rejects implementations that depend on
16
+ * method binding.
17
17
  */
18
+ /** Native UUIDv4 text; default calls trust the proper native generator's result directly. */
19
+ uuidV4?(this: void): string;
20
+ /** Native current-time UUIDv7 text; configured clocks and sequence state stay on generators. */
21
+ uuidV7?(this: void): string;
22
+ /** Native current-time UUIDv7 as one canonical unpadded base64url plain slug. */
23
+ uuidV7Slug?(this: void): string;
24
+ /** Optional native hex conversion for the runtime's selected UUID text writer. */
25
+ uuidHex?(this: void, bytes: Uint8Array): string;
18
26
  /**
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.
27
+ * Create a reusable buffer whose bytes a native call turns into a flat Latin-1 string. Adapters
28
+ * provide it only where that call beats building text from JavaScript strings.
33
29
  */
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;
30
+ latin1Scratch?(this: void, length: number): Latin1Scratch;
31
+ }
32
+
33
+ export interface Latin1Scratch {
34
+ readonly bytes: Uint8Array;
35
+ /** Return every byte of `bytes` as one Latin-1 string. */
36
+ text(this: void): string;
49
37
  }
@@ -0,0 +1,13 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // Only the 26-character plain spelling is case-insensitive. Normalizing a base64url key would
4
+ // merge distinct UUIDs; exact hits and codecs without sentinels require no normalization.
5
+ export function findSentinel<Value>(
6
+ sentinels: ReadonlyMap<string, Value>,
7
+ slug: string,
8
+ ): Value | undefined {
9
+ return (
10
+ sentinels.get(slug) ??
11
+ (slug.length === 26 && sentinels.size !== 0 ? sentinels.get(slug.toLowerCase()) : undefined)
12
+ );
13
+ }
package/src/siphash.ts CHANGED
@@ -6,19 +6,20 @@
6
6
  * without the key its output on a chosen input is not computable, which is exactly what `mix32` — a
7
7
  * fixed, public, unkeyed bijection — could never be, and the reason it replaced it.
8
8
  *
9
- * One primitive serves both callers that need one: the Feistel round function (`feistel.ts`) and the
10
- * key derivation (`schema.ts`). Neither justifies its own.
9
+ * Key derivation (`mask.ts`) calls this function. The Feistel round (`feistel.ts`) writes the same
10
+ * function out for its fixed two-word message because the call cost measurably more per masked slug;
11
+ * the published vectors grade this transcription, and the Feistel and wire-format vectors grade that one.
11
12
  *
12
13
  * Chosen over full SipHash-2-4 because that is defined over 64-bit words, which JavaScript has only
13
14
  * as `BigInt` or as hand-emulated 32-bit pairs — the first far too slow for a hot path, the second a
14
15
  * re-implementation whose errors nothing would catch. HalfSipHash is 32-bit BY SPECIFICATION, so
15
- * this is a transcription, and `test/siphash.test.ts` holds it to all 64 published vectors. That
16
+ * this is a transcription, and `__test__/siphash.test.ts` holds it to all 64 published vectors. That
16
17
  * external check is the whole reason a standard primitive beat anything tuned here: nothing in this
17
18
  * repository can grade a mixing function (see `feistel.ts` — every instrument here passes a
18
19
  * two-round network), so agreement with a specification somebody else wrote is the only evidence
19
20
  * available that can actually fail.
20
21
  *
21
- * Its key is 64 bits. `schema.ts` runs two independently keyed instances and XORs them, the standard
22
+ * Its key is 64 bits. `mask.ts` runs two independently keyed instances and XORs them, the standard
22
23
  * cascade for widening a PRF's key; see there.
23
24
  */
24
25