@anizoptera/uuid-slug 0.2.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.
@@ -0,0 +1,647 @@
1
+ import crypto from "node:crypto";
2
+ //#region src/errors.ts
3
+ var UuidSlugError = class extends Error {
4
+ code;
5
+ constructor(code, message, options) {
6
+ super(message, options);
7
+ this.name = "UuidSlugError";
8
+ this.code = code;
9
+ }
10
+ };
11
+ var UuidRuntimeError = class extends UuidSlugError {
12
+ constructor(message, options) {
13
+ super("rng_unavailable", message, options);
14
+ this.name = "UuidRuntimeError";
15
+ }
16
+ };
17
+ //#endregion
18
+ //#region src/base64url.ts
19
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
20
+ const DECODE = (/* @__PURE__ */ new Int16Array(128)).fill(-1);
21
+ for (let i = 0; i < 64; i += 1) DECODE[ALPHABET.charCodeAt(i)] = i;
22
+ function byteAt(bytes, index) {
23
+ return bytes[index] ?? 0;
24
+ }
25
+ function encodeBase64Url(bytes) {
26
+ let out = "";
27
+ let i = 0;
28
+ for (; i + 2 < bytes.length; i += 3) {
29
+ const value = byteAt(bytes, i) << 16 | byteAt(bytes, i + 1) << 8 | byteAt(bytes, i + 2);
30
+ out += ALPHABET[value >>> 18 & 63];
31
+ out += ALPHABET[value >>> 12 & 63];
32
+ out += ALPHABET[value >>> 6 & 63];
33
+ out += ALPHABET[value & 63];
34
+ }
35
+ const remaining = bytes.length - i;
36
+ if (remaining === 1) {
37
+ const value = byteAt(bytes, i) << 16;
38
+ out += ALPHABET[value >>> 18 & 63];
39
+ out += ALPHABET[value >>> 12 & 63];
40
+ }
41
+ if (remaining === 2) {
42
+ const value = byteAt(bytes, i) << 16 | byteAt(bytes, i + 1) << 8;
43
+ out += ALPHABET[value >>> 18 & 63];
44
+ out += ALPHABET[value >>> 12 & 63];
45
+ out += ALPHABET[value >>> 6 & 63];
46
+ }
47
+ return out;
48
+ }
49
+ function decodeBase64Url(value, out, offset = 0) {
50
+ if (value.includes("=")) return new UuidSlugError("invalid_base64url", "Base64url value must be unpadded.");
51
+ if (value.length % 4 === 1) return new UuidSlugError("invalid_base64url", "Base64url length is impossible.");
52
+ const byteLength = Math.floor(value.length * 6 / 8);
53
+ const target = out ?? new Uint8Array(byteLength);
54
+ if (offset < 0 || offset + byteLength > target.length) return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
55
+ let buffer = 0;
56
+ let bits = 0;
57
+ let written = 0;
58
+ for (let i = 0; i < value.length; i += 1) {
59
+ const code = value.charCodeAt(i);
60
+ const decoded = code < DECODE.length ? DECODE[code] ?? -1 : -1;
61
+ if (decoded < 0) return new UuidSlugError("invalid_base64url", `Invalid base64url character at offset ${i}.`);
62
+ buffer = buffer << 6 | decoded;
63
+ bits += 6;
64
+ if (bits >= 8) {
65
+ bits -= 8;
66
+ target[offset + written] = buffer >>> bits & 255;
67
+ written += 1;
68
+ }
69
+ }
70
+ if (bits > 0 && (buffer & (1 << bits) - 1) !== 0) return new UuidSlugError("invalid_base64url", "Base64url value has non-canonical trailing bits.");
71
+ return out ? target : target.subarray(0, byteLength);
72
+ }
73
+ function isBase64Url(value) {
74
+ if (!value || value.includes("=") || value.length % 4 === 1) return false;
75
+ return decodeBase64Url(value) instanceof Error ? false : true;
76
+ }
77
+ //#endregion
78
+ //#region src/runtime/node.ts
79
+ const cryptoWithV7 = crypto;
80
+ const runtime = {
81
+ fillRandom(bytes) {
82
+ bytes.set(crypto.randomBytes(bytes.length));
83
+ },
84
+ uuidV4() {
85
+ return crypto.randomUUID();
86
+ },
87
+ uuidV7() {
88
+ if (!cryptoWithV7.randomUUIDv7) throw new UuidRuntimeError("Node crypto.randomUUIDv7 is unavailable.");
89
+ return cryptoWithV7.randomUUIDv7();
90
+ }
91
+ };
92
+ //#endregion
93
+ //#region src/uuid.ts
94
+ const HEX = "0123456789abcdef";
95
+ const HEX_DECODE = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
96
+ for (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;
97
+ for (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;
98
+ const UUID_LENGTH = 36;
99
+ const SLUG_LENGTH = 22;
100
+ const UUID_BYTE_OFFSETS = [
101
+ 0,
102
+ 2,
103
+ 4,
104
+ 6,
105
+ 9,
106
+ 11,
107
+ 14,
108
+ 16,
109
+ 19,
110
+ 21,
111
+ 24,
112
+ 26,
113
+ 28,
114
+ 30,
115
+ 32,
116
+ 34
117
+ ];
118
+ function hexValue(code) {
119
+ return code < HEX_DECODE.length ? HEX_DECODE[code] : -1;
120
+ }
121
+ function parseUuid(uuid, out, offset = 0) {
122
+ if (uuid.length !== UUID_LENGTH) return new UuidSlugError("invalid_uuid", "UUID must be 36 characters.");
123
+ if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return new UuidSlugError("invalid_uuid", "UUID hyphen positions are invalid.");
124
+ const target = out ?? /* @__PURE__ */ new Uint8Array(16);
125
+ if (offset < 0 || offset + 16 > target.length) return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
126
+ for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {
127
+ const textOffset = UUID_BYTE_OFFSETS[byteIndex] ?? 0;
128
+ const high = hexValue(uuid.charCodeAt(textOffset)) ?? -1;
129
+ const low = hexValue(uuid.charCodeAt(textOffset + 1)) ?? -1;
130
+ if (high < 0 || low < 0) return new UuidSlugError("invalid_uuid", `Invalid UUID hex at offset ${textOffset}.`);
131
+ target[offset + byteIndex] = high << 4 | low;
132
+ }
133
+ return target;
134
+ }
135
+ function formatUuid(bytes, offset = 0) {
136
+ if (offset < 0 || offset + 16 > bytes.length) return new UuidSlugError("invalid_buffer", "UUID byte buffer is too small.");
137
+ let out = "";
138
+ for (let i = 0; i < 16; i += 1) {
139
+ if (i === 4 || i === 6 || i === 8 || i === 10) out += "-";
140
+ const byte = bytes[offset + i] ?? 0;
141
+ out += HEX[byte >>> 4];
142
+ out += HEX[byte & 15];
143
+ }
144
+ return out;
145
+ }
146
+ function uuidVersion(bytes, offset = 0) {
147
+ return (bytes[offset + 6] ?? 0) >>> 4;
148
+ }
149
+ function isRfcVariant(bytes, offset = 0) {
150
+ return (bytes[offset + 8] ?? 0) >>> 6 === 2;
151
+ }
152
+ function isUuidString(uuid) {
153
+ if (!uuid) return false;
154
+ return parseUuid(uuid) instanceof Error ? false : true;
155
+ }
156
+ function isUuidV4String(uuid) {
157
+ if (!uuid) return false;
158
+ const bytes = parseUuid(uuid);
159
+ return bytes instanceof Error ? false : uuidVersion(bytes) === 4 && isRfcVariant(bytes);
160
+ }
161
+ function isUuidV7String(uuid) {
162
+ if (!uuid) return false;
163
+ const bytes = parseUuid(uuid);
164
+ return bytes instanceof Error ? false : uuidVersion(bytes) === 7 && isRfcVariant(bytes);
165
+ }
166
+ function isUuidV7Bytes(bytes) {
167
+ return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);
168
+ }
169
+ function uuidBytesToSlug(bytes, offset = 0) {
170
+ if (offset < 0 || offset + 16 > bytes.length) return new UuidSlugError("invalid_buffer", "UUID byte buffer is too small.");
171
+ return encodeBase64Url(bytes.subarray(offset, offset + 16));
172
+ }
173
+ function slugToUuidBytes(slug, out, offset = 0) {
174
+ if (slug.length !== SLUG_LENGTH) return new UuidSlugError("invalid_uuid_slug", "UUID slug must be 22 characters.");
175
+ return decodeBase64Url(slug, out, offset);
176
+ }
177
+ function uuidToSlug(uuid) {
178
+ const bytes = parseUuid(uuid);
179
+ if (bytes instanceof Error) return bytes;
180
+ return uuidBytesToSlug(bytes);
181
+ }
182
+ function slugToUuid(slug) {
183
+ const bytes = slugToUuidBytes(slug);
184
+ if (bytes instanceof Error) return bytes;
185
+ return formatUuid(bytes);
186
+ }
187
+ function formatUuidSlug(bytes, offset = 0) {
188
+ return uuidBytesToSlug(bytes, offset);
189
+ }
190
+ function parseUuidSlug(slug, out, offset = 0) {
191
+ return slugToUuidBytes(slug, out, offset);
192
+ }
193
+ function isUuidSlug(slug) {
194
+ if (!slug || slug.length !== SLUG_LENGTH) return false;
195
+ return slugToUuidBytes(slug) instanceof Error ? false : true;
196
+ }
197
+ function isUuidV4Slug(slug) {
198
+ if (!slug) return false;
199
+ const bytes = slugToUuidBytes(slug);
200
+ return bytes instanceof Error ? false : uuidVersion(bytes) === 4 && isRfcVariant(bytes);
201
+ }
202
+ function isUuidV7Slug(slug) {
203
+ if (!slug) return false;
204
+ const bytes = slugToUuidBytes(slug);
205
+ return bytes instanceof Error ? false : uuidVersion(bytes) === 7 && isRfcVariant(bytes);
206
+ }
207
+ function extractUuidV7Timestamp(bytes, offset = 0) {
208
+ let timestamp = 0;
209
+ for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);
210
+ return timestamp;
211
+ }
212
+ function hasUuidV7Entropy(bytes, offset = 0) {
213
+ const randA = ((bytes[offset + 6] ?? 0) & 15) << 8 | (bytes[offset + 7] ?? 0);
214
+ const randBFirst = (bytes[offset + 8] ?? 0) & 63;
215
+ let restZero = true;
216
+ let restMax = true;
217
+ for (let i = 9; i < 16; i += 1) {
218
+ const byte = bytes[offset + i] ?? 0;
219
+ if (byte !== 0) restZero = false;
220
+ if (byte !== 255) restMax = false;
221
+ }
222
+ return !(randA === 0 && randBFirst === 0 && restZero) && !(randA === 4095 && randBFirst === 63 && restMax);
223
+ }
224
+ //#endregion
225
+ //#region src/mask.ts
226
+ function checksum4(bytes) {
227
+ let acc = 0;
228
+ for (const byte of bytes) acc ^= byte;
229
+ return acc >>> 4 ^ acc & 15;
230
+ }
231
+ function checksum6(bytes) {
232
+ let acc = 0;
233
+ for (let i = 0; i < bytes.length; i += 1) acc = acc + (bytes[i] ?? 0) * (i + 17) & 255;
234
+ return (acc >>> 2 ^ acc) & 63;
235
+ }
236
+ function tagFor(bytes, tagBits) {
237
+ return tagBits === 4 ? checksum4(bytes) : checksum6(bytes);
238
+ }
239
+ function injectTag(bytes, tag, tagBits) {
240
+ bytes[6] = (tag & 15) << 4 | (bytes[6] ?? 0) & 15;
241
+ if (tagBits === 6) bytes[8] = (tag & 48) << 2 | (bytes[8] ?? 0) & 63;
242
+ }
243
+ function extractTag(bytes, tagBits) {
244
+ const versionBits = (bytes[6] ?? 0) >>> 4;
245
+ if (tagBits === 4) return versionBits;
246
+ return versionBits | (bytes[8] ?? 0) >>> 6 << 4;
247
+ }
248
+ function restoreV7(bytes, tagBits) {
249
+ bytes[6] = (bytes[6] ?? 0) & 15 | 112;
250
+ if (tagBits === 6) bytes[8] = (bytes[8] ?? 0) & 63 | 128;
251
+ }
252
+ function uuidToMaskedSlugWithSchema(uuid, schema) {
253
+ const raw = parseUuid(uuid);
254
+ if (raw instanceof Error) return raw;
255
+ if (uuidVersion(raw) !== 7 || !isRfcVariant(raw)) return new UuidSlugError("invalid_uuid_version", "Masked UUID slugs currently require UUIDv7.");
256
+ return uuidV7BytesToMaskedSlug(raw, schema);
257
+ }
258
+ function uuidV7BytesToMaskedSlug(raw, schema) {
259
+ const tagged = new Uint8Array(raw);
260
+ injectTag(tagged, tagFor(raw, schema.tagBits), schema.tagBits);
261
+ const mixed = /* @__PURE__ */ new Uint8Array(16);
262
+ for (let i = 0; i < 16; i += 1) mixed[i] = (tagged[schema.permute[i] ?? 0] ?? 0) ^ (schema.xor[i] ?? 0);
263
+ const slug = uuidBytesToSlug(mixed);
264
+ return slug instanceof Error ? slug : slug;
265
+ }
266
+ function maskedSlugToUuidWithSchema(slug, schema) {
267
+ const mixed = slugToUuidBytes(slug);
268
+ if (mixed instanceof Error) return mixed;
269
+ const unmixed = /* @__PURE__ */ new Uint8Array(16);
270
+ for (let i = 0; i < 16; i += 1) {
271
+ const source = schema.inverse[i] ?? 0;
272
+ unmixed[i] = (mixed[source] ?? 0) ^ (schema.xor[source] ?? 0);
273
+ }
274
+ const foundTag = extractTag(unmixed, schema.tagBits);
275
+ restoreV7(unmixed, schema.tagBits);
276
+ if (tagFor(unmixed, schema.tagBits) !== foundTag) return new UuidSlugError("invalid_uuid_slug", "Masked UUID slug failed schema validation.");
277
+ return formatUuid(unmixed);
278
+ }
279
+ //#endregion
280
+ //#region src/schema.ts
281
+ const LEGACY_PERMUTE = Uint8Array.from([
282
+ 9,
283
+ 13,
284
+ 3,
285
+ 8,
286
+ 14,
287
+ 0,
288
+ 11,
289
+ 7,
290
+ 6,
291
+ 1,
292
+ 15,
293
+ 4,
294
+ 2,
295
+ 5,
296
+ 10,
297
+ 12
298
+ ]);
299
+ const LEGACY_XOR = Uint8Array.from([
300
+ 162,
301
+ 112,
302
+ 50,
303
+ 127,
304
+ 152,
305
+ 184,
306
+ 155,
307
+ 94,
308
+ 27,
309
+ 38,
310
+ 182,
311
+ 22,
312
+ 150,
313
+ 249,
314
+ 234,
315
+ 62
316
+ ]);
317
+ function clone16(bytes, name) {
318
+ if (bytes.length !== 16) return new UuidSlugError("invalid_mask_schema", `${name} must contain exactly 16 bytes.`);
319
+ return new Uint8Array(bytes);
320
+ }
321
+ function inversePermutation(permute) {
322
+ if (permute.length !== 16) return new UuidSlugError("invalid_mask_schema", "Permutation must contain exactly 16 bytes.");
323
+ const seen = /* @__PURE__ */ new Uint8Array(16);
324
+ const inverse = /* @__PURE__ */ new Uint8Array(16);
325
+ for (let i = 0; i < 16; i += 1) {
326
+ const value = permute[i] ?? 255;
327
+ if (value > 15 || seen[value] === 1) return new UuidSlugError("invalid_mask_schema", "Permutation must be a bijection over 0..15.");
328
+ seen[value] = 1;
329
+ inverse[value] = i;
330
+ }
331
+ return inverse;
332
+ }
333
+ function fnv1a64(data) {
334
+ let hash = 14695981039346656037n;
335
+ for (const byte of data) {
336
+ hash ^= BigInt(byte);
337
+ hash = BigInt.asUintN(64, hash * 1099511628211n);
338
+ }
339
+ return hash;
340
+ }
341
+ function seedBytes(seed) {
342
+ if (typeof seed !== "string") return new Uint8Array(seed);
343
+ return new TextEncoder().encode(seed);
344
+ }
345
+ function next64(state) {
346
+ state.value ^= state.value << 13n;
347
+ state.value ^= state.value >> 7n;
348
+ state.value ^= state.value << 17n;
349
+ state.value = BigInt.asUintN(64, state.value);
350
+ return state.value;
351
+ }
352
+ function derivedBytes(seed, purpose, length) {
353
+ const state = { value: fnv1a64(Uint8Array.from([...seed, purpose])) || 11400714819323198485n };
354
+ const out = new Uint8Array(length);
355
+ for (let i = 0; i < length; i += 1) out[i] = Number(next64(state) >> BigInt(i % 8 * 8) & 255n);
356
+ return out;
357
+ }
358
+ function derivedPermutation(seed) {
359
+ const random = derivedBytes(seed, 2, 64);
360
+ const permute = Uint8Array.from({ length: 16 }, (_, i) => i);
361
+ let cursor = 0;
362
+ for (let i = 15; i > 0; i -= 1) {
363
+ const j = (random[cursor] ?? 0) % (i + 1);
364
+ cursor += 1;
365
+ const tmp = permute[i] ?? 0;
366
+ permute[i] = permute[j] ?? 0;
367
+ permute[j] = tmp;
368
+ }
369
+ return permute;
370
+ }
371
+ function completeSchema(id, xorInput, permuteInput, tagBits) {
372
+ const xor = clone16(xorInput, "XOR mask");
373
+ if (xor instanceof Error) return xor;
374
+ const permute = clone16(permuteInput, "Permutation");
375
+ if (permute instanceof Error) return permute;
376
+ const inverse = inversePermutation(permute);
377
+ if (inverse instanceof Error) return inverse;
378
+ return {
379
+ id,
380
+ inverse,
381
+ permute,
382
+ tagBits,
383
+ xor
384
+ };
385
+ }
386
+ const LEGACY_MASK_SCHEMA_V1 = completeSchema("legacy-mask-v1", LEGACY_XOR, LEGACY_PERMUTE, 4);
387
+ function defineMaskSchema(schema) {
388
+ return completeSchema(schema.id ?? "explicit", schema.xor, schema.permute, schema.tagBits);
389
+ }
390
+ function createMaskSchema(options) {
391
+ const seed = seedBytes(options.seed);
392
+ if (seed.length === 0) return new UuidSlugError("invalid_mask_schema", "Mask seed must not be empty.");
393
+ const tagBits = options.tagBits ?? 6;
394
+ if (tagBits !== 4 && tagBits !== 6) return new UuidSlugError("invalid_mask_schema", "Mask tagBits must be 4 or 6.");
395
+ return completeSchema(options.id ?? "seeded", derivedBytes(seed, 1, 16), derivedPermutation(seed), tagBits);
396
+ }
397
+ const DEFAULT_MASK_SCHEMA = createMaskSchema({
398
+ id: "default",
399
+ seed: "anizoptera.uuid-slug.default-mask.v1"
400
+ });
401
+ //#endregion
402
+ //#region src/v7.ts
403
+ function writeTimestamp(bytes, ms) {
404
+ let value = Math.trunc(ms);
405
+ for (let i = 5; i >= 0; i -= 1) {
406
+ bytes[i] = value & 255;
407
+ value = Math.floor(value / 256);
408
+ }
409
+ }
410
+ function writeCounter(bytes, counter) {
411
+ bytes[6] = 112 | Number(counter >> 38n & 15n);
412
+ bytes[7] = Number(counter >> 30n & 255n);
413
+ bytes[8] = 128 | Number(counter >> 24n & 63n);
414
+ bytes[9] = Number(counter >> 16n & 255n);
415
+ bytes[10] = Number(counter >> 8n & 255n);
416
+ bytes[11] = Number(counter & 255n);
417
+ }
418
+ function readCounterSeed(bytes) {
419
+ return BigInt(bytes[0] ?? 0) << 34n | BigInt(bytes[1] ?? 0) << 26n | BigInt(bytes[2] ?? 0) << 18n | BigInt(bytes[3] ?? 0) << 10n | BigInt(bytes[4] ?? 0) << 2n | BigInt(bytes[5] ?? 0) & 3n;
420
+ }
421
+ function createUuidV7Generator(options) {
422
+ const clock = options.clock ?? Date.now;
423
+ const random = /* @__PURE__ */ new Uint8Array(16);
424
+ let lastMs = -1;
425
+ let counter = 0n;
426
+ function reseed(ms) {
427
+ options.fillRandom(random);
428
+ lastMs = ms;
429
+ counter = readCounterSeed(random);
430
+ }
431
+ function bytes(out, offset = 0) {
432
+ const target = out ?? /* @__PURE__ */ new Uint8Array(16);
433
+ if (offset < 0 || offset + 16 > target.length) return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
434
+ const now = Math.trunc(clock());
435
+ if (lastMs < 0 || now > lastMs) reseed(now);
436
+ else {
437
+ counter += 1n;
438
+ if (counter > 4398046511103n) reseed(lastMs + 1);
439
+ else options.fillRandom(random);
440
+ }
441
+ const uuid = target.subarray(offset, offset + 16);
442
+ writeTimestamp(uuid, lastMs);
443
+ writeCounter(uuid, counter);
444
+ target[offset + 12] = random[12] ?? 0;
445
+ target[offset + 13] = random[13] ?? 0;
446
+ target[offset + 14] = random[14] ?? 0;
447
+ target[offset + 15] = random[15] ?? 0;
448
+ return target;
449
+ }
450
+ return {
451
+ uuidV7() {
452
+ const result = bytes();
453
+ if (result instanceof Error) throw result;
454
+ const formatted = formatUuid(result);
455
+ if (formatted instanceof Error) throw formatted;
456
+ return formatted;
457
+ },
458
+ uuidV7Bytes: bytes
459
+ };
460
+ }
461
+ function createRuntimeGenerator(runtime) {
462
+ const fallback = createUuidV7Generator({ fillRandom: runtime.fillRandom });
463
+ return {
464
+ uuidV7() {
465
+ if (!runtime.uuidV7) return fallback.uuidV7();
466
+ try {
467
+ return runtime.uuidV7();
468
+ } catch {
469
+ return fallback.uuidV7();
470
+ }
471
+ },
472
+ uuidV7Bytes(out, offset = 0) {
473
+ if (!runtime.uuidV7Bytes) return fallback.uuidV7Bytes(out, offset);
474
+ try {
475
+ return runtime.uuidV7Bytes(out, offset);
476
+ } catch (cause) {
477
+ return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", { cause });
478
+ }
479
+ }
480
+ };
481
+ }
482
+ //#endregion
483
+ //#region src/codec.ts
484
+ const UUID_V7_SENTINEL_DEFINITIONS = [
485
+ {
486
+ name: "nil",
487
+ uuid: "00000000-0000-7000-8000-000000000000"
488
+ },
489
+ {
490
+ name: "anonymousUser",
491
+ uuid: "00000000-0001-7000-8000-000000000000"
492
+ },
493
+ {
494
+ name: "unknownUser",
495
+ uuid: "00000000-0002-7000-8000-000000000000"
496
+ }
497
+ ];
498
+ function schemaFromOption(mask) {
499
+ if (!mask) return DEFAULT_MASK_SCHEMA;
500
+ if ("xor" in mask && "permute" in mask && "inverse" in mask) return mask;
501
+ return createMaskSchema(mask);
502
+ }
503
+ function createSentinels(definitions) {
504
+ const sentinels = [];
505
+ const byUuid = /* @__PURE__ */ new Map();
506
+ const bySlug = /* @__PURE__ */ new Map();
507
+ for (const definition of definitions) {
508
+ const slug = uuidToSlug(definition.uuid);
509
+ if (slug instanceof Error) throw slug;
510
+ const sentinel = {
511
+ name: definition.name,
512
+ slug,
513
+ uuid: definition.uuid
514
+ };
515
+ sentinels.push(sentinel);
516
+ byUuid.set(definition.uuid, sentinel.slug);
517
+ bySlug.set(sentinel.slug, definition.uuid);
518
+ }
519
+ return {
520
+ bySlug,
521
+ byUuid,
522
+ sentinels
523
+ };
524
+ }
525
+ /**
526
+ * Randomness is drawn into a private buffer and copied out instead of filled through a view
527
+ * of the caller's array. `fillRandom` requires a plain `ArrayBuffer` because Web Crypto
528
+ * rejects a `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee.
529
+ * Reused rather than allocated per call, matching the v7 generator, so the cost is one
530
+ * 16-byte copy.
531
+ */
532
+ const v4Random = /* @__PURE__ */ new Uint8Array(16);
533
+ function generateUuidV4Bytes(out, offset = 0) {
534
+ const target = out ?? /* @__PURE__ */ new Uint8Array(16);
535
+ if (offset < 0 || offset + 16 > target.length) return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
536
+ runtime.fillRandom(v4Random);
537
+ target.set(v4Random, offset);
538
+ target[offset + 6] = (target[offset + 6] ?? 0) & 15 | 64;
539
+ target[offset + 8] = (target[offset + 8] ?? 0) & 63 | 128;
540
+ return target;
541
+ }
542
+ function errorOrThrow(value) {
543
+ if (value instanceof Error) throw value;
544
+ return value;
545
+ }
546
+ function createUuidSlugCodec(options = {}) {
547
+ const schema = errorOrThrow(schemaFromOption(options.mask));
548
+ const legacyMasks = options.legacy?.masks ?? [];
549
+ const generator = options.generator ?? createRuntimeGenerator(runtime);
550
+ const sentinelState = createSentinels(options.sentinels ?? UUID_V7_SENTINEL_DEFINITIONS);
551
+ function decodeMasked(slug) {
552
+ const sentinel = sentinelState.bySlug.get(slug);
553
+ if (sentinel) return sentinel;
554
+ const primary = maskedSlugToUuidWithSchema(slug, schema);
555
+ if (!(primary instanceof Error)) return primary;
556
+ for (const legacy of legacyMasks) {
557
+ const decoded = maskedSlugToUuidWithSchema(slug, legacy);
558
+ if (!(decoded instanceof Error)) return decoded;
559
+ }
560
+ if (options.legacy?.directDecode === true) return slugToUuid(slug);
561
+ return primary;
562
+ }
563
+ function uuidV7ToMaskedSlug(uuid) {
564
+ const sentinel = sentinelState.byUuid.get(uuid);
565
+ if (sentinel) return sentinel;
566
+ return uuidToMaskedSlugWithSchema(uuid, schema);
567
+ }
568
+ return {
569
+ sentinels: sentinelState.sentinels,
570
+ uuidV4() {
571
+ const native = runtime.uuidV4?.();
572
+ if (native) return native;
573
+ return errorOrThrow(formatUuid(errorOrThrow(generateUuidV4Bytes())));
574
+ },
575
+ uuidV7() {
576
+ return generator.uuidV7();
577
+ },
578
+ uuidV4Bytes: generateUuidV4Bytes,
579
+ uuidV7Bytes: generator.uuidV7Bytes,
580
+ uuidV4Slug() {
581
+ return errorOrThrow(uuidBytesToSlug(errorOrThrow(generateUuidV4Bytes())));
582
+ },
583
+ uuidV7Slug() {
584
+ if (runtime.uuidV7Slug) return runtime.uuidV7Slug();
585
+ return errorOrThrow(uuidBytesToSlug(errorOrThrow(generator.uuidV7Bytes())));
586
+ },
587
+ uuidV7MaskedSlug() {
588
+ return errorOrThrow(uuidV7BytesToMaskedSlug(errorOrThrow(generator.uuidV7Bytes()), schema));
589
+ },
590
+ uuidToSlug,
591
+ slugToUuid,
592
+ uuidToMaskedSlug(uuid) {
593
+ return uuidV7ToMaskedSlug(uuid);
594
+ },
595
+ maskedSlugToUuid: decodeMasked,
596
+ uuidV7ToMaskedSlug,
597
+ maskedSlugToUuidV7(slug) {
598
+ const decoded = decodeMasked(slug);
599
+ if (decoded instanceof Error) return decoded;
600
+ return isUuidV7String(decoded) ? decoded : new UuidSlugError("invalid_uuid_version", "Decoded UUID is not UUIDv7.");
601
+ },
602
+ parseUuid,
603
+ formatUuid,
604
+ parseUuidSlug,
605
+ formatUuidSlug
606
+ };
607
+ }
608
+ const defaultCodec = createUuidSlugCodec();
609
+ function validateUuidV7Fresh(uuid, options = {}) {
610
+ if (!isUuidV7String(uuid)) return new UuidSlugError("invalid_uuid", "Expected canonical UUIDv7 string.");
611
+ const bytes = parseUuid(uuid);
612
+ if (bytes instanceof Error) return bytes;
613
+ const windowMs = options.windowMs ?? 864e5;
614
+ const now = options.now?.() ?? Date.now();
615
+ const timestamp = extractUuidV7Timestamp(bytes);
616
+ if (timestamp < now - windowMs || timestamp > now + windowMs) return new UuidSlugError("stale_uuid", "UUIDv7 timestamp is outside the accepted window.");
617
+ if (!hasUuidV7Entropy(bytes)) return new UuidSlugError("invalid_uuid", "UUIDv7 random payload is degenerate.");
618
+ return uuid;
619
+ }
620
+ function validateUuidV7SlugFresh(slug, options) {
621
+ const uuid = slugToUuid(slug);
622
+ if (uuid instanceof Error) return uuid;
623
+ const valid = validateUuidV7Fresh(uuid, options);
624
+ return valid instanceof Error ? valid : slug;
625
+ }
626
+ function validateMaskedUuidV7SlugFresh(slug, options) {
627
+ const uuid = defaultCodec.maskedSlugToUuidV7(slug);
628
+ if (uuid instanceof Error) return uuid;
629
+ const valid = validateUuidV7Fresh(uuid, options);
630
+ return valid instanceof Error ? valid : slug;
631
+ }
632
+ //#endregion
633
+ //#region src/index.ts
634
+ const uuidV4 = defaultCodec.uuidV4;
635
+ const uuidV7 = defaultCodec.uuidV7;
636
+ const uuidV4Bytes = defaultCodec.uuidV4Bytes;
637
+ const uuidV7Bytes = defaultCodec.uuidV7Bytes;
638
+ const uuidV4Slug = defaultCodec.uuidV4Slug;
639
+ const uuidV7Slug = defaultCodec.uuidV7Slug;
640
+ const uuidV7MaskedSlug = defaultCodec.uuidV7MaskedSlug;
641
+ const uuidToMaskedSlug = defaultCodec.uuidToMaskedSlug;
642
+ const maskedSlugToUuid = defaultCodec.maskedSlugToUuid;
643
+ const uuidV7ToMaskedSlug = defaultCodec.uuidV7ToMaskedSlug;
644
+ const maskedSlugToUuidV7 = defaultCodec.maskedSlugToUuidV7;
645
+ const UUID_V7_SENTINELS = defaultCodec.sentinels;
646
+ //#endregion
647
+ export { DEFAULT_MASK_SCHEMA, LEGACY_MASK_SCHEMA_V1, UUID_V7_SENTINELS, UUID_V7_SENTINEL_DEFINITIONS, UuidRuntimeError, UuidSlugError, createMaskSchema, createRuntimeGenerator, createUuidSlugCodec, createUuidV7Generator, decodeBase64Url, defaultCodec, defineMaskSchema, encodeBase64Url, extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isBase64Url, isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Bytes, isUuidV7Slug, isUuidV7String, maskedSlugToUuid, maskedSlugToUuidV7, parseUuid, parseUuidSlug, slugToUuid, slugToUuidBytes, uuidBytesToSlug, uuidToMaskedSlug, uuidToSlug, uuidV4, uuidV4Bytes, uuidV4Slug, uuidV7, uuidV7Bytes, uuidV7MaskedSlug, uuidV7Slug, uuidV7ToMaskedSlug, validateMaskedUuidV7SlugFresh, validateUuidV7Fresh, validateUuidV7SlugFresh };