@anizoptera/uuid-slug 0.3.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 (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1052 -261
  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 +14 -9
  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
@@ -0,0 +1,245 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { runtime } from "#runtime";
4
+ import {
5
+ findUnknownOption,
6
+ INVALID_OPTIONS,
7
+ isPlainRecord,
8
+ isSuccessfulUuidBytes,
9
+ stringInput,
10
+ UuidSlugError,
11
+ } from "./errors.ts";
12
+ import {
13
+ UUID_V7_ROLLBACK_ERROR,
14
+ UUID_V7_ROLLBACK_PRESERVE,
15
+ UUID_V7_ROLLBACK_RESET,
16
+ } from "./types.ts";
17
+ import type {
18
+ Uuid,
19
+ UuidRandomFill,
20
+ UuidV7ClockRollbackPolicy,
21
+ UuidV7Generator,
22
+ UuidV7GeneratorValueOptions,
23
+ UuidV7MaskingCodec,
24
+ } from "./types.ts";
25
+ import { readUuidV7Instant } from "./instant.ts";
26
+ import { createUuidValue } from "./uuid-value.ts";
27
+ import { createPortableUuidV7Generator } from "./v7.ts";
28
+ import { uuidV7GeneratorSlugMethods } from "./v7-slug.ts";
29
+ import { stampPackageUuidV7Generator } from "./v7-generator-input.ts";
30
+ import { readUuidV7MaskingCodec, readUuidV7ValueOptions } from "./v7-value-options.ts";
31
+
32
+ /** Configure one UUIDv7 sequence's clock and rollback behavior. */
33
+ export interface UuidV7GeneratorOptions {
34
+ /**
35
+ * Return Unix milliseconds. Fractional readings feed `subMillisecondFractionBits`; otherwise
36
+ * they are truncated. Invalid readings and thrown values return `invalid_timestamp`.
37
+ *
38
+ * @defaultValue `Date.now` with no fraction bits; otherwise the runtime high-resolution clock
39
+ * when present, then `Date.now`
40
+ */
41
+ readonly readUnixMs?: () => number;
42
+ /**
43
+ * Whole number from 0 through 12 assigning leading payload bits to the RFC 9562
44
+ * sub-millisecond fraction. The remaining leading payload bits hold the random-start counter.
45
+ * Monotonic continuation can advance the encoded fraction ahead of a stalled or backward clock.
46
+ *
47
+ * @defaultValue `0`
48
+ */
49
+ readonly subMillisecondFractionBits?: number;
50
+ /**
51
+ * Handle a reading below the accepted clock high-water mark. Preserve-order behavior is the
52
+ * default. Reset and error policies preserve small rollbacks through their inclusive tolerance.
53
+ *
54
+ * @defaultValue `{ action: "preserve" }`
55
+ */
56
+ readonly clockRollback?: UuidV7ClockRollbackPolicy;
57
+ }
58
+
59
+ const GENERATOR_OPTIONS = {
60
+ clockRollback: true,
61
+ readUnixMs: true,
62
+ subMillisecondFractionBits: true,
63
+ } as const satisfies Record<keyof UuidV7GeneratorOptions, true>;
64
+ const INVALID_GENERATOR_OPTIONS = "Generator options must be an object.";
65
+ const INVALID_ROLLBACK_POLICY = "Generator clockRollback must be a policy object.";
66
+ const UUID_V7_GENERATOR_VALUE_OPTIONS = {
67
+ at: true,
68
+ maskingCodec: true,
69
+ } as const satisfies Record<keyof UuidV7GeneratorValueOptions, true>;
70
+ const AT_OPTION = "at";
71
+
72
+ const highResolutionClock = globalThis.performance;
73
+ function createHighResolutionClock(clock: Performance) {
74
+ let fractionBucket12 = 0;
75
+ const origin = clock.timeOrigin;
76
+ const originMs = Math.floor(origin);
77
+ const originFraction = origin - originMs;
78
+ // Adding the epoch to elapsed time first rounds fine clock bits away. Split each reading
79
+ // before addition; keep the bucket beside its integer timestamp without allocating per draw.
80
+ // This clock belongs to one generator so reentrant calls on another cannot overwrite it.
81
+ return {
82
+ readUnixMs() {
83
+ const elapsed = clock.now();
84
+ const elapsedMs = Math.floor(elapsed);
85
+ const fraction = originFraction + (elapsed - elapsedMs);
86
+ const carry = Math.floor(fraction);
87
+ fractionBucket12 = Math.floor((fraction - carry) * 4096);
88
+ return originMs + elapsedMs + carry;
89
+ },
90
+ readFractionBucket12: () => fractionBucket12,
91
+ };
92
+ }
93
+
94
+ function validatedRollback(
95
+ value: unknown,
96
+ ):
97
+ | Extract<UuidV7ClockRollbackPolicy, { readonly toleranceMs: number }>
98
+ | UuidSlugError
99
+ | undefined {
100
+ if (value === undefined) return undefined;
101
+ if (value === null || typeof value !== "object")
102
+ return new UuidSlugError(INVALID_OPTIONS, INVALID_ROLLBACK_POLICY);
103
+ try {
104
+ if (Array.isArray(value)) return new UuidSlugError(INVALID_OPTIONS, INVALID_ROLLBACK_POLICY);
105
+ const rawAction = (value as { readonly action?: unknown }).action;
106
+ const action = stringInput(rawAction) ?? rawAction;
107
+ const accepted =
108
+ action === UUID_V7_ROLLBACK_PRESERVE
109
+ ? ({ action: true } as const)
110
+ : ({ action: true, toleranceMs: true } as const);
111
+ const unknown = findUnknownOption(value, accepted);
112
+ if (unknown !== undefined)
113
+ return new UuidSlugError(INVALID_OPTIONS, `Unknown clock rollback option: ${unknown}.`);
114
+ if (action === UUID_V7_ROLLBACK_PRESERVE) return undefined;
115
+ if (action !== UUID_V7_ROLLBACK_RESET && action !== UUID_V7_ROLLBACK_ERROR)
116
+ return new UuidSlugError(INVALID_OPTIONS, "Clock rollback action is not supported.");
117
+ const toleranceMs = (value as { readonly toleranceMs?: unknown }).toleranceMs;
118
+ if (!Number.isSafeInteger(toleranceMs) || (toleranceMs as number) < 0)
119
+ return new UuidSlugError(
120
+ INVALID_OPTIONS,
121
+ "Clock rollback toleranceMs must be a nonnegative whole number.",
122
+ );
123
+ return { action, toleranceMs: toleranceMs as number };
124
+ } catch (cause) {
125
+ return new UuidSlugError(INVALID_OPTIONS, "Reading clock rollback policy failed.", { cause });
126
+ }
127
+ }
128
+
129
+ function buildGenerator(
130
+ options: UuidV7GeneratorOptions,
131
+ fillRandom: (bytes: Uint8Array<ArrayBuffer>) => unknown,
132
+ ): UuidV7Generator | UuidSlugError {
133
+ if (options === null || typeof options !== "object")
134
+ return new UuidSlugError(INVALID_OPTIONS, INVALID_GENERATOR_OPTIONS);
135
+ let readUnixMs: UuidV7GeneratorOptions["readUnixMs"];
136
+ let clockRollback: unknown;
137
+ let subMillisecondFractionBits: unknown;
138
+ try {
139
+ if (!isPlainRecord(options))
140
+ return new UuidSlugError(INVALID_OPTIONS, INVALID_GENERATOR_OPTIONS);
141
+ const unknown = findUnknownOption(options, GENERATOR_OPTIONS);
142
+ if (unknown !== undefined)
143
+ return new UuidSlugError(INVALID_OPTIONS, `Unknown generator option: ${unknown}.`);
144
+ readUnixMs = options.readUnixMs;
145
+ clockRollback = options.clockRollback;
146
+ subMillisecondFractionBits = options.subMillisecondFractionBits;
147
+ } catch (cause) {
148
+ return new UuidSlugError(INVALID_OPTIONS, "Reading generator options failed.", { cause });
149
+ }
150
+ if (readUnixMs !== undefined && typeof readUnixMs !== "function")
151
+ return new UuidSlugError(INVALID_OPTIONS, "Generator readUnixMs must be a function.");
152
+ if (
153
+ subMillisecondFractionBits !== undefined &&
154
+ (!Number.isInteger(subMillisecondFractionBits) ||
155
+ (subMillisecondFractionBits as number) < 0 ||
156
+ (subMillisecondFractionBits as number) > 12)
157
+ )
158
+ return new UuidSlugError(
159
+ INVALID_OPTIONS,
160
+ "Generator subMillisecondFractionBits must be a whole number from 0 through 12.",
161
+ );
162
+ const rollback = validatedRollback(clockRollback);
163
+ if (rollback instanceof Error) return rollback;
164
+ const fractionBits = (subMillisecondFractionBits as number | undefined) ?? 0;
165
+ const clock =
166
+ readUnixMs === undefined && fractionBits !== 0 && highResolutionClock !== undefined
167
+ ? createHighResolutionClock(highResolutionClock)
168
+ : undefined;
169
+ const generator = createPortableUuidV7Generator({
170
+ ...(rollback === undefined ? {} : { clockRollback: rollback }),
171
+ readUnixMs: readUnixMs ?? Date.now,
172
+ ...clock,
173
+ subMillisecondFractionBits: fractionBits,
174
+ fillRandom,
175
+ });
176
+ /** One draw for every method on this object: the sequence's own bytes, at `at` or at its clock. */
177
+ const drawSequencedBytes = (values: { readonly at?: unknown }) => {
178
+ if (!Object.hasOwn(values, AT_OPTION)) return generator.drawUuidV7Bytes(undefined);
179
+ const instant = readUuidV7Instant(values.at);
180
+ return instant instanceof Error ? instant : generator.drawUuidV7Bytes(instant);
181
+ };
182
+ // Omission cannot prove a retained codec; the configured overload requires its runtime options.
183
+ function generateUuidV7Value(valueOptions?: undefined): Uuid<7, false, true> | UuidSlugError;
184
+ function generateUuidV7Value<const Options extends UuidV7GeneratorValueOptions>(
185
+ valueOptions: Options,
186
+ ):
187
+ | Uuid<7, Options extends { readonly maskingCodec: UuidV7MaskingCodec } ? true : false, true>
188
+ | UuidSlugError;
189
+ function generateUuidV7Value(
190
+ valueOptions?: UuidV7GeneratorValueOptions,
191
+ ): Uuid<7, boolean, true> | UuidSlugError {
192
+ const values = readUuidV7ValueOptions(valueOptions, UUID_V7_GENERATOR_VALUE_OPTIONS);
193
+ if (values instanceof Error) return values;
194
+ const maskingCodec = readUuidV7MaskingCodec(values.maskingCodec);
195
+ if (maskingCodec instanceof Error) return maskingCodec;
196
+ const generated = drawSequencedBytes(values);
197
+ return isSuccessfulUuidBytes(generated)
198
+ ? createUuidValue<7, boolean, true>(generated, maskingCodec, generator.payloadLayout)
199
+ : generated;
200
+ }
201
+ // Named properties rather than a spread keep the internal draw off the public object.
202
+ const created = stampPackageUuidV7Generator(
203
+ {
204
+ payloadLayout: generator.payloadLayout,
205
+ generateUuidV7: generator.generateUuidV7,
206
+ generateUuidV7Bytes: generator.generateUuidV7Bytes,
207
+ ...uuidV7GeneratorSlugMethods(drawSequencedBytes),
208
+ generateUuidV7Value,
209
+ },
210
+ generator,
211
+ );
212
+ return Object.freeze(created);
213
+ }
214
+
215
+ /**
216
+ * Create a UUIDv7 sequence with its own state, clock policy, and platform randomness.
217
+ * Invalid numeric ranges or clock policies return `UuidSlugError`.
218
+ */
219
+ export function createUuidV7Generator(
220
+ options?: UuidV7GeneratorOptions,
221
+ ): UuidV7Generator | UuidSlugError;
222
+ export function createUuidV7Generator(
223
+ options: UuidV7GeneratorOptions = {},
224
+ ): UuidV7Generator | UuidSlugError {
225
+ return buildGenerator(options, runtime.fillRandom);
226
+ }
227
+
228
+ /**
229
+ * Create a UUIDv7 sequence using the caller's synchronous random-byte source.
230
+ * Invalid numeric ranges or clock policies return `UuidSlugError`.
231
+ */
232
+ export function createUuidV7GeneratorWithRandomFill(
233
+ fillRandom: UuidRandomFill,
234
+ options?: UuidV7GeneratorOptions,
235
+ ): UuidV7Generator | UuidSlugError;
236
+ export function createUuidV7GeneratorWithRandomFill(
237
+ fillRandom: UuidRandomFill,
238
+ options: UuidV7GeneratorOptions = {},
239
+ ): UuidV7Generator | UuidSlugError {
240
+ if (typeof fillRandom !== "function")
241
+ return new UuidSlugError(INVALID_OPTIONS, "Generator fillRandom must be a function.");
242
+ // The generator's draw boundary owns failure recognition and exception containment.
243
+ // Pass the source unchanged so marker-only failures cannot become successful draws.
244
+ return buildGenerator(options, fillRandom);
245
+ }
@@ -0,0 +1,354 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /** Keyless operations avoid codec setup. Masking stays on codecs because it requires their key. */
4
+ import { runtime } from "#runtime";
5
+ import {
6
+ ERROR_MARKER,
7
+ fillRandomBytes,
8
+ generatedOrThrow,
9
+ INVALID_TIMESTAMP,
10
+ portableAfterNative,
11
+ readClock,
12
+ stringInput,
13
+ UuidSlugError,
14
+ } from "./errors.ts";
15
+ import { readGenerationOptions } from "./generation-options.ts";
16
+ import { UUID_TEXT_LOWERCASE, UUID_TEXT_UPPERCASE } from "./types.ts";
17
+ import type {
18
+ GenerateUuidV7Options,
19
+ GenerateUuidV7BytesIntoOptions,
20
+ GenerateUuidV7BytesOptions,
21
+ UuidOutput,
22
+ UuidTextCase,
23
+ UuidTextCaseArguments,
24
+ UuidV7Bytes,
25
+ UuidV7StringFor,
26
+ } from "./types.ts";
27
+ import type { UuidV7PayloadLayout } from "./types.ts";
28
+ import { readUuidV7Instant } from "./instant.ts";
29
+ import { formatUuidBytesUnchecked, resolveUuidTextCase } from "./uuid.ts";
30
+ import { createPortableUuidV7Generator } from "./v7.ts";
31
+ import type { PortableUuidV7Generator } from "./v7.ts";
32
+ import { generateUuidV7BytesWithGenerator, readUuidV7Generator } from "./v7-generator-input.ts";
33
+
34
+ const UUID_V7_TEXT_OPTIONS = {
35
+ at: true,
36
+ generator: true,
37
+ textCase: true,
38
+ } as const satisfies Record<keyof GenerateUuidV7Options, true>;
39
+ const AT_OPTION = "at";
40
+ const UUID_V7_GENERATION = "UUIDv7 generation";
41
+ const UUID_V7_BYTE_OPTIONS = {
42
+ at: true,
43
+ generator: true,
44
+ output: true,
45
+ outputOffset: true,
46
+ } as const satisfies Record<keyof GenerateUuidV7BytesIntoOptions<Uint8Array>, true>;
47
+
48
+ /**
49
+ * Text and bytes keep independent lazy state so neither output form pays cross-form coordination.
50
+ * Native defaults avoid constructing this generator. Explicit time, configured generators and
51
+ * native failure still need portable state; bench/PERFORMANCE.md owns the selection evidence.
52
+ */
53
+ let textGenerator: PortableUuidV7Generator | undefined;
54
+ let byteGenerator: PortableUuidV7Generator | undefined;
55
+ const v7Text = () =>
56
+ (textGenerator ??= createPortableUuidV7Generator({
57
+ coordinateExplicitInstants: false,
58
+ fillRandom: runtime.fillRandom,
59
+ textScratch: keylessTextBytes,
60
+ }));
61
+ const v7Bytes = () =>
62
+ (byteGenerator ??= createPortableUuidV7Generator({
63
+ coordinateExplicitInstants: false,
64
+ fillRandom: runtime.fillRandom,
65
+ }));
66
+ export const uuidV7DefaultPayloadLayout = (): UuidV7PayloadLayout => v7Bytes().payloadLayout;
67
+ // Text formatting reads these bytes before returning, and the module generators run no caller code.
68
+ const keylessTextBytes = new Uint8Array(16);
69
+
70
+ /**
71
+ * Draw with options this module already read. Rebuilding an options object for the generator's
72
+ * public method allocated it and read every option a second time (bench/PERFORMANCE.md).
73
+ */
74
+ function drawFromReadOptions(
75
+ generator: PortableUuidV7Generator,
76
+ values: { readonly at?: unknown },
77
+ output?: Uint8Array,
78
+ outputOffset?: number,
79
+ ): Uint8Array | UuidSlugError {
80
+ return Object.hasOwn(values, AT_OPTION)
81
+ ? drawAt(generator, values.at, output, outputOffset)
82
+ : generator.drawUuidV7Bytes(undefined, output, outputOffset);
83
+ }
84
+
85
+ function drawAt(
86
+ generator: PortableUuidV7Generator,
87
+ at: unknown,
88
+ output?: Uint8Array,
89
+ outputOffset?: number,
90
+ ): Uint8Array | UuidSlugError {
91
+ const instant = readUuidV7Instant(at);
92
+ return instant instanceof Error
93
+ ? instant
94
+ : generator.drawUuidV7Bytes(instant, output, outputOffset);
95
+ }
96
+
97
+ /** Module-generator bytes at an `at` option value the caller has read but not validated. */
98
+ export const uuidV7BytesAt = (at: unknown): Uint8Array | UuidSlugError => drawAt(v7Bytes(), at);
99
+
100
+ /*
101
+ * Slug and pair writers encode their bytes before returning and draw nothing in between, so they
102
+ * borrow the generator's private text scratch instead of validating a second module buffer as
103
+ * caller output. Text keeps cached generator delegation; replacing it with a direct module
104
+ * formatter has not earned its cost on the primary calls (bench/PERFORMANCE.md).
105
+ * Keep configured output validation and the generator's reentrancy guard; a borrowed buffer
106
+ * must never escape or survive another draw. Remeasure complete calls when either writer changes
107
+ * (bench/PERFORMANCE.md), rather than assuming fewer checks improve every runtime.
108
+ */
109
+ export const currentUuidV7Scratch = (): Uint8Array | UuidSlugError =>
110
+ v7Text().drawUuidV7Bytes(undefined, keylessTextBytes);
111
+ export const uuidV7ScratchAt = (at: unknown): Uint8Array | UuidSlugError =>
112
+ drawAt(v7Text(), at, keylessTextBytes);
113
+ // Select without a draw so native hosts avoid portable setup and other hosts keep the original
114
+ // public call body. Remeasure defaults and configured calls if this boundary changes.
115
+ let generateDefaultUuidV7: ((textCase: UuidTextCase) => string | UuidSlugError) | undefined =
116
+ runtime.uuidV7 ? generateNativeDefaultUuidV7 : undefined;
117
+ let generatePortableUuidV7: PortableUuidV7Generator["generateUuidV7"] | undefined;
118
+ let generateDefaultUuidV7Bytes: PortableUuidV7Generator["generateUuidV7Bytes"] | undefined;
119
+
120
+ // Keep fallback lazy and error-valued so both native and portable causes survive a dual failure.
121
+ const portableUuidV7Text = (textCase: UuidTextCase): string | UuidSlugError =>
122
+ (generatePortableUuidV7 ??= v7Text().generateUuidV7)(textCase);
123
+
124
+ // Trust proper native results directly; validation and identity tracking add guarantees beyond
125
+ // the default native baseline. Keep exception fallback separate from configured calls, and
126
+ // remeasure complete calls when host capabilities change; bench/PERFORMANCE.md owns evidence.
127
+ function generateNativeDefaultUuidV7<Case extends UuidTextCase>(
128
+ selectedCase: Case,
129
+ ): UuidV7StringFor<Case> | UuidSlugError {
130
+ const native = runtime.uuidV7;
131
+ if (!native) return portableUuidV7Text(selectedCase) as UuidV7StringFor<Case> | UuidSlugError;
132
+ let uuid: string | UuidSlugError;
133
+ try {
134
+ uuid = native();
135
+ } catch (nativeCause) {
136
+ uuid = portableAfterNative(
137
+ nativeCause,
138
+ portableUuidV7Text,
139
+ UUID_TEXT_LOWERCASE,
140
+ UUID_V7_GENERATION,
141
+ );
142
+ }
143
+ // Only the public preset call owns the permitted throw; fallback here retains error values.
144
+ if (typeof uuid !== "string") return uuid;
145
+ return (
146
+ selectedCase === UUID_TEXT_UPPERCASE ? uuid.toUpperCase() : uuid
147
+ ) as UuidV7StringFor<Case>;
148
+ }
149
+
150
+ /*
151
+ * Return types are DECLARED, not inferred, on all four. Inference reads them off the generator, so
152
+ * a widened method there silently widens the package's public surface. A declared type turns that
153
+ * mismatch into a compile error at the one site that is wrong.
154
+ */
155
+ /**
156
+ * Generate current-time UUIDv7 text, lowercase by default. Module-level calls do not provide
157
+ * ordering across calls; the runtime's logical timestamp can advance during bursts. Use an
158
+ * explicitly created generator when clock policy or payload layout must be controlled.
159
+ * Native runtime results are trusted without additional output guarantees.
160
+ *
161
+ * @param textCase - Built-in output spelling. Omit for lowercase.
162
+ * @throws `UuidSlugError` with code `rng_unavailable` when generation cannot obtain
163
+ * secure randomness.
164
+ */
165
+ export function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
166
+ ...textCase: UuidTextCaseArguments<Case>
167
+ ): UuidV7StringFor<Case>;
168
+ /**
169
+ * Generate UUIDv7 text at an explicit time or the current clock reading. Explicit time does not
170
+ * join module-level sequence state.
171
+ *
172
+ * @param options - Time, sequence, and text spelling. Omit `generator` for an independent call.
173
+ */
174
+ export function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
175
+ options: GenerateUuidV7Options<Case>,
176
+ ): UuidV7StringFor<Case> | UuidSlugError;
177
+ export function generateUuidV7<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
178
+ textCaseOrOptions?: Case | GenerateUuidV7Options<Case>,
179
+ ): UuidV7StringFor<Case> | UuidSlugError {
180
+ const directCase =
181
+ textCaseOrOptions === undefined
182
+ ? UUID_TEXT_LOWERCASE
183
+ : typeof textCaseOrOptions === "string"
184
+ ? textCaseOrOptions
185
+ : undefined;
186
+ // A spelling preset is the only input on this path, and an unknown one can arrive only from an
187
+ // untyped call, so it stays an error value while a failed draw is thrown.
188
+ if (directCase !== undefined) {
189
+ const selectedCase = resolveUuidTextCase(directCase);
190
+ return selectedCase instanceof Error
191
+ ? selectedCase
192
+ : (generatedOrThrow(
193
+ (generateDefaultUuidV7 ??= v7Text().generateUuidV7)(selectedCase),
194
+ ) as UuidV7StringFor<Case>);
195
+ }
196
+ let values = readGenerationOptions(textCaseOrOptions, UUID_V7_TEXT_OPTIONS, UUID_V7_GENERATION);
197
+ if (values instanceof Error) {
198
+ const wrappedCase = stringInput(textCaseOrOptions);
199
+ if (wrappedCase !== undefined) {
200
+ const selectedCase = resolveUuidTextCase(wrappedCase);
201
+ return selectedCase instanceof Error
202
+ ? selectedCase
203
+ : (generatedOrThrow(
204
+ (generateDefaultUuidV7 ??= v7Text().generateUuidV7)(selectedCase),
205
+ ) as UuidV7StringFor<Case>);
206
+ }
207
+ }
208
+ if (values instanceof Error) return values;
209
+ const textCase = resolveUuidTextCase(values.textCase ?? UUID_TEXT_LOWERCASE);
210
+ if (textCase instanceof Error) return textCase;
211
+ const generator = readUuidV7Generator(values.generator);
212
+ if (generator instanceof Error) return generator;
213
+ // Package sequences already own text scratch. Current-time text can reuse it without allocating
214
+ // bytes; explicit time keeps the validated draw because text delegation would reread its options.
215
+ // Structural generators retain the byte seam. Remeasure if either dispatch contract changes.
216
+ const generateText = generator?.generateUuidV7;
217
+ if (generateText && !Object.hasOwn(values, AT_OPTION))
218
+ return generateText(textCase) as UuidV7StringFor<Case> | UuidSlugError;
219
+ const bytes = generator
220
+ ? generateUuidV7BytesWithGenerator(generator, values, true)
221
+ : drawFromReadOptions(v7Text(), values, keylessTextBytes);
222
+ // The draw already validates bytes and recognizes failures. Inline this union check because
223
+ // another predicate call adds work to structural generators; no second UUID validation is needed.
224
+ if (!ArrayBuffer.isView(bytes)) return bytes;
225
+ let failed = false;
226
+ try {
227
+ failed = (bytes as Uint8Array & { readonly [ERROR_MARKER]?: unknown })[ERROR_MARKER] === true;
228
+ } catch {
229
+ // A valid view with an inaccessible marker cannot be an unmarked native Error.
230
+ }
231
+ return failed
232
+ ? (bytes as Uint8Array & UuidSlugError)
233
+ : (formatUuidBytesUnchecked(bytes, 0, textCase) as UuidV7StringFor<Case>);
234
+ }
235
+
236
+ /**
237
+ * Generate UUIDv7 bytes with platform randomness in a new plain 16-byte `Uint8Array`. Module-level
238
+ * calls do not provide ordering across calls.
239
+ *
240
+ * @throws `UuidSlugError` with code `rng_unavailable` when generation cannot obtain
241
+ * secure randomness.
242
+ */
243
+ export function generateUuidV7Bytes(): UuidV7Bytes;
244
+ /**
245
+ * Write UUIDv7 bytes into caller-owned storage only after successful generation. Module-level calls
246
+ * do not provide ordering across calls.
247
+ *
248
+ * @param output - Caller-owned array that receives the 16 UUID bytes.
249
+ * @param outputOffset - Zero-based index where writing starts. Omit to start at index 0. Bytes
250
+ * outside the written range stay unchanged.
251
+ */
252
+ export function generateUuidV7Bytes<Output extends Uint8Array>(
253
+ output: Output,
254
+ outputOffset?: number,
255
+ ): UuidOutput<Output> | UuidSlugError;
256
+ /** Generate package-owned UUIDv7 bytes at an explicit time or the current clock reading. */
257
+ export function generateUuidV7Bytes(
258
+ options: GenerateUuidV7BytesOptions,
259
+ ): UuidV7Bytes | UuidSlugError;
260
+ /** Write UUIDv7 bytes at an explicit time or the current clock reading into caller-owned storage. */
261
+ export function generateUuidV7Bytes<Output extends Uint8Array>(
262
+ options: GenerateUuidV7BytesIntoOptions<Output>,
263
+ ): UuidOutput<Output> | UuidSlugError;
264
+ export function generateUuidV7Bytes(
265
+ outOrOptions?:
266
+ | Uint8Array
267
+ | GenerateUuidV7BytesOptions
268
+ | GenerateUuidV7BytesIntoOptions<Uint8Array>,
269
+ offset?: number,
270
+ ): Uint8Array | UuidSlugError {
271
+ // Only an untyped call reaches an offset without storage; that misuse stays an error value.
272
+ if (outOrOptions === undefined && (offset === undefined || offset === 0))
273
+ return generatedOrThrow(generateSelectedDefaultUuidV7Bytes());
274
+ return uuidV7BytesFor(outOrOptions, offset);
275
+ }
276
+
277
+ /** Current-time bytes from the module generator with failures returned for option-taking callers. */
278
+ export const currentUuidV7Bytes = (): UuidV7Bytes | UuidSlugError =>
279
+ (generateDefaultUuidV7Bytes ??= v7Bytes().generateUuidV7Bytes)();
280
+
281
+ // Independent draws remove unrequested sequence work from owned defaults. Keep JITless on its
282
+ // measured generator path; configured calls and immutable values retain their declared layout.
283
+ // Remeasure complete calls if entropy, timestamp writing or runtime selection changes;
284
+ // bench/PERFORMANCE.md owns runtime comparisons rather than this selection comment.
285
+ const generateSelectedDefaultUuidV7Bytes = runtime.jitless
286
+ ? currentUuidV7Bytes
287
+ : generateDefaultOwnedUuidV7Bytes;
288
+
289
+ /** Every module-level byte form with failures returned; public seams without fallible input throw. */
290
+ export function uuidV7BytesFor(
291
+ outOrOptions?:
292
+ | Uint8Array
293
+ | GenerateUuidV7BytesOptions
294
+ | GenerateUuidV7BytesIntoOptions<Uint8Array>,
295
+ offset?: number,
296
+ ): Uint8Array | UuidSlugError {
297
+ if (
298
+ outOrOptions !== undefined &&
299
+ outOrOptions !== null &&
300
+ typeof outOrOptions === "object" &&
301
+ !Array.isArray(outOrOptions) &&
302
+ !ArrayBuffer.isView(outOrOptions)
303
+ ) {
304
+ const values = readGenerationOptions(
305
+ outOrOptions,
306
+ UUID_V7_BYTE_OPTIONS,
307
+ "UUIDv7 byte generation",
308
+ );
309
+ if (values instanceof Error) return values;
310
+ const generator = readUuidV7Generator(values.generator);
311
+ if (generator instanceof Error) return generator;
312
+ if (generator) return generateUuidV7BytesWithGenerator(generator, values);
313
+ return drawFromReadOptions(
314
+ v7Bytes(),
315
+ values,
316
+ values.output as Uint8Array | undefined,
317
+ values.outputOffset as number | undefined,
318
+ );
319
+ }
320
+ const generate = (generateDefaultUuidV7Bytes ??= v7Bytes().generateUuidV7Bytes) as (
321
+ outputOrOptions?:
322
+ | Uint8Array
323
+ | GenerateUuidV7BytesOptions
324
+ | GenerateUuidV7BytesIntoOptions<Uint8Array>,
325
+ outputOffset?: number,
326
+ ) => Uint8Array | UuidSlugError;
327
+ return generate(outOrOptions, offset);
328
+ }
329
+
330
+ function generateDefaultOwnedUuidV7Bytes(): UuidV7Bytes | UuidSlugError {
331
+ // The shared boundaries preserve clock and entropy failures. Fill the result directly instead
332
+ // of generating UUIDv4 first, which retains unrelated generation code in packed consumers.
333
+ const clock = readClock(Date.now);
334
+ if (clock instanceof Error) return clock;
335
+ if (typeof clock !== "number" || !(clock >= 0 && clock < 0x1_0000_0000_0000))
336
+ return new UuidSlugError(INVALID_TIMESTAMP, "Clock must fit the UUIDv7 timestamp.");
337
+ const ms = Math.trunc(clock);
338
+ const bytes = new Uint8Array(16);
339
+ const failed = fillRandomBytes(runtime.fillRandom, bytes);
340
+ if (failed) return failed;
341
+ // Fixed stores avoid repeated division while preserving all 48 timestamp bits; 32-bit shifts
342
+ // alone would discard the high word. Version and variant replacement leaves 74 random bits.
343
+ const high = Math.floor(ms / 0x1_0000_0000);
344
+ const low = ms >>> 0;
345
+ bytes[0] = high >>> 8;
346
+ bytes[1] = high;
347
+ bytes[2] = low >>> 24;
348
+ bytes[3] = low >>> 16;
349
+ bytes[4] = low >>> 8;
350
+ bytes[5] = low;
351
+ bytes[6] = (bytes[6]! & 0x0f) | 0x70;
352
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
353
+ return bytes as UuidV7Bytes;
354
+ }