@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.
- package/LICENSE +54 -31
- package/README.md +1175 -30
- package/dist/alphabet.d.ts +9 -0
- package/dist/alphabet.d.ts.map +1 -0
- package/dist/alphabet.js +166 -0
- package/dist/alphabet.js.map +1 -0
- package/dist/base64url-name.d.ts +7 -0
- package/dist/base64url-name.d.ts.map +1 -0
- package/dist/base64url-name.js +8 -0
- package/dist/base64url-name.js.map +1 -0
- package/dist/errors.d.ts +57 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +162 -0
- package/dist/errors.js.map +1 -0
- package/dist/feistel.js +39 -0
- package/dist/feistel.js.map +1 -0
- package/dist/generation-options.js +20 -0
- package/dist/generation-options.js.map +1 -0
- package/dist/index.d.ts +23 -168
- package/dist/index.js +22 -649
- package/dist/instant.js +83 -0
- package/dist/instant.js.map +1 -0
- package/dist/mask-handle.d.ts +16 -0
- package/dist/mask-handle.d.ts.map +1 -0
- package/dist/mask-handle.js +60 -0
- package/dist/mask-handle.js.map +1 -0
- package/dist/mask.d.ts +27 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +164 -0
- package/dist/mask.js.map +1 -0
- package/dist/masking-codec-protocol.js +23 -0
- package/dist/masking-codec-protocol.js.map +1 -0
- package/dist/masking-codec-types.d.ts +245 -0
- package/dist/masking-codec-types.d.ts.map +1 -0
- package/dist/masking-codec.d.ts +19 -0
- package/dist/masking-codec.d.ts.map +1 -0
- package/dist/masking-codec.js +391 -0
- package/dist/masking-codec.js.map +1 -0
- package/dist/migration.js +129 -0
- package/dist/migration.js.map +1 -0
- package/dist/node/runtime.js +39 -0
- package/dist/node/runtime.js.map +1 -0
- package/dist/payload.d.ts +7 -0
- package/dist/payload.d.ts.map +1 -0
- package/dist/payload.js +118 -0
- package/dist/payload.js.map +1 -0
- package/dist/runtime/pool.js +30 -0
- package/dist/runtime/pool.js.map +1 -0
- package/dist/runtime/portable.js +27 -0
- package/dist/runtime/portable.js.map +1 -0
- package/dist/sentinel.js +10 -0
- package/dist/sentinel.js.map +1 -0
- package/dist/siphash.js +29 -0
- package/dist/siphash.js.map +1 -0
- package/dist/slug.d.ts +169 -0
- package/dist/slug.d.ts.map +1 -0
- package/dist/slug.js +268 -0
- package/dist/slug.js.map +1 -0
- package/dist/timestamp.d.ts +19 -0
- package/dist/timestamp.d.ts.map +1 -0
- package/dist/timestamp.js +44 -0
- package/dist/timestamp.js.map +1 -0
- package/dist/types.d.ts +535 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +8 -0
- package/dist/types.js.map +1 -0
- package/dist/uuid-value-protocol.js +46 -0
- package/dist/uuid-value-protocol.js.map +1 -0
- package/dist/uuid-value.d.ts +17 -0
- package/dist/uuid-value.d.ts.map +1 -0
- package/dist/uuid-value.js +127 -0
- package/dist/uuid-value.js.map +1 -0
- package/dist/uuid.d.ts +65 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +232 -0
- package/dist/uuid.js.map +1 -0
- package/dist/v4-slug.d.ts +16 -0
- package/dist/v4-slug.d.ts.map +1 -0
- package/dist/v4-slug.js +16 -0
- package/dist/v4-slug.js.map +1 -0
- package/dist/v4.d.ts +42 -0
- package/dist/v4.d.ts.map +1 -0
- package/dist/v4.js +85 -0
- package/dist/v4.js.map +1 -0
- package/dist/v7-bounds.d.ts +36 -0
- package/dist/v7-bounds.d.ts.map +1 -0
- package/dist/v7-bounds.js +49 -0
- package/dist/v7-bounds.js.map +1 -0
- package/dist/v7-generator-input.js +75 -0
- package/dist/v7-generator-input.js.map +1 -0
- package/dist/v7-generator.d.ts +43 -0
- package/dist/v7-generator.d.ts.map +1 -0
- package/dist/v7-generator.js +105 -0
- package/dist/v7-generator.js.map +1 -0
- package/dist/v7-keyless.d.ts +46 -0
- package/dist/v7-keyless.d.ts.map +1 -0
- package/dist/v7-keyless.js +106 -0
- package/dist/v7-keyless.js.map +1 -0
- package/dist/v7-payload.js +54 -0
- package/dist/v7-payload.js.map +1 -0
- package/dist/v7-slug.d.ts +46 -0
- package/dist/v7-slug.d.ts.map +1 -0
- package/dist/v7-slug.js +127 -0
- package/dist/v7-slug.js.map +1 -0
- package/dist/v7-timestamp.js +9 -0
- package/dist/v7-timestamp.js.map +1 -0
- package/dist/v7-value-options.js +28 -0
- package/dist/v7-value-options.js.map +1 -0
- package/dist/v7-value.d.ts +23 -0
- package/dist/v7-value.d.ts.map +1 -0
- package/dist/v7-value.js +31 -0
- package/dist/v7-value.js.map +1 -0
- package/dist/v7.js +143 -0
- package/dist/v7.js.map +1 -0
- package/package.json +18 -17
- package/src/alphabet.ts +616 -0
- package/src/base64url-name.ts +5 -0
- package/src/errors.ts +423 -13
- package/src/feistel.ts +141 -0
- package/src/generation-options.ts +48 -0
- package/src/index.ts +137 -57
- package/src/instant.ts +196 -0
- package/src/keyless.ts +9 -0
- package/src/mask-handle.ts +141 -0
- package/src/mask.ts +377 -90
- package/src/masking-codec-protocol.ts +29 -0
- package/src/masking-codec-types.ts +380 -0
- package/src/masking-codec.ts +923 -0
- package/src/migration.ts +257 -0
- package/src/payload.ts +321 -0
- package/src/runtime/bun.ts +31 -25
- package/src/runtime/node.ts +55 -18
- package/src/runtime/pool.ts +90 -0
- package/src/runtime/portable.ts +68 -0
- package/src/runtime/types.ts +30 -5
- package/src/sentinel.ts +13 -0
- package/src/siphash.ts +128 -0
- package/src/slug.ts +884 -0
- package/src/timestamp.ts +122 -0
- package/src/types.ts +799 -61
- package/src/uuid-value-protocol.ts +77 -0
- package/src/uuid-value.ts +341 -0
- package/src/uuid.ts +527 -108
- package/src/v4-slug.ts +27 -0
- package/src/v4.ts +234 -0
- package/src/v7-bounds.ts +171 -0
- package/src/v7-generator-input.ts +169 -0
- package/src/v7-generator.ts +245 -0
- package/src/v7-keyless.ts +354 -0
- package/src/v7-payload.ts +121 -0
- package/src/v7-slug.ts +293 -0
- package/src/v7-timestamp.ts +21 -0
- package/src/v7-value-options.ts +62 -0
- package/src/v7-value.ts +54 -0
- package/src/v7.ts +433 -84
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/node/index.js +0 -647
- package/dist/web/index.js +0 -648
- package/src/base64url.ts +0 -76
- package/src/codec.ts +0 -218
- package/src/runtime/web.ts +0 -20
- package/src/schema.ts +0 -123
package/src/slug.ts
ADDED
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
BASE32HEX,
|
|
5
|
+
BASE32HEX_NAME,
|
|
6
|
+
BASE64URL,
|
|
7
|
+
BASE64URL_NAME,
|
|
8
|
+
decodeInto,
|
|
9
|
+
encode,
|
|
10
|
+
isEncoded,
|
|
11
|
+
} from "./alphabet.ts";
|
|
12
|
+
import type { Alphabet } from "./alphabet.ts";
|
|
13
|
+
import {
|
|
14
|
+
checkByteRange,
|
|
15
|
+
checkRange,
|
|
16
|
+
exactLocalUuidBytes,
|
|
17
|
+
INVALID_OPTIONS,
|
|
18
|
+
INVALID_UUID,
|
|
19
|
+
INVALID_UUID_SLUG,
|
|
20
|
+
INVALID_UUID_VERSION,
|
|
21
|
+
isUuidSlugError,
|
|
22
|
+
isUint8Array,
|
|
23
|
+
normalizeUuidSlugInput,
|
|
24
|
+
normalizeUuidStringInput,
|
|
25
|
+
stringInput,
|
|
26
|
+
uuidByteView,
|
|
27
|
+
UuidSlugError,
|
|
28
|
+
} from "./errors.ts";
|
|
29
|
+
import type {
|
|
30
|
+
PlainUuidSlugInput,
|
|
31
|
+
PreserveUuidVersion,
|
|
32
|
+
PlainUuidSlug,
|
|
33
|
+
UuidBytes,
|
|
34
|
+
UuidByteInput,
|
|
35
|
+
UuidV4Bytes,
|
|
36
|
+
UuidV7Bytes,
|
|
37
|
+
UuidStringInput,
|
|
38
|
+
PlainUuidV4Slug,
|
|
39
|
+
PlainUuidV7Slug,
|
|
40
|
+
PlainUuidV7SlugInput,
|
|
41
|
+
UuidV7BytesInput,
|
|
42
|
+
UuidV7TimestampInput,
|
|
43
|
+
UuidV7TimestampWindow,
|
|
44
|
+
UuidV7Payload,
|
|
45
|
+
UuidV7PayloadLayout,
|
|
46
|
+
UuidStringFor,
|
|
47
|
+
UuidInput,
|
|
48
|
+
UuidStringResult,
|
|
49
|
+
UuidBytesResult,
|
|
50
|
+
PlainUuidSlugResult,
|
|
51
|
+
UuidOutput,
|
|
52
|
+
UuidTextCase,
|
|
53
|
+
UuidTextCaseArguments,
|
|
54
|
+
UuidV4StringFor,
|
|
55
|
+
UuidV7StringFor,
|
|
56
|
+
UuidVersion,
|
|
57
|
+
KeylessUuidInput,
|
|
58
|
+
} from "./types.ts";
|
|
59
|
+
import { UUID_TEXT_LOWERCASE } from "./types.ts";
|
|
60
|
+
import { uuidValueBytes } from "./uuid-value-protocol.ts";
|
|
61
|
+
import { extractPayloadFields } from "./v7-payload.ts";
|
|
62
|
+
|
|
63
|
+
import { validateTimestampBytes } from "./timestamp.ts";
|
|
64
|
+
import { runtime } from "#runtime";
|
|
65
|
+
import {
|
|
66
|
+
bytesToUuidString,
|
|
67
|
+
exactUuidByteView,
|
|
68
|
+
formatUuidBytesUnchecked,
|
|
69
|
+
invalidUuidBytes,
|
|
70
|
+
isUuidString,
|
|
71
|
+
resolveUuidTextCase,
|
|
72
|
+
isUuidV7Text,
|
|
73
|
+
isRfcVariant,
|
|
74
|
+
uuidTimestampFromBytesUnchecked,
|
|
75
|
+
uuidStringToBytes,
|
|
76
|
+
uuidVersion,
|
|
77
|
+
} from "./uuid.ts";
|
|
78
|
+
|
|
79
|
+
export { isUuidSlugError } from "./errors.ts";
|
|
80
|
+
export { UuidSlugError };
|
|
81
|
+
export type { UuidSlugErrorCode } from "./errors.ts";
|
|
82
|
+
export type { PlainUuidSlug, PlainUuidV4Slug, PlainUuidV7Slug } from "./types.ts";
|
|
83
|
+
|
|
84
|
+
const UUID_V7_TIMESTAMP_ONLY = "Timestamp is only defined for UUIDv7.";
|
|
85
|
+
// Capture once so caller-owned methods cannot replace encoding. A named pure capture keeps the
|
|
86
|
+
// build's removal annotation intact: decoder-only consumers must drop this encoding-only probe.
|
|
87
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
88
|
+
function captureNativePlainUuidBase64() {
|
|
89
|
+
return typeof Bun === "undefined"
|
|
90
|
+
? undefined
|
|
91
|
+
: (
|
|
92
|
+
Uint8Array.prototype as {
|
|
93
|
+
toBase64?: (options: { alphabet: typeof BASE64URL_NAME; omitPadding: boolean }) => string;
|
|
94
|
+
}
|
|
95
|
+
).toBase64;
|
|
96
|
+
}
|
|
97
|
+
let nativePlainUuidBase64 = /*#__PURE__*/ captureNativePlainUuidBase64();
|
|
98
|
+
const NATIVE_PLAIN_UUID_BASE64_OPTIONS = { alphabet: BASE64URL_NAME, omitPadding: true } as const;
|
|
99
|
+
// Keep general normalization separate from ordinary exact-array presets so its branch count does
|
|
100
|
+
// not grow their hot body. Remeasure complete calls if accepted input forms or dispatch change.
|
|
101
|
+
function uuidBytesToPlainSlugGeneral(
|
|
102
|
+
bytes: UuidByteInput | UuidSlugError,
|
|
103
|
+
offsetOrAlphabet: number | SlugAlphabet,
|
|
104
|
+
alphabet?: SlugAlphabet,
|
|
105
|
+
): PlainUuidSlug | UuidSlugError {
|
|
106
|
+
const alphabetIsSecond = typeof offsetOrAlphabet !== "number";
|
|
107
|
+
const offset = alphabetIsSecond ? 0 : offsetOrAlphabet;
|
|
108
|
+
const view = isUint8Array(bytes) ? bytes : exactUuidByteView(bytes);
|
|
109
|
+
if (view instanceof Error) return view;
|
|
110
|
+
const badRange = checkRange(view.length, offset, 16);
|
|
111
|
+
if (badRange) return badRange;
|
|
112
|
+
if (alphabetIsSecond && alphabet !== undefined)
|
|
113
|
+
return new UuidSlugError(
|
|
114
|
+
INVALID_OPTIONS,
|
|
115
|
+
"Pass the alphabet once: second for a whole UUID, or third after a numeric offset.",
|
|
116
|
+
);
|
|
117
|
+
// Unreachable from TypeScript, where the name is a two-member union. Reached from JavaScript,
|
|
118
|
+
// which is why it answers rather than indexing into `undefined`.
|
|
119
|
+
// Scalar presets already identify the alphabet; a resolver call repeats normalization work.
|
|
120
|
+
// Keep that resolver for boxed and invalid selectors. Remeasure if the alphabet set grows.
|
|
121
|
+
const selectedAlphabet = alphabetIsSecond ? offsetOrAlphabet : (alphabet ?? BASE64URL_NAME);
|
|
122
|
+
const alpha =
|
|
123
|
+
selectedAlphabet === BASE64URL_NAME
|
|
124
|
+
? BASE64URL
|
|
125
|
+
: selectedAlphabet === BASE32HEX_NAME
|
|
126
|
+
? BASE32HEX
|
|
127
|
+
: resolveSlugAlphabet(selectedAlphabet);
|
|
128
|
+
if (alpha instanceof Error) return alpha;
|
|
129
|
+
return encode(
|
|
130
|
+
view.length === 16 ? view : view.subarray(offset, offset + 16),
|
|
131
|
+
alpha,
|
|
132
|
+
) as PlainUuidSlug;
|
|
133
|
+
}
|
|
134
|
+
/*
|
|
135
|
+
* The alphabets a plain slug may be written in. base64url is the default and the shortest;
|
|
136
|
+
* base32hex costs four more characters and buys the one property base64url cannot offer: its
|
|
137
|
+
* characters are in ASCII order, so base32hex slugs of UUIDv7s sort chronologically as plain
|
|
138
|
+
* strings. Writers and guards use lowercase; decoders also accept the RFC uppercase spelling.
|
|
139
|
+
*
|
|
140
|
+
* Masked output selects its alphabet independently: base32hex preserves case-insensitive filenames,
|
|
141
|
+
* but sorting masked ciphertext does not recover chronological order.
|
|
142
|
+
*/
|
|
143
|
+
const ALTERNATIVE_SEPARATOR = " or ";
|
|
144
|
+
const textSlugScratch = new Uint8Array(16);
|
|
145
|
+
/*
|
|
146
|
+
* A byteOffset of zero is the spelling of "no offset", so it must read exactly like the standalone
|
|
147
|
+
* form for every accepted input, or a caller forwarding `offset ?? 0` through a wrapper would see
|
|
148
|
+
* text and buffers fail on the value the documentation calls the default. Only a non-zero offset
|
|
149
|
+
* needs bytes around the UUID, and `Uint8Array` is the one accepted form that can carry them:
|
|
150
|
+
* text, slugs and the exact buffer views each hold one UUID and nothing else.
|
|
151
|
+
*/
|
|
152
|
+
const BYTE_OFFSET_NEEDS_BYTES =
|
|
153
|
+
"Only Uint8Array input accepts a non-zero byteOffset. Wrap another buffer in a Uint8Array, or omit the offset.";
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Select plain-slug output: 22-character base64url, or 26-character lowercase base32hex.
|
|
157
|
+
* Base64url is shorter. Base32hex UUIDv7 slugs sort by timestamp as plain strings and are safe on
|
|
158
|
+
* case-insensitive filesystems. Decoders infer the alphabet from length. JavaScript also accepts
|
|
159
|
+
* genuine `String` objects where an alphabet is selected.
|
|
160
|
+
*/
|
|
161
|
+
export type SlugAlphabet = typeof BASE64URL_NAME | typeof BASE32HEX_NAME;
|
|
162
|
+
|
|
163
|
+
const SLUG_ALPHABET_CODECS = {
|
|
164
|
+
base32hex: BASE32HEX,
|
|
165
|
+
base64url: BASE64URL,
|
|
166
|
+
} as const satisfies Record<SlugAlphabet, Alphabet>;
|
|
167
|
+
|
|
168
|
+
/** Reject values outside the public alphabet union when untyped JavaScript bypasses TypeScript. */
|
|
169
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
170
|
+
export function resolveSlugAlphabet(alphabet: SlugAlphabet): Alphabet | UuidSlugError {
|
|
171
|
+
const name = typeof alphabet === "string" ? alphabet : stringInput(alphabet);
|
|
172
|
+
// Fixed comparisons avoid an own-property call and keyed lookup on every conversion.
|
|
173
|
+
// Packed complete-call comparisons favor this over SLUG_ALPHABET_CODECS; remeasure if
|
|
174
|
+
// the supported alphabet vocabulary grows. Wrapper normalization remains shared.
|
|
175
|
+
if (name === BASE64URL_NAME) return BASE64URL;
|
|
176
|
+
if (name === BASE32HEX_NAME) return BASE32HEX;
|
|
177
|
+
return new UuidSlugError(
|
|
178
|
+
INVALID_OPTIONS,
|
|
179
|
+
`Unknown slug alphabet; expected ${BASE64URL_NAME}${ALTERNATIVE_SEPARATOR}${BASE32HEX_NAME}.`,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */
|
|
184
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
185
|
+
function slugLength(alpha: Alphabet) {
|
|
186
|
+
return Math.ceil(128 / alpha.bitsPerChar);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are
|
|
191
|
+
* disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed
|
|
192
|
+
* rather than searched because every decode and every type guard pays this lookup.
|
|
193
|
+
*/
|
|
194
|
+
const SLUG_ALPHABET_BY_LENGTH: readonly (Alphabet | undefined)[] = /*#__PURE__*/ Object.values(
|
|
195
|
+
SLUG_ALPHABET_CODECS,
|
|
196
|
+
).reduce<(Alphabet | undefined)[]>((table, alpha) => {
|
|
197
|
+
table[slugLength(alpha)] = alpha;
|
|
198
|
+
return table;
|
|
199
|
+
}, []);
|
|
200
|
+
|
|
201
|
+
const SLUG_LENGTHS = /*#__PURE__*/ Object.values(SLUG_ALPHABET_CODECS)
|
|
202
|
+
.map((alpha) => `${slugLength(alpha)} (${alpha.name})`)
|
|
203
|
+
.join(ALTERNATIVE_SEPARATOR);
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Encode a standalone 16-byte UUID as a plain slug, using base64url by default. An `ArrayBuffer`
|
|
207
|
+
* uses its whole contents; a `DataView` uses its declared range. Invalid input or alphabet returns
|
|
208
|
+
* `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
|
|
209
|
+
*
|
|
210
|
+
* @param bytes - One exact 16-byte UUID source.
|
|
211
|
+
* @param alphabet - Output spelling. Omit for the shorter 22-character base64url form.
|
|
212
|
+
*/
|
|
213
|
+
export function uuidBytesToPlainSlug(
|
|
214
|
+
bytes: UuidByteInput | UuidSlugError,
|
|
215
|
+
alphabet?: SlugAlphabet,
|
|
216
|
+
): PlainUuidSlug | UuidSlugError;
|
|
217
|
+
/**
|
|
218
|
+
* Encode 16 bytes within a larger array as a plain slug. A preceding `UuidSlugError` is returned
|
|
219
|
+
* unchanged.
|
|
220
|
+
*
|
|
221
|
+
* @param bytes - Array containing at least one complete 16-byte UUID.
|
|
222
|
+
* @param byteOffset - Zero-based index where the UUID starts.
|
|
223
|
+
* @param alphabet - Output spelling. Omit for the shorter 22-character base64url form.
|
|
224
|
+
*/
|
|
225
|
+
export function uuidBytesToPlainSlug(
|
|
226
|
+
bytes: Uint8Array | UuidSlugError,
|
|
227
|
+
byteOffset: number,
|
|
228
|
+
alphabet?: SlugAlphabet,
|
|
229
|
+
): PlainUuidSlug | UuidSlugError;
|
|
230
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
231
|
+
export function uuidBytesToPlainSlug(
|
|
232
|
+
bytes: UuidByteInput | UuidSlugError,
|
|
233
|
+
offsetOrAlphabet: number | SlugAlphabet = 0,
|
|
234
|
+
alphabet?: SlugAlphabet,
|
|
235
|
+
): PlainUuidSlug | UuidSlugError {
|
|
236
|
+
// Exact-array presets share one payload check and one writer choice. Duplicate selectors and
|
|
237
|
+
// non-zero offsets must retain general validation; they cannot become successful preset calls.
|
|
238
|
+
if (isUint8Array(bytes) && bytes.length === 16) {
|
|
239
|
+
const selectedAlphabet =
|
|
240
|
+
offsetOrAlphabet === 0
|
|
241
|
+
? (alphabet ?? BASE64URL_NAME)
|
|
242
|
+
: alphabet === undefined
|
|
243
|
+
? offsetOrAlphabet
|
|
244
|
+
: undefined;
|
|
245
|
+
if (selectedAlphabet === BASE32HEX_NAME) return encode(bytes, BASE32HEX) as PlainUuidSlug;
|
|
246
|
+
// Native encoding owns this exact plain-payload job. Offset windows and non-array forms retain
|
|
247
|
+
// general conversion; masked tails never enter here. Keep base32 controls in the comparison
|
|
248
|
+
// when changing this dispatch (bench/PERFORMANCE.md).
|
|
249
|
+
if (selectedAlphabet === BASE64URL_NAME) {
|
|
250
|
+
if (nativePlainUuidBase64) {
|
|
251
|
+
try {
|
|
252
|
+
return nativePlainUuidBase64.call(
|
|
253
|
+
bytes,
|
|
254
|
+
NATIVE_PLAIN_UUID_BASE64_OPTIONS,
|
|
255
|
+
) as PlainUuidSlug;
|
|
256
|
+
} catch {
|
|
257
|
+
// Valid payloads must not pay for the same unavailable host capability on every call.
|
|
258
|
+
nativePlainUuidBase64 = undefined;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// An absent capability must not add a normalization call for an already validated payload.
|
|
262
|
+
return encode(bytes, BASE64URL) as PlainUuidSlug;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return uuidBytesToPlainSlugGeneral(bytes, offsetOrAlphabet, alphabet);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Decode a canonical plain slug into a new plain 16-byte `Uint8Array`. Its length selects
|
|
270
|
+
* base64url or base32hex. Known UUID and masked values are rejected by TypeScript; invalid input
|
|
271
|
+
* returns `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
|
|
272
|
+
*
|
|
273
|
+
* @param plainUuidSlug - Canonical 22-character base64url or 26-character base32hex plain UUID slug.
|
|
274
|
+
* JavaScript also accepts a genuine `String` object.
|
|
275
|
+
*/
|
|
276
|
+
export function plainSlugToUuidBytes<Input extends string | UuidSlugError>(
|
|
277
|
+
plainUuidSlug: PlainUuidSlugInput<Input>,
|
|
278
|
+
): PreserveUuidVersion<Input, UuidBytes, UuidV4Bytes, UuidV7Bytes> | UuidSlugError;
|
|
279
|
+
/**
|
|
280
|
+
* Decode a canonical plain slug into caller-owned storage after validating the full input. A
|
|
281
|
+
* preceding `UuidSlugError` is returned unchanged without writing.
|
|
282
|
+
*
|
|
283
|
+
* @param plainUuidSlug - Canonical 22-character base64url or 26-character base32hex plain UUID slug.
|
|
284
|
+
* JavaScript also accepts a genuine `String` object.
|
|
285
|
+
* @param output - Caller-owned array that receives the 16 UUID bytes.
|
|
286
|
+
* @param outputOffset - Zero-based index where writing starts. Omit to start at index 0. Bytes
|
|
287
|
+
* outside the written range stay unchanged.
|
|
288
|
+
*/
|
|
289
|
+
export function plainSlugToUuidBytes<
|
|
290
|
+
Input extends string | UuidSlugError,
|
|
291
|
+
Output extends Uint8Array,
|
|
292
|
+
>(
|
|
293
|
+
plainUuidSlug: PlainUuidSlugInput<Input>,
|
|
294
|
+
output: Output,
|
|
295
|
+
outputOffset?: number,
|
|
296
|
+
): UuidOutput<Output> | UuidSlugError;
|
|
297
|
+
export function plainSlugToUuidBytes(
|
|
298
|
+
plainUuidSlug: string | UuidSlugError,
|
|
299
|
+
output?: Uint8Array,
|
|
300
|
+
outputOffset = 0,
|
|
301
|
+
): Uint8Array | UuidSlugError {
|
|
302
|
+
let slug = plainUuidSlug;
|
|
303
|
+
if (typeof slug !== "string") {
|
|
304
|
+
slug = normalizeUuidSlugInput(slug);
|
|
305
|
+
if (typeof slug !== "string") return slug;
|
|
306
|
+
}
|
|
307
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
308
|
+
if (!alpha)
|
|
309
|
+
return new UuidSlugError(
|
|
310
|
+
INVALID_UUID_SLUG,
|
|
311
|
+
slug.length === 27
|
|
312
|
+
? "27 characters is a masked base32hex slug; decode it with the codec that issued it."
|
|
313
|
+
: `UUID slug must be ${SLUG_LENGTHS} characters, got ${slug.length}.`,
|
|
314
|
+
);
|
|
315
|
+
const target = output ?? new Uint8Array(16);
|
|
316
|
+
const badRange =
|
|
317
|
+
output === undefined
|
|
318
|
+
? checkRange(16, outputOffset, 16)
|
|
319
|
+
: checkByteRange(output, outputOffset, 16);
|
|
320
|
+
if (badRange) return badRange;
|
|
321
|
+
if (output && !isEncoded(slug, alpha, 16, true)) {
|
|
322
|
+
for (let i = 0; i < slug.length; i += 1) {
|
|
323
|
+
const code = slug.charCodeAt(i);
|
|
324
|
+
if (code >= 128 || (alpha.decode[code] as number) < 0)
|
|
325
|
+
return new UuidSlugError(
|
|
326
|
+
alpha.code,
|
|
327
|
+
`Invalid ${alpha.name} character ${JSON.stringify(slug[i])} at offset ${i}.`,
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
return new UuidSlugError(alpha.code, `${alpha.name} value has non-canonical trailing bits.`);
|
|
331
|
+
}
|
|
332
|
+
const result = decodeInto(slug, alpha, target, outputOffset, 16);
|
|
333
|
+
return result instanceof Error ? result : target;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Encode accepted mixed-case UUID text as a reversible plain slug, using base64url by default.
|
|
338
|
+
* A known UUID version is preserved in the result type. TypeScript rejects known slug
|
|
339
|
+
* values; invalid text or alphabet returns `UuidSlugError`. A preceding `UuidSlugError` is returned
|
|
340
|
+
* unchanged.
|
|
341
|
+
*
|
|
342
|
+
* @param uuid - UUID text in an accepted spelling. JavaScript also accepts a genuine `String` object.
|
|
343
|
+
* @param alphabet - Output spelling. Omit for the shorter 22-character base64url form.
|
|
344
|
+
*/
|
|
345
|
+
export function uuidStringToPlainSlug<Input extends string | UuidSlugError>(
|
|
346
|
+
uuid: UuidStringInput<Input>,
|
|
347
|
+
alphabet?: SlugAlphabet,
|
|
348
|
+
): PreserveUuidVersion<Input, PlainUuidSlug, PlainUuidV4Slug, PlainUuidV7Slug> | UuidSlugError;
|
|
349
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
350
|
+
export function uuidStringToPlainSlug(
|
|
351
|
+
uuid: string | UuidSlugError,
|
|
352
|
+
alphabet: SlugAlphabet = BASE64URL_NAME,
|
|
353
|
+
): PlainUuidSlug | UuidSlugError {
|
|
354
|
+
let uuidText = uuid;
|
|
355
|
+
if (typeof uuidText !== "string") {
|
|
356
|
+
uuidText = normalizeUuidStringInput(uuidText);
|
|
357
|
+
if (typeof uuidText !== "string") return uuidText;
|
|
358
|
+
}
|
|
359
|
+
const alpha = resolveSlugAlphabet(alphabet);
|
|
360
|
+
if (alpha instanceof Error) return alpha;
|
|
361
|
+
// Resolve caller selectors before scratch is live, then parse and encode without callbacks.
|
|
362
|
+
// Separate text-to-slug
|
|
363
|
+
// writers read hex pairs and concatenated characters, and were slower on every runtime
|
|
364
|
+
// (bench/PERFORMANCE.md). Reassess scratch ownership if encoding adds caller-controlled work.
|
|
365
|
+
const bytes = uuidStringToBytes(uuidText, textSlugScratch);
|
|
366
|
+
if (bytes instanceof Error) return bytes;
|
|
367
|
+
return encode(bytes, alpha) as PlainUuidSlug;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Decode a plain slug to hyphenated UUID text; its length selects base64url or base32hex.
|
|
372
|
+
* Base32hex input accepts uppercase or lowercase. Base64url remains case-sensitive.
|
|
373
|
+
* A known UUID version is preserved in the result type. TypeScript rejects known UUID and masked
|
|
374
|
+
* values; invalid input returns `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
|
|
375
|
+
*
|
|
376
|
+
* @param plainUuidSlug - Canonical 22-character base64url or 26-character base32hex plain UUID slug.
|
|
377
|
+
* @param textCase - Built-in output spelling. Omit for lowercase.
|
|
378
|
+
*/
|
|
379
|
+
export function plainSlugToUuidString<
|
|
380
|
+
Input extends string | UuidSlugError,
|
|
381
|
+
Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
|
|
382
|
+
>(
|
|
383
|
+
plainUuidSlug: PlainUuidSlugInput<Input>,
|
|
384
|
+
...textCase: UuidTextCaseArguments<Case>
|
|
385
|
+
):
|
|
386
|
+
| PreserveUuidVersion<Input, UuidStringFor<Case>, UuidV4StringFor<Case>, UuidV7StringFor<Case>>
|
|
387
|
+
| UuidSlugError;
|
|
388
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
389
|
+
export function plainSlugToUuidString(
|
|
390
|
+
plainUuidSlug: string | UuidSlugError,
|
|
391
|
+
textCase: UuidTextCase = UUID_TEXT_LOWERCASE,
|
|
392
|
+
): string | UuidSlugError {
|
|
393
|
+
const selectedCase = resolveUuidTextCase(textCase);
|
|
394
|
+
if (selectedCase instanceof Error) return selectedCase;
|
|
395
|
+
let slug = plainUuidSlug;
|
|
396
|
+
if (typeof slug !== "string") {
|
|
397
|
+
slug = normalizeUuidSlugInput(slug);
|
|
398
|
+
if (typeof slug !== "string") return slug;
|
|
399
|
+
}
|
|
400
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
401
|
+
// decodeInto validates while writing. Private scratch needs no transactional prevalidation
|
|
402
|
+
// or discarded owned array from plainSlugToUuidBytes; caller buffers still require both passes.
|
|
403
|
+
// Normalize before scratch is live, then decode and format without caller callbacks. Revisit
|
|
404
|
+
// reuse if either operation gains callbacks; failed writes cannot escape this private buffer.
|
|
405
|
+
// The public byte decoder owns invalid-length diagnostics, so keep that exceptional path shared.
|
|
406
|
+
const decoded = alpha
|
|
407
|
+
? decodeInto(slug, alpha, textSlugScratch, 0, 16)
|
|
408
|
+
: plainSlugToUuidBytes(slug);
|
|
409
|
+
if (decoded instanceof Error) return decoded;
|
|
410
|
+
// A successful decode yields exactly 16 bytes, so the checked formatter would repeat work.
|
|
411
|
+
return formatUuidBytesUnchecked(textSlugScratch, 0, selectedCase);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// Package-created decode failures are local Errors. A caller-owned cross-realm package error is
|
|
415
|
+
// the only failure arm that can bypass `instanceof`, and this function returns it unchanged;
|
|
416
|
+
// identity keeps marker recognition off successful conversion paths.
|
|
417
|
+
export function decodeKeylessUuid(uuid: unknown): Uint8Array | UuidSlugError {
|
|
418
|
+
let text: string;
|
|
419
|
+
if (typeof uuid === "string") text = uuid;
|
|
420
|
+
else {
|
|
421
|
+
const input = readObjectUuidInput(uuid);
|
|
422
|
+
if (typeof input !== "string") return input;
|
|
423
|
+
text = input;
|
|
424
|
+
}
|
|
425
|
+
return text.length === 22 || text.length === 26
|
|
426
|
+
? plainSlugToUuidBytes(text)
|
|
427
|
+
: uuidStringToBytes(text);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Read a non-string UUID input as borrowed bytes, a parsed UUID's bytes, recovered `String` text, or
|
|
432
|
+
* the failure it carries. An error is built only when nothing matches: a discarded error would make
|
|
433
|
+
* every accepted object pay for a stack capture that costs more than the conversion.
|
|
434
|
+
*/
|
|
435
|
+
export function readObjectUuidInput(uuid: unknown): Uint8Array | string | UuidSlugError {
|
|
436
|
+
const view = uuidByteView(uuid);
|
|
437
|
+
if (view) return view.length === 16 ? view : invalidUuidBytes();
|
|
438
|
+
const valueBytes = uuidValueBytes(uuid);
|
|
439
|
+
if (valueBytes) return valueBytes;
|
|
440
|
+
if (isUuidSlugError(uuid)) return uuid;
|
|
441
|
+
return stringInput(uuid) ?? invalidUuidBytes();
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Return the four-bit UUID version field from UUID text, exact bytes, or a plain slug after full
|
|
446
|
+
* input validation. This reports the stored field, including zero for nil and 15 for max; it does
|
|
447
|
+
* not prove that the UUID has the RFC variant or that the version is assigned.
|
|
448
|
+
*
|
|
449
|
+
* @param uuid - Any unmasked UUID representation supported by the package.
|
|
450
|
+
*/
|
|
451
|
+
export function extractUuidVersion<Input extends UuidInput>(
|
|
452
|
+
uuid: KeylessUuidInput<Input>,
|
|
453
|
+
): UuidVersion | UuidSlugError {
|
|
454
|
+
const localBytes = exactLocalUuidBytes(uuid);
|
|
455
|
+
if (localBytes) return uuidVersion(localBytes, 0);
|
|
456
|
+
const bytes = decodeKeylessUuid(uuid);
|
|
457
|
+
if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
|
|
458
|
+
return uuidVersion(bytes, 0);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Convert UUID text, bytes, or a plain UUID slug to new or caller-owned UUID bytes.
|
|
463
|
+
* Only `Uint8Array` input accepts a non-zero offset; `0` means the same as omitting it.
|
|
464
|
+
*
|
|
465
|
+
* @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
|
|
466
|
+
*/
|
|
467
|
+
export function uuidToBytes<Input extends UuidInput>(
|
|
468
|
+
uuid: KeylessUuidInput<Input>,
|
|
469
|
+
): UuidBytesResult<Input>;
|
|
470
|
+
export function uuidToBytes<Input extends UuidInput, Output extends Uint8Array>(
|
|
471
|
+
uuid: KeylessUuidInput<Input>,
|
|
472
|
+
output: Output,
|
|
473
|
+
outputOffset?: number,
|
|
474
|
+
): UuidOutput<Output> | UuidSlugError;
|
|
475
|
+
export function uuidToBytes(uuid: Uint8Array, byteOffset: number): UuidBytesResult<Uint8Array>;
|
|
476
|
+
export function uuidToBytes<Output extends Uint8Array>(
|
|
477
|
+
uuid: Uint8Array,
|
|
478
|
+
byteOffset: number,
|
|
479
|
+
output: Output,
|
|
480
|
+
outputOffset?: number,
|
|
481
|
+
): UuidOutput<Output> | UuidSlugError;
|
|
482
|
+
export function uuidToBytes(
|
|
483
|
+
uuid: unknown,
|
|
484
|
+
outputOrByteOffset?: unknown,
|
|
485
|
+
outputOrOutputOffset?: unknown,
|
|
486
|
+
offsetAfterOutput = 0,
|
|
487
|
+
): Uint8Array | UuidSlugError {
|
|
488
|
+
const readsAtOffset = typeof outputOrByteOffset === "number";
|
|
489
|
+
const output = readsAtOffset ? outputOrOutputOffset : outputOrByteOffset;
|
|
490
|
+
const outputOffset = readsAtOffset
|
|
491
|
+
? offsetAfterOutput
|
|
492
|
+
: ((outputOrOutputOffset as number | undefined) ?? 0);
|
|
493
|
+
const badRange = output === undefined ? undefined : checkByteRange(output, outputOffset, 16);
|
|
494
|
+
if (badRange) return badRange;
|
|
495
|
+
const destination = output as Uint8Array | undefined;
|
|
496
|
+
if (readsAtOffset) {
|
|
497
|
+
const byteOffset = outputOrByteOffset;
|
|
498
|
+
if (isUint8Array(uuid)) {
|
|
499
|
+
const badSource = checkRange(uuid.length, byteOffset, 16);
|
|
500
|
+
if (badSource) return badSource;
|
|
501
|
+
const source = uuid.subarray(byteOffset, byteOffset + 16);
|
|
502
|
+
if (!destination) return new Uint8Array(source);
|
|
503
|
+
destination.set(source, outputOffset);
|
|
504
|
+
return destination;
|
|
505
|
+
}
|
|
506
|
+
if (byteOffset !== 0) return new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
507
|
+
}
|
|
508
|
+
const localBytes = exactLocalUuidBytes(uuid);
|
|
509
|
+
if (localBytes) {
|
|
510
|
+
if (!destination) return new Uint8Array(localBytes);
|
|
511
|
+
destination.set(localBytes, outputOffset);
|
|
512
|
+
return destination;
|
|
513
|
+
}
|
|
514
|
+
const bytes = decodeKeylessUuid(uuid);
|
|
515
|
+
if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
|
|
516
|
+
// Text decoders already own fresh bytes; only borrowed binary or parsed input needs a copy.
|
|
517
|
+
if (!destination) return typeof uuid === "string" ? bytes : new Uint8Array(bytes);
|
|
518
|
+
destination.set(bytes, outputOffset);
|
|
519
|
+
return destination;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Convert UUID text, bytes, or a plain UUID slug to normalized UUID text.
|
|
524
|
+
* Only `Uint8Array` input accepts a non-zero offset; `0` means the same as omitting it.
|
|
525
|
+
*
|
|
526
|
+
* @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
|
|
527
|
+
*/
|
|
528
|
+
export function uuidToString<
|
|
529
|
+
Input extends UuidInput,
|
|
530
|
+
Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
|
|
531
|
+
>(
|
|
532
|
+
uuid: KeylessUuidInput<Input>,
|
|
533
|
+
...textCase: UuidTextCaseArguments<Case>
|
|
534
|
+
): UuidStringResult<Input, Case>;
|
|
535
|
+
export function uuidToString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
|
|
536
|
+
uuid: Uint8Array,
|
|
537
|
+
byteOffset: number,
|
|
538
|
+
...textCase: UuidTextCaseArguments<Case>
|
|
539
|
+
): UuidStringResult<Uint8Array, Case>;
|
|
540
|
+
export function uuidToString(
|
|
541
|
+
uuid: unknown,
|
|
542
|
+
byteOffsetOrCase: number | UuidTextCase = UUID_TEXT_LOWERCASE,
|
|
543
|
+
caseAfterOffset: UuidTextCase = UUID_TEXT_LOWERCASE,
|
|
544
|
+
): string | UuidSlugError {
|
|
545
|
+
let textCase: UuidTextCase;
|
|
546
|
+
if (typeof byteOffsetOrCase === "number") {
|
|
547
|
+
if (isUint8Array(uuid)) return bytesToUuidString(uuid, byteOffsetOrCase, caseAfterOffset);
|
|
548
|
+
if (byteOffsetOrCase !== 0) return new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
549
|
+
textCase = caseAfterOffset;
|
|
550
|
+
} else textCase = byteOffsetOrCase;
|
|
551
|
+
// Canonical lowercase text is already the default output, so it is returned without decoding.
|
|
552
|
+
// An inline `typeof` guard ahead of the helper slowed Node mixed-case text (bench/PERFORMANCE.md).
|
|
553
|
+
if (textCase === UUID_TEXT_LOWERCASE && isUuidString(uuid)) return uuid;
|
|
554
|
+
const localBytes = exactLocalUuidBytes(uuid);
|
|
555
|
+
if (localBytes) {
|
|
556
|
+
const selectedCase = resolveUuidTextCase(textCase);
|
|
557
|
+
if (selectedCase instanceof Error) return selectedCase;
|
|
558
|
+
return formatUuidBytesUnchecked(localBytes, 0, selectedCase);
|
|
559
|
+
}
|
|
560
|
+
const input = typeof uuid === "string" ? uuid : readObjectUuidInput(uuid);
|
|
561
|
+
// Canonical mixed text needs only case normalization, not uuidStringToBytes and formatting.
|
|
562
|
+
// Compact and wrapped text keep that parser; reconstructing them slowed complete calls.
|
|
563
|
+
// Remeasure these boundaries when the guard or native string operations change.
|
|
564
|
+
if (typeof input === "string" && input.length === 36) {
|
|
565
|
+
const lower = input.toLowerCase();
|
|
566
|
+
if (isUuidString(lower)) {
|
|
567
|
+
const selectedCase = resolveUuidTextCase(textCase);
|
|
568
|
+
if (selectedCase instanceof Error) return selectedCase;
|
|
569
|
+
return selectedCase === UUID_TEXT_LOWERCASE ? lower : lower.toUpperCase();
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
// Only text leaves this call. Reuse private scratch instead of an owned decode array;
|
|
573
|
+
// public caller-buffer decoding adds validation and copying (bench/PERFORMANCE.md).
|
|
574
|
+
const alpha = typeof input === "string" ? SLUG_ALPHABET_BY_LENGTH[input.length] : undefined;
|
|
575
|
+
const decoded =
|
|
576
|
+
typeof input === "string"
|
|
577
|
+
? alpha
|
|
578
|
+
? decodeInto(input, alpha, textSlugScratch, 0, 16)
|
|
579
|
+
: uuidStringToBytes(input)
|
|
580
|
+
: input;
|
|
581
|
+
const bytes = typeof decoded === "number" ? textSlugScratch : decoded;
|
|
582
|
+
if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
|
|
583
|
+
const selectedCase = resolveUuidTextCase(textCase);
|
|
584
|
+
if (selectedCase instanceof Error) return selectedCase;
|
|
585
|
+
// A successful decode yields exactly 16 bytes, so the checked formatter's range and argument
|
|
586
|
+
// dispatch would repeat work.
|
|
587
|
+
return formatUuidBytesUnchecked(bytes, 0, selectedCase);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Convert UUID text, bytes, or a plain UUID slug to a plain slug.
|
|
592
|
+
* Only `Uint8Array` input accepts a non-zero offset; `0` means the same as omitting it.
|
|
593
|
+
*
|
|
594
|
+
* @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
|
|
595
|
+
*/
|
|
596
|
+
export function uuidToPlainSlug<Input extends UuidInput>(
|
|
597
|
+
uuid: KeylessUuidInput<Input>,
|
|
598
|
+
alphabet?: SlugAlphabet,
|
|
599
|
+
): PlainUuidSlugResult<Input>;
|
|
600
|
+
export function uuidToPlainSlug(
|
|
601
|
+
uuid: Uint8Array,
|
|
602
|
+
byteOffset: number,
|
|
603
|
+
alphabet?: SlugAlphabet,
|
|
604
|
+
): PlainUuidSlugResult<Uint8Array>;
|
|
605
|
+
export function uuidToPlainSlug(
|
|
606
|
+
uuid: unknown,
|
|
607
|
+
byteOffsetOrAlphabet: number | SlugAlphabet = BASE64URL_NAME,
|
|
608
|
+
alphabetAfterOffset: SlugAlphabet = BASE64URL_NAME,
|
|
609
|
+
): PlainUuidSlug | UuidSlugError {
|
|
610
|
+
let alphabet: SlugAlphabet;
|
|
611
|
+
if (typeof byteOffsetOrAlphabet === "number") {
|
|
612
|
+
if (isUint8Array(uuid))
|
|
613
|
+
return uuidBytesToPlainSlug(uuid, byteOffsetOrAlphabet, alphabetAfterOffset);
|
|
614
|
+
if (byteOffsetOrAlphabet !== 0)
|
|
615
|
+
return new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
616
|
+
alphabet = alphabetAfterOffset;
|
|
617
|
+
} else alphabet = byteOffsetOrAlphabet;
|
|
618
|
+
const localBytes = exactLocalUuidBytes(uuid);
|
|
619
|
+
if (localBytes) return uuidBytesToPlainSlug(localBytes, alphabet);
|
|
620
|
+
const bytes = decodeKeylessUuid(uuid);
|
|
621
|
+
if (bytes instanceof Error || (bytes === uuid && isUuidSlugError(bytes))) return bytes;
|
|
622
|
+
return uuidBytesToPlainSlug(bytes, alphabet);
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Check a canonical 22-character base64url or 26-character lowercase base32hex plain slug. */
|
|
626
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
627
|
+
export function isPlainUuidSlug(value: unknown): value is PlainUuidSlug {
|
|
628
|
+
if (typeof value !== "string" || !value) return false;
|
|
629
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[value.length];
|
|
630
|
+
return alpha !== undefined && isEncoded(value, alpha, 16);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Read only the version/variant bytes after canonical validation, without decoding a whole UUID. */
|
|
634
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
635
|
+
function slugByte(slug: string, alpha: Alphabet, offset: number): number {
|
|
636
|
+
const start = Math.floor((offset * 8) / alpha.bitsPerChar);
|
|
637
|
+
const end = Math.floor((offset * 8 + 7) / alpha.bitsPerChar);
|
|
638
|
+
let value = 0;
|
|
639
|
+
for (let i = start; i <= end; i += 1)
|
|
640
|
+
value = (value << alpha.bitsPerChar) | (alpha.decode[slug.charCodeAt(i)] as number);
|
|
641
|
+
return (value >>> ((end + 1) * alpha.bitsPerChar - (offset + 1) * 8)) & 255;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
645
|
+
function isVersionedSlug(slug: unknown, version: number): slug is PlainUuidSlug {
|
|
646
|
+
if (!isPlainUuidSlug(slug)) return false;
|
|
647
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length] as Alphabet;
|
|
648
|
+
return slugByte(slug, alpha, 6) >>> 4 === version && slugByte(slug, alpha, 8) >>> 6 === 2;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** Check a canonical plain slug whose payload is an RFC-variant UUIDv4. */
|
|
652
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
653
|
+
export function isPlainUuidV4Slug(value: unknown): value is PlainUuidV4Slug {
|
|
654
|
+
return isVersionedSlug(value, 4);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** Check a canonical plain slug whose payload is an RFC-variant UUIDv7. */
|
|
658
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
659
|
+
export function isPlainUuidV7Slug(value: unknown): value is PlainUuidV7Slug {
|
|
660
|
+
return isVersionedSlug(value, 7);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function validatedHexNibble(text: string, index: number): number {
|
|
664
|
+
// Full text validation precedes this read; both ASCII hex cases share their low four bits.
|
|
665
|
+
const code = text.charCodeAt(index);
|
|
666
|
+
return (code & 15) + (code > 57 ? 9 : 0);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function fixedCanonicalUuidV7UnixMs(text: string): number {
|
|
670
|
+
// Fixed reads avoid parseInt's sliced/joined strings. Split at 32 bits and unsigned-coerce the
|
|
671
|
+
// low word so timestamps above its sign bit preserve all 48 bits. Only validated canonical text
|
|
672
|
+
// reaches this helper; compact text retains its contiguous parse. Table reads slightly favor
|
|
673
|
+
// Bun but lose on Node in the source screen; remeasure complete calls after parser or engine
|
|
674
|
+
// changes (bench/PERFORMANCE.md).
|
|
675
|
+
const high =
|
|
676
|
+
(validatedHexNibble(text, 0) << 12) |
|
|
677
|
+
(validatedHexNibble(text, 1) << 8) |
|
|
678
|
+
(validatedHexNibble(text, 2) << 4) |
|
|
679
|
+
validatedHexNibble(text, 3);
|
|
680
|
+
const low =
|
|
681
|
+
((validatedHexNibble(text, 4) << 28) |
|
|
682
|
+
(validatedHexNibble(text, 5) << 24) |
|
|
683
|
+
(validatedHexNibble(text, 6) << 20) |
|
|
684
|
+
(validatedHexNibble(text, 7) << 16) |
|
|
685
|
+
(validatedHexNibble(text, 9) << 12) |
|
|
686
|
+
(validatedHexNibble(text, 10) << 8) |
|
|
687
|
+
(validatedHexNibble(text, 11) << 4) |
|
|
688
|
+
validatedHexNibble(text, 12)) >>>
|
|
689
|
+
0;
|
|
690
|
+
return high * 0x1_0000_0000 + low;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function parsedCanonicalUuidV7UnixMs(text: string): number {
|
|
694
|
+
// Native radix parsing avoids interpreted digit calls when Node disables its JIT.
|
|
695
|
+
return parseInt(text.slice(0, 8) + text.slice(9, 13), 16);
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// Reuse the runtime's settled JIT selection; no flag parsing or table construction belongs here.
|
|
699
|
+
// Recheck both complete calls after engine changes against bench/PERFORMANCE.md.
|
|
700
|
+
const canonicalUuidV7UnixMsUnchecked = runtime.jitless
|
|
701
|
+
? parsedCanonicalUuidV7UnixMs
|
|
702
|
+
: fixedCanonicalUuidV7UnixMs;
|
|
703
|
+
|
|
704
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
705
|
+
function extractStringTimestamp(value: string): number | UuidSlugError {
|
|
706
|
+
let timestamp = 0;
|
|
707
|
+
if (isUuidV7Text(value) && (value.length === 32 || value.length === 36))
|
|
708
|
+
return value.length === 36
|
|
709
|
+
? canonicalUuidV7UnixMsUnchecked(value)
|
|
710
|
+
: parseInt(value.slice(0, 12), 16);
|
|
711
|
+
if (isPlainUuidV7Slug(value)) {
|
|
712
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[value.length] as Alphabet;
|
|
713
|
+
for (let index = 0; index < 6; index += 1)
|
|
714
|
+
timestamp = timestamp * 256 + slugByte(value, alpha, index);
|
|
715
|
+
return timestamp;
|
|
716
|
+
}
|
|
717
|
+
const bytes = uuidStringToBytes(value);
|
|
718
|
+
if (!(bytes instanceof Error)) {
|
|
719
|
+
if (uuidVersion(bytes) !== 7 || !isRfcVariant(bytes))
|
|
720
|
+
return new UuidSlugError(INVALID_UUID_VERSION, UUID_V7_TIMESTAMP_ONLY);
|
|
721
|
+
return uuidTimestampFromBytesUnchecked(bytes, 0);
|
|
722
|
+
}
|
|
723
|
+
if (isPlainUuidSlug(value))
|
|
724
|
+
return new UuidSlugError(INVALID_UUID_VERSION, UUID_V7_TIMESTAMP_ONLY);
|
|
725
|
+
return new UuidSlugError(INVALID_UUID, "Expected UUIDv7 text or a plain UUIDv7 slug.");
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Return the 48-bit Unix millisecond encoded by accepted UUIDv7 text, a plain UUIDv7 slug, or
|
|
730
|
+
* UUIDv7 bytes. Compact and canonical text and both plain slug alphabets avoid a byte allocation.
|
|
731
|
+
* Use `codec.extractMaskedUuidV7UnixMs` for masked or sentinel slugs. Other UUID versions and malformed
|
|
732
|
+
* values return `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
|
|
733
|
+
*
|
|
734
|
+
* @param value - UUIDv7 text in an accepted spelling, or a plain UUIDv7 slug in either alphabet.
|
|
735
|
+
*/
|
|
736
|
+
export function extractUuidV7UnixMs<Input extends string | UuidSlugError>(
|
|
737
|
+
value: UuidV7TimestampInput<Input>,
|
|
738
|
+
): number | UuidSlugError;
|
|
739
|
+
/**
|
|
740
|
+
* Return the 48-bit Unix millisecond encoded by UUIDv7 bytes. An `ArrayBuffer` uses its whole
|
|
741
|
+
* contents; a `DataView` uses its declared range. Only `Uint8Array` input accepts a non-zero
|
|
742
|
+
* offset; `0` means the same as omitting it.
|
|
743
|
+
*
|
|
744
|
+
* @param value - One supported UUIDv7 byte source.
|
|
745
|
+
* @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
|
|
746
|
+
*/
|
|
747
|
+
export function extractUuidV7UnixMs<Input extends UuidByteInput | UuidSlugError>(
|
|
748
|
+
value: UuidV7BytesInput<Input>,
|
|
749
|
+
byteOffset?: number,
|
|
750
|
+
): number | UuidSlugError;
|
|
751
|
+
/** Read Unix milliseconds from supported text/byte unions; a preceding error passes through unchanged. */
|
|
752
|
+
export function extractUuidV7UnixMs<Input extends string | UuidByteInput | UuidSlugError>(
|
|
753
|
+
value: UuidV7TimestampInput<Input>,
|
|
754
|
+
): number | UuidSlugError;
|
|
755
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
756
|
+
export function extractUuidV7UnixMs(
|
|
757
|
+
value: string | UuidByteInput | UuidSlugError,
|
|
758
|
+
byteOffset = 0,
|
|
759
|
+
): number | UuidSlugError {
|
|
760
|
+
if (typeof value === "string")
|
|
761
|
+
return byteOffset === 0
|
|
762
|
+
? extractStringTimestamp(value)
|
|
763
|
+
: new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
764
|
+
if (isUuidSlugError(value)) return value;
|
|
765
|
+
if (byteOffset !== 0 && !isUint8Array(value))
|
|
766
|
+
return new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
767
|
+
const bytes = isUint8Array(value) ? value : exactUuidByteView(value);
|
|
768
|
+
if (bytes instanceof Error) {
|
|
769
|
+
const text = stringInput(value);
|
|
770
|
+
return text === undefined ? bytes : extractStringTimestamp(text);
|
|
771
|
+
}
|
|
772
|
+
const badRange = checkRange(bytes.length, byteOffset, 16);
|
|
773
|
+
if (badRange) return badRange;
|
|
774
|
+
if (uuidVersion(bytes, byteOffset) !== 7 || !isRfcVariant(bytes, byteOffset))
|
|
775
|
+
return new UuidSlugError(INVALID_UUID_VERSION, UUID_V7_TIMESTAMP_ONLY);
|
|
776
|
+
return uuidTimestampFromBytesUnchecked(bytes, byteOffset);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Decode the UUIDv7 payload under a layout supplied by the caller. The UUID does not identify its
|
|
781
|
+
* generator or payload layout, so this operation never guesses. Fraction bits follow RFC 9562
|
|
782
|
+
* Method 3; counter bits immediately follow them as in Method 1. All other bits remain uninterpreted.
|
|
783
|
+
*
|
|
784
|
+
* @param value - UUIDv7 text in an accepted spelling, or a plain UUIDv7 slug in either alphabet.
|
|
785
|
+
* @param layout - Known leading fraction and fixed-counter widths.
|
|
786
|
+
* @returns The millisecond timestamp, declared fields, and every undeclared low payload bit; or a
|
|
787
|
+
* `UuidSlugError` for an invalid UUID, byte range, or layout.
|
|
788
|
+
* @remarks A fraction value `n` in `b` bits identifies the half-open interval
|
|
789
|
+
* `[unixMs + n / 2**b, unixMs + (n + 1) / 2**b)` milliseconds, not an exact instant.
|
|
790
|
+
*/
|
|
791
|
+
export function extractUuidV7Payload<Input extends string | UuidSlugError>(
|
|
792
|
+
value: UuidV7TimestampInput<Input>,
|
|
793
|
+
layout: UuidV7PayloadLayout,
|
|
794
|
+
): UuidV7Payload | UuidSlugError;
|
|
795
|
+
/**
|
|
796
|
+
* Decode a UUIDv7 byte source under the same caller-supplied payload layout. Only `Uint8Array`
|
|
797
|
+
* input accepts a non-zero offset; `0` means the same as omitting it.
|
|
798
|
+
*
|
|
799
|
+
* @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
|
|
800
|
+
*/
|
|
801
|
+
export function extractUuidV7Payload<Input extends UuidByteInput | UuidSlugError>(
|
|
802
|
+
value: UuidV7BytesInput<Input>,
|
|
803
|
+
layout: UuidV7PayloadLayout,
|
|
804
|
+
byteOffset?: number,
|
|
805
|
+
): UuidV7Payload | UuidSlugError;
|
|
806
|
+
/** Interpret supported text/byte unions under the supplied layout; a preceding error passes through unchanged. */
|
|
807
|
+
export function extractUuidV7Payload<Input extends string | UuidByteInput | UuidSlugError>(
|
|
808
|
+
value: UuidV7TimestampInput<Input>,
|
|
809
|
+
layout: UuidV7PayloadLayout,
|
|
810
|
+
): UuidV7Payload | UuidSlugError;
|
|
811
|
+
/*#__NO_SIDE_EFFECTS__*/
|
|
812
|
+
export function extractUuidV7Payload(
|
|
813
|
+
value: string | UuidByteInput | UuidSlugError,
|
|
814
|
+
layout: UuidV7PayloadLayout,
|
|
815
|
+
byteOffset = 0,
|
|
816
|
+
): UuidV7Payload | UuidSlugError {
|
|
817
|
+
let bytes: Uint8Array | UuidSlugError;
|
|
818
|
+
if (typeof value === "string") {
|
|
819
|
+
if (byteOffset !== 0) return new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
820
|
+
bytes = decodeKeylessUuid(value);
|
|
821
|
+
} else if (isUuidSlugError(value)) {
|
|
822
|
+
return value;
|
|
823
|
+
} else {
|
|
824
|
+
if (byteOffset !== 0 && !isUint8Array(value))
|
|
825
|
+
return new UuidSlugError(INVALID_OPTIONS, BYTE_OFFSET_NEEDS_BYTES);
|
|
826
|
+
bytes = isUint8Array(value) ? value : exactUuidByteView(value);
|
|
827
|
+
if (bytes instanceof Error) {
|
|
828
|
+
const text = stringInput(value);
|
|
829
|
+
if (text !== undefined) bytes = uuidToBytes(text);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
if (bytes instanceof Error) return bytes;
|
|
833
|
+
const badRange = checkRange(bytes.length, byteOffset, 16);
|
|
834
|
+
if (badRange) return badRange;
|
|
835
|
+
if (uuidVersion(bytes, byteOffset) !== 7 || !isRfcVariant(bytes, byteOffset))
|
|
836
|
+
return new UuidSlugError(INVALID_UUID_VERSION, UUID_V7_TIMESTAMP_ONLY);
|
|
837
|
+
return extractPayloadFields(
|
|
838
|
+
bytes,
|
|
839
|
+
byteOffset,
|
|
840
|
+
uuidTimestampFromBytesUnchecked(bytes, byteOffset),
|
|
841
|
+
layout,
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* Return a canonical plain UUIDv7 slug when its timestamp is inside the inclusive symmetric window.
|
|
847
|
+
* Base32hex output is lowercase; case-sensitive base64url is unchanged.
|
|
848
|
+
* Return `timestamp_outside_window` when it is not. Use a codec method for masked or sentinel
|
|
849
|
+
* input. TypeScript rejects known UUID text, masked slugs, and UUIDv4 slugs. A preceding
|
|
850
|
+
* `UuidSlugError` is returned unchanged.
|
|
851
|
+
*
|
|
852
|
+
* @param slug - Plain UUIDv7 slug to validate and normalize. JavaScript also accepts a
|
|
853
|
+
* genuine `String` object.
|
|
854
|
+
* @param window - Inclusive maximum distance from an explicit or current reference time.
|
|
855
|
+
*/
|
|
856
|
+
export function validatePlainUuidV7SlugUnixMs<Input extends string | UuidSlugError>(
|
|
857
|
+
slug: PlainUuidV7SlugInput<Input>,
|
|
858
|
+
window: UuidV7TimestampWindow,
|
|
859
|
+
): (Input extends PlainUuidSlug ? Input & PlainUuidV7Slug : PlainUuidV7Slug) | UuidSlugError;
|
|
860
|
+
export function validatePlainUuidV7SlugUnixMs(
|
|
861
|
+
slug: unknown,
|
|
862
|
+
window: UuidV7TimestampWindow,
|
|
863
|
+
): PlainUuidV7Slug | UuidSlugError {
|
|
864
|
+
let plainSlug: string;
|
|
865
|
+
if (typeof slug === "string") {
|
|
866
|
+
plainSlug = slug;
|
|
867
|
+
} else {
|
|
868
|
+
const normalized = normalizeUuidSlugInput(slug);
|
|
869
|
+
if (typeof normalized !== "string") return normalized;
|
|
870
|
+
plainSlug = normalized;
|
|
871
|
+
}
|
|
872
|
+
// Only text leaves this call. Private scratch avoids an owned decode array; the timestamp
|
|
873
|
+
// validator captures all byte fields before caller-owned window accessors can reenter.
|
|
874
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[plainSlug.length];
|
|
875
|
+
const decoded = alpha
|
|
876
|
+
? decodeInto(plainSlug, alpha, textSlugScratch, 0, 16)
|
|
877
|
+
: plainSlugToUuidBytes(plainSlug);
|
|
878
|
+
if (decoded instanceof Error) return decoded;
|
|
879
|
+
const bytes = typeof decoded === "number" ? textSlugScratch : decoded;
|
|
880
|
+
const valid = validateTimestampBytes(bytes, window);
|
|
881
|
+
if (valid instanceof Error) return valid;
|
|
882
|
+
// Fold accepted base32 text without re-encoding bytes; base64url characters carry case-sensitive bits.
|
|
883
|
+
return (plainSlug.length === 22 ? plainSlug : plainSlug.toLowerCase()) as PlainUuidV7Slug;
|
|
884
|
+
}
|