@anizoptera/uuid-slug 0.2.0 → 0.4.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 (163) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1175 -30
  3. package/dist/alphabet.d.ts +9 -0
  4. package/dist/alphabet.d.ts.map +1 -0
  5. package/dist/alphabet.js +166 -0
  6. package/dist/alphabet.js.map +1 -0
  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 +57 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +162 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/feistel.js +39 -0
  16. package/dist/feistel.js.map +1 -0
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +23 -168
  20. package/dist/index.js +22 -649
  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 +164 -0
  30. package/dist/mask.js.map +1 -0
  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 +129 -0
  40. package/dist/migration.js.map +1 -0
  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 +30 -0
  48. package/dist/runtime/pool.js.map +1 -0
  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 +29 -0
  54. package/dist/siphash.js.map +1 -0
  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 +535 -0
  64. package/dist/types.d.ts.map +1 -0
  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 +65 -0
  74. package/dist/uuid.d.ts.map +1 -0
  75. package/dist/uuid.js +232 -0
  76. package/dist/uuid.js.map +1 -0
  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 +143 -0
  114. package/dist/v7.js.map +1 -0
  115. package/package.json +18 -17
  116. package/src/alphabet.ts +616 -0
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +423 -13
  119. package/src/feistel.ts +141 -0
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +137 -57
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +9 -0
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +377 -90
  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 +257 -0
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +31 -25
  132. package/src/runtime/node.ts +55 -18
  133. package/src/runtime/pool.ts +90 -0
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +30 -5
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +128 -0
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +799 -61
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +527 -108
  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 +433 -84
  156. package/dist/index.d.ts.map +0 -1
  157. package/dist/index.js.map +0 -1
  158. package/dist/node/index.js +0 -647
  159. package/dist/web/index.js +0 -648
  160. package/src/base64url.ts +0 -76
  161. package/src/codec.ts +0 -218
  162. package/src/runtime/web.ts +0 -20
  163. package/src/schema.ts +0 -123
package/src/v7.ts CHANGED
@@ -1,106 +1,455 @@
1
- import { UuidSlugError } from "./errors";
2
- import type { UuidV7Generator, UuidV7String } from "./types";
3
- import { formatUuid } from "./uuid";
4
- import type { Runtime } from "./runtime/types";
5
-
6
- export interface UuidV7GeneratorOptions {
7
- readonly clock?: () => number;
8
- readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => void;
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import {
4
+ checkByteRange,
5
+ checkRange,
6
+ diagnosticValue,
7
+ fillRandomBytes,
8
+ INVALID_TIMESTAMP,
9
+ RNG_UNAVAILABLE,
10
+ isUuidSlugError,
11
+ isUint8Array,
12
+ readClock,
13
+ stringInput,
14
+ UuidSlugError,
15
+ } from "./errors.ts";
16
+ import { readGenerationOptions } from "./generation-options.ts";
17
+ import { readUuidV7Instant } from "./instant.ts";
18
+ import type { NormalizedUuidV7Instant } from "./instant.ts";
19
+ import { UUID_TEXT_LOWERCASE, UUID_V7_ROLLBACK_ERROR } from "./types.ts";
20
+ import type {
21
+ GenerateUuidV7BytesIntoOptions,
22
+ GenerateUuidV7BytesOptions,
23
+ GenerateUuidV7Options,
24
+ UuidOutput,
25
+ UuidTextCase,
26
+ UuidTextCaseArguments,
27
+ UuidV7Bytes,
28
+ UuidV7ClockRollbackPolicy,
29
+ UuidV7Generator,
30
+ UuidV7StringFor,
31
+ } from "./types.ts";
32
+ import { formatUuidBytesUnchecked, resolveUuidTextCase } from "./uuid.ts";
33
+ import { MAX_UUID_V7_UNIX_MS, isValidUuidV7UnixMs } from "./v7-timestamp.ts";
34
+
35
+ /** Internal controls for exercising the portable UUIDv7 state machine. */
36
+ interface PortableUuidV7GeneratorOptions {
37
+ /** Return Unix milliseconds; selected fraction bits consume the fractional part. */
38
+ readonly readUnixMs?: () => number;
39
+ // Package-owned clocks split epoch and elapsed time before addition. Read this bucket only
40
+ // after their paired timestamp succeeds; caller clocks retain their numeric contract.
41
+ readonly readFractionBucket12?: () => number;
42
+ /** Fill every byte. Returned or thrown failures are contained by generation. */
43
+ readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => unknown;
44
+ /** Policy already validated at the public seam. */
45
+ readonly clockRollback?: Extract<UuidV7ClockRollbackPolicy, { readonly toleranceMs: number }>;
46
+ /** Number of leading payload bits assigned to the clock fraction. */
47
+ readonly subMillisecondFractionBits?: number;
48
+ /** Keep explicit instants in this generator's ordering and rollback state. */
49
+ readonly coordinateExplicitInstants?: boolean;
50
+ // Module writers share their private 16-byte storage with text generation. Public construction
51
+ // never supplies this control; caller buffers must continue through the range checks below.
52
+ readonly textScratch?: Uint8Array<ArrayBuffer>;
9
53
  }
10
54
 
11
- function writeTimestamp(bytes: Uint8Array, ms: number) {
12
- let value = Math.trunc(ms);
13
- for (let i = 5; i >= 0; i -= 1) {
14
- bytes[i] = value & 0xff;
55
+ // The slug and value methods are attached by the public seam, which owns the slug encoder and the
56
+ // UUID value graph; keeping them out here lets a generation-only consumer drop both.
57
+ export type PortableUuidV7Generator = Omit<
58
+ UuidV7Generator,
59
+ "generatePlainUuidV7Slug" | "generateUuidV7Value" | "generateUuidV7WithPlainSlug"
60
+ > & {
61
+ /**
62
+ * Draw after the caller has read its options: `instant` is already normalized and `output` is
63
+ * checked again here. Package callers use it to avoid rebuilding and rereading an options object;
64
+ * it must never reach a public object.
65
+ */
66
+ readonly drawUuidV7Bytes: (
67
+ instant: NormalizedUuidV7Instant | undefined,
68
+ output?: Uint8Array,
69
+ outputOffset?: number,
70
+ ) => Uint8Array | UuidSlugError;
71
+ };
72
+
73
+ const UUID_V7_TEXT_OPTIONS = {
74
+ at: true,
75
+ textCase: true,
76
+ } as const satisfies Record<keyof Omit<GenerateUuidV7Options<UuidTextCase>, "generator">, true>;
77
+ const UUID_V7_BYTE_OPTIONS = {
78
+ at: true,
79
+ output: true,
80
+ outputOffset: true,
81
+ } as const satisfies Record<
82
+ keyof Omit<GenerateUuidV7BytesOptions & GenerateUuidV7BytesIntoOptions<Uint8Array>, "generator">,
83
+ true
84
+ >;
85
+ const AT_OPTION = "at";
86
+
87
+ function writeTimestampWords(bytes: Uint8Array, ms: number, offset: number) {
88
+ // Split the fixed 48-bit field once: JavaScript bitwise operators keep the low 32 bits, while
89
+ // division supplies the independent high 16 bits without BigInt or six iterative divisions.
90
+ const high = Math.floor(ms / 0x1_0000_0000);
91
+ bytes[offset] = high >>> 8;
92
+ bytes[offset + 1] = high;
93
+ bytes[offset + 2] = ms >>> 24;
94
+ bytes[offset + 3] = ms >>> 16;
95
+ bytes[offset + 4] = ms >>> 8;
96
+ bytes[offset + 5] = ms;
97
+ }
98
+
99
+ function writeTimestampLoop(bytes: Uint8Array, ms: number, offset: number) {
100
+ let value = ms;
101
+ for (let index = 5; index >= 0; index -= 1) {
102
+ bytes[offset + index] = value & 0xff;
15
103
  value = Math.floor(value / 256);
16
104
  }
17
105
  }
18
106
 
19
- function writeCounter(bytes: Uint8Array, counter: bigint) {
20
- bytes[6] = 0x70 | Number((counter >> 38n) & 0x0fn);
21
- bytes[7] = Number((counter >> 30n) & 0xffn);
22
- bytes[8] = 0x80 | Number((counter >> 24n) & 0x3fn);
23
- bytes[9] = Number((counter >> 16n) & 0xffn);
24
- bytes[10] = Number((counter >> 8n) & 0xffn);
25
- bytes[11] = Number(counter & 0xffn);
107
+ // Measured Bun favors the loop while Node and Chromium favor fixed writes; select once so generation
108
+ // pays no per-call branch. bench/PERFORMANCE.md owns the measurements and replacement condition.
109
+ const writeTimestamp = (globalThis as { Bun?: object }).Bun
110
+ ? writeTimestampLoop
111
+ : writeTimestampWords;
112
+
113
+ /**
114
+ * Writes the 42-bit sequence RFC 9562 §6.2 allows in `rand_a` plus the top of `rand_b`, along
115
+ * with the version and variant bits that bracket it.
116
+ *
117
+ * The sequence is carried as a 10-bit high half and a 32-bit low half rather than one 42-bit
118
+ * BigInt, so every operation here is a 32-bit integer op the JIT emits directly. Measured on the
119
+ * increment-and-write step alone: 9.99M ops/s (Bun) and 11.8M (Node) as a BigInt, against 252M
120
+ * and 149M in this form. The bit layout is unchanged, so the ids are identical either way.
121
+ */
122
+ function writeCounter(bytes: Uint8Array, hi: number, lo: number, offset: number) {
123
+ bytes[offset + 6] = 0x70 | ((hi >>> 6) & 0x0f);
124
+ bytes[offset + 7] = (((hi & 0x3f) << 2) | (lo >>> 30)) & 0xff;
125
+ bytes[offset + 8] = 0x80 | ((lo >>> 24) & 0x3f);
126
+ bytes[offset + 9] = (lo >>> 16) & 0xff;
127
+ bytes[offset + 10] = (lo >>> 8) & 0xff;
128
+ bytes[offset + 11] = lo & 0xff;
26
129
  }
27
130
 
28
- function readCounterSeed(bytes: Uint8Array) {
29
- return (
30
- (BigInt(bytes[0] ?? 0) << 34n) |
31
- (BigInt(bytes[1] ?? 0) << 26n) |
32
- (BigInt(bytes[2] ?? 0) << 18n) |
33
- (BigInt(bytes[3] ?? 0) << 10n) |
34
- (BigInt(bytes[4] ?? 0) << 2n) |
35
- (BigInt(bytes[5] ?? 0) & 0x03n)
131
+ // A successful draw returns the exact private destination; callbacks cannot return that buffer.
132
+ // Identity preserves foreign failures without a protocol scan on successful text calls. The writer,
133
+ // rather than the version-neutral formatter, establishes the UUIDv7 brand.
134
+ const formatUuidV7 = /* @__NO_SIDE_EFFECTS__ */ <Case extends UuidTextCase>(
135
+ result: Uint8Array | UuidSlugError,
136
+ textCase: Case,
137
+ output: Uint8Array,
138
+ ): UuidV7StringFor<Case> | UuidSlugError =>
139
+ result === output
140
+ ? (formatUuidBytesUnchecked(output, 0, textCase) as UuidV7StringFor<Case>)
141
+ : (result as UuidSlugError);
142
+
143
+ const reenteredGeneration = /* @__NO_SIDE_EFFECTS__ */ () =>
144
+ new UuidSlugError(
145
+ RNG_UNAVAILABLE,
146
+ "UUIDv7 generation cannot be reentered from its readUnixMs or entropy callback.",
36
147
  );
37
- }
38
148
 
39
- export function createUuidV7Generator(options: UuidV7GeneratorOptions): UuidV7Generator {
40
- const clock = options.clock ?? Date.now;
41
- const random = new Uint8Array(16);
149
+ /**
150
+ * Seeds the sequence from the same six random bytes and the same bit positions as before, split
151
+ * across the two halves: byte 0 and the top 2 bits of byte 1 form the high half, the rest the
152
+ * low half. Starting each millisecond at a random point rather than zero is what stops the
153
+ * sequence leaking how many ids were issued in the previous millisecond.
154
+ */
155
+ const seedHi = /* @__NO_SIDE_EFFECTS__ */ (bytes: Uint8Array) =>
156
+ (((bytes[0] ?? 0) << 2) | ((bytes[1] ?? 0) >>> 6)) & 0x3ff;
157
+
158
+ const seedLo = /* @__NO_SIDE_EFFECTS__ */ (bytes: Uint8Array) =>
159
+ ((((bytes[1] ?? 0) & 0x3f) << 26) |
160
+ ((bytes[2] ?? 0) << 18) |
161
+ ((bytes[3] ?? 0) << 10) |
162
+ ((bytes[4] ?? 0) << 2) |
163
+ ((bytes[5] ?? 0) & 0x03)) >>>
164
+ 0;
165
+
166
+ /**
167
+ * Create a stateful UUIDv7 generator from package-owned, statically checked dependencies.
168
+ * Clock and entropy failures return `UuidSlugError`; reentrant calls preserve sequence state.
169
+ */
170
+ export function createPortableUuidV7Generator(
171
+ options: PortableUuidV7GeneratorOptions,
172
+ ): PortableUuidV7Generator {
173
+ const readUnixMs = options.readUnixMs ?? Date.now;
174
+ const fill = options.fillRandom;
175
+ const rollback = options.clockRollback;
176
+ const fractionBits = options.subMillisecondFractionBits ?? 0;
177
+ const coordinateExplicitInstants = options.coordinateExplicitInstants ?? true;
178
+ const counterBits = 42 - fractionBits;
179
+ const counterModulus = 2 ** counterBits;
180
+ const payloadLayout = Object.freeze({
181
+ subMillisecondFractionBits: fractionBits,
182
+ counterBits,
183
+ });
184
+ // The sequence seed consumes six bytes and the UUID tail consumes four. Drawing a full UUID
185
+ // block would copy six bytes that version, variant, timestamp, and sequence fields replace.
186
+ const random = new Uint8Array(10);
187
+ // Continuations retain the sequence seed, so expose only the four bytes their UUID tail consumes.
188
+ const randomTail = random.subarray(6);
189
+ /**
190
+ * Below every timestamp the readUnixMs check admits, which is what makes it the uninitialised
191
+ * sentinel rather than a value: `now > lastMs` alone therefore takes the reseed branch on the
192
+ * first call, and no separate "have we started" flag is needed. The coupling is deliberate and
193
+ * is why the readUnixMs is validated before this is compared against — an unvalidated readUnixMs returning
194
+ * a negative millisecond would make `lastMs` stay below it forever, so the monotonic counter
195
+ * would never be used and every call would reseed.
196
+ */
42
197
  let lastMs = -1;
43
- let counter = 0n;
198
+ let clockHighWaterMs = -1;
199
+ let counterHi = 0;
200
+ let counterLo = 0;
201
+ let generating = false;
202
+ const textBytes = options.textScratch ?? new Uint8Array(16);
44
203
 
45
- function reseed(ms: number) {
46
- options.fillRandom(random);
204
+ function reseed(ms: number, fraction: number) {
205
+ const failed = fillRandomBytes(fill, random);
206
+ if (failed) return failed;
207
+ const seededCounter = (seedHi(random) * 0x1_0000_0000 + seedLo(random)) % counterModulus;
208
+ const payloadPrefix = fraction * counterModulus + seededCounter;
47
209
  lastMs = ms;
48
- counter = readCounterSeed(random);
210
+ counterHi = Math.floor(payloadPrefix / 0x1_0000_0000);
211
+ counterLo = payloadPrefix >>> 0;
212
+ return undefined;
49
213
  }
50
214
 
51
- function bytes(out?: Uint8Array, offset = 0): Error | Uint8Array {
52
- const target = out ?? new Uint8Array(16);
53
- if (offset < 0 || offset + 16 > target.length)
54
- return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
55
- const now = Math.trunc(clock());
56
- if (lastMs < 0 || now > lastMs) reseed(now);
57
- else {
58
- counter += 1n;
59
- if (counter > 0x3ffffffffffn) reseed(lastMs + 1);
60
- else options.fillRandom(random);
61
- }
62
- const uuid = target.subarray(offset, offset + 16);
63
- writeTimestamp(uuid, lastMs);
64
- writeCounter(uuid, counter);
65
- target[offset + 12] = random[12] ?? 0;
66
- target[offset + 13] = random[13] ?? 0;
67
- target[offset + 14] = random[14] ?? 0;
68
- target[offset + 15] = random[15] ?? 0;
215
+ function writeBytes(
216
+ target: Uint8Array,
217
+ offset: number,
218
+ ms: number,
219
+ sequenceHi: number,
220
+ sequenceLo: number,
221
+ ) {
222
+ writeTimestamp(target, ms, offset);
223
+ writeCounter(target, sequenceHi, sequenceLo, offset);
224
+ for (let i = 12; i < 16; i += 1) target[offset + i] = randomTail[i - 12] as number;
69
225
  return target;
70
226
  }
71
227
 
72
- return {
73
- uuidV7() {
74
- const result = bytes();
75
- if (result instanceof Error) throw result;
76
- const formatted = formatUuid(result);
77
- if (formatted instanceof Error) throw formatted;
78
- return formatted as UuidV7String;
79
- },
80
- uuidV7Bytes: bytes,
81
- };
82
- }
83
-
84
- export function createRuntimeGenerator(runtime: Runtime): UuidV7Generator {
85
- const fallback = createUuidV7Generator({ fillRandom: runtime.fillRandom });
86
- return {
87
- uuidV7() {
88
- if (!runtime.uuidV7) return fallback.uuidV7();
89
- try {
90
- return runtime.uuidV7() as UuidV7String;
91
- } catch {
92
- return fallback.uuidV7();
228
+ function advanceSequence(now: number, fraction: number): UuidSlugError | undefined {
229
+ const rollbackMs = rollback === undefined ? 0 : clockHighWaterMs - now;
230
+ if (rollback !== undefined && rollbackMs > rollback.toleranceMs) {
231
+ if (rollback.action === UUID_V7_ROLLBACK_ERROR)
232
+ return new UuidSlugError(
233
+ INVALID_TIMESTAMP,
234
+ `Clock moved backward by ${rollbackMs} milliseconds; clockRollback allows ${rollback.toleranceMs}. Increase tolerance or choose reset/preserve if this rollback is acceptable.`,
235
+ );
236
+ const failed = reseed(now, fraction);
237
+ if (failed) return failed;
238
+ clockHighWaterMs = now;
239
+ } else if (
240
+ now > lastMs ||
241
+ (now === lastMs &&
242
+ fraction > Math.floor((counterHi * 0x1_0000_0000 + counterLo) / counterModulus))
243
+ ) {
244
+ const failed = reseed(now, fraction);
245
+ if (failed) return failed;
246
+ } else {
247
+ const nextLo = (counterLo + 1) >>> 0;
248
+ const nextHi = counterHi + (nextLo === 0 ? 1 : 0);
249
+ // Past 42 bits the sequence no longer fits `rand_a` plus the borrowed `rand_b` bits.
250
+ // Borrowing the next millisecond keeps ids ordered and unique rather than wrapping into
251
+ // values this millisecond has already issued.
252
+ if (nextHi > 0x3ff) {
253
+ // At the ceiling there is no next millisecond to borrow: `writeTimestamp` truncates to
254
+ // six bytes, so `lastMs + 1` wraps to 0 and the generator restarts in 1970 — ordering
255
+ // broken permanently, and silently, from that call onward. Unreachable on a real clock
256
+ // until the year 10889; reachable from a supplied instant near the ceiling.
257
+ if (lastMs >= MAX_UUID_V7_UNIX_MS)
258
+ return new UuidSlugError(
259
+ INVALID_TIMESTAMP,
260
+ `UUIDv7 sequence exhausted at Unix millisecond ${MAX_UUID_V7_UNIX_MS}; another UUID would exceed the 48-bit timestamp.`,
261
+ );
262
+ const failed = reseed(lastMs + 1, 0);
263
+ if (failed) return failed;
264
+ } else {
265
+ const failed = fillRandomBytes(fill, randomTail);
266
+ if (failed) return failed;
267
+ // Commit only after entropy succeeds; a failed draw must not consume sequence state.
268
+ counterLo = nextLo;
269
+ counterHi = nextHi;
93
270
  }
94
- },
95
- uuidV7Bytes(out?: Uint8Array, offset = 0) {
96
- if (!runtime.uuidV7Bytes) return fallback.uuidV7Bytes(out, offset);
97
- try {
98
- return runtime.uuidV7Bytes(out, offset);
99
- } catch (cause) {
100
- return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", {
101
- cause,
102
- });
271
+ }
272
+ if (rollback !== undefined && now > clockHighWaterMs) clockHighWaterMs = now;
273
+ return undefined;
274
+ }
275
+
276
+ function bytes(out?: Uint8Array, offset = 0): Uint8Array | UuidSlugError {
277
+ if (generating) return reenteredGeneration();
278
+ generating = true;
279
+ try {
280
+ const target = out ?? new Uint8Array(16);
281
+ // Allocation proves the zero-offset range; caller storage and other offsets still need checks.
282
+ const badRange =
283
+ target === textBytes
284
+ ? undefined
285
+ : out === undefined
286
+ ? offset === 0
287
+ ? undefined
288
+ : checkRange(16, offset, 16)
289
+ : checkByteRange(out, offset, 16);
290
+ if (badRange) return badRange;
291
+ // Split THEN validated, in that order and not the other. A readUnixMs is allowed to be
292
+ // fractional — `performance.timeOrigin + performance.now()` is, and is a perfectly good one —
293
+ // so rejecting non-integers here would refuse a legitimate caller. What must not survive is a
294
+ // truncated value the format cannot carry: `writeTimestamp` keeps the low 48 bits of whatever
295
+ // it is handed, so NaN and 2**48 both silently produced the 1970 prefix and a negative
296
+ // millisecond produced the year 10889 by two's-complement wrap. All three now report.
297
+ // The raw reading is kept for the message rather than calling `readUnixMs()` again: a second call
298
+ // is a second reading, and the message would name a value other than the one refused.
299
+ const reading = readClock(readUnixMs);
300
+ if (isUuidSlugError(reading)) return reading;
301
+ const now = typeof reading === "number" ? Math.trunc(reading) : NaN;
302
+ if (typeof reading !== "number" || reading < 0 || !isValidUuidV7UnixMs(now))
303
+ return new UuidSlugError(
304
+ INVALID_TIMESTAMP,
305
+ `Clock returned ${diagnosticValue(reading)}, which is not a millisecond in 0..${MAX_UUID_V7_UNIX_MS}.`,
306
+ );
307
+ const fraction =
308
+ fractionBits === 0
309
+ ? 0
310
+ : options.readFractionBucket12 !== undefined
311
+ ? options.readFractionBucket12() >>> (12 - fractionBits)
312
+ : Math.min(2 ** fractionBits - 1, Math.floor((reading - now) * 2 ** fractionBits));
313
+ const failed = advanceSequence(now, fraction);
314
+ if (failed) return failed;
315
+ return writeBytes(target, offset, lastMs, counterHi, counterLo);
316
+ } finally {
317
+ generating = false;
318
+ }
319
+ }
320
+
321
+ function bytesAt(
322
+ instant: NormalizedUuidV7Instant,
323
+ out?: Uint8Array,
324
+ offset = 0,
325
+ ): Uint8Array | UuidSlugError {
326
+ if (generating) return reenteredGeneration();
327
+ generating = true;
328
+ try {
329
+ const target = out ?? new Uint8Array(16);
330
+ // Match current-time ownership: checking an owned zero-offset range would prove nothing new.
331
+ const badRange =
332
+ out === undefined
333
+ ? offset === 0
334
+ ? undefined
335
+ : checkRange(16, offset, 16)
336
+ : checkByteRange(out, offset, 16);
337
+ if (badRange) return badRange;
338
+ const fraction = fractionBits === 0 ? 0 : instant.fractionBucket12 >>> (12 - fractionBits);
339
+ if (coordinateExplicitInstants) {
340
+ const failed = advanceSequence(instant.unixMs, fraction);
341
+ if (failed) return failed;
342
+ return writeBytes(target, offset, lastMs, counterHi, counterLo);
103
343
  }
104
- },
344
+ const failed = fillRandomBytes(fill, random);
345
+ if (failed) return failed;
346
+ const seededCounter = (seedHi(random) * 0x1_0000_0000 + seedLo(random)) % counterModulus;
347
+ const payloadPrefix = fraction * counterModulus + seededCounter;
348
+ return writeBytes(
349
+ target,
350
+ offset,
351
+ instant.unixMs,
352
+ Math.floor(payloadPrefix / 0x1_0000_0000),
353
+ payloadPrefix >>> 0,
354
+ );
355
+ } finally {
356
+ generating = false;
357
+ }
358
+ }
359
+
360
+ function generateUuidV7Bytes(): UuidV7Bytes | UuidSlugError;
361
+ function generateUuidV7Bytes<Output extends Uint8Array>(
362
+ out: Output,
363
+ offset?: number,
364
+ ): UuidOutput<Output> | UuidSlugError;
365
+ function generateUuidV7Bytes(
366
+ options: Omit<GenerateUuidV7BytesOptions, "generator">,
367
+ ): UuidV7Bytes | UuidSlugError;
368
+ function generateUuidV7Bytes<Output extends Uint8Array>(
369
+ options: Omit<GenerateUuidV7BytesIntoOptions<Output>, "generator">,
370
+ ): UuidOutput<Output> | UuidSlugError;
371
+ function generateUuidV7Bytes(
372
+ outOrOptions?:
373
+ | Uint8Array
374
+ | Omit<GenerateUuidV7BytesOptions, "generator">
375
+ | Omit<GenerateUuidV7BytesIntoOptions<Uint8Array>, "generator">,
376
+ offset?: number,
377
+ ): Uint8Array | UuidSlugError {
378
+ if (outOrOptions === undefined || isUint8Array(outOrOptions))
379
+ return bytes(outOrOptions, offset);
380
+ if (Array.isArray(outOrOptions) || ArrayBuffer.isView(outOrOptions))
381
+ return checkByteRange(outOrOptions, offset ?? 0, 16) as UuidSlugError;
382
+ const values = readGenerationOptions(
383
+ outOrOptions,
384
+ UUID_V7_BYTE_OPTIONS,
385
+ "UUIDv7 byte generation",
386
+ );
387
+ if (values instanceof Error) return values;
388
+ const output = values.output as Uint8Array | undefined;
389
+ const outputOffset = values.outputOffset as number | undefined;
390
+ if (!Object.hasOwn(values, AT_OPTION)) return bytes(output, outputOffset);
391
+ const instant = readUuidV7Instant(values.at);
392
+ return instant instanceof Error ? instant : bytesAt(instant, output, outputOffset);
393
+ }
394
+
395
+ function drawUuidV7Bytes(
396
+ instant: NormalizedUuidV7Instant | undefined,
397
+ output?: Uint8Array,
398
+ outputOffset?: number,
399
+ ): Uint8Array | UuidSlugError {
400
+ return instant === undefined
401
+ ? bytes(output, outputOffset)
402
+ : bytesAt(instant, output, outputOffset);
403
+ }
404
+
405
+ function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
406
+ ...textCase: UuidTextCaseArguments<Case>
407
+ ): UuidV7StringFor<Case> | UuidSlugError;
408
+ function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
409
+ options: Omit<GenerateUuidV7Options<Case>, "generator">,
410
+ ): UuidV7StringFor<Case> | UuidSlugError;
411
+ function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
412
+ textCaseOrOptions:
413
+ | Case
414
+ | Omit<GenerateUuidV7Options<Case>, "generator"> = UUID_TEXT_LOWERCASE as Case,
415
+ ): UuidV7StringFor<Case> | UuidSlugError {
416
+ if (typeof textCaseOrOptions === "string") {
417
+ const textCase = resolveUuidTextCase(textCaseOrOptions);
418
+ if (textCase instanceof Error) return textCase;
419
+ // Preset text consumes this exact destination, so passing it through a formatting helper
420
+ // adds no information. Keep configured calls shared; remeasure when either writer changes.
421
+ const result = bytes(textBytes);
422
+ return result === textBytes
423
+ ? (formatUuidBytesUnchecked(textBytes, 0, textCase) as UuidV7StringFor<Case>)
424
+ : (result as UuidSlugError);
425
+ }
426
+ let values = readGenerationOptions(
427
+ textCaseOrOptions,
428
+ UUID_V7_TEXT_OPTIONS,
429
+ "UUIDv7 generation",
430
+ );
431
+ if (values instanceof Error) {
432
+ const wrappedCase = stringInput(textCaseOrOptions);
433
+ if (wrappedCase !== undefined) values = { textCase: wrappedCase };
434
+ }
435
+ if (values instanceof Error) return values;
436
+ const textCase = resolveUuidTextCase(values.textCase ?? UUID_TEXT_LOWERCASE);
437
+ if (textCase instanceof Error) return textCase;
438
+ if (!Object.hasOwn(values, AT_OPTION))
439
+ return formatUuidV7(bytes(textBytes), textCase, textBytes) as UuidV7StringFor<Case>;
440
+ const instant = readUuidV7Instant(values.at);
441
+ return instant instanceof Error
442
+ ? instant
443
+ : (formatUuidV7(bytesAt(instant, textBytes), textCase, textBytes) as UuidV7StringFor<Case>);
444
+ }
445
+
446
+ return {
447
+ // Text formatting consumes bytes synchronously, so one generator-owned buffer removes an
448
+ // allocation without exposing mutable storage. The reentrancy guard protects it while readUnixMs
449
+ // and entropy callbacks run.
450
+ payloadLayout,
451
+ generateUuidV7,
452
+ generateUuidV7Bytes,
453
+ drawUuidV7Bytes,
105
454
  };
106
455
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/base64url.ts","../src/uuid.ts","../src/codec.ts","../src/errors.ts","../src/schema.ts","../src/runtime/types.ts","../src/v7.ts","../src/index.ts"],"mappings":"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"}