@anizoptera/uuid-slug 0.2.0 → 0.3.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/README.md +381 -27
- package/dist/alphabet.d.ts +21 -0
- package/dist/alphabet.d.ts.map +1 -0
- package/dist/alphabet.js +132 -0
- package/dist/alphabet.js.map +1 -0
- package/dist/base64url.d.ts +20 -0
- package/dist/base64url.d.ts.map +1 -0
- package/dist/base64url.js +33 -0
- package/dist/base64url.js.map +1 -0
- package/dist/codec.d.ts +17 -0
- package/dist/codec.d.ts.map +1 -0
- package/dist/codec.js +192 -0
- package/dist/codec.js.map +1 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -0
- package/dist/feistel.js +105 -0
- package/dist/feistel.js.map +1 -0
- package/dist/index.d.ts +11 -168
- package/dist/index.js +10 -649
- package/dist/keyless.d.ts +31 -0
- package/dist/keyless.d.ts.map +1 -0
- package/dist/keyless.js +93 -0
- package/dist/keyless.js.map +1 -0
- package/dist/legacy-mask.js +55 -0
- package/dist/legacy-mask.js.map +1 -0
- package/dist/mask.js +108 -0
- package/dist/mask.js.map +1 -0
- package/dist/migration.js +66 -0
- package/dist/migration.js.map +1 -0
- package/dist/node/alphabet.js +130 -0
- package/dist/node/base64url.js +31 -0
- package/dist/node/codec.js +190 -0
- package/dist/node/errors.js +78 -0
- package/dist/node/feistel.js +103 -0
- package/dist/node/index.js +10 -647
- package/dist/node/keyless.js +91 -0
- package/dist/node/legacy-mask.js +53 -0
- package/dist/node/mask.js +106 -0
- package/dist/node/migration.js +64 -0
- package/dist/node/runtime/node.js +33 -0
- package/dist/node/runtime/pool.js +53 -0
- package/dist/node/schema.js +214 -0
- package/dist/node/siphash.js +106 -0
- package/dist/node/uuid.js +226 -0
- package/dist/node/v7.js +185 -0
- package/dist/node/yield.js +20 -0
- package/dist/runtime/pool.js +55 -0
- package/dist/runtime/pool.js.map +1 -0
- package/dist/runtime/web.js +39 -0
- package/dist/runtime/web.js.map +1 -0
- package/dist/schema.d.ts +20 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +216 -0
- package/dist/schema.js.map +1 -0
- package/dist/siphash.js +108 -0
- package/dist/siphash.js.map +1 -0
- package/dist/types.d.ts +255 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/uuid.d.ts +78 -0
- package/dist/uuid.d.ts.map +1 -0
- package/dist/uuid.js +228 -0
- package/dist/uuid.js.map +1 -0
- package/dist/v7.d.ts +12 -0
- package/dist/v7.d.ts.map +1 -0
- package/dist/v7.js +187 -0
- package/dist/v7.js.map +1 -0
- package/dist/yield.js +22 -0
- package/dist/yield.js.map +1 -0
- package/package.json +8 -12
- package/src/alphabet.ts +187 -0
- package/src/base64url.ts +28 -63
- package/src/codec.ts +227 -125
- package/src/errors.ts +83 -9
- package/src/feistel.ts +128 -0
- package/src/index.ts +52 -26
- package/src/keyless.ts +136 -0
- package/src/legacy-mask.ts +25 -0
- package/src/mask.ts +129 -67
- package/src/migration.ts +104 -0
- package/src/runtime/bun.ts +49 -24
- package/src/runtime/node.ts +33 -15
- package/src/runtime/pool.ts +62 -0
- package/src/runtime/types.ts +42 -5
- package/src/runtime/web.ts +37 -9
- package/src/schema.ts +274 -97
- package/src/siphash.ts +127 -0
- package/src/types.ts +221 -37
- package/src/uuid.ts +189 -50
- package/src/v7.ts +217 -45
- package/src/yield.ts +22 -0
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/web/index.js +0 -648
package/src/types.ts
CHANGED
|
@@ -1,49 +1,120 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import type { UuidSlugError } from "./errors";
|
|
4
|
+
import type { SlugAlphabet } from "./uuid";
|
|
5
|
+
|
|
1
6
|
declare const brand: unique symbol;
|
|
2
7
|
|
|
3
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Nominal marker. The names ACCUMULATE as a key set rather than replacing one another, which is
|
|
10
|
+
* what makes nesting work: `Brand<Brand<string, "A">, "B">` carries both keys, so it is assignable
|
|
11
|
+
* to the "A" brand but not the reverse and not to a sibling "C".
|
|
12
|
+
*
|
|
13
|
+
* Writing the name as the property's TYPE instead — `{ [brand]?: Name }` — intersects to
|
|
14
|
+
* `"A" & "B"`, i.e. `never`, on the second level. Every nested brand then has the same `never`
|
|
15
|
+
* marker and they are all mutually assignable: measured 2026-08-12, `UuidV4Slug` and `UuidV7Slug`
|
|
16
|
+
* were interchangeable, as were a plain slug and a masked one, for the entire life of the type.
|
|
17
|
+
*
|
|
18
|
+
* The property stays OPTIONAL so a string literal is still accepted wherever a brand is asked for.
|
|
19
|
+
* These types separate values the package produces; they are not a parsing obligation on callers.
|
|
20
|
+
*/
|
|
21
|
+
export type Brand<T, Name extends string> = T & { readonly [brand]?: { [K in Name]: true } };
|
|
4
22
|
|
|
5
23
|
export type Base64UrlString = Brand<string, "Base64UrlString">;
|
|
6
24
|
export type UuidString = Brand<string, "UuidString">;
|
|
7
25
|
export type UuidV4String = Brand<UuidString, "UuidV4String">;
|
|
8
26
|
export type UuidV7String = Brand<UuidString, "UuidV7String">;
|
|
9
|
-
|
|
27
|
+
/** Either alphabet — 22 base64url characters or 26 base32hex — so NOT a `Base64UrlString`. */
|
|
28
|
+
export type UuidSlug = Brand<string, "UuidSlug">;
|
|
10
29
|
export type UuidV4Slug = Brand<UuidSlug, "UuidV4Slug">;
|
|
11
30
|
export type UuidV7Slug = Brand<UuidSlug, "UuidV7Slug">;
|
|
12
|
-
|
|
31
|
+
/** Masked slugs are base64url only, so this narrows where `UuidSlug` cannot. */
|
|
32
|
+
export type MaskedUuidSlug = Brand<Base64UrlString & UuidSlug, "MaskedUuidSlug">;
|
|
13
33
|
export type MaskedUuidV7Slug = Brand<MaskedUuidSlug, "MaskedUuidV7Slug">;
|
|
14
34
|
export type SentinelUuidV7Slug = Brand<UuidV7Slug, "SentinelUuidV7Slug">;
|
|
15
35
|
export type PublicUuidV7Slug = MaskedUuidV7Slug | SentinelUuidV7Slug;
|
|
16
36
|
export type UuidBytes = Brand<Uint8Array, "UuidBytes">;
|
|
17
37
|
|
|
18
38
|
export interface FreshValidationOptions {
|
|
39
|
+
/** Finite Unix milliseconds; read once per validation. */
|
|
19
40
|
now?: () => number;
|
|
41
|
+
/** Finite, nonnegative radius around now, inclusive in both directions; default 24 hours. */
|
|
20
42
|
windowMs?: number;
|
|
21
43
|
}
|
|
22
44
|
|
|
23
45
|
export interface UuidV7Generator {
|
|
24
|
-
uuidV7(): UuidV7String;
|
|
25
|
-
uuidV7Bytes(out?: Uint8Array, offset?: number):
|
|
46
|
+
uuidV7(this: void): UuidV7String;
|
|
47
|
+
uuidV7Bytes(this: void, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
48
|
+
/**
|
|
49
|
+
* Generate at a caller-supplied millisecond. A SEPARATE entry point rather than an optional
|
|
50
|
+
* trailing parameter on the pair above, because an optional positional timestamp is silently
|
|
51
|
+
* mappable: `Array.from({length: n}, gen.uuidV7Bytes)` would pass the index as the instant and
|
|
52
|
+
* mint n ids dated 1970, with no type error. Taking the timestamp FIRST makes that impossible.
|
|
53
|
+
*
|
|
54
|
+
* Returns an Error rather than throwing on a bad instant: a caller-supplied value out of range
|
|
55
|
+
* is ordinary input validation, not an exceptional condition.
|
|
56
|
+
*/
|
|
57
|
+
uuidV7At(this: void, timestamp: number): UuidSlugError | UuidV7String;
|
|
58
|
+
uuidV7BytesAt(
|
|
59
|
+
this: void,
|
|
60
|
+
timestamp: number,
|
|
61
|
+
out?: Uint8Array,
|
|
62
|
+
offset?: number,
|
|
63
|
+
): UuidSlugError | Uint8Array;
|
|
26
64
|
}
|
|
27
65
|
|
|
66
|
+
/**
|
|
67
|
+
* A schema is its mixing step, not the data behind one. Holding `mix` as a function rather than
|
|
68
|
+
* exposing a permutation and an XOR table is what lets the masking code stay ignorant of which
|
|
69
|
+
* scheme it is running: adding one is a new constructor in `schema.ts` and no branch anywhere.
|
|
70
|
+
*
|
|
71
|
+
* It is also the ONLY extension point, and deliberately so. This interface is public, so a caller
|
|
72
|
+
* with a scheme of their own supplies it directly; the package ships no table-shaped constructor
|
|
73
|
+
* beside it, because one would privilege a single foreign layout while being strictly less
|
|
74
|
+
* capable than the function it wraps. `createUuidSlugCodec` smoke-tests supplied schemas; callers remain responsible for
|
|
75
|
+
* invertibility across their full input domain.
|
|
76
|
+
*/
|
|
28
77
|
export interface MaskSchema {
|
|
29
78
|
readonly id: string;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Transforms 16 bytes; `forward: false` MUST be the exact inverse. `input` and `output` MUST
|
|
81
|
+
* NOT be the same array: a scheme that permutes reads source bytes it would already have
|
|
82
|
+
* overwritten, which corrupts silently rather than failing.
|
|
83
|
+
*/
|
|
84
|
+
mix(input: Uint8Array, output: Uint8Array, forward: boolean): void;
|
|
34
85
|
}
|
|
35
86
|
|
|
87
|
+
/**
|
|
88
|
+
* There is no scheme to choose. The check's width is fixed by arithmetic — a UUIDv7 carries 116
|
|
89
|
+
* bits of content, so the encoding's remainder is the check — and the mixing step is the Feistel,
|
|
90
|
+
* because the only alternative this package ever shipped left the timestamp legible: one output
|
|
91
|
+
* byte per input byte meant 4 of 16 bytes held constant across a second, defeating the entire
|
|
92
|
+
* point of masking. A caller who genuinely needs a different cipher passes a `MaskSchema`.
|
|
93
|
+
*/
|
|
36
94
|
export interface MaskSchemaOptions {
|
|
37
95
|
readonly id?: string;
|
|
96
|
+
/**
|
|
97
|
+
* Generate a secret, for example with `openssl rand -base64 32`, and keep it outside source
|
|
98
|
+
* control. At least 16 bytes are required; strings are UTF-8 encoded. A known UUID/slug pair
|
|
99
|
+
* permits offline guesses, so length alone is not protection. Preserve old seeds for decoding
|
|
100
|
+
* issued slugs; rotate by retaining their schema settings in `previousMasks`.
|
|
101
|
+
*/
|
|
38
102
|
readonly seed: string | Uint8Array;
|
|
39
|
-
|
|
103
|
+
/**
|
|
104
|
+
* Work factor for turning the seed into key material, default 1 — the cheapest setting, chosen so
|
|
105
|
+
* that codec construction does only the requested work. Higher counts add construction and
|
|
106
|
+
* seed-guessing cost; they are paid when the schema is built, never per id.
|
|
107
|
+
*
|
|
108
|
+
* WIRE-FORMAT-BEARING, exactly as `seed` is: a different count derives different keys, so every
|
|
109
|
+
* masked slug issued under the old count stops decoding. Rotate it the way a seed is rotated —
|
|
110
|
+
* the new setting in `mask`, the old one kept in `previousMasks` — never by editing in place.
|
|
111
|
+
*/
|
|
112
|
+
readonly keyIterations?: number;
|
|
40
113
|
}
|
|
41
114
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
readonly
|
|
45
|
-
readonly tagBits: 4 | 6;
|
|
46
|
-
readonly xor: Uint8Array;
|
|
115
|
+
/** The synchronous seed options plus cooperative cancellation; no scheduling knobs are required. */
|
|
116
|
+
export interface AsyncMaskSchemaOptions extends MaskSchemaOptions {
|
|
117
|
+
readonly signal?: AbortSignal;
|
|
47
118
|
}
|
|
48
119
|
|
|
49
120
|
export interface UuidV7SentinelDefinition {
|
|
@@ -57,33 +128,146 @@ export interface UuidV7Sentinel {
|
|
|
57
128
|
readonly uuid: UuidV7String;
|
|
58
129
|
}
|
|
59
130
|
|
|
131
|
+
/** Select a known encoding instead of guessing from overlapping slug text. */
|
|
132
|
+
export type MigrationFormat = "current" | "original" | "plain";
|
|
133
|
+
|
|
134
|
+
/** Enable only formats your application has issued; writers keep using the codec. */
|
|
135
|
+
export interface UuidSlugMigrationOptions {
|
|
136
|
+
readonly original?: boolean;
|
|
137
|
+
readonly plain?: boolean;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface UuidSlugMigration {
|
|
141
|
+
/** Return the first candidate: sentinel, current keys, original mask, then plain UUID. */
|
|
142
|
+
decode(this: void, slug: string, format?: MigrationFormat): UuidSlugError | UuidString;
|
|
143
|
+
/** Return distinct candidates for one application lookup; an empty array means no match. */
|
|
144
|
+
candidates(this: void, slug: string, format?: MigrationFormat): UuidSlugError | UuidString[];
|
|
145
|
+
}
|
|
146
|
+
|
|
60
147
|
export interface UuidSlugCodecOptions {
|
|
61
148
|
readonly generator?: UuidV7Generator;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
149
|
+
/**
|
|
150
|
+
* Also decode plain, unmasked slugs when no schema matches — the migration path for ids issued
|
|
151
|
+
* before masking existed. Its own option rather than a field beside the key list, because the
|
|
152
|
+
* two answer different questions and share only the accident of both concerning the past.
|
|
153
|
+
*
|
|
154
|
+
* Turn it off once the migration ends. It costs one wrong answer per 2^checkBits: a direct slug
|
|
155
|
+
* that happens to satisfy a mask's check decodes as that mask instead, and both are the same 22
|
|
156
|
+
* characters of the same alphabet, so nothing else can tell them apart.
|
|
157
|
+
*/
|
|
158
|
+
readonly acceptUnmaskedSlugs?: boolean;
|
|
159
|
+
/**
|
|
160
|
+
* Schemas to try after `mask`, in the order given — how a seed is rotated. Takes a seed exactly
|
|
161
|
+
* as `mask` does: a rotated seed is the ordinary reason this list exists, and requiring a
|
|
162
|
+
* pre-built schema for it cost the commonest case a constructor and an error branch that naming
|
|
163
|
+
* the current seed never needed. Named for rotation rather than for legacy, because a previous
|
|
164
|
+
* key is not a different kind of thing from the current one — rotation is only a change of
|
|
165
|
+
* position between this list and `mask`.
|
|
166
|
+
*
|
|
167
|
+
* Keep it short. Each entry is tried in turn, so the codec's wrong-answer rate is the sum over
|
|
168
|
+
* the whole list.
|
|
169
|
+
*/
|
|
170
|
+
readonly previousMasks?: readonly (MaskSchema | MaskSchemaOptions)[];
|
|
171
|
+
/**
|
|
172
|
+
* The schema that ENCODES, and the first tried when decoding. Kept separate from the list above
|
|
173
|
+
* rather than folded into one ordered array: in a single list the encoding schema is whichever
|
|
174
|
+
* happens to be first, so appending a rotated seed leaves you still issuing ids under the old
|
|
175
|
+
* one while believing you rotated. Nothing about that failure is visible.
|
|
176
|
+
*
|
|
177
|
+
* OPTIONAL, and omitting it is the one choice here with a security consequence: the codec then
|
|
178
|
+
* masks under `DEFAULT_MASK_SCHEMA`, whose seed is a string literal in this published package,
|
|
179
|
+
* so its masked slugs are readable by anyone who installed it. Supply `{ seed }` — any stable
|
|
180
|
+
* string you keep out of the repository — for masking to obfuscate anything at all.
|
|
181
|
+
*/
|
|
66
182
|
readonly mask?: MaskSchema | MaskSchemaOptions;
|
|
67
183
|
readonly sentinels?: readonly UuidV7SentinelDefinition[];
|
|
184
|
+
/**
|
|
185
|
+
* Alphabet for PLAIN slugs from `uuidV4Slug` and `uuidV7Slug`. `"base32hex"` costs four characters
|
|
186
|
+
* (26 rather than 22) and buys chronological sort order: its characters are in ASCII order and a
|
|
187
|
+
* UUIDv7's leading bytes are its timestamp, so base32hex slugs sort by creation time as plain
|
|
188
|
+
* strings. base64url's alphabet cannot — it runs `A-Za-z0-9-_`, so its character order and its
|
|
189
|
+
* value order disagree. Being alphanumeric also spares base32hex the `-` and `_` that make a
|
|
190
|
+
* base64url slug awkward to select by double-click.
|
|
191
|
+
*
|
|
192
|
+
* Codec-level rather than per call so a system cannot mint half its ids in each spelling.
|
|
193
|
+
* Decoding takes no such option: the two lengths are disjoint, so `slugToUuid` reads both and a
|
|
194
|
+
* change of alphabet leaves every previously issued slug working.
|
|
195
|
+
*
|
|
196
|
+
* It does NOT reach masked slugs or sentinels, which stay base64url. Masked bytes are ciphertext
|
|
197
|
+
* and sort in no useful order, and a sentinel is matched against masked input, so a sentinel in a
|
|
198
|
+
* different alphabet could never be recognised there.
|
|
199
|
+
*
|
|
200
|
+
* Costs throughput when set: `uuidV7Slug` can no longer use a runtime's native base64url slug
|
|
201
|
+
* generator and falls back to generating bytes and encoding them.
|
|
202
|
+
*/
|
|
203
|
+
readonly slugAlphabet?: SlugAlphabet;
|
|
68
204
|
}
|
|
69
205
|
|
|
70
|
-
|
|
206
|
+
/**
|
|
207
|
+
* Only what depends on the codec's own state: the generator it draws from, and the mask schema
|
|
208
|
+
* plus sentinels it was built with.
|
|
209
|
+
*
|
|
210
|
+
* The plain conversions (`uuidToSlug`, `parseUuid`, `formatUuidSlug`, …) are module-level
|
|
211
|
+
* functions and deliberately absent here. They are pure — the same input gives the same output
|
|
212
|
+
* whatever seed the codec holds — so carrying them as methods implied a dependency on the seed
|
|
213
|
+
* that does not exist, and was the single most misleading thing about the previous shape.
|
|
214
|
+
*
|
|
215
|
+
* Extending `UuidV7Generator` makes the compiler require forwarding every generator method.
|
|
216
|
+
*/
|
|
217
|
+
export interface UuidSlugCodec extends UuidV7Generator {
|
|
71
218
|
readonly sentinels: readonly UuidV7Sentinel[];
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
219
|
+
/** Create an opt-in reader without changing generation or ordinary codec decoding. */
|
|
220
|
+
migration(this: void, options?: UuidSlugMigrationOptions): UuidSlugMigration;
|
|
221
|
+
/**
|
|
222
|
+
* `this: void` lets callers detach methods without `.bind`; implementations cannot rely on `this`.
|
|
223
|
+
*/
|
|
224
|
+
uuidV4(this: void): UuidV4String;
|
|
225
|
+
uuidV4Bytes(this: void, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
226
|
+
uuidV4Slug(this: void): UuidV4Slug;
|
|
227
|
+
uuidV7Slug(this: void): UuidV7Slug;
|
|
228
|
+
uuidV7MaskedSlug(this: void): PublicUuidV7Slug;
|
|
229
|
+
/**
|
|
230
|
+
* Masking is UUIDv7-only, and the reason is that the whole format is spent. The check rides in
|
|
231
|
+
* bits a v7 provably wastes — its constant version and variant, and the timestamp's top six —
|
|
232
|
+
* plus whatever the encoding has left over. Another version would have to store its real
|
|
233
|
+
* version and its full timestamp somewhere, and there is no somewhere: every one of the 132
|
|
234
|
+
* bits in 22 characters already has a job. Supporting all versions would cost a 23rd character
|
|
235
|
+
* on every masked slug forever, to hide a creation time only v7 discloses.
|
|
236
|
+
*/
|
|
237
|
+
uuidV7ToMaskedSlug(this: void, uuid: string): UuidSlugError | PublicUuidV7Slug;
|
|
238
|
+
maskedSlugToUuidV7(this: void, slug: string): UuidSlugError | UuidV7String;
|
|
239
|
+
/**
|
|
240
|
+
* Decodes to whatever version comes out, where `maskedSlugToUuidV7` insists on v7.
|
|
241
|
+
*
|
|
242
|
+
* NOT a redundant widening of that method, which is what it looks like: with
|
|
243
|
+
* `acceptUnmaskedSlugs` enabled a slug that matches no schema is tried as a plain unmasked
|
|
244
|
+
* slug, and a system migrating off unmasked ids may well have UUIDv4 ones. Those decode here
|
|
245
|
+
* and are rejected by the v7 form. Deleting this on the assumption it was a duplicate was
|
|
246
|
+
* measured to break exactly that migration path.
|
|
247
|
+
*/
|
|
248
|
+
maskedSlugToUuid(this: void, slug: string): UuidSlugError | UuidString;
|
|
249
|
+
/**
|
|
250
|
+
* `maskedSlugToUuidV7` plus the freshness rules of `validateUuidV7Fresh`, returning the slug.
|
|
251
|
+
*
|
|
252
|
+
* Lives on the codec because unmasking needs the codec's key. Its module-level predecessor
|
|
253
|
+
* `validateMaskedUuidV7SlugFresh` did not: it reached for `defaultCodec`, whose seed is
|
|
254
|
+
* published in this package's source, so it answered under the wrong key for every caller who
|
|
255
|
+
* supplied their own and returned a confident Error for valid slugs. There is no keyless
|
|
256
|
+
* counterpart to this for the same reason; `validateUuidV7SlugFresh` stays module-level because
|
|
257
|
+
* a PLAIN slug decodes without one.
|
|
258
|
+
*
|
|
259
|
+
* Returns the slug it was GIVEN, at the type it was given, which is the only type that is true
|
|
260
|
+
* of it. Declaring `MaskedUuidV7Slug` was a lie the compiler could not catch: that brand is
|
|
261
|
+
* `Base64UrlString & UuidSlug`, but with `acceptUnmaskedSlugs` the decode falls through to
|
|
262
|
+
* `slugToUuid`, which accepts 26-character base32hex too — so a base32hex slug came back typed as
|
|
263
|
+
* base64url and `isBase64Url` on it was false. Narrowing the fallback to base64url would have
|
|
264
|
+
* been the wrong repair: a codec built with `slugAlphabet: "base32hex"` has exactly those legacy
|
|
265
|
+
* ids, and refusing them breaks the migration this flag exists for. The behaviour is right; the
|
|
266
|
+
* claim about it was not.
|
|
267
|
+
*/
|
|
268
|
+
validateMaskedSlugFresh<S extends string>(
|
|
269
|
+
this: void,
|
|
270
|
+
slug: S,
|
|
271
|
+
freshness?: FreshValidationOptions,
|
|
272
|
+
): UuidSlugError | S;
|
|
89
273
|
}
|
package/src/uuid.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
|
|
3
|
+
import { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded } from "./alphabet";
|
|
4
|
+
import type { Alphabet } from "./alphabet";
|
|
5
|
+
import { checkRange, UuidSlugError } from "./errors";
|
|
3
6
|
import type {
|
|
4
7
|
UuidSlug,
|
|
5
8
|
UuidString,
|
|
@@ -10,19 +13,81 @@ import type {
|
|
|
10
13
|
} from "./types";
|
|
11
14
|
|
|
12
15
|
const HEX = "0123456789abcdef";
|
|
16
|
+
// Probe once and allocate the byte-pair fallback only on engines that need it.
|
|
17
|
+
const nativeToHex = (Uint8Array.prototype as { toHex?: () => string }).toHex;
|
|
18
|
+
const HEX_BYTES = nativeToHex
|
|
19
|
+
? []
|
|
20
|
+
: /*#__PURE__*/ Array.from(
|
|
21
|
+
{ length: 256 },
|
|
22
|
+
(_, byte) => (HEX[byte >>> 4] as string) + (HEX[byte & 15] as string),
|
|
23
|
+
);
|
|
13
24
|
const HEX_DECODE = new Int8Array(128).fill(-1);
|
|
14
25
|
for (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;
|
|
15
26
|
for (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;
|
|
16
27
|
|
|
17
28
|
const UUID_LENGTH = 36;
|
|
18
|
-
const SLUG_LENGTH = 22;
|
|
19
29
|
const UUID_BYTE_OFFSETS = [0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34] as const;
|
|
20
30
|
|
|
31
|
+
/**
|
|
32
|
+
* The alphabets a plain slug may be written in. base64url is the default and the shortest;
|
|
33
|
+
* base32hex costs four more characters and buys the one property base64url cannot offer: its
|
|
34
|
+
* characters are in ASCII order, so base32hex slugs of UUIDv7s sort chronologically as plain
|
|
35
|
+
* strings. Only the lowercase spelling decodes — the table is built from `chars` — so slugs have
|
|
36
|
+
* no second spelling, as everywhere else in this format.
|
|
37
|
+
*
|
|
38
|
+
* MASKED slugs are always base64url (Art's ruling, 2026-08-12). Sort order there would be order of
|
|
39
|
+
* ciphertext, which carries nothing, so the extra characters would buy only the case-insensitivity.
|
|
40
|
+
*/
|
|
41
|
+
const SLUG_ALPHABETS: { base32hex: Alphabet; base64url: Alphabet } = {
|
|
42
|
+
base32hex: BASE32HEX,
|
|
43
|
+
base64url: BASE64URL,
|
|
44
|
+
} as const;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Callers name an alphabet rather than passing one. `Alphabet` holds a decode table and a bit
|
|
48
|
+
* width — internals that would become public surface the moment the type escaped — and accepting
|
|
49
|
+
* an arbitrary one would also open a second extension point beside `MaskSchema`, which this
|
|
50
|
+
* package documents as its only one. A union of two names cannot be widened by a caller at all, so
|
|
51
|
+
* there is nothing to validate.
|
|
52
|
+
*/
|
|
53
|
+
export type SlugAlphabet = keyof typeof SLUG_ALPHABETS;
|
|
54
|
+
|
|
55
|
+
/** Reject inherited property names as well as unknown names from JavaScript callers. */
|
|
56
|
+
export function resolveSlugAlphabet(alphabet: SlugAlphabet): Alphabet | UuidSlugError {
|
|
57
|
+
return Object.hasOwn(SLUG_ALPHABETS, alphabet)
|
|
58
|
+
? SLUG_ALPHABETS[alphabet]
|
|
59
|
+
: new UuidSlugError(
|
|
60
|
+
"invalid_uuid_slug",
|
|
61
|
+
`Unknown slug alphabet "${alphabet}"; expected ${Object.keys(SLUG_ALPHABETS).join(" or ")}.`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */
|
|
66
|
+
function slugLength(alpha: Alphabet) {
|
|
67
|
+
return Math.ceil(128 / alpha.bitsPerChar);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are
|
|
72
|
+
* disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed
|
|
73
|
+
* rather than searched because every decode and every type guard pays this lookup.
|
|
74
|
+
*/
|
|
75
|
+
const SLUG_ALPHABET_BY_LENGTH: readonly (Alphabet | undefined)[] = Object.values(
|
|
76
|
+
SLUG_ALPHABETS,
|
|
77
|
+
).reduce<(Alphabet | undefined)[]>((table, alpha) => {
|
|
78
|
+
table[slugLength(alpha)] = alpha;
|
|
79
|
+
return table;
|
|
80
|
+
}, []);
|
|
81
|
+
|
|
82
|
+
const SLUG_LENGTHS = Object.values(SLUG_ALPHABETS)
|
|
83
|
+
.map((alpha) => `${slugLength(alpha)} (${alpha.name})`)
|
|
84
|
+
.join(" or ");
|
|
85
|
+
|
|
21
86
|
function hexValue(code: number) {
|
|
22
|
-
return
|
|
87
|
+
return HEX_DECODE[code] ?? -1;
|
|
23
88
|
}
|
|
24
89
|
|
|
25
|
-
export function parseUuid(uuid: string, out?: Uint8Array, offset = 0):
|
|
90
|
+
export function parseUuid(uuid: string, out?: Uint8Array, offset = 0): UuidSlugError | Uint8Array {
|
|
26
91
|
if (uuid.length !== UUID_LENGTH)
|
|
27
92
|
return new UuidSlugError("invalid_uuid", "UUID must be 36 characters.");
|
|
28
93
|
if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") {
|
|
@@ -30,13 +95,13 @@ export function parseUuid(uuid: string, out?: Uint8Array, offset = 0): Error | U
|
|
|
30
95
|
}
|
|
31
96
|
|
|
32
97
|
const target = out ?? new Uint8Array(16);
|
|
33
|
-
|
|
34
|
-
|
|
98
|
+
const badRange = checkRange(target.length, offset, 16);
|
|
99
|
+
if (badRange) return badRange;
|
|
35
100
|
|
|
36
101
|
for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {
|
|
37
|
-
const textOffset = UUID_BYTE_OFFSETS[byteIndex]
|
|
38
|
-
const high = hexValue(uuid.charCodeAt(textOffset))
|
|
39
|
-
const low = hexValue(uuid.charCodeAt(textOffset + 1))
|
|
102
|
+
const textOffset = UUID_BYTE_OFFSETS[byteIndex] as number;
|
|
103
|
+
const high = hexValue(uuid.charCodeAt(textOffset));
|
|
104
|
+
const low = hexValue(uuid.charCodeAt(textOffset + 1));
|
|
40
105
|
if (high < 0 || low < 0)
|
|
41
106
|
return new UuidSlugError("invalid_uuid", `Invalid UUID hex at offset ${textOffset}.`);
|
|
42
107
|
target[offset + byteIndex] = (high << 4) | low;
|
|
@@ -44,17 +109,20 @@ export function parseUuid(uuid: string, out?: Uint8Array, offset = 0): Error | U
|
|
|
44
109
|
return target;
|
|
45
110
|
}
|
|
46
111
|
|
|
47
|
-
export function formatUuid(bytes: Uint8Array, offset = 0):
|
|
48
|
-
|
|
49
|
-
|
|
112
|
+
export function formatUuid(bytes: Uint8Array, offset = 0): UuidSlugError | UuidString {
|
|
113
|
+
const badRange = checkRange(bytes.length, offset, 16);
|
|
114
|
+
if (badRange) return badRange;
|
|
115
|
+
if (nativeToHex) {
|
|
116
|
+
const hex = nativeToHex.call(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16));
|
|
117
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
118
|
+
}
|
|
50
119
|
let out = "";
|
|
51
120
|
for (let i = 0; i < 16; i += 1) {
|
|
52
121
|
if (i === 4 || i === 6 || i === 8 || i === 10) out += "-";
|
|
53
122
|
const byte = bytes[offset + i] ?? 0;
|
|
54
|
-
out +=
|
|
55
|
-
out += HEX[byte & 0x0f];
|
|
123
|
+
out += HEX_BYTES[byte];
|
|
56
124
|
}
|
|
57
|
-
return out
|
|
125
|
+
return out;
|
|
58
126
|
}
|
|
59
127
|
|
|
60
128
|
export function uuidVersion(bytes: Uint8Array, offset = 0): number {
|
|
@@ -65,83 +133,154 @@ export function isRfcVariant(bytes: Uint8Array, offset = 0): boolean {
|
|
|
65
133
|
return (bytes[offset + 8] ?? 0) >>> 6 === 0b10;
|
|
66
134
|
}
|
|
67
135
|
|
|
136
|
+
// Predicates inspect the same hex table as parsing without allocating output bytes or Errors.
|
|
68
137
|
export function isUuidString(uuid: null | string | undefined): uuid is UuidString {
|
|
69
|
-
if (!uuid) return false;
|
|
70
|
-
|
|
138
|
+
if (!uuid || uuid.length !== UUID_LENGTH) return false;
|
|
139
|
+
if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return false;
|
|
140
|
+
for (let i = 0; i < UUID_BYTE_OFFSETS.length; i += 1) {
|
|
141
|
+
const offset = UUID_BYTE_OFFSETS[i] as number;
|
|
142
|
+
if (hexValue(uuid.charCodeAt(offset)) < 0 || hexValue(uuid.charCodeAt(offset + 1)) < 0)
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The string has already passed canonical validation, so the variant digit is a known hex value. */
|
|
149
|
+
function stringHasRfcVariant(uuid: string): boolean {
|
|
150
|
+
return (HEX_DECODE[uuid.charCodeAt(19)] as number) >>> 2 === 2;
|
|
71
151
|
}
|
|
72
152
|
|
|
73
153
|
export function isUuidV4String(uuid: null | string | undefined): uuid is UuidV4String {
|
|
74
|
-
|
|
75
|
-
const bytes = parseUuid(uuid);
|
|
76
|
-
return bytes instanceof Error ? false : uuidVersion(bytes) === 4 && isRfcVariant(bytes);
|
|
154
|
+
return isUuidString(uuid) && uuid[14] === "4" && stringHasRfcVariant(uuid);
|
|
77
155
|
}
|
|
78
156
|
|
|
79
157
|
export function isUuidV7String(uuid: null | string | undefined): uuid is UuidV7String {
|
|
80
|
-
|
|
81
|
-
const bytes = parseUuid(uuid);
|
|
82
|
-
return bytes instanceof Error ? false : uuidVersion(bytes) === 7 && isRfcVariant(bytes);
|
|
158
|
+
return isUuidString(uuid) && uuid[14] === "7" && stringHasRfcVariant(uuid);
|
|
83
159
|
}
|
|
84
160
|
|
|
161
|
+
/**
|
|
162
|
+
* The only BYTE-level predicate, and the asymmetry against `isUuidV4String` is deliberate: masking
|
|
163
|
+
* accepts v7 alone, so a caller holding raw bytes has a reason to ask this and none to ask the v4
|
|
164
|
+
* question. `isUuidV4Bytes` is absent because nothing needs it, not because it was overlooked —
|
|
165
|
+
* add it when a caller appears, never for symmetry, since an export is permanent surface.
|
|
166
|
+
*/
|
|
85
167
|
export function isUuidV7Bytes(bytes: Uint8Array): boolean {
|
|
86
168
|
return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);
|
|
87
169
|
}
|
|
88
170
|
|
|
89
|
-
export function
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
171
|
+
export function formatUuidSlug(
|
|
172
|
+
bytes: Uint8Array,
|
|
173
|
+
offset = 0,
|
|
174
|
+
alphabet: SlugAlphabet = "base64url",
|
|
175
|
+
): UuidSlugError | UuidSlug {
|
|
176
|
+
const badRange = checkRange(bytes.length, offset, 16);
|
|
177
|
+
if (badRange) return badRange;
|
|
178
|
+
// Unreachable from TypeScript, where the name is a two-member union. Reached from JavaScript,
|
|
179
|
+
// which is why it answers rather than indexing into `undefined`.
|
|
180
|
+
const alpha = resolveSlugAlphabet(alphabet);
|
|
181
|
+
if (alpha instanceof Error) return alpha;
|
|
182
|
+
return encode(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16), alpha);
|
|
93
183
|
}
|
|
94
184
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
185
|
+
/** Accepts either alphabet; the length says which, so there is nothing to pass and nothing to get wrong. */
|
|
186
|
+
export function parseUuidSlug(
|
|
187
|
+
slug: string,
|
|
188
|
+
out?: Uint8Array,
|
|
189
|
+
offset = 0,
|
|
190
|
+
): UuidSlugError | Uint8Array {
|
|
191
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
192
|
+
if (!alpha)
|
|
193
|
+
return new UuidSlugError(
|
|
194
|
+
"invalid_uuid_slug",
|
|
195
|
+
`UUID slug must be ${SLUG_LENGTHS} characters, got ${slug.length}.`,
|
|
196
|
+
);
|
|
197
|
+
const target = out ?? new Uint8Array(16);
|
|
198
|
+
const result = decodeInto(slug, alpha, target, offset, 16);
|
|
199
|
+
return result instanceof Error ? result : target;
|
|
99
200
|
}
|
|
100
201
|
|
|
101
|
-
export function uuidToSlug(
|
|
202
|
+
export function uuidToSlug(
|
|
203
|
+
uuid: string,
|
|
204
|
+
alphabet: SlugAlphabet = "base64url",
|
|
205
|
+
): UuidSlugError | UuidSlug {
|
|
102
206
|
const bytes = parseUuid(uuid);
|
|
103
207
|
if (bytes instanceof Error) return bytes;
|
|
104
|
-
return
|
|
208
|
+
return formatUuidSlug(bytes, 0, alphabet);
|
|
105
209
|
}
|
|
106
210
|
|
|
107
|
-
export function slugToUuid(slug: string):
|
|
108
|
-
const bytes =
|
|
211
|
+
export function slugToUuid(slug: string): UuidSlugError | UuidString {
|
|
212
|
+
const bytes = parseUuidSlug(slug);
|
|
109
213
|
if (bytes instanceof Error) return bytes;
|
|
110
214
|
return formatUuid(bytes);
|
|
111
215
|
}
|
|
112
216
|
|
|
113
|
-
export function
|
|
114
|
-
|
|
217
|
+
export function isUuidSlug(slug: null | string | undefined): slug is UuidSlug {
|
|
218
|
+
if (!slug) return false;
|
|
219
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
220
|
+
return alpha !== undefined && isEncoded(slug, alpha, 16);
|
|
115
221
|
}
|
|
116
222
|
|
|
117
|
-
|
|
118
|
-
|
|
223
|
+
/** Read only the version/variant bytes after canonical validation, without decoding a whole UUID. */
|
|
224
|
+
function slugByte(slug: string, alpha: Alphabet, offset: number): number {
|
|
225
|
+
const start = Math.floor((offset * 8) / alpha.bitsPerChar);
|
|
226
|
+
const end = Math.floor((offset * 8 + 7) / alpha.bitsPerChar);
|
|
227
|
+
let value = 0;
|
|
228
|
+
for (let i = start; i <= end; i += 1)
|
|
229
|
+
value = (value << alpha.bitsPerChar) | (alpha.decode[slug.charCodeAt(i)] as number);
|
|
230
|
+
return (value >>> ((end + 1) * alpha.bitsPerChar - (offset + 1) * 8)) & 255;
|
|
119
231
|
}
|
|
120
232
|
|
|
121
|
-
|
|
122
|
-
if (!slug
|
|
123
|
-
|
|
233
|
+
function isVersionedSlug(slug: null | string | undefined, version: number): boolean {
|
|
234
|
+
if (!isUuidSlug(slug)) return false;
|
|
235
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length] as Alphabet;
|
|
236
|
+
return slugByte(slug, alpha, 6) >>> 4 === version && slugByte(slug, alpha, 8) >>> 6 === 2;
|
|
124
237
|
}
|
|
125
238
|
|
|
126
239
|
export function isUuidV4Slug(slug: null | string | undefined): slug is UuidV4Slug {
|
|
127
|
-
|
|
128
|
-
const bytes = slugToUuidBytes(slug);
|
|
129
|
-
return bytes instanceof Error ? false : uuidVersion(bytes) === 4 && isRfcVariant(bytes);
|
|
240
|
+
return isVersionedSlug(slug, 4);
|
|
130
241
|
}
|
|
131
242
|
|
|
132
243
|
export function isUuidV7Slug(slug: null | string | undefined): slug is UuidV7Slug {
|
|
133
|
-
|
|
134
|
-
const bytes = slugToUuidBytes(slug);
|
|
135
|
-
return bytes instanceof Error ? false : uuidVersion(bytes) === 7 && isRfcVariant(bytes);
|
|
244
|
+
return isVersionedSlug(slug, 7);
|
|
136
245
|
}
|
|
137
246
|
|
|
138
|
-
|
|
247
|
+
/**
|
|
248
|
+
* The 48-bit millisecond a UUIDv7 was minted at.
|
|
249
|
+
*
|
|
250
|
+
* It REFUSES anything that is not a v7, which is the whole point of the return type: the first six
|
|
251
|
+
* bytes of a v4 are random, so reading them yields a confident, well-formed date drawn uniformly
|
|
252
|
+
* from the next nine thousand years. A caller that passed the wrong version got that date silently,
|
|
253
|
+
* and a freshness check built on it would accept or reject by coin flip while looking correct.
|
|
254
|
+
*
|
|
255
|
+
* Short input is reported separately from wrong version, because `uuidVersion` reads a missing byte
|
|
256
|
+
* as zero and would otherwise blame a truncated buffer for holding a v0.
|
|
257
|
+
*/
|
|
258
|
+
export function extractUuidV7Timestamp(bytes: Uint8Array, offset = 0): UuidSlugError | number {
|
|
259
|
+
const badRange = checkRange(bytes.length, offset, 16);
|
|
260
|
+
if (badRange) return badRange;
|
|
261
|
+
if (uuidVersion(bytes, offset) !== 7 || !isRfcVariant(bytes, offset))
|
|
262
|
+
return new UuidSlugError("invalid_uuid_version", "Timestamp is only defined for UUIDv7.");
|
|
139
263
|
let timestamp = 0;
|
|
140
264
|
for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);
|
|
141
265
|
return timestamp;
|
|
142
266
|
}
|
|
143
267
|
|
|
268
|
+
/**
|
|
269
|
+
* Whether a v7's 74 random bits are anything other than all-zero or all-one — the two patterns a
|
|
270
|
+
* generator produces when its entropy source is absent rather than working.
|
|
271
|
+
*
|
|
272
|
+
* Out of range answers `false`, and the direction is the whole point. Without the check the reads
|
|
273
|
+
* below fall through `?? 0`, so a missing byte is indistinguishable from a zero byte and only ever
|
|
274
|
+
* in the reassuring direction: a short buffer reported entropy PRESENT, and an offset past the end
|
|
275
|
+
* reported the degenerate case for data that was never examined. Both are answers about bytes the
|
|
276
|
+
* caller does not have. `false` is the honest one — it means "cannot be shown to carry entropy",
|
|
277
|
+
* which is what a caller acts on, and it is what a truly degenerate id gets too.
|
|
278
|
+
*
|
|
279
|
+
* Boolean rather than `UuidSlugError | boolean` because the sole use is a guard in a condition; an error
|
|
280
|
+
* return would have every call site unwrap a value it is already treating as a yes/no.
|
|
281
|
+
*/
|
|
144
282
|
export function hasUuidV7Entropy(bytes: Uint8Array, offset = 0): boolean {
|
|
283
|
+
if (checkRange(bytes.length, offset, 16)) return false;
|
|
145
284
|
const randA = (((bytes[offset + 6] ?? 0) & 0x0f) << 8) | (bytes[offset + 7] ?? 0);
|
|
146
285
|
const randBFirst = (bytes[offset + 8] ?? 0) & 0x3f;
|
|
147
286
|
let restZero = true;
|