@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
@@ -0,0 +1,923 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import {
4
+ checkByteRange,
5
+ exactLocalUuidBytes,
6
+ findUnknownOption,
7
+ INVALID_MASK,
8
+ INVALID_OPTIONS,
9
+ INVALID_SENTINEL,
10
+ INVALID_TIMESTAMP,
11
+ INVALID_UUID_VERSION,
12
+ RNG_UNAVAILABLE,
13
+ isSuccessfulUuidBytes,
14
+ isUuidSlugError,
15
+ isUint8Array,
16
+ normalizeUuidSlugInput,
17
+ stringInput,
18
+ UuidSlugError,
19
+ } from "./errors.ts";
20
+ import { BASE32HEX_NAME, BASE64URL_NAME } from "./alphabet.ts";
21
+ import {
22
+ uuidV7BytesFor as generateDefaultUuidV7Bytes,
23
+ uuidV7DefaultPayloadLayout,
24
+ } from "./v7-keyless.ts";
25
+ import {
26
+ MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS,
27
+ ownedUuidV7BytesToMaskedSlug,
28
+ noMaskedSlugMatch,
29
+ unmaskSlug,
30
+ } from "./payload.ts";
31
+ import { createMigration } from "./migration.ts";
32
+ import { findSentinel } from "./sentinel.ts";
33
+ import { registerMaskingCodec } from "./masking-codec-protocol.ts";
34
+ import { isMaskHandle } from "./mask-handle.ts";
35
+ import { deriveUuidV7Mask } from "./mask.ts";
36
+ import { validateTimestampBytes } from "./timestamp.ts";
37
+ import type {
38
+ SEEDED_MASK_FORMAT,
39
+ EnabledMigrationFormat,
40
+ GeneratedUuidV7,
41
+ UuidV7Mask,
42
+ UuidV7MaskOptions,
43
+ MaskedOrSentinelUuidV7Slug,
44
+ MaskingCodecUuidInput,
45
+ SentinelUuidV7Slug,
46
+ UuidSlugMigrationDecoder,
47
+ UuidSlugMigrationOptions,
48
+ UuidV7MaskingCodec,
49
+ UuidV7MaskingCodecOptions,
50
+ UuidV7PreviousMask,
51
+ UuidV7Bytes,
52
+ UuidBytes,
53
+ PlainUuidV7Slug,
54
+ PlainUuidSlug,
55
+ UuidV7Sentinel,
56
+ UuidV7String,
57
+ UuidStringFor,
58
+ UuidInput,
59
+ UuidStringResult,
60
+ UuidBytesResult,
61
+ PlainUuidSlugResult,
62
+ UuidOutput,
63
+ UuidTextCase,
64
+ UuidTextCaseArguments,
65
+ UuidV7StringFor,
66
+ UuidV7Payload,
67
+ UuidV7PayloadLayout,
68
+ UuidV7MaskingCodecValueOptions,
69
+ GenerateUuidV7WithMaskedSlugOptions,
70
+ GenerateUuidV7BytesOptions,
71
+ UuidV7Instant,
72
+ } from "./types.ts";
73
+ import { UUID_TEXT_LOWERCASE } from "./types.ts";
74
+ import {
75
+ resolveSlugAlphabet,
76
+ plainSlugToUuidBytes as decodePlainSlugToBytes,
77
+ readObjectUuidInput,
78
+ uuidBytesToPlainSlug,
79
+ extractUuidV7UnixMs,
80
+ extractUuidV7Payload,
81
+ uuidToBytes as keylessUuidToBytes,
82
+ uuidToPlainSlug as keylessUuidToPlainSlug,
83
+ uuidToString as keylessUuidToString,
84
+ } from "./slug.ts";
85
+ import {
86
+ formatUuidBytesUnchecked,
87
+ isUuidString,
88
+ resolveUuidTextCase,
89
+ isUuidV7Bytes,
90
+ uuidStringToBytes,
91
+ } from "./uuid.ts";
92
+ import type { UuidV7TimestampWindow, UuidV7SentinelConfig } from "./types.ts";
93
+ import type { SlugAlphabet } from "./slug.ts";
94
+ import { createUuidValue, parseUuidWithCodec } from "./uuid-value.ts";
95
+ import { generateUuidV7ValueWithGenerator, readUuidV7ValueOptions } from "./v7-value-options.ts";
96
+ import { generateUuidV7BytesWithGenerator, readUuidV7Generator } from "./v7-generator-input.ts";
97
+ import { readGenerationOptions } from "./generation-options.ts";
98
+
99
+ type EncodedSentinel = { uuid: UuidV7String; bytes: Uint8Array; slug: SentinelUuidV7Slug };
100
+
101
+ const CODEC_CONSTRUCTION_FAILED = "UUIDv7 masking-codec construction failed.";
102
+ const UUID_V7_GENERATION_FAILED = "generateUuidV7Bytes threw while generating UUIDv7 bytes.";
103
+ const INVALID_MASKED_UUID_BYTES = "Masking requires exactly 16 RFC-variant UUIDv7 bytes.";
104
+ const INVALID_SENTINEL_SHAPE = "Each sentinel must have a name and UUIDv7 string.";
105
+ const AT_OPTION = "at";
106
+ const CODEC_OPTIONS = {
107
+ mask: true,
108
+ maskedSlugAlphabet: true,
109
+ maskSeed: true,
110
+ previousMasks: true,
111
+ sentinels: true,
112
+ timestampRangeStartUnixMs: true,
113
+ } as const satisfies Record<keyof UuidV7MaskingCodecOptions, true>;
114
+ const UUID_V7_MASKING_CODEC_VALUE_OPTIONS = {
115
+ at: true,
116
+ generator: true,
117
+ } as const satisfies Record<keyof UuidV7MaskingCodecValueOptions, true>;
118
+ const PREVIOUS_MASK_OPTIONS = {
119
+ mask: true,
120
+ timestampRangeStartUnixMs: true,
121
+ } as const satisfies Record<keyof UuidV7PreviousMask, true>;
122
+ const SENTINEL_OPTIONS = {
123
+ name: true,
124
+ uuid: true,
125
+ } as const satisfies Record<keyof UuidV7SentinelConfig, true>;
126
+ const MASKED_PAIR_GENERATION_OPTIONS = {
127
+ at: true,
128
+ generator: true,
129
+ textCase: true,
130
+ } as const satisfies Record<keyof GenerateUuidV7WithMaskedSlugOptions, true>;
131
+ type EncodedSentinelIndex = {
132
+ readonly fingerprints: Uint32Array;
133
+ readonly positions: Uint32Array;
134
+ readonly mask: number;
135
+ };
136
+
137
+ type SentinelState = {
138
+ readonly bySlug: ReadonlyMap<string, EncodedSentinel>;
139
+ readonly byUuid: ReadonlyMap<string, SentinelUuidV7Slug>;
140
+ readonly encoded: readonly EncodedSentinel[];
141
+ readonly encodedByFingerprint: EncodedSentinelIndex | undefined;
142
+ readonly sentinels: readonly UuidV7Sentinel[];
143
+ };
144
+
145
+ function invalidGeneratedUuidV7Bytes(value: unknown): UuidSlugError {
146
+ if (!isUint8Array(value) || value.length !== 16)
147
+ return new UuidSlugError(
148
+ INVALID_OPTIONS,
149
+ `generateUuidV7Bytes must return exactly 16 UUID bytes or UuidSlugError; got ${isUint8Array(value) ? `${value.length} bytes` : typeof value}.`,
150
+ );
151
+ return new UuidSlugError(
152
+ INVALID_UUID_VERSION,
153
+ "generateUuidV7Bytes returned 16 bytes that are not an RFC-variant UUIDv7.",
154
+ );
155
+ }
156
+
157
+ const EMPTY_SENTINELS: readonly UuidV7Sentinel[] = Object.freeze([]);
158
+ const EMPTY_ENCODED_SENTINELS: readonly EncodedSentinel[] = Object.freeze([]);
159
+ const EMPTY_SENTINEL_STATE: SentinelState = Object.freeze({
160
+ bySlug: new Map(),
161
+ byUuid: new Map(),
162
+ encoded: EMPTY_ENCODED_SENTINELS,
163
+ encodedByFingerprint: undefined,
164
+ sentinels: EMPTY_SENTINELS,
165
+ });
166
+
167
+ function maskFromOption(
168
+ mask: UuidV7Mask | UuidV7MaskOptions | UuidSlugError,
169
+ ): UuidV7Mask | UuidSlugError {
170
+ if (isUuidSlugError(mask)) return mask;
171
+ if (isMaskHandle(mask)) return mask;
172
+ if (typeof mask !== "object" || mask === null)
173
+ return new UuidSlugError(
174
+ INVALID_MASK,
175
+ "Pass a mask from deriveUuidV7Mask or mask options containing a private seed.",
176
+ );
177
+ return deriveUuidV7Mask(mask);
178
+ }
179
+
180
+ const MAX_UUID_V7_UNIX_MS = 2 ** 48 - 1;
181
+ const MAX_TIMESTAMP_RANGE_START_UNIX_MS =
182
+ MAX_UUID_V7_UNIX_MS - MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS;
183
+
184
+ function timestampRangeStart(value: unknown, option: string): number | UuidSlugError {
185
+ if (value === undefined) return 0;
186
+ if (
187
+ Number.isSafeInteger(value) &&
188
+ (value as number) >= 0 &&
189
+ (value as number) <= MAX_TIMESTAMP_RANGE_START_UNIX_MS
190
+ )
191
+ return value as number;
192
+ const received = typeof value === "number" || value === null ? `${value}` : typeof value;
193
+ return new UuidSlugError(
194
+ INVALID_TIMESTAMP,
195
+ `${option} must be an integer from 0 through ${MAX_TIMESTAMP_RANGE_START_UNIX_MS}; got ${received}.`,
196
+ );
197
+ }
198
+
199
+ /*#__NO_SIDE_EFFECTS__*/
200
+ function sentinelFingerprint(bytes: Uint8Array): number {
201
+ let hash = 0x811c9dc5;
202
+ for (let index = 0; index < 16; index += 1)
203
+ hash = Math.imul(hash ^ (bytes[index] as number), 0x01000193);
204
+ return hash >>> 0;
205
+ }
206
+
207
+ // Fingerprints select candidates only. Full equality is mandatory because callers control sentinel
208
+ // values and can produce collisions deliberately or accidentally.
209
+ /*#__NO_SIDE_EFFECTS__*/
210
+ function findIndexedByteSentinel(
211
+ encoded: readonly EncodedSentinel[],
212
+ encodedByFingerprint: EncodedSentinelIndex,
213
+ bytes: Uint8Array,
214
+ ): SentinelUuidV7Slug | undefined {
215
+ const fingerprint = sentinelFingerprint(bytes);
216
+ let slot = fingerprint & encodedByFingerprint.mask;
217
+ let position = encodedByFingerprint.positions[slot] as number;
218
+ while (position !== 0) {
219
+ if (encodedByFingerprint.fingerprints[slot] === fingerprint) {
220
+ const indexed = encoded[position] as EncodedSentinel;
221
+ let index = 0;
222
+ while (index < 16 && indexed.bytes[index] === bytes[index]) index += 1;
223
+ if (index === 16) return indexed.slug;
224
+ }
225
+ slot = (slot + 1) & encodedByFingerprint.mask;
226
+ position = encodedByFingerprint.positions[slot] as number;
227
+ }
228
+ return undefined;
229
+ }
230
+
231
+ function createSentinels(
232
+ definitions: readonly UuidV7SentinelConfig[],
233
+ alphabet: SlugAlphabet,
234
+ ): SentinelState | UuidSlugError {
235
+ const sentinels: UuidV7Sentinel[] = [];
236
+ const names = new Set<string>();
237
+ const byUuid = new Map<string, SentinelUuidV7Slug>();
238
+ const encoded: EncodedSentinel[] = [];
239
+ const bySlug = new Map<string, EncodedSentinel>();
240
+ for (const definition of definitions) {
241
+ if (typeof definition !== "object" || definition === null)
242
+ return new UuidSlugError(INVALID_SENTINEL, INVALID_SENTINEL_SHAPE);
243
+ const name = stringInput(definition.name);
244
+ if (name === undefined) return new UuidSlugError(INVALID_SENTINEL, INVALID_SENTINEL_SHAPE);
245
+ // Validate the same value an accessor supplied; a second read could select a different ID.
246
+ const givenUuid = definition.uuid;
247
+ const uuidInput = typeof givenUuid === "string" ? givenUuid : stringInput(givenUuid);
248
+ if (uuidInput === undefined) return new UuidSlugError(INVALID_SENTINEL, INVALID_SENTINEL_SHAPE);
249
+ const unknown = findUnknownOption(definition, SENTINEL_OPTIONS);
250
+ if (unknown !== undefined)
251
+ return new UuidSlugError(INVALID_SENTINEL, `Unknown sentinel option: ${unknown}.`);
252
+ if (name.length === 0)
253
+ return new UuidSlugError(INVALID_SENTINEL, "Sentinel names must not be empty.");
254
+ if (names.has(name))
255
+ return new UuidSlugError(
256
+ INVALID_SENTINEL,
257
+ `Sentinel name "${name}" must be unique within a UUIDv7 masking codec.`,
258
+ );
259
+ // Sentinel configuration accepts raw strings so callers do not need casts before reaching the
260
+ // validating seam. Check each value here, while a bad definition is still a constructor error
261
+ // rather than a codec that fails on every later decode.
262
+ const bytes = uuidStringToBytes(uuidInput);
263
+ if (bytes instanceof Error) return bytes;
264
+ if (!isUuidV7Bytes(bytes))
265
+ return new UuidSlugError(
266
+ INVALID_UUID_VERSION,
267
+ `Sentinel "${name}" must be a UUIDv7, got ${uuidInput}.`,
268
+ );
269
+ const uuid = formatUuidBytesUnchecked(bytes) as UuidV7String;
270
+ // Reject duplicate UUIDs before the array and lookup maps can disagree about which exposed
271
+ // sentinel owns the reserved value.
272
+ if (byUuid.has(uuid))
273
+ return new UuidSlugError(
274
+ INVALID_SENTINEL,
275
+ `Sentinel "${name}" repeats the UUID of an earlier sentinel.`,
276
+ );
277
+ // Sentinels remain raw UUIDs; only their writer follows the masked alphabet selection.
278
+ const slug = uuidBytesToPlainSlug(bytes, alphabet);
279
+ if (slug instanceof Error) return slug;
280
+ const sentinel = Object.freeze({
281
+ name,
282
+ // Both brands come from the UUIDv7 byte check above.
283
+ slug: slug as SentinelUuidV7Slug,
284
+ uuid,
285
+ });
286
+ sentinels.push(sentinel);
287
+ names.add(name);
288
+ byUuid.set(uuid, sentinel.slug);
289
+ // Share the indexed entry with byte matching; its canonical key also serves normalized
290
+ // timestamp results without another case-fold operation or a second retained spelling.
291
+ const entry = { uuid: sentinel.uuid, bytes, slug: sentinel.slug };
292
+ encoded.push(entry);
293
+ bySlug.set(sentinel.slug, entry);
294
+ const alternate = uuidBytesToPlainSlug(
295
+ bytes,
296
+ alphabet === BASE64URL_NAME ? BASE32HEX_NAME : BASE64URL_NAME,
297
+ );
298
+ if (alternate instanceof Error) return alternate;
299
+ bySlug.set(alternate, { uuid: sentinel.uuid, bytes, slug: alternate as SentinelUuidV7Slug });
300
+ }
301
+ let encodedByFingerprint: EncodedSentinelIndex | undefined;
302
+ // Small sets are faster and smaller as a linear scan. Larger sets amortize one immutable index;
303
+ // excluding the first entry reserves zero as the empty-slot marker without another bitmap.
304
+ if (encoded.length >= 16) {
305
+ let capacity = 1;
306
+ while (capacity < (encoded.length - 1) * 2) capacity *= 2;
307
+ const fingerprints = new Uint32Array(capacity);
308
+ const positions = new Uint32Array(capacity);
309
+ const mask = capacity - 1;
310
+ for (let index = 1; index < encoded.length; index += 1) {
311
+ const sentinel = encoded[index] as EncodedSentinel;
312
+ const fingerprint = sentinelFingerprint(sentinel.bytes);
313
+ let slot = fingerprint & mask;
314
+ while (positions[slot] !== 0) slot = (slot + 1) & mask;
315
+ fingerprints[slot] = fingerprint;
316
+ positions[slot] = index;
317
+ }
318
+ encodedByFingerprint = { fingerprints, positions, mask };
319
+ }
320
+ return {
321
+ bySlug,
322
+ byUuid,
323
+ encoded,
324
+ encodedByFingerprint,
325
+ sentinels: Object.freeze(sentinels),
326
+ };
327
+ }
328
+
329
+ /**
330
+ * Build an immutable UUIDv7 masking codec from a private `maskSeed`, or from an explicit `mask` when
331
+ * it is derived elsewhere or needs a label or work factor. It reads the writer first, then
332
+ * `previousMasks` in caller order. Invalid masks, sentinels, options, or callbacks return
333
+ * `UuidSlugError`; no implicit public mask is selected. Masked writers return `invalid_timestamp`
334
+ * outside the configured inclusive timestamp range; registered sentinels remain plain.
335
+ *
336
+ * @param options - The writer mask as `maskSeed` or `mask`, exactly one of the two, plus the
337
+ * optional timestamp range, readers, sentinels, and output spelling.
338
+ * @returns The masking codec, or `UuidSlugError` when its configuration is invalid.
339
+ */
340
+ export function createUuidV7MaskingCodec(
341
+ options: UuidV7MaskingCodecOptions,
342
+ ): UuidV7MaskingCodec | UuidSlugError {
343
+ try {
344
+ // Codec generation keeps every failure as a value: a configured timestamp range can reject
345
+ // the current time, so no codec generation call is free of fallible input.
346
+ return buildUuidSlugCodec(options, generateDefaultUuidV7Bytes);
347
+ } catch (cause) {
348
+ return new UuidSlugError(INVALID_MASK, CODEC_CONSTRUCTION_FAILED, { cause });
349
+ }
350
+ }
351
+
352
+ /** Internal seam for exercising generator failures without weakening public generation. */
353
+ export function createUuidV7MaskingCodecWithGenerator(
354
+ options: UuidV7MaskingCodecOptions,
355
+ generateUuidV7Bytes: (
356
+ this: void,
357
+ options?: GenerateUuidV7BytesOptions,
358
+ ) => Uint8Array | UuidSlugError,
359
+ ): UuidV7MaskingCodec | UuidSlugError {
360
+ try {
361
+ return buildUuidSlugCodec(options, generateUuidV7Bytes);
362
+ } catch (cause) {
363
+ return new UuidSlugError(INVALID_MASK, CODEC_CONSTRUCTION_FAILED, { cause });
364
+ }
365
+ }
366
+
367
+ function buildUuidSlugCodec(
368
+ options: UuidV7MaskingCodecOptions,
369
+ generateBytes: (this: void, options?: GenerateUuidV7BytesOptions) => Uint8Array | UuidSlugError,
370
+ ): UuidV7MaskingCodec | UuidSlugError {
371
+ const validOptions = typeof options === "object" && options !== null && !Array.isArray(options);
372
+ const mask = validOptions ? options.mask : undefined;
373
+ const maskSeed = validOptions ? options.maskSeed : undefined;
374
+ // Both keys reach the same derivation, so accepting both would leave the writer mask ambiguous.
375
+ const hasMask = mask !== undefined && mask !== null;
376
+ const hasSeed = maskSeed !== undefined && maskSeed !== null;
377
+ if (hasMask === hasSeed)
378
+ return new UuidSlugError(
379
+ INVALID_MASK,
380
+ hasMask
381
+ ? "Pass maskSeed for private key material or mask for a derived mask, never both."
382
+ : "Pass { maskSeed } for private masking or { mask: UUID_V7_TEST_MASK } for public examples.",
383
+ );
384
+ const unknown = findUnknownOption(options, CODEC_OPTIONS);
385
+ if (unknown !== undefined)
386
+ return new UuidSlugError(INVALID_MASK, `Unknown UUIDv7 masking-codec option: ${unknown}.`);
387
+ const maskResult = maskFromOption(hasMask ? mask : { seed: maskSeed as string | Uint8Array });
388
+ if (isUuidSlugError(maskResult)) return maskResult;
389
+ const handle = maskResult;
390
+ const currentTimestampRangeStartResult = timestampRangeStart(
391
+ options.timestampRangeStartUnixMs,
392
+ "timestampRangeStartUnixMs",
393
+ );
394
+ if (typeof currentTimestampRangeStartResult !== "number") return currentTimestampRangeStartResult;
395
+ const currentTimestampRangeStart = currentTimestampRangeStartResult;
396
+ const current = { mask: handle, timestampRangeStartUnixMs: currentTimestampRangeStart };
397
+ // Decode tries exactly the caller's masks in order. Every added mask increases false
398
+ // acceptance, and the first passing mask decides the result, so no fallback is added here.
399
+ const previousMasks: { mask: UuidV7Mask; timestampRangeStartUnixMs: number }[] = [];
400
+ const previousMaskOptions = options.previousMasks ?? [];
401
+ if (!Array.isArray(previousMaskOptions))
402
+ return new UuidSlugError(
403
+ INVALID_MASK,
404
+ "previousMasks must be an array of masks, mask options, or retained mask-and-range objects.",
405
+ );
406
+ for (const previousOption of previousMaskOptions) {
407
+ const configured =
408
+ typeof previousOption === "object" &&
409
+ previousOption !== null &&
410
+ !isUuidSlugError(previousOption) &&
411
+ "mask" in previousOption;
412
+ if (configured) {
413
+ const unknownPrevious = findUnknownOption(previousOption, PREVIOUS_MASK_OPTIONS);
414
+ if (unknownPrevious !== undefined)
415
+ return new UuidSlugError(INVALID_MASK, `Unknown previous-mask option: ${unknownPrevious}.`);
416
+ }
417
+ const previous = maskFromOption(configured ? previousOption.mask : previousOption);
418
+ if (isUuidSlugError(previous)) return previous;
419
+ const start = timestampRangeStart(
420
+ configured ? previousOption.timestampRangeStartUnixMs : undefined,
421
+ "previousMasks[].timestampRangeStartUnixMs",
422
+ );
423
+ if (typeof start !== "number") return start;
424
+ previousMasks.push({ mask: previous, timestampRangeStartUnixMs: start });
425
+ }
426
+ const maskedSlugAlphabetResult = resolveSlugAlphabet(
427
+ options.maskedSlugAlphabet ?? BASE64URL_NAME,
428
+ );
429
+ if (maskedSlugAlphabetResult instanceof Error) return maskedSlugAlphabetResult;
430
+ const maskedSlugAlphabet = maskedSlugAlphabetResult.name as SlugAlphabet;
431
+ const sentinelDefinitions = options.sentinels ?? EMPTY_SENTINELS;
432
+ if (!Array.isArray(sentinelDefinitions))
433
+ return new UuidSlugError(
434
+ INVALID_SENTINEL,
435
+ "sentinels must be an array of named UUIDv7 values.",
436
+ );
437
+ const sentinelState =
438
+ sentinelDefinitions.length === 0
439
+ ? EMPTY_SENTINEL_STATE
440
+ : createSentinels(sentinelDefinitions, maskedSlugAlphabet);
441
+ if (sentinelState instanceof Error) return sentinelState;
442
+ const sentinels = sentinelState;
443
+ // Borrowed-byte encoding is synchronous. Built-in masks call no user code, and custom masks
444
+ // isolate callbacks with an input copy, so nested codec calls cannot observe this shared block.
445
+ const encodeScratch = new Uint8Array(16);
446
+
447
+ // Package-created decode failures are local Errors. A caller-owned cross-realm package error is
448
+ // the only failure arm that can bypass `instanceof`, and this function returns it unchanged;
449
+ // identity keeps marker recognition off successful conversion paths.
450
+ function decodeUuid(uuid: unknown): Uint8Array | UuidSlugError {
451
+ let text: string;
452
+ if (typeof uuid === "string") text = uuid;
453
+ else {
454
+ const input = readObjectUuidInput(uuid);
455
+ if (typeof input !== "string") return input;
456
+ text = input;
457
+ }
458
+ const sentinel = findSentinel(sentinels.bySlug, text)?.bytes;
459
+ if (sentinel) return sentinel;
460
+ if (text.length === 26) return decodePlainSlugToBytes(text);
461
+ if (text.length === 27) return unmaskSlug(text, current, previousMasks) ?? noMaskedSlugMatch();
462
+ if (text.length !== 22) return uuidStringToBytes(text);
463
+ // One masked base64url slug in 16 is also the canonical plain slug of a different UUID, so the
464
+ // codec's check is the only evidence of meaning: a slug that passes it under any configured
465
+ // mask is masked, and the plain reading is used only once every mask has rejected the text.
466
+ // Alphabet errors and mask-callback failures are returned as they are; only a failed check
467
+ // falls through to the plain reading.
468
+ const masked = unmaskSlug(text, current, previousMasks);
469
+ if (masked !== undefined) return masked;
470
+ const plain = decodePlainSlugToBytes(text);
471
+ return plain instanceof Error ? noMaskedSlugMatch() : plain;
472
+ }
473
+
474
+ function encodeMasked(
475
+ bytes: Uint8Array,
476
+ owned = false,
477
+ ): MaskedOrSentinelUuidV7Slug | UuidSlugError {
478
+ if (!isUuidV7Bytes(bytes))
479
+ return new UuidSlugError(INVALID_UUID_VERSION, INVALID_MASKED_UUID_BYTES);
480
+ if (sentinels.encodedByFingerprint) {
481
+ const first = sentinels.encoded[0] as EncodedSentinel;
482
+ let index = 0;
483
+ while (index < 16 && first.bytes[index] === bytes[index]) index += 1;
484
+ if (index === 16) return first.slug;
485
+ const sentinel = findIndexedByteSentinel(
486
+ sentinels.encoded,
487
+ sentinels.encodedByFingerprint,
488
+ bytes,
489
+ );
490
+ if (sentinel) return sentinel;
491
+ } else {
492
+ for (const sentinel of sentinels.encoded) {
493
+ let index = 0;
494
+ while (index < 16 && sentinel.bytes[index] === bytes[index]) index += 1;
495
+ if (index === 16) return sentinel.slug;
496
+ }
497
+ }
498
+ // Branch after common validation so ordinary callers retain one plain borrowed-byte route.
499
+ // Split guard helpers slowed that Bun route; reconsider only with packed mixed-workload evidence.
500
+ if (owned)
501
+ return ownedUuidV7BytesToMaskedSlug(
502
+ bytes,
503
+ handle,
504
+ maskedSlugAlphabet,
505
+ sentinels.bySlug,
506
+ currentTimestampRangeStart,
507
+ );
508
+ encodeScratch.set(bytes);
509
+ return ownedUuidV7BytesToMaskedSlug(
510
+ encodeScratch,
511
+ handle,
512
+ maskedSlugAlphabet,
513
+ sentinels.bySlug,
514
+ currentTimestampRangeStart,
515
+ );
516
+ }
517
+
518
+ function uuidToString<
519
+ Input extends UuidInput,
520
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
521
+ >(
522
+ uuid: Input,
523
+ ...textCase: UuidTextCaseArguments<Case>
524
+ ): UuidStringResult<MaskingCodecUuidInput<Input>, Case>;
525
+ function uuidToString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
526
+ uuid: Uint8Array,
527
+ byteOffset: number,
528
+ ...textCase: UuidTextCaseArguments<Case>
529
+ ): UuidStringResult<Uint8Array, Case>;
530
+ function uuidToString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
531
+ uuid: unknown,
532
+ byteOffsetOrCase: number | Case = UUID_TEXT_LOWERCASE as Case,
533
+ caseAfterOffset?: Case,
534
+ ): UuidStringFor<Case> | UuidSlugError {
535
+ // Bytes at an offset carry no masked spelling, so the keyless reader owns every offset read and
536
+ // its rejection of an offset beside another form. Zero is the spelling of "no offset", so it
537
+ // stays here: sending a masked slug to the keyless reader would spell out a different UUID.
538
+ let textCase: Case;
539
+ if (typeof byteOffsetOrCase === "number") {
540
+ if (isUint8Array(uuid) || byteOffsetOrCase !== 0)
541
+ // Public overloads require the non-default case; the implementation alone admits omission.
542
+ return keylessUuidToString(uuid as Uint8Array, byteOffsetOrCase, caseAfterOffset) as
543
+ | UuidStringFor<Case>
544
+ | UuidSlugError;
545
+ textCase = caseAfterOffset ?? (UUID_TEXT_LOWERCASE as Case);
546
+ } else textCase = byteOffsetOrCase;
547
+ const selectedCase = resolveUuidTextCase(textCase);
548
+ if (selectedCase instanceof Error) return selectedCase;
549
+ const localBytes = exactLocalUuidBytes(uuid);
550
+ if (localBytes)
551
+ return formatUuidBytesUnchecked(localBytes, 0, selectedCase) as UuidStringFor<Case>;
552
+ if (typeof uuid === "string") {
553
+ // Canonical lowercase text is already the default output. No sentinel slug is 36 characters
554
+ // long, so the length keeps the text pattern off the sentinel lookup. This branch grows the
555
+ // function past the size JavaScriptCore inlines into a small caller, which costs Bun sentinel
556
+ // reads a few nanoseconds; moving it into a helper cost more because Bun did not inline the
557
+ // helper either. Recheck `sentinel.base32.decode` on Bun when this function changes
558
+ // (bench/decisions.md).
559
+ if (uuid.length === 36) {
560
+ if (selectedCase === UUID_TEXT_LOWERCASE && isUuidString(uuid))
561
+ return uuid as UuidStringFor<Case>;
562
+ } else {
563
+ const sentinel = findSentinel(sentinels.bySlug, uuid);
564
+ if (sentinel)
565
+ return (
566
+ selectedCase === UUID_TEXT_LOWERCASE
567
+ ? sentinel.uuid
568
+ : formatUuidBytesUnchecked(sentinel.bytes, 0, selectedCase)
569
+ ) as UuidStringFor<Case>;
570
+ }
571
+ }
572
+ const bytes = decodeUuid(uuid);
573
+ if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
574
+ return formatUuidBytesUnchecked(bytes, 0, selectedCase) as UuidStringFor<Case>;
575
+ }
576
+
577
+ function uuidToBytes<Input extends UuidInput>(
578
+ uuid: Input,
579
+ ): UuidBytesResult<MaskingCodecUuidInput<Input>>;
580
+ function uuidToBytes<Output extends Uint8Array>(
581
+ uuid: UuidInput,
582
+ output: Output,
583
+ outputOffset?: number,
584
+ ): UuidOutput<Output> | UuidSlugError;
585
+ function uuidToBytes(uuid: Uint8Array, byteOffset: number): UuidBytesResult<Uint8Array>;
586
+ function uuidToBytes<Output extends Uint8Array>(
587
+ uuid: Uint8Array,
588
+ byteOffset: number,
589
+ output: Output,
590
+ outputOffset?: number,
591
+ ): UuidOutput<Output> | UuidSlugError;
592
+ function uuidToBytes(
593
+ uuid: unknown,
594
+ outputOrByteOffset?: unknown,
595
+ outputOrOutputOffset?: unknown,
596
+ offsetAfterOutput = 0,
597
+ ): UuidBytes | Uint8Array | UuidSlugError {
598
+ // Bytes at an offset carry no masked spelling, so the keyless reader owns every offset read and
599
+ // its rejection of an offset beside another form. Zero is the spelling of "no offset", so it
600
+ // stays here: sending a masked slug to the keyless reader would decode a different UUID.
601
+ const readsAtOffset = typeof outputOrByteOffset === "number";
602
+ if (readsAtOffset && (isUint8Array(uuid) || outputOrByteOffset !== 0))
603
+ return outputOrOutputOffset === undefined
604
+ ? keylessUuidToBytes(uuid as Uint8Array, outputOrByteOffset)
605
+ : keylessUuidToBytes(
606
+ uuid as Uint8Array,
607
+ outputOrByteOffset,
608
+ outputOrOutputOffset as Uint8Array,
609
+ offsetAfterOutput,
610
+ );
611
+ const output = readsAtOffset ? outputOrOutputOffset : outputOrByteOffset;
612
+ const outputOffset = readsAtOffset
613
+ ? offsetAfterOutput
614
+ : ((outputOrOutputOffset as number | undefined) ?? 0);
615
+ const badRange = output === undefined ? undefined : checkByteRange(output, outputOffset, 16);
616
+ if (badRange) return badRange;
617
+ const destination = output as Uint8Array | undefined;
618
+ const localBytes = exactLocalUuidBytes(uuid);
619
+ if (localBytes) {
620
+ if (destination) {
621
+ destination.set(localBytes, outputOffset);
622
+ return destination;
623
+ }
624
+ return new Uint8Array(localBytes);
625
+ }
626
+ const bytes = decodeUuid(uuid);
627
+ if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
628
+ if (destination) {
629
+ destination.set(bytes, outputOffset);
630
+ return destination;
631
+ }
632
+ return new Uint8Array(bytes);
633
+ }
634
+
635
+ function uuidToPlainSlug<Input extends UuidInput>(
636
+ uuid: Input,
637
+ alphabet?: SlugAlphabet,
638
+ ): PlainUuidSlugResult<MaskingCodecUuidInput<Input>>;
639
+ function uuidToPlainSlug(
640
+ uuid: Uint8Array,
641
+ byteOffset: number,
642
+ alphabet?: SlugAlphabet,
643
+ ): PlainUuidSlugResult<Uint8Array>;
644
+ function uuidToPlainSlug(
645
+ uuid: unknown,
646
+ byteOffsetOrAlphabet: number | SlugAlphabet = BASE64URL_NAME,
647
+ alphabetAfterOffset?: SlugAlphabet,
648
+ ): PlainUuidSlug | UuidSlugError {
649
+ // Bytes at an offset carry no masked spelling, so the keyless reader owns every offset read and
650
+ // its rejection of an offset beside another form. Zero is the spelling of "no offset", so it
651
+ // stays here: sending a masked slug to the keyless reader would return it unchanged as plain.
652
+ let alphabet: SlugAlphabet;
653
+ if (typeof byteOffsetOrAlphabet === "number") {
654
+ if (isUint8Array(uuid) || byteOffsetOrAlphabet !== 0)
655
+ return keylessUuidToPlainSlug(
656
+ uuid as Uint8Array,
657
+ byteOffsetOrAlphabet,
658
+ alphabetAfterOffset,
659
+ );
660
+ alphabet = alphabetAfterOffset ?? BASE64URL_NAME;
661
+ } else alphabet = byteOffsetOrAlphabet;
662
+ const localBytes = exactLocalUuidBytes(uuid);
663
+ if (localBytes) return uuidBytesToPlainSlug(localBytes, alphabet);
664
+ const bytes = decodeUuid(uuid);
665
+ if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
666
+ return uuidBytesToPlainSlug(bytes, alphabet);
667
+ }
668
+
669
+ function uuidToMaskedSlug(uuid: unknown): MaskedOrSentinelUuidV7Slug | UuidSlugError {
670
+ // UUID text lengths cannot be slugs. Parse into private scratch to avoid an allocation and
671
+ // copy; encodeMasked recognizes sentinels before mutation and custom masks isolate callbacks.
672
+ // Borrowed bytes retain the copy below. Remeasure complete calls if parsing or masking changes.
673
+ if (typeof uuid === "string" && (uuid.length === 36 || uuid.length === 32)) {
674
+ const bytes = uuidStringToBytes(uuid, encodeScratch);
675
+ return bytes instanceof Error ? bytes : encodeMasked(encodeScratch, true);
676
+ }
677
+ const localBytes = exactLocalUuidBytes(uuid);
678
+ if (localBytes) return encodeMasked(localBytes);
679
+ const bytes = decodeUuid(uuid);
680
+ if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
681
+ return encodeMasked(bytes);
682
+ }
683
+
684
+ function plainToMaskedUuidSlug(
685
+ plainUuidSlug: string | UuidSlugError,
686
+ ): MaskedOrSentinelUuidV7Slug | UuidSlugError {
687
+ const slug = normalizeUuidSlugInput(plainUuidSlug);
688
+ if (typeof slug !== "string") return slug;
689
+ const bytes = decodePlainSlugToBytes(slug, encodeScratch);
690
+ return bytes instanceof Error ? bytes : encodeMasked(encodeScratch, true);
691
+ }
692
+
693
+ function maskedSlugToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
694
+ maskedUuidSlug: string | UuidSlugError,
695
+ ...textCase: UuidTextCaseArguments<Case>
696
+ ): UuidV7StringFor<Case> | UuidSlugError;
697
+ function maskedSlugToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
698
+ maskedUuidSlug: string | UuidSlugError,
699
+ textCase: Case = UUID_TEXT_LOWERCASE as Case,
700
+ ): UuidV7StringFor<Case> | UuidSlugError {
701
+ const slug = normalizeUuidSlugInput(maskedUuidSlug);
702
+ if (typeof slug !== "string") return slug;
703
+ const selectedCase = resolveUuidTextCase(textCase);
704
+ if (selectedCase instanceof Error) return selectedCase;
705
+ const sentinel = findSentinel(sentinels.bySlug, slug);
706
+ if (sentinel)
707
+ return (
708
+ selectedCase === UUID_TEXT_LOWERCASE
709
+ ? sentinel.uuid
710
+ : formatUuidBytesUnchecked(sentinel.bytes, 0, selectedCase)
711
+ ) as UuidV7StringFor<Case>;
712
+ const decoded = unmaskSlug(slug, current, previousMasks) ?? noMaskedSlugMatch();
713
+ if (decoded instanceof Error) return decoded;
714
+ return formatUuidBytesUnchecked(decoded, 0, selectedCase) as UuidV7StringFor<Case>;
715
+ }
716
+
717
+ function maskedSlugToUuidBytes(
718
+ maskedUuidSlug: string | UuidSlugError,
719
+ ): UuidV7Bytes | UuidSlugError;
720
+ function maskedSlugToUuidBytes<Output extends Uint8Array>(
721
+ maskedUuidSlug: string | UuidSlugError,
722
+ output: Output,
723
+ outputOffset?: number,
724
+ ): UuidOutput<Output> | UuidSlugError;
725
+ function maskedSlugToUuidBytes(
726
+ maskedUuidSlug: string | UuidSlugError,
727
+ output?: Uint8Array,
728
+ outputOffset = 0,
729
+ ): Uint8Array | UuidSlugError {
730
+ const slug = normalizeUuidSlugInput(maskedUuidSlug);
731
+ if (typeof slug !== "string") return slug;
732
+ const badRange = output === undefined ? undefined : checkByteRange(output, outputOffset, 16);
733
+ if (badRange) return badRange;
734
+ const sentinelBytes = findSentinel(sentinels.bySlug, slug)?.bytes;
735
+ const decoded =
736
+ sentinelBytes ?? unmaskSlug(slug, current, previousMasks) ?? noMaskedSlugMatch();
737
+ if (decoded instanceof Error) return decoded;
738
+ if (output) {
739
+ output.set(decoded, outputOffset);
740
+ return output;
741
+ }
742
+ return sentinelBytes ? new Uint8Array(sentinelBytes) : decoded;
743
+ }
744
+
745
+ function generateCodecBytesFromValues(values: {
746
+ readonly at?: unknown;
747
+ readonly generator?: unknown;
748
+ }): UuidV7Bytes | UuidSlugError {
749
+ const generator = readUuidV7Generator(values.generator);
750
+ if (generator instanceof Error) return generator;
751
+ try {
752
+ const bytes = generator
753
+ ? generateUuidV7BytesWithGenerator(generator, values, true)
754
+ : Object.hasOwn(values, AT_OPTION)
755
+ ? generateBytes({ at: values.at as UuidV7Instant })
756
+ : generateBytes();
757
+ if (!isUint8Array(bytes) || !isUuidV7Bytes(bytes))
758
+ return isUuidSlugError(bytes) ? bytes : invalidGeneratedUuidV7Bytes(bytes);
759
+ return bytes;
760
+ } catch (cause) {
761
+ return new UuidSlugError(RNG_UNAVAILABLE, UUID_V7_GENERATION_FAILED, { cause });
762
+ }
763
+ }
764
+
765
+ function generateCodecBytes(generationOptions?: unknown): UuidV7Bytes | UuidSlugError {
766
+ const values = readUuidV7ValueOptions(generationOptions, UUID_V7_MASKING_CODEC_VALUE_OPTIONS);
767
+ return values instanceof Error ? values : generateCodecBytesFromValues(values);
768
+ }
769
+
770
+ function generateMaskedUuidV7Slug(
771
+ generationOptions?: UuidV7MaskingCodecValueOptions,
772
+ ): MaskedOrSentinelUuidV7Slug | UuidSlugError {
773
+ const bytes = generateCodecBytes(generationOptions);
774
+ return isUuidSlugError(bytes) ? bytes : encodeMasked(bytes, true);
775
+ }
776
+
777
+ function maskedToPlainUuidSlug(
778
+ maskedUuidSlug: string | UuidSlugError,
779
+ alphabet: SlugAlphabet = BASE64URL_NAME,
780
+ ): PlainUuidV7Slug | UuidSlugError {
781
+ const bytes = maskedSlugToUuidBytes(maskedUuidSlug, encodeScratch);
782
+ if (isUuidSlugError(bytes)) return bytes;
783
+ return uuidBytesToPlainSlug(encodeScratch, alphabet) as PlainUuidV7Slug | UuidSlugError;
784
+ }
785
+
786
+ function generateUuidV7WithMaskedSlug<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
787
+ ...textCase: UuidTextCaseArguments<Case>
788
+ ): GeneratedUuidV7<MaskedOrSentinelUuidV7Slug, Case> | UuidSlugError;
789
+ function generateUuidV7WithMaskedSlug<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
790
+ options: GenerateUuidV7WithMaskedSlugOptions<Case>,
791
+ ): GeneratedUuidV7<MaskedOrSentinelUuidV7Slug, Case> | UuidSlugError;
792
+ function generateUuidV7WithMaskedSlug<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
793
+ textCaseOrOptions:
794
+ | Case
795
+ | GenerateUuidV7WithMaskedSlugOptions<Case> = UUID_TEXT_LOWERCASE as Case,
796
+ ): GeneratedUuidV7<MaskedOrSentinelUuidV7Slug, Case> | UuidSlugError {
797
+ let directTextCase = typeof textCaseOrOptions === "string";
798
+ let values =
799
+ typeof textCaseOrOptions === "string"
800
+ ? { textCase: textCaseOrOptions }
801
+ : readGenerationOptions(
802
+ textCaseOrOptions,
803
+ MASKED_PAIR_GENERATION_OPTIONS,
804
+ "masked UUIDv7 pair generation",
805
+ );
806
+ if (values instanceof Error) {
807
+ const wrappedCase = stringInput(textCaseOrOptions);
808
+ if (wrappedCase !== undefined) {
809
+ directTextCase = true;
810
+ values = { textCase: wrappedCase };
811
+ }
812
+ }
813
+ if (values instanceof Error) return values;
814
+ const textCase = resolveUuidTextCase(values.textCase ?? UUID_TEXT_LOWERCASE);
815
+ if (textCase instanceof Error) return textCase;
816
+ const bytes = directTextCase ? generateCodecBytes() : generateCodecBytesFromValues(values);
817
+ // Supplied generators can return recognized failures without local Error identity.
818
+ if (!isSuccessfulUuidBytes(bytes)) return bytes;
819
+ const uuid = formatUuidBytesUnchecked(bytes, 0, textCase) as UuidV7StringFor<Case>;
820
+ const slug = encodeMasked(bytes, true);
821
+ return slug instanceof Error ? slug : { uuid, slug };
822
+ }
823
+
824
+ function extractMaskedUuidV7UnixMs(
825
+ maskedUuidSlug: string | UuidSlugError,
826
+ ): number | UuidSlugError {
827
+ const slug = normalizeUuidSlugInput(maskedUuidSlug);
828
+ if (typeof slug !== "string") return slug;
829
+ const bytes =
830
+ findSentinel(sentinels.bySlug, slug)?.bytes ??
831
+ unmaskSlug(slug, current, previousMasks) ??
832
+ noMaskedSlugMatch();
833
+ return bytes instanceof Error ? bytes : extractUuidV7UnixMs(bytes);
834
+ }
835
+
836
+ function extractMaskedUuidV7Payload(
837
+ maskedUuidSlug: string | UuidSlugError,
838
+ layout: UuidV7PayloadLayout,
839
+ ): UuidV7Payload | UuidSlugError {
840
+ const slug = normalizeUuidSlugInput(maskedUuidSlug);
841
+ if (typeof slug !== "string") return slug;
842
+ const bytes =
843
+ findSentinel(sentinels.bySlug, slug)?.bytes ??
844
+ unmaskSlug(slug, current, previousMasks) ??
845
+ noMaskedSlugMatch();
846
+ return bytes instanceof Error ? bytes : extractUuidV7Payload(bytes, layout);
847
+ }
848
+
849
+ function createUuidSlugMigrationDecoder(
850
+ migrationOptions?: undefined,
851
+ ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
852
+ // Structural typing permits extra keys and accessors; createMigration can reject either even
853
+ // when boolean fields type-check. Only omission removes that configuration failure boundary.
854
+ function createUuidSlugMigrationDecoder<const Options extends UuidSlugMigrationOptions>(
855
+ migrationOptions: Options | undefined,
856
+ ): UuidSlugMigrationDecoder<EnabledMigrationFormat<Options>> | UuidSlugError;
857
+ function createUuidSlugMigrationDecoder(
858
+ migrationOptions?: UuidSlugMigrationOptions,
859
+ ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT> | UuidSlugError {
860
+ return createMigration([current, ...previousMasks], sentinels.bySlug, migrationOptions);
861
+ }
862
+
863
+ function validateMaskedUuidV7SlugUnixMs<Input extends string | UuidSlugError>(
864
+ maskedUuidSlug: Input,
865
+ window: UuidV7TimestampWindow,
866
+ ):
867
+ | (Input extends PlainUuidSlug | MaskedOrSentinelUuidV7Slug
868
+ ? Input & MaskedOrSentinelUuidV7Slug
869
+ : MaskedOrSentinelUuidV7Slug)
870
+ | UuidSlugError;
871
+ function validateMaskedUuidV7SlugUnixMs(
872
+ maskedUuidSlug: unknown,
873
+ window: UuidV7TimestampWindow,
874
+ ): MaskedOrSentinelUuidV7Slug | UuidSlugError {
875
+ const slug = normalizeUuidSlugInput(maskedUuidSlug);
876
+ if (typeof slug !== "string") return slug;
877
+ const sentinel = findSentinel(sentinels.bySlug, slug);
878
+ const bytes =
879
+ sentinel?.bytes ?? unmaskSlug(slug, current, previousMasks) ?? noMaskedSlugMatch();
880
+ if (bytes instanceof Error) return bytes;
881
+ const valid = validateTimestampBytes(bytes, window);
882
+ if (valid instanceof Error) return valid;
883
+ // The matched sentinel owns its canonical spelling in the input alphabet. Masked base32
884
+ // needs folding; re-encoding would repeat masking and change the selected spelling.
885
+ return (sentinel?.slug ??
886
+ (slug.length === 22 ? slug : slug.toLowerCase())) as MaskedOrSentinelUuidV7Slug;
887
+ }
888
+
889
+ function generateUuidV7Value(valueOptions?: UuidV7MaskingCodecValueOptions) {
890
+ const values = readUuidV7ValueOptions(valueOptions, UUID_V7_MASKING_CODEC_VALUE_OPTIONS);
891
+ if (values instanceof Error) return values;
892
+ const generator = readUuidV7Generator(values.generator);
893
+ if (generator instanceof Error) return generator;
894
+ if (generator) return generateUuidV7ValueWithGenerator(generator, values, maskingCodec);
895
+ const generated = !Object.hasOwn(values, AT_OPTION)
896
+ ? generateDefaultUuidV7Bytes()
897
+ : generateDefaultUuidV7Bytes({ at: values.at as UuidV7Instant });
898
+ return generated instanceof Error
899
+ ? generated
900
+ : createUuidValue<7, true, true>(generated, maskingCodec, uuidV7DefaultPayloadLayout());
901
+ }
902
+
903
+ const maskingCodec: UuidV7MaskingCodec = {
904
+ sentinels: sentinels.sentinels,
905
+ generateUuidV7Value,
906
+ parseUuid: (uuid) => parseUuidWithCodec(uuid, maskingCodec),
907
+ uuidToString,
908
+ uuidToBytes,
909
+ uuidToPlainSlug,
910
+ createUuidSlugMigrationDecoder,
911
+ generateMaskedUuidV7Slug,
912
+ generateUuidV7WithMaskedSlug,
913
+ uuidToMaskedSlug,
914
+ plainToMaskedUuidSlug,
915
+ maskedToPlainUuidSlug,
916
+ maskedSlugToUuidString,
917
+ maskedSlugToUuidBytes,
918
+ extractMaskedUuidV7UnixMs,
919
+ extractMaskedUuidV7Payload,
920
+ validateMaskedUuidV7SlugUnixMs,
921
+ };
922
+ return Object.freeze(registerMaskingCodec(maskingCodec));
923
+ }