@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
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
//#region src/siphash.ts
|
|
4
|
+
/**
|
|
5
|
+
* HalfSipHash-2-4 with 64-bit output — the 32-bit-word member of the SipHash family (Aumasson and
|
|
6
|
+
* Bernstein), transcribed from the reference implementation. It is a KEYED pseudorandom function:
|
|
7
|
+
* without the key its output on a chosen input is not computable, which is exactly what `mix32` — a
|
|
8
|
+
* fixed, public, unkeyed bijection — could never be, and the reason it replaced it.
|
|
9
|
+
*
|
|
10
|
+
* One primitive serves both callers that need one: the Feistel round function (`feistel.ts`) and the
|
|
11
|
+
* key derivation (`schema.ts`). Neither justifies its own.
|
|
12
|
+
*
|
|
13
|
+
* Chosen over full SipHash-2-4 because that is defined over 64-bit words, which JavaScript has only
|
|
14
|
+
* as `BigInt` or as hand-emulated 32-bit pairs — the first far too slow for a hot path, the second a
|
|
15
|
+
* re-implementation whose errors nothing would catch. HalfSipHash is 32-bit BY SPECIFICATION, so
|
|
16
|
+
* this is a transcription, and `test/siphash.test.ts` holds it to all 64 published vectors. That
|
|
17
|
+
* external check is the whole reason a standard primitive beat anything tuned here: nothing in this
|
|
18
|
+
* repository can grade a mixing function (see `feistel.ts` — every instrument here passes a
|
|
19
|
+
* two-round network), so agreement with a specification somebody else wrote is the only evidence
|
|
20
|
+
* available that can actually fail.
|
|
21
|
+
*
|
|
22
|
+
* Its key is 64 bits. `schema.ts` runs two independently keyed instances and XORs them, the standard
|
|
23
|
+
* cascade for widening a PRF's key; see there.
|
|
24
|
+
*/
|
|
25
|
+
/** Message-absorption rounds per block — the `2` of HalfSipHash-**2**-4. */
|
|
26
|
+
const C_ROUNDS = 2;
|
|
27
|
+
/** Finalisation rounds per output word — the `4` of HalfSipHash-2-**4**. */
|
|
28
|
+
const D_ROUNDS = 4;
|
|
29
|
+
/**
|
|
30
|
+
* HalfSipHash-2-4 over a message supplied as 32-bit LITTLE-ENDIAN words, writing the two output
|
|
31
|
+
* words into `out`.
|
|
32
|
+
*
|
|
33
|
+
* Words rather than bytes because both callers already hold words, and the specification absorbs the
|
|
34
|
+
* message in 32-bit little-endian blocks regardless — so this is the same function with the byte
|
|
35
|
+
* reassembly left to whoever actually has bytes. Taking a `Uint8Array` would make the hot path pack
|
|
36
|
+
* bytes it had just unpacked.
|
|
37
|
+
*
|
|
38
|
+
* `byteLength` is the message length the specification hashes and stamps into the final block.
|
|
39
|
+
* `words` must therefore hold `ceil(byteLength / 4)` entries, with any trailing 1-3 bytes packed
|
|
40
|
+
* little-endian into the low bytes of the last one. Internal cooperative callers may pass a
|
|
41
|
+
* positive block limit and resume the returned continuation with exactly the same inputs.
|
|
42
|
+
*/
|
|
43
|
+
function halfSipHash(key0, key1, words, byteLength, out, continuation, blockLimit = Infinity) {
|
|
44
|
+
let v0 = key0 | 0;
|
|
45
|
+
let v1 = key1 ^ 238 | 0;
|
|
46
|
+
let v2 = key0 ^ 1819895653 | 0;
|
|
47
|
+
let v3 = key1 ^ 1952801890 | 0;
|
|
48
|
+
if (continuation) ({v0, v1, v2, v3} = continuation);
|
|
49
|
+
const fullWords = byteLength >>> 2;
|
|
50
|
+
const spare = byteLength & 3;
|
|
51
|
+
const tail = spare === 0 ? 0 : words[fullWords] & (1 << spare * 8) - 1;
|
|
52
|
+
const lengthBlock = byteLength << 24 | tail | 0;
|
|
53
|
+
const start = continuation?.block ?? 0;
|
|
54
|
+
const end = blockLimit === Infinity ? fullWords : Math.min(fullWords, start + blockLimit - 1);
|
|
55
|
+
for (let block = start; block <= end; block += 1) {
|
|
56
|
+
const m = block === fullWords ? lengthBlock : words[block];
|
|
57
|
+
v3 ^= m;
|
|
58
|
+
for (let round = 0; round < C_ROUNDS; round += 1) {
|
|
59
|
+
v0 = v0 + v1 | 0;
|
|
60
|
+
v1 = v1 << 5 | v1 >>> 27;
|
|
61
|
+
v1 ^= v0;
|
|
62
|
+
v0 = v0 << 16 | v0 >>> 16;
|
|
63
|
+
v2 = v2 + v3 | 0;
|
|
64
|
+
v3 = v3 << 8 | v3 >>> 24;
|
|
65
|
+
v3 ^= v2;
|
|
66
|
+
v0 = v0 + v3 | 0;
|
|
67
|
+
v3 = v3 << 7 | v3 >>> 25;
|
|
68
|
+
v3 ^= v0;
|
|
69
|
+
v2 = v2 + v1 | 0;
|
|
70
|
+
v1 = v1 << 13 | v1 >>> 19;
|
|
71
|
+
v1 ^= v2;
|
|
72
|
+
v2 = v2 << 16 | v2 >>> 16;
|
|
73
|
+
}
|
|
74
|
+
v0 ^= m;
|
|
75
|
+
}
|
|
76
|
+
if (end < fullWords) return {
|
|
77
|
+
block: end + 1,
|
|
78
|
+
v0,
|
|
79
|
+
v1,
|
|
80
|
+
v2,
|
|
81
|
+
v3
|
|
82
|
+
};
|
|
83
|
+
v2 ^= 238;
|
|
84
|
+
for (let half = 0; half < 2; half += 1) {
|
|
85
|
+
for (let round = 0; round < D_ROUNDS; round += 1) {
|
|
86
|
+
v0 = v0 + v1 | 0;
|
|
87
|
+
v1 = v1 << 5 | v1 >>> 27;
|
|
88
|
+
v1 ^= v0;
|
|
89
|
+
v0 = v0 << 16 | v0 >>> 16;
|
|
90
|
+
v2 = v2 + v3 | 0;
|
|
91
|
+
v3 = v3 << 8 | v3 >>> 24;
|
|
92
|
+
v3 ^= v2;
|
|
93
|
+
v0 = v0 + v3 | 0;
|
|
94
|
+
v3 = v3 << 7 | v3 >>> 25;
|
|
95
|
+
v3 ^= v0;
|
|
96
|
+
v2 = v2 + v1 | 0;
|
|
97
|
+
v1 = v1 << 13 | v1 >>> 19;
|
|
98
|
+
v1 ^= v2;
|
|
99
|
+
v2 = v2 << 16 | v2 >>> 16;
|
|
100
|
+
}
|
|
101
|
+
out[half] = v1 ^ v3;
|
|
102
|
+
v1 ^= 221;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { halfSipHash };
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidSlugError, checkRange } from "./errors.js";
|
|
4
|
+
import { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded } from "./alphabet.js";
|
|
5
|
+
//#region src/uuid.ts
|
|
6
|
+
const HEX = "0123456789abcdef";
|
|
7
|
+
const nativeToHex = Uint8Array.prototype.toHex;
|
|
8
|
+
const HEX_BYTES = nativeToHex ? [] : /*#__PURE__*/ Array.from({ length: 256 }, (_, byte) => HEX[byte >>> 4] + HEX[byte & 15]);
|
|
9
|
+
const HEX_DECODE = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
|
|
10
|
+
for (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;
|
|
11
|
+
for (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;
|
|
12
|
+
const UUID_LENGTH = 36;
|
|
13
|
+
const UUID_BYTE_OFFSETS = [
|
|
14
|
+
0,
|
|
15
|
+
2,
|
|
16
|
+
4,
|
|
17
|
+
6,
|
|
18
|
+
9,
|
|
19
|
+
11,
|
|
20
|
+
14,
|
|
21
|
+
16,
|
|
22
|
+
19,
|
|
23
|
+
21,
|
|
24
|
+
24,
|
|
25
|
+
26,
|
|
26
|
+
28,
|
|
27
|
+
30,
|
|
28
|
+
32,
|
|
29
|
+
34
|
|
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 = {
|
|
42
|
+
base32hex: BASE32HEX,
|
|
43
|
+
base64url: BASE64URL
|
|
44
|
+
};
|
|
45
|
+
/** Reject inherited property names as well as unknown names from JavaScript callers. */
|
|
46
|
+
function resolveSlugAlphabet(alphabet) {
|
|
47
|
+
return Object.hasOwn(SLUG_ALPHABETS, alphabet) ? SLUG_ALPHABETS[alphabet] : new UuidSlugError("invalid_uuid_slug", `Unknown slug alphabet "${alphabet}"; expected ${Object.keys(SLUG_ALPHABETS).join(" or ")}.`);
|
|
48
|
+
}
|
|
49
|
+
/** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */
|
|
50
|
+
function slugLength(alpha) {
|
|
51
|
+
return Math.ceil(128 / alpha.bitsPerChar);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are
|
|
55
|
+
* disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed
|
|
56
|
+
* rather than searched because every decode and every type guard pays this lookup.
|
|
57
|
+
*/
|
|
58
|
+
const SLUG_ALPHABET_BY_LENGTH = Object.values(SLUG_ALPHABETS).reduce((table, alpha) => {
|
|
59
|
+
table[slugLength(alpha)] = alpha;
|
|
60
|
+
return table;
|
|
61
|
+
}, []);
|
|
62
|
+
const SLUG_LENGTHS = Object.values(SLUG_ALPHABETS).map((alpha) => `${slugLength(alpha)} (${alpha.name})`).join(" or ");
|
|
63
|
+
function hexValue(code) {
|
|
64
|
+
return HEX_DECODE[code] ?? -1;
|
|
65
|
+
}
|
|
66
|
+
function parseUuid(uuid, out, offset = 0) {
|
|
67
|
+
if (uuid.length !== UUID_LENGTH) return new UuidSlugError("invalid_uuid", "UUID must be 36 characters.");
|
|
68
|
+
if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return new UuidSlugError("invalid_uuid", "UUID hyphen positions are invalid.");
|
|
69
|
+
const target = out ?? /* @__PURE__ */ new Uint8Array(16);
|
|
70
|
+
const badRange = checkRange(target.length, offset, 16);
|
|
71
|
+
if (badRange) return badRange;
|
|
72
|
+
for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {
|
|
73
|
+
const textOffset = UUID_BYTE_OFFSETS[byteIndex];
|
|
74
|
+
const high = hexValue(uuid.charCodeAt(textOffset));
|
|
75
|
+
const low = hexValue(uuid.charCodeAt(textOffset + 1));
|
|
76
|
+
if (high < 0 || low < 0) return new UuidSlugError("invalid_uuid", `Invalid UUID hex at offset ${textOffset}.`);
|
|
77
|
+
target[offset + byteIndex] = high << 4 | low;
|
|
78
|
+
}
|
|
79
|
+
return target;
|
|
80
|
+
}
|
|
81
|
+
function formatUuid(bytes, offset = 0) {
|
|
82
|
+
const badRange = checkRange(bytes.length, offset, 16);
|
|
83
|
+
if (badRange) return badRange;
|
|
84
|
+
if (nativeToHex) {
|
|
85
|
+
const hex = nativeToHex.call(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16));
|
|
86
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
87
|
+
}
|
|
88
|
+
let out = "";
|
|
89
|
+
for (let i = 0; i < 16; i += 1) {
|
|
90
|
+
if (i === 4 || i === 6 || i === 8 || i === 10) out += "-";
|
|
91
|
+
const byte = bytes[offset + i] ?? 0;
|
|
92
|
+
out += HEX_BYTES[byte];
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
function uuidVersion(bytes, offset = 0) {
|
|
97
|
+
return (bytes[offset + 6] ?? 0) >>> 4;
|
|
98
|
+
}
|
|
99
|
+
function isRfcVariant(bytes, offset = 0) {
|
|
100
|
+
return (bytes[offset + 8] ?? 0) >>> 6 === 2;
|
|
101
|
+
}
|
|
102
|
+
function isUuidString(uuid) {
|
|
103
|
+
if (!uuid || uuid.length !== UUID_LENGTH) return false;
|
|
104
|
+
if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return false;
|
|
105
|
+
for (let i = 0; i < UUID_BYTE_OFFSETS.length; i += 1) {
|
|
106
|
+
const offset = UUID_BYTE_OFFSETS[i];
|
|
107
|
+
if (hexValue(uuid.charCodeAt(offset)) < 0 || hexValue(uuid.charCodeAt(offset + 1)) < 0) return false;
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
/** The string has already passed canonical validation, so the variant digit is a known hex value. */
|
|
112
|
+
function stringHasRfcVariant(uuid) {
|
|
113
|
+
return HEX_DECODE[uuid.charCodeAt(19)] >>> 2 === 2;
|
|
114
|
+
}
|
|
115
|
+
function isUuidV4String(uuid) {
|
|
116
|
+
return isUuidString(uuid) && uuid[14] === "4" && stringHasRfcVariant(uuid);
|
|
117
|
+
}
|
|
118
|
+
function isUuidV7String(uuid) {
|
|
119
|
+
return isUuidString(uuid) && uuid[14] === "7" && stringHasRfcVariant(uuid);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The only BYTE-level predicate, and the asymmetry against `isUuidV4String` is deliberate: masking
|
|
123
|
+
* accepts v7 alone, so a caller holding raw bytes has a reason to ask this and none to ask the v4
|
|
124
|
+
* question. `isUuidV4Bytes` is absent because nothing needs it, not because it was overlooked —
|
|
125
|
+
* add it when a caller appears, never for symmetry, since an export is permanent surface.
|
|
126
|
+
*/
|
|
127
|
+
function isUuidV7Bytes(bytes) {
|
|
128
|
+
return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);
|
|
129
|
+
}
|
|
130
|
+
function formatUuidSlug(bytes, offset = 0, alphabet = "base64url") {
|
|
131
|
+
const badRange = checkRange(bytes.length, offset, 16);
|
|
132
|
+
if (badRange) return badRange;
|
|
133
|
+
const alpha = resolveSlugAlphabet(alphabet);
|
|
134
|
+
if (alpha instanceof Error) return alpha;
|
|
135
|
+
return encode(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16), alpha);
|
|
136
|
+
}
|
|
137
|
+
/** Accepts either alphabet; the length says which, so there is nothing to pass and nothing to get wrong. */
|
|
138
|
+
function parseUuidSlug(slug, out, offset = 0) {
|
|
139
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
140
|
+
if (!alpha) return new UuidSlugError("invalid_uuid_slug", `UUID slug must be ${SLUG_LENGTHS} characters, got ${slug.length}.`);
|
|
141
|
+
const target = out ?? /* @__PURE__ */ new Uint8Array(16);
|
|
142
|
+
const result = decodeInto(slug, alpha, target, offset, 16);
|
|
143
|
+
return result instanceof Error ? result : target;
|
|
144
|
+
}
|
|
145
|
+
function uuidToSlug(uuid, alphabet = "base64url") {
|
|
146
|
+
const bytes = parseUuid(uuid);
|
|
147
|
+
if (bytes instanceof Error) return bytes;
|
|
148
|
+
return formatUuidSlug(bytes, 0, alphabet);
|
|
149
|
+
}
|
|
150
|
+
function slugToUuid(slug) {
|
|
151
|
+
const bytes = parseUuidSlug(slug);
|
|
152
|
+
if (bytes instanceof Error) return bytes;
|
|
153
|
+
return formatUuid(bytes);
|
|
154
|
+
}
|
|
155
|
+
function isUuidSlug(slug) {
|
|
156
|
+
if (!slug) return false;
|
|
157
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
158
|
+
return alpha !== void 0 && isEncoded(slug, alpha, 16);
|
|
159
|
+
}
|
|
160
|
+
/** Read only the version/variant bytes after canonical validation, without decoding a whole UUID. */
|
|
161
|
+
function slugByte(slug, alpha, offset) {
|
|
162
|
+
const start = Math.floor(offset * 8 / alpha.bitsPerChar);
|
|
163
|
+
const end = Math.floor((offset * 8 + 7) / alpha.bitsPerChar);
|
|
164
|
+
let value = 0;
|
|
165
|
+
for (let i = start; i <= end; i += 1) value = value << alpha.bitsPerChar | alpha.decode[slug.charCodeAt(i)];
|
|
166
|
+
return value >>> (end + 1) * alpha.bitsPerChar - (offset + 1) * 8 & 255;
|
|
167
|
+
}
|
|
168
|
+
function isVersionedSlug(slug, version) {
|
|
169
|
+
if (!isUuidSlug(slug)) return false;
|
|
170
|
+
const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
|
|
171
|
+
return slugByte(slug, alpha, 6) >>> 4 === version && slugByte(slug, alpha, 8) >>> 6 === 2;
|
|
172
|
+
}
|
|
173
|
+
function isUuidV4Slug(slug) {
|
|
174
|
+
return isVersionedSlug(slug, 4);
|
|
175
|
+
}
|
|
176
|
+
function isUuidV7Slug(slug) {
|
|
177
|
+
return isVersionedSlug(slug, 7);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The 48-bit millisecond a UUIDv7 was minted at.
|
|
181
|
+
*
|
|
182
|
+
* It REFUSES anything that is not a v7, which is the whole point of the return type: the first six
|
|
183
|
+
* bytes of a v4 are random, so reading them yields a confident, well-formed date drawn uniformly
|
|
184
|
+
* from the next nine thousand years. A caller that passed the wrong version got that date silently,
|
|
185
|
+
* and a freshness check built on it would accept or reject by coin flip while looking correct.
|
|
186
|
+
*
|
|
187
|
+
* Short input is reported separately from wrong version, because `uuidVersion` reads a missing byte
|
|
188
|
+
* as zero and would otherwise blame a truncated buffer for holding a v0.
|
|
189
|
+
*/
|
|
190
|
+
function extractUuidV7Timestamp(bytes, offset = 0) {
|
|
191
|
+
const badRange = checkRange(bytes.length, offset, 16);
|
|
192
|
+
if (badRange) return badRange;
|
|
193
|
+
if (uuidVersion(bytes, offset) !== 7 || !isRfcVariant(bytes, offset)) return new UuidSlugError("invalid_uuid_version", "Timestamp is only defined for UUIDv7.");
|
|
194
|
+
let timestamp = 0;
|
|
195
|
+
for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);
|
|
196
|
+
return timestamp;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Whether a v7's 74 random bits are anything other than all-zero or all-one — the two patterns a
|
|
200
|
+
* generator produces when its entropy source is absent rather than working.
|
|
201
|
+
*
|
|
202
|
+
* Out of range answers `false`, and the direction is the whole point. Without the check the reads
|
|
203
|
+
* below fall through `?? 0`, so a missing byte is indistinguishable from a zero byte and only ever
|
|
204
|
+
* in the reassuring direction: a short buffer reported entropy PRESENT, and an offset past the end
|
|
205
|
+
* reported the degenerate case for data that was never examined. Both are answers about bytes the
|
|
206
|
+
* caller does not have. `false` is the honest one — it means "cannot be shown to carry entropy",
|
|
207
|
+
* which is what a caller acts on, and it is what a truly degenerate id gets too.
|
|
208
|
+
*
|
|
209
|
+
* Boolean rather than `UuidSlugError | boolean` because the sole use is a guard in a condition; an error
|
|
210
|
+
* return would have every call site unwrap a value it is already treating as a yes/no.
|
|
211
|
+
*/
|
|
212
|
+
function hasUuidV7Entropy(bytes, offset = 0) {
|
|
213
|
+
if (checkRange(bytes.length, offset, 16)) return false;
|
|
214
|
+
const randA = ((bytes[offset + 6] ?? 0) & 15) << 8 | (bytes[offset + 7] ?? 0);
|
|
215
|
+
const randBFirst = (bytes[offset + 8] ?? 0) & 63;
|
|
216
|
+
let restZero = true;
|
|
217
|
+
let restMax = true;
|
|
218
|
+
for (let i = 9; i < 16; i += 1) {
|
|
219
|
+
const byte = bytes[offset + i] ?? 0;
|
|
220
|
+
if (byte !== 0) restZero = false;
|
|
221
|
+
if (byte !== 255) restMax = false;
|
|
222
|
+
}
|
|
223
|
+
return !(randA === 0 && randBFirst === 0 && restZero) && !(randA === 4095 && randBFirst === 63 && restMax);
|
|
224
|
+
}
|
|
225
|
+
//#endregion
|
|
226
|
+
export { extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isRfcVariant, isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Bytes, isUuidV7Slug, isUuidV7String, parseUuid, parseUuidSlug, resolveSlugAlphabet, slugToUuid, uuidToSlug, uuidVersion };
|
package/dist/node/v7.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidSlugError, checkRange, fillRandomBytes, readClock } from "./errors.js";
|
|
4
|
+
import { formatUuid } from "./uuid.js";
|
|
5
|
+
//#region src/v7.ts
|
|
6
|
+
function writeTimestamp(bytes, ms, offset) {
|
|
7
|
+
let value = Math.trunc(ms);
|
|
8
|
+
for (let i = 5; i >= 0; i -= 1) {
|
|
9
|
+
bytes[offset + i] = value & 255;
|
|
10
|
+
value = Math.floor(value / 256);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Writes the 42-bit sequence RFC 9562 §6.2 allows in `rand_a` plus the top of `rand_b`, along
|
|
15
|
+
* with the version and variant bits that bracket it.
|
|
16
|
+
*
|
|
17
|
+
* The sequence is carried as a 10-bit high half and a 32-bit low half rather than one 42-bit
|
|
18
|
+
* BigInt, so every operation here is a 32-bit integer op the JIT emits directly. Measured on the
|
|
19
|
+
* increment-and-write step alone: 9.99M ops/s (Bun) and 11.8M (Node) as a BigInt, against 252M
|
|
20
|
+
* and 149M in this form. The bit layout is unchanged, so the ids are identical either way.
|
|
21
|
+
*/
|
|
22
|
+
function writeCounter(bytes, hi, lo, offset) {
|
|
23
|
+
bytes[offset + 6] = 112 | hi >>> 6 & 15;
|
|
24
|
+
bytes[offset + 7] = ((hi & 63) << 2 | lo >>> 30) & 255;
|
|
25
|
+
bytes[offset + 8] = 128 | lo >>> 24 & 63;
|
|
26
|
+
bytes[offset + 9] = lo >>> 16 & 255;
|
|
27
|
+
bytes[offset + 10] = lo >>> 8 & 255;
|
|
28
|
+
bytes[offset + 11] = lo & 255;
|
|
29
|
+
}
|
|
30
|
+
/** The 48 bits RFC 9562 gives the timestamp; beyond it the value cannot be represented. */
|
|
31
|
+
const MAX_TIMESTAMP = 0xffffffffffff;
|
|
32
|
+
/**
|
|
33
|
+
* `Number.isInteger` rather than `isFinite`, because the error message promises a WHOLE number of
|
|
34
|
+
* milliseconds and `Math.trunc` on the write path would otherwise honour that promise silently:
|
|
35
|
+
* 1.5 became 1 with nothing reported. It also rejects NaN and Infinity, which matters because a
|
|
36
|
+
* native generator need not — measured 2026-08-12, `Bun.randomUUIDv7("hex", NaN)` and the same
|
|
37
|
+
* call at 2^48 both return the 1970 prefix `000000000000` without throwing, while -1 and 1.5 do
|
|
38
|
+
* throw. Validating here rather than trusting the platform is what makes the two agree.
|
|
39
|
+
*/
|
|
40
|
+
const isValidUuidV7Timestamp = (ms) => Number.isInteger(ms) && ms >= 0 && ms <= MAX_TIMESTAMP;
|
|
41
|
+
/**
|
|
42
|
+
* The one check and the one message for a caller-supplied instant. Both the portable generator and
|
|
43
|
+
* the runtime-backed one call it, and the runtime-backed one calls it BEFORE delegating: a native
|
|
44
|
+
* generator may accept what we reject and answer wrongly rather than fail.
|
|
45
|
+
*/
|
|
46
|
+
const rejectInstant = (ms) => isValidUuidV7Timestamp(ms) ? void 0 : new UuidSlugError("invalid_timestamp", `UUIDv7 timestamp must be a whole number of milliseconds in 0..${MAX_TIMESTAMP}.`);
|
|
47
|
+
/**
|
|
48
|
+
* Both string forms differ only in where the instant comes from, so the byte-or-error result is
|
|
49
|
+
* carried through here rather than unwrapped twice. The narrowing is an assertion because
|
|
50
|
+
* `formatUuid` is version-agnostic: the v7-ness is established by the caller having produced the
|
|
51
|
+
* bytes, not by anything the formatter can check.
|
|
52
|
+
*/
|
|
53
|
+
const formatUuidV7 = (result) => result instanceof Error ? result : formatUuid(result);
|
|
54
|
+
/**
|
|
55
|
+
* Seeds the sequence from the same six random bytes and the same bit positions as before, split
|
|
56
|
+
* across the two halves: byte 0 and the top 2 bits of byte 1 form the high half, the rest the
|
|
57
|
+
* low half. Starting each millisecond at a random point rather than zero is what stops the
|
|
58
|
+
* sequence leaking how many ids were issued in the previous millisecond.
|
|
59
|
+
*/
|
|
60
|
+
const seedHi = (bytes) => ((bytes[0] ?? 0) << 2 | (bytes[1] ?? 0) >>> 6) & 1023;
|
|
61
|
+
const seedLo = (bytes) => (((bytes[1] ?? 0) & 63) << 26 | (bytes[2] ?? 0) << 18 | (bytes[3] ?? 0) << 10 | (bytes[4] ?? 0) << 2 | (bytes[5] ?? 0) & 3) >>> 0;
|
|
62
|
+
function createUuidV7Generator(options) {
|
|
63
|
+
const clock = options.clock ?? Date.now;
|
|
64
|
+
const fill = options.fillRandom;
|
|
65
|
+
const random = /* @__PURE__ */ new Uint8Array(16);
|
|
66
|
+
/**
|
|
67
|
+
* Below every timestamp the clock check admits, which is what makes it the uninitialised
|
|
68
|
+
* sentinel rather than a value: `now > lastMs` alone therefore takes the reseed branch on the
|
|
69
|
+
* first call, and no separate "have we started" flag is needed. The coupling is deliberate and
|
|
70
|
+
* is why the clock is validated before this is compared against — an unvalidated clock returning
|
|
71
|
+
* a negative millisecond would make `lastMs` stay below it forever, so the monotonic counter
|
|
72
|
+
* would never be used and every call would reseed.
|
|
73
|
+
*/
|
|
74
|
+
let lastMs = -1;
|
|
75
|
+
let counterHi = 0;
|
|
76
|
+
let counterLo = 0;
|
|
77
|
+
function reseed(ms) {
|
|
78
|
+
const failed = fillRandomBytes(fill, random);
|
|
79
|
+
if (failed) return failed;
|
|
80
|
+
lastMs = ms;
|
|
81
|
+
counterHi = seedHi(random);
|
|
82
|
+
counterLo = seedLo(random);
|
|
83
|
+
}
|
|
84
|
+
function bytes(out, offset = 0, timestamp, explicit = false) {
|
|
85
|
+
const target = out ?? /* @__PURE__ */ new Uint8Array(16);
|
|
86
|
+
const badRange = checkRange(target.length, offset, 16);
|
|
87
|
+
if (badRange) return badRange;
|
|
88
|
+
let ms;
|
|
89
|
+
let sequenceHi;
|
|
90
|
+
let sequenceLo;
|
|
91
|
+
if (explicit) {
|
|
92
|
+
const invalid = rejectInstant(timestamp);
|
|
93
|
+
if (invalid) return invalid;
|
|
94
|
+
const failed = fillRandomBytes(fill, random);
|
|
95
|
+
if (failed) return failed;
|
|
96
|
+
ms = timestamp;
|
|
97
|
+
sequenceHi = seedHi(random);
|
|
98
|
+
sequenceLo = seedLo(random);
|
|
99
|
+
} else {
|
|
100
|
+
const reading = readClock(clock);
|
|
101
|
+
if (reading instanceof Error) return reading;
|
|
102
|
+
const now = Math.trunc(reading);
|
|
103
|
+
if (reading < 0 || !isValidUuidV7Timestamp(now)) return new UuidSlugError("invalid_timestamp", `Clock returned ${String(reading)}, which is not a millisecond in 0..${MAX_TIMESTAMP}.`);
|
|
104
|
+
if (now > lastMs) {
|
|
105
|
+
const failed = reseed(now);
|
|
106
|
+
if (failed) return failed;
|
|
107
|
+
} else {
|
|
108
|
+
counterLo = counterLo + 1 >>> 0;
|
|
109
|
+
if (counterLo === 0) counterHi += 1;
|
|
110
|
+
if (counterHi > 1023) {
|
|
111
|
+
if (lastMs >= MAX_TIMESTAMP) return new UuidSlugError("invalid_timestamp", `Sequence exhausted at the last representable millisecond (${MAX_TIMESTAMP}).`);
|
|
112
|
+
const failed = reseed(lastMs + 1);
|
|
113
|
+
if (failed) return failed;
|
|
114
|
+
} else {
|
|
115
|
+
const failed = fillRandomBytes(fill, random);
|
|
116
|
+
if (failed) return failed;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
ms = lastMs;
|
|
120
|
+
sequenceHi = counterHi;
|
|
121
|
+
sequenceLo = counterLo;
|
|
122
|
+
}
|
|
123
|
+
writeTimestamp(target, ms, offset);
|
|
124
|
+
writeCounter(target, sequenceHi, sequenceLo, offset);
|
|
125
|
+
for (let i = 12; i < 16; i += 1) target[offset + i] = random[i];
|
|
126
|
+
return target;
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
uuidV7() {
|
|
130
|
+
const formatted = formatUuidV7(bytes());
|
|
131
|
+
if (formatted instanceof Error) throw formatted;
|
|
132
|
+
return formatted;
|
|
133
|
+
},
|
|
134
|
+
uuidV7At: (timestamp) => formatUuidV7(bytes(void 0, 0, timestamp, true)),
|
|
135
|
+
uuidV7Bytes: (out, offset) => bytes(out, offset),
|
|
136
|
+
uuidV7BytesAt: (timestamp, out, offset) => bytes(out, offset, timestamp, true)
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function createRuntimeGenerator(runtime) {
|
|
140
|
+
const fallback = createUuidV7Generator({ fillRandom: runtime.fillRandom });
|
|
141
|
+
return {
|
|
142
|
+
uuidV7() {
|
|
143
|
+
if (!runtime.uuidV7) return fallback.uuidV7();
|
|
144
|
+
try {
|
|
145
|
+
return runtime.uuidV7();
|
|
146
|
+
} catch {
|
|
147
|
+
return fallback.uuidV7();
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
uuidV7Bytes(out, offset = 0) {
|
|
151
|
+
if (!runtime.uuidV7Bytes) return fallback.uuidV7Bytes(out, offset);
|
|
152
|
+
const badRange = checkRange(out?.length ?? 16, offset, 16);
|
|
153
|
+
if (badRange) return badRange;
|
|
154
|
+
try {
|
|
155
|
+
return runtime.uuidV7Bytes(out, offset);
|
|
156
|
+
} catch (cause) {
|
|
157
|
+
return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", { cause });
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
uuidV7At(timestamp) {
|
|
161
|
+
if (!runtime.uuidV7At) return fallback.uuidV7At(timestamp);
|
|
162
|
+
const invalid = rejectInstant(timestamp);
|
|
163
|
+
if (invalid) return invalid;
|
|
164
|
+
try {
|
|
165
|
+
return runtime.uuidV7At(timestamp);
|
|
166
|
+
} catch {
|
|
167
|
+
return fallback.uuidV7At(timestamp);
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
uuidV7BytesAt(timestamp, out, offset = 0) {
|
|
171
|
+
if (!runtime.uuidV7BytesAt) return fallback.uuidV7BytesAt(timestamp, out, offset);
|
|
172
|
+
const invalid = rejectInstant(timestamp);
|
|
173
|
+
if (invalid) return invalid;
|
|
174
|
+
const badRange = checkRange(out?.length ?? 16, offset, 16);
|
|
175
|
+
if (badRange) return badRange;
|
|
176
|
+
try {
|
|
177
|
+
return runtime.uuidV7BytesAt(timestamp, out, offset);
|
|
178
|
+
} catch (cause) {
|
|
179
|
+
return new UuidSlugError("rng_unavailable", "Runtime UUIDv7 byte generation failed.", { cause });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
export { createRuntimeGenerator, createUuidV7Generator };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
//#region src/yield.ts
|
|
4
|
+
const host = globalThis;
|
|
5
|
+
const immediate = host.setImmediate?.bind(host);
|
|
6
|
+
/** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */
|
|
7
|
+
function yieldToHost() {
|
|
8
|
+
if (immediate) return new Promise((resolve) => immediate(resolve));
|
|
9
|
+
return new Promise((resolve) => {
|
|
10
|
+
const channel = new MessageChannel();
|
|
11
|
+
channel.port1.onmessage = () => {
|
|
12
|
+
channel.port1.close();
|
|
13
|
+
channel.port2.close();
|
|
14
|
+
resolve();
|
|
15
|
+
};
|
|
16
|
+
channel.port2.postMessage(null);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { yieldToHost };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
//#region src/runtime/pool.ts
|
|
4
|
+
/**
|
|
5
|
+
* Draws cryptographic randomness a page at a time instead of per id.
|
|
6
|
+
*
|
|
7
|
+
* The underlying primitives cost far more per call than per byte, and a v7 id needs only 16
|
|
8
|
+
* bytes, so per-id draws spend nearly all of their time on call overhead. Measured 2026-08-11
|
|
9
|
+
* filling 16 bytes: 1.94M/s (Node 24) and 4.85M/s (Bun) drawing directly, against 38.9M/s and
|
|
10
|
+
* 77.9M/s from an 8 KiB pool — 20x and 16x. Node's own `randomUUID` batches for the same reason,
|
|
11
|
+
* which is why `crypto.randomUUID` measures 8.9M/s against 1.5M/s with its cache disabled.
|
|
12
|
+
*
|
|
13
|
+
* 8 KiB is the knee: 64 KiB gains nothing further on Node and measured slightly worse on Bun,
|
|
14
|
+
* while holding eight times as much unissued material in memory.
|
|
15
|
+
*
|
|
16
|
+
* The source is unchanged — this batches the same CSPRNG, it does not replace or stretch it.
|
|
17
|
+
*/
|
|
18
|
+
const POOL_BYTES = 8192;
|
|
19
|
+
/**
|
|
20
|
+
* Wraps a direct random-fill primitive in a pool.
|
|
21
|
+
*
|
|
22
|
+
* Consumed bytes are zeroed as they are handed out. Batching is what creates the need: without
|
|
23
|
+
* a pool, material for an id is gone once used, whereas a live 8 KiB buffer would otherwise
|
|
24
|
+
* retain the random half of up to 512 already-issued ids, so a heap dump would expose ids the
|
|
25
|
+
* process had already handed out. Zeroing restores the property batching would remove; the cost
|
|
26
|
+
* is one write per byte already being copied.
|
|
27
|
+
*
|
|
28
|
+
* Each module instance owns its pool, so worker threads never share one. This is safe under
|
|
29
|
+
* Node's process model because a new process gets a fresh heap; it would NOT be safe under a
|
|
30
|
+
* POSIX `fork` that copies the heap, where parent and child would issue identical bytes.
|
|
31
|
+
*/
|
|
32
|
+
function pooledFill(fill) {
|
|
33
|
+
const pool = new Uint8Array(POOL_BYTES);
|
|
34
|
+
let offset = POOL_BYTES;
|
|
35
|
+
return (bytes) => {
|
|
36
|
+
const { length } = bytes;
|
|
37
|
+
if (length > POOL_BYTES) {
|
|
38
|
+
fill(bytes);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (offset + length > POOL_BYTES) {
|
|
42
|
+
fill(pool);
|
|
43
|
+
offset = 0;
|
|
44
|
+
}
|
|
45
|
+
for (let i = 0; i < length; i += 1) {
|
|
46
|
+
bytes[i] = pool[offset + i];
|
|
47
|
+
pool[offset + i] = 0;
|
|
48
|
+
}
|
|
49
|
+
offset += length;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { pooledFill };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=pool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pool.js","names":[],"sources":["../../src/runtime/pool.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Draws cryptographic randomness a page at a time instead of per id.\n *\n * The underlying primitives cost far more per call than per byte, and a v7 id needs only 16\n * bytes, so per-id draws spend nearly all of their time on call overhead. Measured 2026-08-11\n * filling 16 bytes: 1.94M/s (Node 24) and 4.85M/s (Bun) drawing directly, against 38.9M/s and\n * 77.9M/s from an 8 KiB pool — 20x and 16x. Node's own `randomUUID` batches for the same reason,\n * which is why `crypto.randomUUID` measures 8.9M/s against 1.5M/s with its cache disabled.\n *\n * 8 KiB is the knee: 64 KiB gains nothing further on Node and measured slightly worse on Bun,\n * while holding eight times as much unissued material in memory.\n *\n * The source is unchanged — this batches the same CSPRNG, it does not replace or stretch it.\n */\nconst POOL_BYTES = 8192;\n\n/**\n * Wraps a direct random-fill primitive in a pool.\n *\n * Consumed bytes are zeroed as they are handed out. Batching is what creates the need: without\n * a pool, material for an id is gone once used, whereas a live 8 KiB buffer would otherwise\n * retain the random half of up to 512 already-issued ids, so a heap dump would expose ids the\n * process had already handed out. Zeroing restores the property batching would remove; the cost\n * is one write per byte already being copied.\n *\n * Each module instance owns its pool, so worker threads never share one. This is safe under\n * Node's process model because a new process gets a fresh heap; it would NOT be safe under a\n * POSIX `fork` that copies the heap, where parent and child would issue identical bytes.\n */\nexport function pooledFill(\n fill: (into: Uint8Array<ArrayBuffer>) => void,\n): (bytes: Uint8Array<ArrayBuffer>) => void {\n const pool = new Uint8Array(POOL_BYTES);\n // STARTS EMPTY, and must. Pre-filling here would move the first call's syscall off the hot path,\n // which looks like a free win and is the one change that breaks heap-snapshot safety: a snapshot\n // taken at import time (V8 or JavaScriptCore startup snapshots, and the serverless platforms\n // built on them) would capture drawn randomness, and every process restored from it would issue\n // the SAME identifiers. Nothing else would notice — the bytes stay perfectly random within any\n // one process, so every other case in this suite passes. `test/entropy.test.ts` gates it by\n // importing the package under the instrument and requiring that no source was touched.\n let offset = POOL_BYTES;\n return (bytes) => {\n const { length } = bytes;\n // A request larger than the pool would refill for a single use; serve it directly instead.\n if (length > POOL_BYTES) {\n fill(bytes);\n return;\n }\n if (offset + length > POOL_BYTES) {\n fill(pool);\n offset = 0;\n }\n // Copy and erase in one pass; `subarray` plus `set` would allocate a view per call.\n for (let i = 0; i < length; i += 1) {\n bytes[i] = pool[offset + i] as number;\n pool[offset + i] = 0;\n }\n offset += length;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,MAAM,aAAa;;;;;;;;;;;;;;AAenB,SAAgB,WACd,MAC0C;CAC1C,MAAM,OAAO,IAAI,WAAW,UAAU;CAQtC,IAAI,SAAS;CACb,QAAQ,UAAU;EAChB,MAAM,EAAE,WAAW;EAEnB,IAAI,SAAS,YAAY;GACvB,KAAK,KAAK;GACV;EACF;EACA,IAAI,SAAS,SAAS,YAAY;GAChC,KAAK,IAAI;GACT,SAAS;EACX;EAEA,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK,GAAG;GAClC,MAAM,KAAK,KAAK,SAAS;GACzB,KAAK,SAAS,KAAK;EACrB;EACA,UAAU;CACZ;AACF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidRuntimeError } from "../errors.js";
|
|
4
|
+
import { pooledFill } from "./pool.js";
|
|
5
|
+
//#region src/runtime/web.ts
|
|
6
|
+
/**
|
|
7
|
+
* Resolve Web Crypto per draw so instrumentation installed after import can observe the source.
|
|
8
|
+
* Binding it at module load would bypass `test/instrument.ts` and hide those calls from the gate.
|
|
9
|
+
*/
|
|
10
|
+
function cryptoObject() {
|
|
11
|
+
const value = globalThis.crypto;
|
|
12
|
+
if (!value?.getRandomValues) throw new UuidRuntimeError("Web Crypto getRandomValues is unavailable.");
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
const runtimeCapabilities = {
|
|
16
|
+
/**
|
|
17
|
+
* Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per
|
|
18
|
+
* byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.
|
|
19
|
+
*/
|
|
20
|
+
fillRandom: pooledFill((into) => {
|
|
21
|
+
cryptoObject().getRandomValues(into);
|
|
22
|
+
}) };
|
|
23
|
+
/**
|
|
24
|
+
* `randomUUID` is probed ONCE here and the method left undefined when it is absent — the rule
|
|
25
|
+
* `runtime/node.ts` already follows and the reason `Runtime`'s methods are optional.
|
|
26
|
+
*
|
|
27
|
+
* It is not the same capability as `getRandomValues`, and a browser can have one without the
|
|
28
|
+
* other: `crypto.randomUUID` is restricted to secure contexts, `getRandomValues` is not. Defined
|
|
29
|
+
* unconditionally with a throw inside, `uuidV4()` was the only one of four entry points that
|
|
30
|
+
* failed on such a page — `uuidV4Slug`, `uuidV4Bytes` and `uuidV7` all answered, because they
|
|
31
|
+
* reach the byte generator rather than this method. Leaving it undefined routes `uuidV4` to that
|
|
32
|
+
* same generator, so the four agree.
|
|
33
|
+
*/
|
|
34
|
+
if (globalThis.crypto?.randomUUID) runtimeCapabilities.uuidV4 = () => cryptoObject().randomUUID();
|
|
35
|
+
const runtime = runtimeCapabilities;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { runtime };
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=web.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web.js","names":[],"sources":["../../src/runtime/web.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { UuidRuntimeError } from \"../errors\";\nimport { pooledFill } from \"./pool\";\nimport type { Runtime } from \"./types\";\n\n/**\n * Resolve Web Crypto per draw so instrumentation installed after import can observe the source.\n * Binding it at module load would bypass `test/instrument.ts` and hide those calls from the gate.\n */\nfunction cryptoObject(): Crypto {\n const value = globalThis.crypto;\n if (!value?.getRandomValues)\n throw new UuidRuntimeError(\"Web Crypto getRandomValues is unavailable.\");\n return value;\n}\n\nconst runtimeCapabilities: Runtime = {\n /**\n * Pooled for the same reason as Node's: `getRandomValues` costs far more per call than per\n * byte, and a v7 id needs 16. Bun draws this path too, where pooling measured 16x.\n */\n fillRandom: pooledFill((into) => {\n cryptoObject().getRandomValues(into);\n }),\n};\n\n/**\n * `randomUUID` is probed ONCE here and the method left undefined when it is absent — the rule\n * `runtime/node.ts` already follows and the reason `Runtime`'s methods are optional.\n *\n * It is not the same capability as `getRandomValues`, and a browser can have one without the\n * other: `crypto.randomUUID` is restricted to secure contexts, `getRandomValues` is not. Defined\n * unconditionally with a throw inside, `uuidV4()` was the only one of four entry points that\n * failed on such a page — `uuidV4Slug`, `uuidV4Bytes` and `uuidV7` all answered, because they\n * reach the byte generator rather than this method. Leaving it undefined routes `uuidV4` to that\n * same generator, so the four agree.\n */\n/*\n * Probed through `Partial<Crypto>` because the DOM lib declares `randomUUID` as always present,\n * so the plain condition is \"always true\" to the compiler (TS2774) while being false on any\n * insecure page. The cast states the divergence rather than suppressing it: the types describe a\n * secure context, the check describes every context.\n */\nif ((globalThis.crypto as Partial<Crypto> | undefined)?.randomUUID)\n runtimeCapabilities.uuidV4 = () => cryptoObject().randomUUID();\n\nexport const runtime: Runtime = runtimeCapabilities;\n"],"mappings":";;;;;;;;;AAUA,SAAS,eAAuB;CAC9B,MAAM,QAAQ,WAAW;CACzB,IAAI,CAAC,OAAO,iBACV,MAAM,IAAI,iBAAiB,4CAA4C;CACzE,OAAO;AACT;AAEA,MAAM,sBAA+B;;;;;AAKnC,YAAY,YAAY,SAAS;CAC/B,aAAa,CAAC,CAAC,gBAAgB,IAAI;AACrC,CAAC,EACH;;;;;;;;;;;;AAmBA,IAAK,WAAW,QAAwC,YACtD,oBAAoB,eAAe,aAAa,CAAC,CAAC,WAAW;AAE/D,MAAa,UAAmB"}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidSlugError } from "./errors.js";
|
|
4
|
+
import { AsyncMaskSchemaOptions, MaskSchema, MaskSchemaOptions } from "./types.js";
|
|
5
|
+
//#region src/schema.d.ts
|
|
6
|
+
declare function createMaskSchema(options: MaskSchemaOptions): UuidSlugError | MaskSchema;
|
|
7
|
+
/**
|
|
8
|
+
* Derive the same schema while allowing other host tasks to run. Options and byte contents are
|
|
9
|
+
* captured before suspension; cancellation returns an `aborted` error with the signal's reason
|
|
10
|
+
* as its cause. Checkpoints stop computation rather than racing a still-running derivation.
|
|
11
|
+
*
|
|
12
|
+
* Two-millisecond work slices leave headroom for host scheduling. This is a responsiveness target,
|
|
13
|
+
* not a bound on the initial byte snapshot, allocation, GC or scheduler delays. Tiny derivations
|
|
14
|
+
* need no host yield. Passing the result as a codec's `mask` avoids deriving it again.
|
|
15
|
+
*/
|
|
16
|
+
declare function createMaskSchemaAsync(options: AsyncMaskSchemaOptions): Promise<MaskSchema | UuidSlugError>;
|
|
17
|
+
declare const DEFAULT_MASK_SCHEMA: MaskSchema;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { DEFAULT_MASK_SCHEMA, createMaskSchema, createMaskSchemaAsync };
|
|
20
|
+
//# sourceMappingURL=schema.d.ts.map
|