@anizoptera/uuid-slug 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1175 -30
  3. package/dist/alphabet.d.ts +9 -0
  4. package/dist/alphabet.d.ts.map +1 -0
  5. package/dist/alphabet.js +166 -0
  6. package/dist/alphabet.js.map +1 -0
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +57 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +162 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/feistel.js +39 -0
  16. package/dist/feistel.js.map +1 -0
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +23 -168
  20. package/dist/index.js +22 -649
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +164 -0
  30. package/dist/mask.js.map +1 -0
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +129 -0
  40. package/dist/migration.js.map +1 -0
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +30 -0
  48. package/dist/runtime/pool.js.map +1 -0
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +29 -0
  54. package/dist/siphash.js.map +1 -0
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +535 -0
  64. package/dist/types.d.ts.map +1 -0
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +65 -0
  74. package/dist/uuid.d.ts.map +1 -0
  75. package/dist/uuid.js +232 -0
  76. package/dist/uuid.js.map +1 -0
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +143 -0
  114. package/dist/v7.js.map +1 -0
  115. package/package.json +18 -17
  116. package/src/alphabet.ts +616 -0
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +423 -13
  119. package/src/feistel.ts +141 -0
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +137 -57
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +9 -0
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +377 -90
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +257 -0
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +31 -25
  132. package/src/runtime/node.ts +55 -18
  133. package/src/runtime/pool.ts +90 -0
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +30 -5
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +128 -0
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +799 -61
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +527 -108
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +433 -84
  156. package/dist/index.d.ts.map +0 -1
  157. package/dist/index.js.map +0 -1
  158. package/dist/node/index.js +0 -647
  159. package/dist/web/index.js +0 -648
  160. package/src/base64url.ts +0 -76
  161. package/src/codec.ts +0 -218
  162. package/src/runtime/web.ts +0 -20
  163. package/src/schema.ts +0 -123
package/src/uuid.ts CHANGED
@@ -1,158 +1,577 @@
1
- import { decodeBase64Url, encodeBase64Url } from "./base64url";
2
- import { UuidSlugError } from "./errors";
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import {
4
+ checkByteRange,
5
+ checkRange,
6
+ INVALID_BUFFER,
7
+ INVALID_OPTIONS,
8
+ INVALID_UUID,
9
+ isUuidSlugError,
10
+ isUint8Array,
11
+ normalizeUuidStringInput,
12
+ stringInput,
13
+ uuidByteView,
14
+ UuidSlugError,
15
+ } from "./errors.ts";
16
+ import { runtime } from "#runtime";
17
+ import type { Latin1Scratch } from "./runtime/types.ts";
18
+ import { UUID_TEXT_LOWERCASE, UUID_TEXT_UPPERCASE } from "./types.ts";
3
19
  import type {
4
- UuidSlug,
20
+ PreserveUuidVersion,
21
+ UuidBytes,
22
+ UuidByteInput,
23
+ UuidV4Bytes,
24
+ UuidV7Bytes,
5
25
  UuidString,
6
- UuidV4Slug,
26
+ UuidStringFor,
27
+ UuidText,
28
+ UuidOutput,
29
+ UuidTextCase,
30
+ UuidTextCaseArguments,
31
+ UuidStringInput,
7
32
  UuidV4String,
8
- UuidV7Slug,
33
+ UuidV4Text,
9
34
  UuidV7String,
10
- } from "./types";
35
+ UuidV7Text,
36
+ UuidVersion,
37
+ } from "./types.ts";
38
+
39
+ export { isUuidSlugError } from "./errors.ts";
40
+ export { UuidSlugError };
41
+ export type { UuidSlugErrorCode } from "./errors.ts";
42
+ export type { UuidBytes, UuidString } from "./types.ts";
43
+
44
+ /** Report byte input that does not hold exactly one 16-byte UUID. */
45
+ export const invalidUuidBytes = /* @__NO_SIDE_EFFECTS__ */ (): UuidSlugError =>
46
+ new UuidSlugError(INVALID_BUFFER, "UUID byte input must contain exactly 16 bytes.");
47
+
48
+ /** Borrow one exact UUID payload from any supported byte source. */
49
+ /*#__NO_SIDE_EFFECTS__*/
50
+ export function exactUuidByteView(value: unknown): Uint8Array | UuidSlugError {
51
+ if (isUuidSlugError(value)) return value;
52
+ const bytes = uuidByteView(value);
53
+ return bytes?.length === 16 ? bytes : invalidUuidBytes();
54
+ }
55
+
56
+ /** The canonical all-zero UUID value, without a version or issuance claim. */
57
+ export const NIL_UUID = "00000000-0000-0000-0000-000000000000" as UuidString;
58
+ /** The canonical all-one UUID value, without a version or issuance claim. */
59
+ export const MAX_UUID = "ffffffff-ffff-ffff-ffff-ffffffffffff" as UuidString;
11
60
 
12
61
  const HEX = "0123456789abcdef";
62
+ const UPPERCASE_HEX = "0123456789ABCDEF";
63
+ const UUID_SEPARATOR = "-";
64
+
65
+ /** Keep case-option validation identical across every UUID-text writer. */
66
+ export const isUuidTextCase = (value: unknown): value is UuidTextCase =>
67
+ value === UUID_TEXT_LOWERCASE || value === UUID_TEXT_UPPERCASE;
68
+
69
+ /** Normalize a JavaScript string wrapper, then validate the public UUID text spelling. */
70
+ export function resolveUuidTextCase(value: unknown): UuidTextCase | UuidSlugError {
71
+ if (value === UUID_TEXT_LOWERCASE || value === UUID_TEXT_UPPERCASE) return value;
72
+ const textCase = stringInput(value);
73
+ return isUuidTextCase(textCase) ? textCase : invalidUuidTextCase();
74
+ }
75
+ export function invalidUuidTextCase(): UuidSlugError {
76
+ return new UuidSlugError(INVALID_OPTIONS, "UUID text case must be lowercase or uppercase.");
77
+ }
78
+ const createLatin1Scratch = runtime.latin1Scratch;
79
+ const nativeToHex = runtime.uuidHex;
13
80
  const HEX_DECODE = new Int8Array(128).fill(-1);
14
81
  for (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;
15
82
  for (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;
83
+ // Nibbles of both hex cases; 0x100 marks every other ASCII character so OR-ed pairs expose it.
84
+ const HEX_NIBBLES = new Uint16Array(128).fill(0x100);
85
+ for (let i = 0; i < 16; i += 1) {
86
+ HEX_NIBBLES[HEX.charCodeAt(i)] = i;
87
+ HEX_NIBBLES[UPPERCASE_HEX.charCodeAt(i)] = i;
88
+ }
89
+ // Bun's Latin-1 writer and the fixed writer share lazily built case tables; native hex needs none.
90
+ // bench/PERFORMANCE.md owns the comparison and recheck conditions. Tables are built on first use.
91
+ let uuidTextScratch: Latin1Scratch | undefined;
92
+ let lowercaseHexCodes: Uint8Array | undefined;
93
+ let uppercaseHexCodes: Uint8Array | undefined;
94
+ function hexCodes(digits: string): Uint8Array {
95
+ const codes = new Uint8Array(512);
96
+ for (let byte = 0; byte < 256; byte += 1) {
97
+ codes[byte * 2] = digits.charCodeAt(byte >>> 4);
98
+ codes[byte * 2 + 1] = digits.charCodeAt(byte & 15);
99
+ }
100
+ return codes;
101
+ }
102
+ function createUuidTextScratch(create: NonNullable<typeof createLatin1Scratch>): Latin1Scratch {
103
+ const scratch = create(UUID_LENGTH);
104
+ // Hyphens never move, so only the hex digits are written per call.
105
+ for (const hyphen of [8, 13, 18, 23]) scratch.bytes[hyphen] = UUID_SEPARATOR.charCodeAt(0);
106
+ return scratch;
107
+ }
108
+ /**
109
+ * Format through one native byte-to-string call instead of hex strings, slices, and concatenation;
110
+ * the result is also flat text that a reader need not flatten. The scratch is safe to share because
111
+ * nothing between these writes and the read can re-enter formatting.
112
+ */
113
+ function formatUuidBytesLatin1(
114
+ create: NonNullable<typeof createLatin1Scratch>,
115
+ bytes: Uint8Array,
116
+ offset: number,
117
+ textCase: UuidTextCase,
118
+ ): string {
119
+ const scratch = (uuidTextScratch ??= createUuidTextScratch(create));
120
+ const codes =
121
+ textCase === UUID_TEXT_UPPERCASE
122
+ ? (uppercaseHexCodes ??= hexCodes(UPPERCASE_HEX))
123
+ : (lowercaseHexCodes ??= hexCodes(HEX));
124
+ const text = scratch.bytes;
125
+ // Fixed positions remove the loop and offset-table reads on Bun's selected writer.
126
+ // The indexed loop loses repeated complete text calls; bench/PERFORMANCE.md owns the evidence.
127
+ // Keep native string construction and shared storage; remeasure after JSC or writer changes.
128
+ const code0 = (bytes[offset + 0] as number) * 2;
129
+ text[0] = codes[code0] as number;
130
+ text[1] = codes[code0 + 1] as number;
131
+ const code1 = (bytes[offset + 1] as number) * 2;
132
+ text[2] = codes[code1] as number;
133
+ text[3] = codes[code1 + 1] as number;
134
+ const code2 = (bytes[offset + 2] as number) * 2;
135
+ text[4] = codes[code2] as number;
136
+ text[5] = codes[code2 + 1] as number;
137
+ const code3 = (bytes[offset + 3] as number) * 2;
138
+ text[6] = codes[code3] as number;
139
+ text[7] = codes[code3 + 1] as number;
140
+ const code4 = (bytes[offset + 4] as number) * 2;
141
+ text[9] = codes[code4] as number;
142
+ text[10] = codes[code4 + 1] as number;
143
+ const code5 = (bytes[offset + 5] as number) * 2;
144
+ text[11] = codes[code5] as number;
145
+ text[12] = codes[code5 + 1] as number;
146
+ const code6 = (bytes[offset + 6] as number) * 2;
147
+ text[14] = codes[code6] as number;
148
+ text[15] = codes[code6 + 1] as number;
149
+ const code7 = (bytes[offset + 7] as number) * 2;
150
+ text[16] = codes[code7] as number;
151
+ text[17] = codes[code7 + 1] as number;
152
+ const code8 = (bytes[offset + 8] as number) * 2;
153
+ text[19] = codes[code8] as number;
154
+ text[20] = codes[code8 + 1] as number;
155
+ const code9 = (bytes[offset + 9] as number) * 2;
156
+ text[21] = codes[code9] as number;
157
+ text[22] = codes[code9 + 1] as number;
158
+ const code10 = (bytes[offset + 10] as number) * 2;
159
+ text[24] = codes[code10] as number;
160
+ text[25] = codes[code10 + 1] as number;
161
+ const code11 = (bytes[offset + 11] as number) * 2;
162
+ text[26] = codes[code11] as number;
163
+ text[27] = codes[code11 + 1] as number;
164
+ const code12 = (bytes[offset + 12] as number) * 2;
165
+ text[28] = codes[code12] as number;
166
+ text[29] = codes[code12 + 1] as number;
167
+ const code13 = (bytes[offset + 13] as number) * 2;
168
+ text[30] = codes[code13] as number;
169
+ text[31] = codes[code13 + 1] as number;
170
+ const code14 = (bytes[offset + 14] as number) * 2;
171
+ text[32] = codes[code14] as number;
172
+ text[33] = codes[code14 + 1] as number;
173
+ const code15 = (bytes[offset + 15] as number) * 2;
174
+ text[34] = codes[code15] as number;
175
+ text[35] = codes[code15 + 1] as number;
176
+ return scratch.text();
177
+ }
178
+ // Caller-owned output must stay unchanged when text fails, so its bytes are decoded here first.
179
+ const decodedUuidScratch = new Uint8Array(16);
16
180
 
17
181
  const UUID_LENGTH = 36;
18
- const SLUG_LENGTH = 22;
182
+ const COMPACT_UUID_LENGTH = 32;
183
+ const UUID_URN_LENGTH = 45;
184
+ const BRACED_UUID_LENGTH = 38;
185
+ const UUID_URN_PREFIX = "urn:uuid:";
186
+ const INVALID_UUID_TEXT_START = -2;
187
+ const COMPACT_UUID_TEXT_START = -1;
19
188
  const UUID_BYTE_OFFSETS = [0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34] as const;
20
189
 
21
- function hexValue(code: number) {
22
- return code < HEX_DECODE.length ? HEX_DECODE[code] : -1;
190
+ /** Return the first canonical UUID character, or the compact/invalid sentinel. */
191
+ /*#__NO_SIDE_EFFECTS__*/
192
+ function uuidTextStart(value: string): number {
193
+ if (value.length === COMPACT_UUID_LENGTH) return COMPACT_UUID_TEXT_START;
194
+ if (value.length === UUID_LENGTH) return 0;
195
+ if (value.length === BRACED_UUID_LENGTH && value[0] === "{" && value[37] === "}") return 1;
196
+ if (value.length === UUID_URN_LENGTH) {
197
+ for (let index = 0; index < UUID_URN_PREFIX.length; index += 1)
198
+ if ((value.charCodeAt(index) | 32) !== UUID_URN_PREFIX.charCodeAt(index))
199
+ return INVALID_UUID_TEXT_START;
200
+ return UUID_URN_PREFIX.length;
201
+ }
202
+ return INVALID_UUID_TEXT_START;
203
+ }
204
+
205
+ /*#__NO_SIDE_EFFECTS__*/
206
+ function lowercaseHexValue(code: number) {
207
+ return HEX_DECODE[code] ?? -1;
23
208
  }
24
209
 
25
- export function parseUuid(uuid: string, out?: Uint8Array, offset = 0): Error | Uint8Array {
26
- if (uuid.length !== UUID_LENGTH)
27
- return new UuidSlugError("invalid_uuid", "UUID must be 36 characters.");
28
- if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") {
29
- return new UuidSlugError("invalid_uuid", "UUID hyphen positions are invalid.");
210
+ /*#__NO_SIDE_EFFECTS__*/
211
+ function parsedHexValue(code: number) {
212
+ return code >= 65 && code <= 70 ? code - 55 : lowercaseHexValue(code);
213
+ }
214
+
215
+ /**
216
+ * Parse accepted mixed-case UUID text into a new plain 16-byte `Uint8Array`. Accept canonical or
217
+ * compact text, a UUID URN, or brace-wrapped canonical text. Known slug values are rejected by
218
+ * TypeScript; invalid text returns `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
219
+ *
220
+ * @param uuid - UUID text in an accepted spelling. JavaScript also accepts a genuine `String` object.
221
+ */
222
+ export function uuidStringToBytes<Input extends string | UuidSlugError>(
223
+ uuid: UuidStringInput<Input>,
224
+ ): PreserveUuidVersion<Input, UuidBytes, UuidV4Bytes, UuidV7Bytes> | UuidSlugError;
225
+ /**
226
+ * Parse accepted mixed-case UUID text into caller-owned storage after validating the full input.
227
+ * A preceding `UuidSlugError` is returned unchanged without writing.
228
+ *
229
+ * @param uuid - UUID text in an accepted spelling. JavaScript also accepts a genuine `String` object.
230
+ * @param output - Caller-owned array that receives the 16 UUID bytes.
231
+ * @param outputOffset - Zero-based index where writing starts. Omit to start at index 0. Bytes
232
+ * outside the written range stay unchanged.
233
+ */
234
+ export function uuidStringToBytes<Input extends string | UuidSlugError, Output extends Uint8Array>(
235
+ uuid: UuidStringInput<Input>,
236
+ output: Output,
237
+ outputOffset?: number,
238
+ ): UuidOutput<Output> | UuidSlugError;
239
+ export function uuidStringToBytes(
240
+ uuid: string | UuidSlugError,
241
+ out?: Uint8Array,
242
+ offset = 0,
243
+ ): Uint8Array | UuidSlugError {
244
+ let uuidText = uuid;
245
+ if (typeof uuidText !== "string") {
246
+ uuidText = normalizeUuidStringInput(uuidText);
247
+ if (typeof uuidText !== "string") return uuidText;
30
248
  }
249
+ const textStart = uuidTextStart(uuidText);
250
+ if (textStart === INVALID_UUID_TEXT_START)
251
+ return new UuidSlugError(
252
+ INVALID_UUID,
253
+ "UUID must be canonical, compact, a UUID URN, or brace-wrapped canonical text.",
254
+ );
255
+ const hyphenated = textStart !== COMPACT_UUID_TEXT_START;
256
+ if (
257
+ hyphenated &&
258
+ (uuidText[textStart + 8] !== UUID_SEPARATOR ||
259
+ uuidText[textStart + 13] !== UUID_SEPARATOR ||
260
+ uuidText[textStart + 18] !== UUID_SEPARATOR ||
261
+ uuidText[textStart + 23] !== UUID_SEPARATOR)
262
+ )
263
+ return new UuidSlugError(INVALID_UUID, "UUID hyphen positions are invalid.");
264
+
265
+ const badRange = out === undefined ? checkRange(16, offset, 16) : checkByteRange(out, offset, 16);
266
+ if (badRange) return badRange;
31
267
 
32
- const target = out ?? new Uint8Array(16);
33
- if (offset < 0 || offset + 16 > target.length)
34
- return new UuidSlugError("invalid_buffer", "Output buffer is too small.");
35
-
36
- for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {
37
- const textOffset = UUID_BYTE_OFFSETS[byteIndex] ?? 0;
38
- const high = hexValue(uuid.charCodeAt(textOffset)) ?? -1;
39
- const low = hexValue(uuid.charCodeAt(textOffset + 1)) ?? -1;
40
- if (high < 0 || low < 0)
41
- return new UuidSlugError("invalid_uuid", `Invalid UUID hex at offset ${textOffset}.`);
42
- target[offset + byteIndex] = (high << 4) | low;
268
+ // One pass decodes and validates: OR-ing every character code and every decoded pair exposes a
269
+ // non-ASCII or non-hex character after the loop. Validating before a second decoding pass cost
270
+ // about twice as much on Node and three times on Bun (bench/PERFORMANCE.md). Only failing text
271
+ // pays a second scan, which locates the offset for the message.
272
+ const target = out === undefined ? new Uint8Array(16) : decodedUuidScratch;
273
+ let codes = 0;
274
+ let pairs = 0;
275
+ for (let byteIndex = 0; byteIndex < 16; byteIndex += 1) {
276
+ const textOffset = hyphenated
277
+ ? textStart + (UUID_BYTE_OFFSETS[byteIndex] as number)
278
+ : byteIndex * 2;
279
+ const high = uuidText.charCodeAt(textOffset);
280
+ const low = uuidText.charCodeAt(textOffset + 1);
281
+ const pair = ((HEX_NIBBLES[high & 127] as number) << 4) | (HEX_NIBBLES[low & 127] as number);
282
+ codes |= high | low;
283
+ pairs |= pair;
284
+ target[byteIndex] = pair;
43
285
  }
44
- return target;
45
- }
46
-
47
- export function formatUuid(bytes: Uint8Array, offset = 0): Error | UuidString {
48
- if (offset < 0 || offset + 16 > bytes.length)
49
- return new UuidSlugError("invalid_buffer", "UUID byte buffer is too small.");
50
- let out = "";
51
- for (let i = 0; i < 16; i += 1) {
52
- if (i === 4 || i === 6 || i === 8 || i === 10) out += "-";
53
- const byte = bytes[offset + i] ?? 0;
54
- out += HEX[byte >>> 4];
55
- out += HEX[byte & 0x0f];
286
+ if (codes < 128 && pairs < 256) {
287
+ if (out === undefined) return target;
288
+ // A byte loop rather than `set`: the native call made Bun text-to-slug conversion slower
289
+ // (bench/PERFORMANCE.md).
290
+ for (let byteIndex = 0; byteIndex < 16; byteIndex += 1)
291
+ out[offset + byteIndex] = target[byteIndex] as number;
292
+ return out;
56
293
  }
57
- return out as UuidString;
294
+ // Name the first invalid pair with the same test as the decoding pass, so the scan stops within
295
+ // the 16 pairs even if the two ever disagree.
296
+ let textOffset = 0;
297
+ for (let byteIndex = 0; byteIndex < 16; byteIndex += 1) {
298
+ textOffset = hyphenated ? textStart + (UUID_BYTE_OFFSETS[byteIndex] as number) : byteIndex * 2;
299
+ const high = uuidText.charCodeAt(textOffset);
300
+ const low = uuidText.charCodeAt(textOffset + 1);
301
+ if (
302
+ (high | low) > 127 ||
303
+ (HEX_NIBBLES[high] as number) > 15 ||
304
+ (HEX_NIBBLES[low] as number) > 15
305
+ )
306
+ break;
307
+ }
308
+ return new UuidSlugError(
309
+ INVALID_UUID,
310
+ `Invalid UUID hex at offset ${textOffset}; use 0-9, a-f, or A-F.`,
311
+ );
58
312
  }
59
313
 
60
- export function uuidVersion(bytes: Uint8Array, offset = 0): number {
61
- return (bytes[offset + 6] ?? 0) >>> 4;
314
+ /**
315
+ * Format 16 bytes as standard hyphenated UUID text without assigning a version. A standalone
316
+ * `ArrayBuffer` uses its whole contents; a `DataView` uses its declared range. Only `Uint8Array`
317
+ * input accepts an explicit offset. Invalid input returns `invalid_buffer`, and a preceding
318
+ * `UuidSlugError` is returned unchanged.
319
+ *
320
+ * @param bytes - One supported UUID byte source.
321
+ * @param textCase - Built-in output spelling. Omit for lowercase.
322
+ * @defaultValue `UUID_TEXT_LOWERCASE`
323
+ * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
324
+ */
325
+ export function bytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
326
+ bytes: UuidByteInput | UuidSlugError,
327
+ ...textCase: UuidTextCaseArguments<Case>
328
+ ): UuidStringFor<Case> | UuidSlugError;
329
+ export function bytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
330
+ bytes: Uint8Array | UuidSlugError,
331
+ byteOffset: number,
332
+ ...textCase: UuidTextCaseArguments<Case>
333
+ ): UuidStringFor<Case> | UuidSlugError;
334
+ /*#__NO_SIDE_EFFECTS__*/
335
+ export function bytesToUuidString(
336
+ bytes: UuidByteInput | UuidSlugError,
337
+ offsetOrCase: number | UuidTextCase = 0,
338
+ textCase: UuidTextCase = UUID_TEXT_LOWERCASE,
339
+ ): UuidString | string | UuidSlugError {
340
+ const view = isUint8Array(bytes) ? bytes : exactUuidByteView(bytes);
341
+ if (view instanceof Error) return view;
342
+ const caseIsSecond =
343
+ typeof offsetOrCase === "string"
344
+ ? Number.isNaN(Number(offsetOrCase))
345
+ : typeof offsetOrCase !== "number";
346
+ const byteOffset = (caseIsSecond ? 0 : offsetOrCase) as number;
347
+ const selectedCase = resolveUuidTextCase(caseIsSecond ? offsetOrCase : textCase);
348
+ if (selectedCase instanceof Error) return selectedCase;
349
+ const badRange = checkRange(view.length, byteOffset, 16);
350
+ if (badRange) return badRange;
351
+ if (nativeToHex) {
352
+ // A small existing view avoids another view; a larger buffer must not encode unrelated bytes.
353
+ const hex =
354
+ view.length <= 32
355
+ ? nativeToHex(view)
356
+ : nativeToHex(view.subarray(byteOffset, byteOffset + 16));
357
+ const offset = view.length <= 32 ? byteOffset * 2 : 0;
358
+ const uuid = hyphenateHex(hex, offset);
359
+ return selectedCase === UUID_TEXT_UPPERCASE ? uuid.toUpperCase() : uuid;
360
+ }
361
+ return formatUuidBytesUnchecked(view, byteOffset, selectedCase);
62
362
  }
63
363
 
64
- export function isRfcVariant(bytes: Uint8Array, offset = 0): boolean {
65
- return (bytes[offset + 8] ?? 0) >>> 6 === 0b10;
66
- }
364
+ const hyphenateHex = /* @__NO_SIDE_EFFECTS__ */ (hex: string, offset: number): UuidString =>
365
+ `${hex.slice(offset, offset + 8)}-${hex.slice(offset + 8, offset + 12)}-${hex.slice(offset + 12, offset + 16)}-${hex.slice(offset + 16, offset + 20)}-${hex.slice(offset + 20, offset + 32)}` as UuidString;
67
366
 
68
- export function isUuidString(uuid: null | string | undefined): uuid is UuidString {
69
- if (!uuid) return false;
70
- return parseUuid(uuid) instanceof Error ? false : true;
367
+ /** Format a complete UUID byte range already validated by its caller. */
368
+ /*#__NO_SIDE_EFFECTS__*/
369
+ export function formatUuidBytesUnchecked<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
370
+ bytes: Uint8Array,
371
+ offset = 0,
372
+ textCase: Case = UUID_TEXT_LOWERCASE as Case,
373
+ ): UuidStringFor<Case> {
374
+ // Bun retains its Latin-1 writer. A fixed argument list makes one flat string without
375
+ // temporary bytes, intermediate hex or concatenation. WebKit selects native hex to avoid
376
+ // repeated mixed-workload losses; remeasure both paths after engine changes
377
+ // (bench/PERFORMANCE.md). Keep case selection and fixed writing together to avoid another call.
378
+ if (createLatin1Scratch)
379
+ return formatUuidBytesLatin1(
380
+ createLatin1Scratch,
381
+ bytes,
382
+ offset,
383
+ textCase,
384
+ ) as UuidStringFor<Case>;
385
+ if (nativeToHex) {
386
+ const uuid = hyphenateHex(nativeToHex(bytes), offset * 2);
387
+ return (textCase === UUID_TEXT_UPPERCASE ? uuid.toUpperCase() : uuid) as UuidStringFor<Case>;
388
+ }
389
+ const codes =
390
+ textCase === UUID_TEXT_UPPERCASE
391
+ ? (uppercaseHexCodes ??= hexCodes(UPPERCASE_HEX))
392
+ : (lowercaseHexCodes ??= hexCodes(HEX));
393
+ const a = (bytes[offset] as number) * 2;
394
+ const b = (bytes[offset + 1] as number) * 2;
395
+ const c = (bytes[offset + 2] as number) * 2;
396
+ const d = (bytes[offset + 3] as number) * 2;
397
+ const e = (bytes[offset + 4] as number) * 2;
398
+ const f = (bytes[offset + 5] as number) * 2;
399
+ const g = (bytes[offset + 6] as number) * 2;
400
+ const h = (bytes[offset + 7] as number) * 2;
401
+ const i = (bytes[offset + 8] as number) * 2;
402
+ const j = (bytes[offset + 9] as number) * 2;
403
+ const k = (bytes[offset + 10] as number) * 2;
404
+ const l = (bytes[offset + 11] as number) * 2;
405
+ const m = (bytes[offset + 12] as number) * 2;
406
+ const n = (bytes[offset + 13] as number) * 2;
407
+ const o = (bytes[offset + 14] as number) * 2;
408
+ const p = (bytes[offset + 15] as number) * 2;
409
+ return String.fromCharCode(
410
+ codes[a] as number,
411
+ codes[a + 1] as number,
412
+ codes[b] as number,
413
+ codes[b + 1] as number,
414
+ codes[c] as number,
415
+ codes[c + 1] as number,
416
+ codes[d] as number,
417
+ codes[d + 1] as number,
418
+ 45,
419
+ codes[e] as number,
420
+ codes[e + 1] as number,
421
+ codes[f] as number,
422
+ codes[f + 1] as number,
423
+ 45,
424
+ codes[g] as number,
425
+ codes[g + 1] as number,
426
+ codes[h] as number,
427
+ codes[h + 1] as number,
428
+ 45,
429
+ codes[i] as number,
430
+ codes[i + 1] as number,
431
+ codes[j] as number,
432
+ codes[j + 1] as number,
433
+ 45,
434
+ codes[k] as number,
435
+ codes[k + 1] as number,
436
+ codes[l] as number,
437
+ codes[l + 1] as number,
438
+ codes[m] as number,
439
+ codes[m + 1] as number,
440
+ codes[n] as number,
441
+ codes[n + 1] as number,
442
+ codes[o] as number,
443
+ codes[o + 1] as number,
444
+ codes[p] as number,
445
+ codes[p + 1] as number,
446
+ ) as UuidStringFor<Case>;
71
447
  }
72
448
 
73
- export function isUuidV4String(uuid: null | string | undefined): uuid is UuidV4String {
74
- if (!uuid) return false;
75
- const bytes = parseUuid(uuid);
76
- return bytes instanceof Error ? false : uuidVersion(bytes) === 4 && isRfcVariant(bytes);
449
+ /*#__NO_SIDE_EFFECTS__*/
450
+ export function uuidVersion(bytes: Uint8Array, offset = 0): UuidVersion {
451
+ return ((bytes[offset + 6] ?? 0) >>> 4) as UuidVersion;
77
452
  }
78
453
 
79
- export function isUuidV7String(uuid: null | string | undefined): uuid is UuidV7String {
80
- if (!uuid) return false;
81
- const bytes = parseUuid(uuid);
82
- return bytes instanceof Error ? false : uuidVersion(bytes) === 7 && isRfcVariant(bytes);
454
+ /*#__NO_SIDE_EFFECTS__*/
455
+ export function isRfcVariant(bytes: Uint8Array, offset = 0): boolean {
456
+ return (bytes[offset + 8] ?? 0) >>> 6 === 0b10;
83
457
  }
84
458
 
85
- export function isUuidV7Bytes(bytes: Uint8Array): boolean {
86
- return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);
459
+ // Accepted-text parsing uses the shared hex table without allocating output bytes or Errors.
460
+ /** Check accepted UUID text without claiming a version, variant, or issuance. */
461
+ /*#__NO_SIDE_EFFECTS__*/
462
+ export function isUuidText(value: unknown): value is UuidText {
463
+ if (typeof value !== "string") return false;
464
+ const textStart = uuidTextStart(value);
465
+ if (textStart === INVALID_UUID_TEXT_START) return false;
466
+ const hyphenated = textStart !== COMPACT_UUID_TEXT_START;
467
+ if (
468
+ hyphenated &&
469
+ (value[textStart + 8] !== UUID_SEPARATOR ||
470
+ value[textStart + 13] !== UUID_SEPARATOR ||
471
+ value[textStart + 18] !== UUID_SEPARATOR ||
472
+ value[textStart + 23] !== UUID_SEPARATOR)
473
+ )
474
+ return false;
475
+ for (let i = 0; i < UUID_BYTE_OFFSETS.length; i += 1) {
476
+ const offset = hyphenated ? textStart + (UUID_BYTE_OFFSETS[i] as number) : i * 2;
477
+ if (
478
+ parsedHexValue(value.charCodeAt(offset)) < 0 ||
479
+ parsedHexValue(value.charCodeAt(offset + 1)) < 0
480
+ )
481
+ return false;
482
+ }
483
+ return true;
87
484
  }
88
485
 
89
- export function uuidBytesToSlug(bytes: Uint8Array, offset = 0): Error | UuidSlug {
90
- if (offset < 0 || offset + 16 > bytes.length)
91
- return new UuidSlugError("invalid_buffer", "UUID byte buffer is too small.");
92
- return encodeBase64Url(bytes.subarray(offset, offset + 16)) as UuidSlug;
93
- }
486
+ // Canonical guards stay regular expressions: a character loop measured slower on Node and Bun
487
+ // (bench/PERFORMANCE.md, Canonical UUID text).
488
+ // Pair repetition improves canonical calls, but slows Bun's successful base32 normalization.
489
+ // Reuse its existing Latin-1 selection once; neither pattern needs a builder or per-call dispatch.
490
+ // Remeasure normalization if this capability moves to another adapter (bench/PERFORMANCE.md).
491
+ const UUID_RE = createLatin1Scratch
492
+ ? /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
493
+ : /^(?:[0-9a-f][0-9a-f]){4}-(?:[0-9a-f][0-9a-f]){2}-(?:[0-9a-f][0-9a-f]){2}-(?:[0-9a-f][0-9a-f]){2}-(?:[0-9a-f][0-9a-f]){6}$/;
494
+ const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
495
+ const UUID_V7_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
496
+ const UUID_V7_TEXT_RE = /*#__PURE__*/ new RegExp(UUID_V7_RE.source, "i");
94
497
 
95
- export function slugToUuidBytes(slug: string, out?: Uint8Array, offset = 0): Error | Uint8Array {
96
- if (slug.length !== SLUG_LENGTH)
97
- return new UuidSlugError("invalid_uuid_slug", "UUID slug must be 22 characters.");
98
- return decodeBase64Url(slug, out, offset);
498
+ /** Check accepted UUID text with version 4 and RFC variant bits. */
499
+ /*#__NO_SIDE_EFFECTS__*/
500
+ export function isUuidV4Text(value: unknown): value is UuidV4Text {
501
+ if (!isUuidText(value)) return false;
502
+ const textStart = uuidTextStart(value);
503
+ const variant = parsedHexValue(
504
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 16 : textStart + 19),
505
+ );
506
+ return (
507
+ parsedHexValue(
508
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 12 : textStart + 14),
509
+ ) === 4 &&
510
+ variant >= 8 &&
511
+ variant <= 11
512
+ );
99
513
  }
100
514
 
101
- export function uuidToSlug(uuid: string): Error | UuidSlug {
102
- const bytes = parseUuid(uuid);
103
- if (bytes instanceof Error) return bytes;
104
- return uuidBytesToSlug(bytes);
515
+ /** Check accepted UUID text with version 7 and RFC variant bits. */
516
+ /*#__NO_SIDE_EFFECTS__*/
517
+ export function isUuidV7Text(value: unknown): value is UuidV7Text {
518
+ // Canonical text uses the same syntax with either case, avoiding the full digit loop before
519
+ // timestamp parsing. Other spellings retain their existing checks; remeasure after engine or
520
+ // accepted-syntax changes (bench/PERFORMANCE.md).
521
+ if (typeof value === "string" && value.length === UUID_LENGTH) return UUID_V7_TEXT_RE.test(value);
522
+ if (!isUuidText(value)) return false;
523
+ const textStart = uuidTextStart(value);
524
+ const variant = parsedHexValue(
525
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 16 : textStart + 19),
526
+ );
527
+ return (
528
+ parsedHexValue(
529
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 12 : textStart + 14),
530
+ ) === 7 &&
531
+ variant >= 8 &&
532
+ variant <= 11
533
+ );
105
534
  }
106
535
 
107
- export function slugToUuid(slug: string): Error | UuidString {
108
- const bytes = slugToUuidBytes(slug);
109
- if (bytes instanceof Error) return bytes;
110
- return formatUuid(bytes);
536
+ /** Check canonical lowercase UUID text without claiming a version, variant, or issuance. */
537
+ export function isUuidString(value: unknown): value is UuidString {
538
+ return typeof value === "string" && UUID_RE.test(value);
111
539
  }
112
-
113
- export function formatUuidSlug(bytes: Uint8Array, offset = 0): Error | UuidSlug {
114
- return uuidBytesToSlug(bytes, offset);
540
+ /** Check canonical lowercase UUIDv4 text with RFC variant bits. */
541
+ export function isUuidV4String(value: unknown): value is UuidV4String {
542
+ return typeof value === "string" && UUID_V4_RE.test(value);
115
543
  }
116
-
117
- export function parseUuidSlug(slug: string, out?: Uint8Array, offset = 0): Error | Uint8Array {
118
- return slugToUuidBytes(slug, out, offset);
544
+ /** Check canonical lowercase UUIDv7 text with RFC variant bits. */
545
+ export function isUuidV7String(value: unknown): value is UuidV7String {
546
+ return typeof value === "string" && UUID_V7_RE.test(value);
119
547
  }
120
548
 
121
- export function isUuidSlug(slug: null | string | undefined): slug is UuidSlug {
122
- if (!slug || slug.length !== SLUG_LENGTH) return false;
123
- return slugToUuidBytes(slug) instanceof Error ? false : true;
549
+ /** Check for a 16-byte `Uint8Array` without claiming a UUID version or issuance. */
550
+ /*#__NO_SIDE_EFFECTS__*/
551
+ export function isUuidBytes(value: unknown): value is UuidBytes {
552
+ return isUint8Array(value) && value.length === 16;
124
553
  }
125
554
 
126
- export function isUuidV4Slug(slug: null | string | undefined): slug is UuidV4Slug {
127
- if (!slug) return false;
128
- const bytes = slugToUuidBytes(slug);
129
- return bytes instanceof Error ? false : uuidVersion(bytes) === 4 && isRfcVariant(bytes);
555
+ /** Check for exactly 16 UUIDv4 bytes with the RFC variant required by generation. */
556
+ /*#__NO_SIDE_EFFECTS__*/
557
+ export function isUuidV4Bytes(value: unknown): value is UuidV4Bytes {
558
+ return isUuidBytes(value) && uuidVersion(value) === 4 && isRfcVariant(value);
130
559
  }
131
560
 
132
- export function isUuidV7Slug(slug: null | string | undefined): slug is UuidV7Slug {
133
- if (!slug) return false;
134
- const bytes = slugToUuidBytes(slug);
135
- return bytes instanceof Error ? false : uuidVersion(bytes) === 7 && isRfcVariant(bytes);
561
+ /**
562
+ * Check for exactly 16 UUIDv7 bytes with the RFC variant required by masking and timestamps.
563
+ * General byte input can use `bytesToUuidString`; this narrower predicate proves the version those
564
+ * v7-only operations require.
565
+ */
566
+ /*#__NO_SIDE_EFFECTS__*/
567
+ export function isUuidV7Bytes(value: unknown): value is UuidV7Bytes {
568
+ return isUuidBytes(value) && uuidVersion(value) === 7 && isRfcVariant(value);
136
569
  }
137
570
 
138
- export function extractUuidV7Timestamp(bytes: Uint8Array, offset = 0): number {
571
+ /** Read one 48-bit big-endian timestamp without allocating an intermediate representation. */
572
+ /*#__NO_SIDE_EFFECTS__*/
573
+ export function uuidTimestampFromBytesUnchecked(bytes: Uint8Array, byteOffset: number): number {
139
574
  let timestamp = 0;
140
- for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);
575
+ for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[byteOffset + i] ?? 0);
141
576
  return timestamp;
142
577
  }
143
-
144
- export function hasUuidV7Entropy(bytes: Uint8Array, offset = 0): boolean {
145
- const randA = (((bytes[offset + 6] ?? 0) & 0x0f) << 8) | (bytes[offset + 7] ?? 0);
146
- const randBFirst = (bytes[offset + 8] ?? 0) & 0x3f;
147
- let restZero = true;
148
- let restMax = true;
149
- for (let i = 9; i < 16; i += 1) {
150
- const byte = bytes[offset + i] ?? 0;
151
- if (byte !== 0x00) restZero = false;
152
- if (byte !== 0xff) restMax = false;
153
- }
154
- return (
155
- !(randA === 0 && randBFirst === 0 && restZero) &&
156
- !(randA === 0x0fff && randBFirst === 0x3f && restMax)
157
- );
158
- }