@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/dist/uuid.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
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 { Alphabet } from "./alphabet.js";
|
|
5
|
+
import { UuidSlug, UuidString, UuidV4Slug, UuidV4String, UuidV7Slug, UuidV7String } from "./types.js";
|
|
6
|
+
//#region src/uuid.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* The alphabets a plain slug may be written in. base64url is the default and the shortest;
|
|
9
|
+
* base32hex costs four more characters and buys the one property base64url cannot offer: its
|
|
10
|
+
* characters are in ASCII order, so base32hex slugs of UUIDv7s sort chronologically as plain
|
|
11
|
+
* strings. Only the lowercase spelling decodes — the table is built from `chars` — so slugs have
|
|
12
|
+
* no second spelling, as everywhere else in this format.
|
|
13
|
+
*
|
|
14
|
+
* MASKED slugs are always base64url (Art's ruling, 2026-08-12). Sort order there would be order of
|
|
15
|
+
* ciphertext, which carries nothing, so the extra characters would buy only the case-insensitivity.
|
|
16
|
+
*/
|
|
17
|
+
declare const SLUG_ALPHABETS: {
|
|
18
|
+
base32hex: Alphabet;
|
|
19
|
+
base64url: Alphabet;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Callers name an alphabet rather than passing one. `Alphabet` holds a decode table and a bit
|
|
23
|
+
* width — internals that would become public surface the moment the type escaped — and accepting
|
|
24
|
+
* an arbitrary one would also open a second extension point beside `MaskSchema`, which this
|
|
25
|
+
* package documents as its only one. A union of two names cannot be widened by a caller at all, so
|
|
26
|
+
* there is nothing to validate.
|
|
27
|
+
*/
|
|
28
|
+
type SlugAlphabet = keyof typeof SLUG_ALPHABETS;
|
|
29
|
+
declare function parseUuid(uuid: string, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
30
|
+
declare function formatUuid(bytes: Uint8Array, offset?: number): UuidSlugError | UuidString;
|
|
31
|
+
declare function isUuidString(uuid: null | string | undefined): uuid is UuidString;
|
|
32
|
+
declare function isUuidV4String(uuid: null | string | undefined): uuid is UuidV4String;
|
|
33
|
+
declare function isUuidV7String(uuid: null | string | undefined): uuid is UuidV7String;
|
|
34
|
+
/**
|
|
35
|
+
* The only BYTE-level predicate, and the asymmetry against `isUuidV4String` is deliberate: masking
|
|
36
|
+
* accepts v7 alone, so a caller holding raw bytes has a reason to ask this and none to ask the v4
|
|
37
|
+
* question. `isUuidV4Bytes` is absent because nothing needs it, not because it was overlooked —
|
|
38
|
+
* add it when a caller appears, never for symmetry, since an export is permanent surface.
|
|
39
|
+
*/
|
|
40
|
+
declare function isUuidV7Bytes(bytes: Uint8Array): boolean;
|
|
41
|
+
declare function formatUuidSlug(bytes: Uint8Array, offset?: number, alphabet?: SlugAlphabet): UuidSlugError | UuidSlug;
|
|
42
|
+
/** Accepts either alphabet; the length says which, so there is nothing to pass and nothing to get wrong. */
|
|
43
|
+
declare function parseUuidSlug(slug: string, out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array;
|
|
44
|
+
declare function uuidToSlug(uuid: string, alphabet?: SlugAlphabet): UuidSlugError | UuidSlug;
|
|
45
|
+
declare function slugToUuid(slug: string): UuidSlugError | UuidString;
|
|
46
|
+
declare function isUuidSlug(slug: null | string | undefined): slug is UuidSlug;
|
|
47
|
+
declare function isUuidV4Slug(slug: null | string | undefined): slug is UuidV4Slug;
|
|
48
|
+
declare function isUuidV7Slug(slug: null | string | undefined): slug is UuidV7Slug;
|
|
49
|
+
/**
|
|
50
|
+
* The 48-bit millisecond a UUIDv7 was minted at.
|
|
51
|
+
*
|
|
52
|
+
* It REFUSES anything that is not a v7, which is the whole point of the return type: the first six
|
|
53
|
+
* bytes of a v4 are random, so reading them yields a confident, well-formed date drawn uniformly
|
|
54
|
+
* from the next nine thousand years. A caller that passed the wrong version got that date silently,
|
|
55
|
+
* and a freshness check built on it would accept or reject by coin flip while looking correct.
|
|
56
|
+
*
|
|
57
|
+
* Short input is reported separately from wrong version, because `uuidVersion` reads a missing byte
|
|
58
|
+
* as zero and would otherwise blame a truncated buffer for holding a v0.
|
|
59
|
+
*/
|
|
60
|
+
declare function extractUuidV7Timestamp(bytes: Uint8Array, offset?: number): UuidSlugError | number;
|
|
61
|
+
/**
|
|
62
|
+
* Whether a v7's 74 random bits are anything other than all-zero or all-one — the two patterns a
|
|
63
|
+
* generator produces when its entropy source is absent rather than working.
|
|
64
|
+
*
|
|
65
|
+
* Out of range answers `false`, and the direction is the whole point. Without the check the reads
|
|
66
|
+
* below fall through `?? 0`, so a missing byte is indistinguishable from a zero byte and only ever
|
|
67
|
+
* in the reassuring direction: a short buffer reported entropy PRESENT, and an offset past the end
|
|
68
|
+
* reported the degenerate case for data that was never examined. Both are answers about bytes the
|
|
69
|
+
* caller does not have. `false` is the honest one — it means "cannot be shown to carry entropy",
|
|
70
|
+
* which is what a caller acts on, and it is what a truly degenerate id gets too.
|
|
71
|
+
*
|
|
72
|
+
* Boolean rather than `UuidSlugError | boolean` because the sole use is a guard in a condition; an error
|
|
73
|
+
* return would have every call site unwrap a value it is already treating as a yes/no.
|
|
74
|
+
*/
|
|
75
|
+
declare function hasUuidV7Entropy(bytes: Uint8Array, offset?: number): boolean;
|
|
76
|
+
//#endregion
|
|
77
|
+
export { SlugAlphabet, extractUuidV7Timestamp, formatUuid, formatUuidSlug, hasUuidV7Entropy, isUuidSlug, isUuidString, isUuidV4Slug, isUuidV4String, isUuidV7Bytes, isUuidV7Slug, isUuidV7String, parseUuid, parseUuidSlug, slugToUuid, uuidToSlug };
|
|
78
|
+
//# sourceMappingURL=uuid.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid.d.ts","names":[],"sources":["../src/uuid.ts"],"mappings":";;;;;;;;;;;;;;;;cAwCM;EAAkB,WAAW;EAAU,WAAW;;;;;;;;;KAY5C,4BAA4B;iBAqCxB,UAAU,cAAc,MAAM,YAAY,kBAAa,gBAAgB;iBAsBvE,WAAW,OAAO,YAAY,kBAAa,gBAAgB;iBAyB3D,aAAa,kCAAkC,QAAQ;iBAgBvD,eAAe,kCAAkC,QAAQ;iBAIzD,eAAe,kCAAkC,QAAQ;;;;;;;iBAUzD,cAAc,OAAO;iBAIrB,eACd,OAAO,YACP,iBACA,WAAU,eACT,gBAAgB;;iBAWH,cACd,cACA,MAAM,YACN,kBACC,gBAAgB;iBAYH,WACd,cACA,WAAU,eACT,gBAAgB;iBAMH,WAAW,eAAe,gBAAgB;iBAM1C,WAAW,kCAAkC,QAAQ;iBAsBrD,aAAa,kCAAkC,QAAQ;iBAIvD,aAAa,kCAAkC,QAAQ;;;;;;;;;;;;iBAevD,uBAAuB,OAAO,YAAY,kBAAa;;;;;;;;;;;;;;;iBAwBvD,iBAAiB,OAAO,YAAY"}
|
package/dist/uuid.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
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 };
|
|
227
|
+
|
|
228
|
+
//# sourceMappingURL=uuid.js.map
|
package/dist/uuid.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid.js","names":[],"sources":["../src/uuid.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded } from \"./alphabet\";\nimport type { Alphabet } from \"./alphabet\";\nimport { checkRange, UuidSlugError } from \"./errors\";\nimport type {\n UuidSlug,\n UuidString,\n UuidV4Slug,\n UuidV4String,\n UuidV7Slug,\n UuidV7String,\n} from \"./types\";\n\nconst HEX = \"0123456789abcdef\";\n// Probe once and allocate the byte-pair fallback only on engines that need it.\nconst nativeToHex = (Uint8Array.prototype as { toHex?: () => string }).toHex;\nconst HEX_BYTES = nativeToHex\n ? []\n : /*#__PURE__*/ Array.from(\n { length: 256 },\n (_, byte) => (HEX[byte >>> 4] as string) + (HEX[byte & 15] as string),\n );\nconst HEX_DECODE = new Int8Array(128).fill(-1);\nfor (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;\nfor (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;\n\nconst UUID_LENGTH = 36;\nconst UUID_BYTE_OFFSETS = [0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34] as const;\n\n/**\n * The alphabets a plain slug may be written in. base64url is the default and the shortest;\n * base32hex costs four more characters and buys the one property base64url cannot offer: its\n * characters are in ASCII order, so base32hex slugs of UUIDv7s sort chronologically as plain\n * strings. Only the lowercase spelling decodes — the table is built from `chars` — so slugs have\n * no second spelling, as everywhere else in this format.\n *\n * MASKED slugs are always base64url (Art's ruling, 2026-08-12). Sort order there would be order of\n * ciphertext, which carries nothing, so the extra characters would buy only the case-insensitivity.\n */\nconst SLUG_ALPHABETS: { base32hex: Alphabet; base64url: Alphabet } = {\n base32hex: BASE32HEX,\n base64url: BASE64URL,\n} as const;\n\n/**\n * Callers name an alphabet rather than passing one. `Alphabet` holds a decode table and a bit\n * width — internals that would become public surface the moment the type escaped — and accepting\n * an arbitrary one would also open a second extension point beside `MaskSchema`, which this\n * package documents as its only one. A union of two names cannot be widened by a caller at all, so\n * there is nothing to validate.\n */\nexport type SlugAlphabet = keyof typeof SLUG_ALPHABETS;\n\n/** Reject inherited property names as well as unknown names from JavaScript callers. */\nexport function resolveSlugAlphabet(alphabet: SlugAlphabet): Alphabet | UuidSlugError {\n return Object.hasOwn(SLUG_ALPHABETS, alphabet)\n ? SLUG_ALPHABETS[alphabet]\n : new UuidSlugError(\n \"invalid_uuid_slug\",\n `Unknown slug alphabet \"${alphabet}\"; expected ${Object.keys(SLUG_ALPHABETS).join(\" or \")}.`,\n );\n}\n\n/** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */\nfunction slugLength(alpha: Alphabet) {\n return Math.ceil(128 / alpha.bitsPerChar);\n}\n\n/**\n * Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are\n * disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed\n * rather than searched because every decode and every type guard pays this lookup.\n */\nconst SLUG_ALPHABET_BY_LENGTH: readonly (Alphabet | undefined)[] = Object.values(\n SLUG_ALPHABETS,\n).reduce<(Alphabet | undefined)[]>((table, alpha) => {\n table[slugLength(alpha)] = alpha;\n return table;\n}, []);\n\nconst SLUG_LENGTHS = Object.values(SLUG_ALPHABETS)\n .map((alpha) => `${slugLength(alpha)} (${alpha.name})`)\n .join(\" or \");\n\nfunction hexValue(code: number) {\n return HEX_DECODE[code] ?? -1;\n}\n\nexport function parseUuid(uuid: string, out?: Uint8Array, offset = 0): UuidSlugError | Uint8Array {\n if (uuid.length !== UUID_LENGTH)\n return new UuidSlugError(\"invalid_uuid\", \"UUID must be 36 characters.\");\n if (uuid[8] !== \"-\" || uuid[13] !== \"-\" || uuid[18] !== \"-\" || uuid[23] !== \"-\") {\n return new UuidSlugError(\"invalid_uuid\", \"UUID hyphen positions are invalid.\");\n }\n\n const target = out ?? new Uint8Array(16);\n const badRange = checkRange(target.length, offset, 16);\n if (badRange) return badRange;\n\n for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {\n const textOffset = UUID_BYTE_OFFSETS[byteIndex] as number;\n const high = hexValue(uuid.charCodeAt(textOffset));\n const low = hexValue(uuid.charCodeAt(textOffset + 1));\n if (high < 0 || low < 0)\n return new UuidSlugError(\"invalid_uuid\", `Invalid UUID hex at offset ${textOffset}.`);\n target[offset + byteIndex] = (high << 4) | low;\n }\n return target;\n}\n\nexport function formatUuid(bytes: Uint8Array, offset = 0): UuidSlugError | UuidString {\n const badRange = checkRange(bytes.length, offset, 16);\n if (badRange) return badRange;\n if (nativeToHex) {\n const hex = nativeToHex.call(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16));\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n let out = \"\";\n for (let i = 0; i < 16; i += 1) {\n if (i === 4 || i === 6 || i === 8 || i === 10) out += \"-\";\n const byte = bytes[offset + i] ?? 0;\n out += HEX_BYTES[byte];\n }\n return out;\n}\n\nexport function uuidVersion(bytes: Uint8Array, offset = 0): number {\n return (bytes[offset + 6] ?? 0) >>> 4;\n}\n\nexport function isRfcVariant(bytes: Uint8Array, offset = 0): boolean {\n return (bytes[offset + 8] ?? 0) >>> 6 === 0b10;\n}\n\n// Predicates inspect the same hex table as parsing without allocating output bytes or Errors.\nexport function isUuidString(uuid: null | string | undefined): uuid is UuidString {\n if (!uuid || uuid.length !== UUID_LENGTH) return false;\n if (uuid[8] !== \"-\" || uuid[13] !== \"-\" || uuid[18] !== \"-\" || uuid[23] !== \"-\") return false;\n for (let i = 0; i < UUID_BYTE_OFFSETS.length; i += 1) {\n const offset = UUID_BYTE_OFFSETS[i] as number;\n if (hexValue(uuid.charCodeAt(offset)) < 0 || hexValue(uuid.charCodeAt(offset + 1)) < 0)\n return false;\n }\n return true;\n}\n\n/** The string has already passed canonical validation, so the variant digit is a known hex value. */\nfunction stringHasRfcVariant(uuid: string): boolean {\n return (HEX_DECODE[uuid.charCodeAt(19)] as number) >>> 2 === 2;\n}\n\nexport function isUuidV4String(uuid: null | string | undefined): uuid is UuidV4String {\n return isUuidString(uuid) && uuid[14] === \"4\" && stringHasRfcVariant(uuid);\n}\n\nexport function isUuidV7String(uuid: null | string | undefined): uuid is UuidV7String {\n return isUuidString(uuid) && uuid[14] === \"7\" && stringHasRfcVariant(uuid);\n}\n\n/**\n * The only BYTE-level predicate, and the asymmetry against `isUuidV4String` is deliberate: masking\n * accepts v7 alone, so a caller holding raw bytes has a reason to ask this and none to ask the v4\n * question. `isUuidV4Bytes` is absent because nothing needs it, not because it was overlooked —\n * add it when a caller appears, never for symmetry, since an export is permanent surface.\n */\nexport function isUuidV7Bytes(bytes: Uint8Array): boolean {\n return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);\n}\n\nexport function formatUuidSlug(\n bytes: Uint8Array,\n offset = 0,\n alphabet: SlugAlphabet = \"base64url\",\n): UuidSlugError | UuidSlug {\n const badRange = checkRange(bytes.length, offset, 16);\n if (badRange) return badRange;\n // Unreachable from TypeScript, where the name is a two-member union. Reached from JavaScript,\n // which is why it answers rather than indexing into `undefined`.\n const alpha = resolveSlugAlphabet(alphabet);\n if (alpha instanceof Error) return alpha;\n return encode(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16), alpha);\n}\n\n/** Accepts either alphabet; the length says which, so there is nothing to pass and nothing to get wrong. */\nexport function parseUuidSlug(\n slug: string,\n out?: Uint8Array,\n offset = 0,\n): UuidSlugError | Uint8Array {\n const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];\n if (!alpha)\n return new UuidSlugError(\n \"invalid_uuid_slug\",\n `UUID slug must be ${SLUG_LENGTHS} characters, got ${slug.length}.`,\n );\n const target = out ?? new Uint8Array(16);\n const result = decodeInto(slug, alpha, target, offset, 16);\n return result instanceof Error ? result : target;\n}\n\nexport function uuidToSlug(\n uuid: string,\n alphabet: SlugAlphabet = \"base64url\",\n): UuidSlugError | UuidSlug {\n const bytes = parseUuid(uuid);\n if (bytes instanceof Error) return bytes;\n return formatUuidSlug(bytes, 0, alphabet);\n}\n\nexport function slugToUuid(slug: string): UuidSlugError | UuidString {\n const bytes = parseUuidSlug(slug);\n if (bytes instanceof Error) return bytes;\n return formatUuid(bytes);\n}\n\nexport function isUuidSlug(slug: null | string | undefined): slug is UuidSlug {\n if (!slug) return false;\n const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];\n return alpha !== undefined && isEncoded(slug, alpha, 16);\n}\n\n/** Read only the version/variant bytes after canonical validation, without decoding a whole UUID. */\nfunction slugByte(slug: string, alpha: Alphabet, offset: number): number {\n const start = Math.floor((offset * 8) / alpha.bitsPerChar);\n const end = Math.floor((offset * 8 + 7) / alpha.bitsPerChar);\n let value = 0;\n for (let i = start; i <= end; i += 1)\n value = (value << alpha.bitsPerChar) | (alpha.decode[slug.charCodeAt(i)] as number);\n return (value >>> ((end + 1) * alpha.bitsPerChar - (offset + 1) * 8)) & 255;\n}\n\nfunction isVersionedSlug(slug: null | string | undefined, version: number): boolean {\n if (!isUuidSlug(slug)) return false;\n const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length] as Alphabet;\n return slugByte(slug, alpha, 6) >>> 4 === version && slugByte(slug, alpha, 8) >>> 6 === 2;\n}\n\nexport function isUuidV4Slug(slug: null | string | undefined): slug is UuidV4Slug {\n return isVersionedSlug(slug, 4);\n}\n\nexport function isUuidV7Slug(slug: null | string | undefined): slug is UuidV7Slug {\n return isVersionedSlug(slug, 7);\n}\n\n/**\n * The 48-bit millisecond a UUIDv7 was minted at.\n *\n * It REFUSES anything that is not a v7, which is the whole point of the return type: the first six\n * bytes of a v4 are random, so reading them yields a confident, well-formed date drawn uniformly\n * from the next nine thousand years. A caller that passed the wrong version got that date silently,\n * and a freshness check built on it would accept or reject by coin flip while looking correct.\n *\n * Short input is reported separately from wrong version, because `uuidVersion` reads a missing byte\n * as zero and would otherwise blame a truncated buffer for holding a v0.\n */\nexport function extractUuidV7Timestamp(bytes: Uint8Array, offset = 0): UuidSlugError | number {\n const badRange = checkRange(bytes.length, offset, 16);\n if (badRange) return badRange;\n if (uuidVersion(bytes, offset) !== 7 || !isRfcVariant(bytes, offset))\n return new UuidSlugError(\"invalid_uuid_version\", \"Timestamp is only defined for UUIDv7.\");\n let timestamp = 0;\n for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);\n return timestamp;\n}\n\n/**\n * Whether a v7's 74 random bits are anything other than all-zero or all-one — the two patterns a\n * generator produces when its entropy source is absent rather than working.\n *\n * Out of range answers `false`, and the direction is the whole point. Without the check the reads\n * below fall through `?? 0`, so a missing byte is indistinguishable from a zero byte and only ever\n * in the reassuring direction: a short buffer reported entropy PRESENT, and an offset past the end\n * reported the degenerate case for data that was never examined. Both are answers about bytes the\n * caller does not have. `false` is the honest one — it means \"cannot be shown to carry entropy\",\n * which is what a caller acts on, and it is what a truly degenerate id gets too.\n *\n * Boolean rather than `UuidSlugError | boolean` because the sole use is a guard in a condition; an error\n * return would have every call site unwrap a value it is already treating as a yes/no.\n */\nexport function hasUuidV7Entropy(bytes: Uint8Array, offset = 0): boolean {\n if (checkRange(bytes.length, offset, 16)) return false;\n const randA = (((bytes[offset + 6] ?? 0) & 0x0f) << 8) | (bytes[offset + 7] ?? 0);\n const randBFirst = (bytes[offset + 8] ?? 0) & 0x3f;\n let restZero = true;\n let restMax = true;\n for (let i = 9; i < 16; i += 1) {\n const byte = bytes[offset + i] ?? 0;\n if (byte !== 0x00) restZero = false;\n if (byte !== 0xff) restMax = false;\n }\n return (\n !(randA === 0 && randBFirst === 0 && restZero) &&\n !(randA === 0x0fff && randBFirst === 0x3f && restMax)\n );\n}\n"],"mappings":";;;;;AAcA,MAAM,MAAM;AAEZ,MAAM,cAAe,WAAW,UAAuC;AACvE,MAAM,YAAY,cACd,CAAC,IACa,oBAAM,KAClB,EAAE,QAAQ,IAAI,IACb,GAAG,SAAU,IAAI,SAAS,KAAiB,IAAI,OAAO,GACzD;AACJ,MAAM,8BAAa,IAAI,UAAU,GAAG,EAAA,CAAE,KAAK,EAAE;AAC7C,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,GAAG,WAAW,KAAK,KAAK;AACrD,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,WAAW,KAAK,KAAK,KAAK;AAEzD,MAAM,cAAc;AACpB,MAAM,oBAAoB;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;AAAE;;;;;;;;;;;AAYpF,MAAM,iBAA+D;CACnE,WAAW;CACX,WAAW;AACb;;AAYA,SAAgB,oBAAoB,UAAkD;CACpF,OAAO,OAAO,OAAO,gBAAgB,QAAQ,IACzC,eAAe,YACf,IAAI,cACF,qBACA,0BAA0B,SAAS,cAAc,OAAO,KAAK,cAAc,CAAC,CAAC,KAAK,MAAM,EAAE,EAC5F;AACN;;AAGA,SAAS,WAAW,OAAiB;CACnC,OAAO,KAAK,KAAK,MAAM,MAAM,WAAW;AAC1C;;;;;;AAOA,MAAM,0BAA6D,OAAO,OACxE,cACF,CAAC,CAAC,QAAkC,OAAO,UAAU;CACnD,MAAM,WAAW,KAAK,KAAK;CAC3B,OAAO;AACT,GAAG,CAAC,CA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KAAM,UAAU;CAC/B;CACA,OACE,EAAE,UAAU,KAAK,eAAe,KAAK,aACrC,EAAE,UAAU,QAAU,eAAe,MAAQ;AAEjD"}
|
package/dist/v7.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidV7Generator } from "./types.js";
|
|
4
|
+
//#region src/v7.d.ts
|
|
5
|
+
interface UuidV7GeneratorOptions {
|
|
6
|
+
readonly clock?: () => number;
|
|
7
|
+
readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => void;
|
|
8
|
+
}
|
|
9
|
+
declare function createUuidV7Generator(options: UuidV7GeneratorOptions): UuidV7Generator;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { UuidV7GeneratorOptions, createUuidV7Generator };
|
|
12
|
+
//# sourceMappingURL=v7.d.ts.map
|
package/dist/v7.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"v7.d.ts","names":[],"sources":["../src/v7.ts"],"mappings":";;;;UAOiB;WACN;WACA,aAAa,OAAO,WAAW;;iBAiF1B,sBAAsB,SAAS,yBAAyB"}
|
package/dist/v7.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
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 };
|
|
186
|
+
|
|
187
|
+
//# sourceMappingURL=v7.js.map
|
package/dist/v7.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"v7.js","names":[],"sources":["../src/v7.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { checkRange, fillRandomBytes, readClock, UuidSlugError } from \"./errors\";\nimport type { UuidV7Generator, UuidV7String } from \"./types\";\nimport { formatUuid } from \"./uuid\";\nimport type { Runtime } from \"./runtime/types\";\n\nexport interface UuidV7GeneratorOptions {\n readonly clock?: () => number;\n readonly fillRandom: (bytes: Uint8Array<ArrayBuffer>) => void;\n}\n\nfunction writeTimestamp(bytes: Uint8Array, ms: number, offset: number) {\n let value = Math.trunc(ms);\n for (let i = 5; i >= 0; i -= 1) {\n bytes[offset + i] = value & 0xff;\n value = Math.floor(value / 256);\n }\n}\n\n/**\n * Writes the 42-bit sequence RFC 9562 §6.2 allows in `rand_a` plus the top of `rand_b`, along\n * with the version and variant bits that bracket it.\n *\n * The sequence is carried as a 10-bit high half and a 32-bit low half rather than one 42-bit\n * BigInt, so every operation here is a 32-bit integer op the JIT emits directly. Measured on the\n * increment-and-write step alone: 9.99M ops/s (Bun) and 11.8M (Node) as a BigInt, against 252M\n * and 149M in this form. The bit layout is unchanged, so the ids are identical either way.\n */\nfunction writeCounter(bytes: Uint8Array, hi: number, lo: number, offset: number) {\n bytes[offset + 6] = 0x70 | ((hi >>> 6) & 0x0f);\n bytes[offset + 7] = (((hi & 0x3f) << 2) | (lo >>> 30)) & 0xff;\n bytes[offset + 8] = 0x80 | ((lo >>> 24) & 0x3f);\n bytes[offset + 9] = (lo >>> 16) & 0xff;\n bytes[offset + 10] = (lo >>> 8) & 0xff;\n bytes[offset + 11] = lo & 0xff;\n}\n\n/** The 48 bits RFC 9562 gives the timestamp; beyond it the value cannot be represented. */\nconst MAX_TIMESTAMP = 0xffff_ffff_ffff;\n\n/**\n * `Number.isInteger` rather than `isFinite`, because the error message promises a WHOLE number of\n * milliseconds and `Math.trunc` on the write path would otherwise honour that promise silently:\n * 1.5 became 1 with nothing reported. It also rejects NaN and Infinity, which matters because a\n * native generator need not — measured 2026-08-12, `Bun.randomUUIDv7(\"hex\", NaN)` and the same\n * call at 2^48 both return the 1970 prefix `000000000000` without throwing, while -1 and 1.5 do\n * throw. Validating here rather than trusting the platform is what makes the two agree.\n */\nconst isValidUuidV7Timestamp = (ms: number): boolean =>\n Number.isInteger(ms) && ms >= 0 && ms <= MAX_TIMESTAMP;\n\n/**\n * The one check and the one message for a caller-supplied instant. Both the portable generator and\n * the runtime-backed one call it, and the runtime-backed one calls it BEFORE delegating: a native\n * generator may accept what we reject and answer wrongly rather than fail.\n */\nconst rejectInstant = (ms: number): UuidSlugError | undefined =>\n isValidUuidV7Timestamp(ms)\n ? undefined\n : new UuidSlugError(\n \"invalid_timestamp\",\n `UUIDv7 timestamp must be a whole number of milliseconds in 0..${MAX_TIMESTAMP}.`,\n );\n\n/**\n * Both string forms differ only in where the instant comes from, so the byte-or-error result is\n * carried through here rather than unwrapped twice. The narrowing is an assertion because\n * `formatUuid` is version-agnostic: the v7-ness is established by the caller having produced the\n * bytes, not by anything the formatter can check.\n */\nconst formatUuidV7 = (result: UuidSlugError | Uint8Array): UuidSlugError | UuidV7String =>\n result instanceof Error ? result : (formatUuid(result) as UuidSlugError | UuidV7String);\n\n/**\n * Seeds the sequence from the same six random bytes and the same bit positions as before, split\n * across the two halves: byte 0 and the top 2 bits of byte 1 form the high half, the rest the\n * low half. Starting each millisecond at a random point rather than zero is what stops the\n * sequence leaking how many ids were issued in the previous millisecond.\n */\nconst seedHi = (bytes: Uint8Array) => (((bytes[0] ?? 0) << 2) | ((bytes[1] ?? 0) >>> 6)) & 0x3ff;\n\nconst seedLo = (bytes: Uint8Array) =>\n ((((bytes[1] ?? 0) & 0x3f) << 26) |\n ((bytes[2] ?? 0) << 18) |\n ((bytes[3] ?? 0) << 10) |\n ((bytes[4] ?? 0) << 2) |\n ((bytes[5] ?? 0) & 0x03)) >>>\n 0;\n\nexport function createUuidV7Generator(options: UuidV7GeneratorOptions): UuidV7Generator {\n const clock = options.clock ?? Date.now;\n const fill = options.fillRandom;\n const random = new Uint8Array(16);\n /**\n * Below every timestamp the clock check admits, which is what makes it the uninitialised\n * sentinel rather than a value: `now > lastMs` alone therefore takes the reseed branch on the\n * first call, and no separate \"have we started\" flag is needed. The coupling is deliberate and\n * is why the clock is validated before this is compared against — an unvalidated clock returning\n * a negative millisecond would make `lastMs` stay below it forever, so the monotonic counter\n * would never be used and every call would reseed.\n */\n let lastMs = -1;\n let counterHi = 0;\n let counterLo = 0;\n\n function reseed(ms: number) {\n const failed = fillRandomBytes(fill, random);\n if (failed) return failed;\n lastMs = ms;\n counterHi = seedHi(random);\n counterLo = seedLo(random);\n return undefined;\n }\n\n function bytes(\n out?: Uint8Array,\n offset = 0,\n timestamp?: number,\n explicit = false,\n ): UuidSlugError | Uint8Array {\n const target = out ?? new Uint8Array(16);\n const badRange = checkRange(target.length, offset, 16);\n if (badRange) return badRange;\n // The two modes differ only in where the millisecond and the 42-bit sequence come from, so\n // they share one write path. A caller-supplied instant takes a RANDOM sequence rather than\n // the monotonic counter, and leaves `lastMs`/`counter` untouched: that counter orders values\n // issued inside the CURRENT millisecond, and a caller naming an arbitrary instant is not\n // extending that sequence. Feeding a supplied timestamp through it would be worse than\n // useless — an older instant fails the `now > lastMs` test and the value would carry the\n // clock's millisecond instead of the requested one.\n let ms: number;\n let sequenceHi: number;\n let sequenceLo: number;\n if (explicit) {\n const invalid = rejectInstant(timestamp as number);\n if (invalid) return invalid;\n const failed = fillRandomBytes(fill, random);\n if (failed) return failed;\n ms = timestamp as number;\n sequenceHi = seedHi(random);\n sequenceLo = seedLo(random);\n } else {\n // Truncated THEN validated, in that order and not the other. A clock is allowed to be\n // fractional — `performance.timeOrigin + performance.now()` is, and is a perfectly good one —\n // so rejecting non-integers here would refuse a legitimate caller, unlike `rejectInstant`,\n // where the fraction is in an argument the caller wrote out. What must not survive is a\n // truncated value the format cannot carry: `writeTimestamp` keeps the low 48 bits of whatever\n // it is handed, so NaN and 2**48 both silently produced the 1970 prefix and a negative\n // millisecond produced the year 10889 by two's-complement wrap. All three now report.\n // The raw reading is kept for the message rather than calling `clock()` again: a second call\n // is a second reading, and the message would name a value other than the one refused.\n const reading = readClock(clock);\n if (reading instanceof Error) return reading;\n const now = Math.trunc(reading);\n if (reading < 0 || !isValidUuidV7Timestamp(now))\n return new UuidSlugError(\n \"invalid_timestamp\",\n `Clock returned ${String(reading)}, which is not a millisecond in 0..${MAX_TIMESTAMP}.`,\n );\n if (now > lastMs) {\n const failed = reseed(now);\n if (failed) return failed;\n } else {\n counterLo = (counterLo + 1) >>> 0;\n if (counterLo === 0) counterHi += 1;\n // Past 42 bits the sequence no longer fits `rand_a` plus the borrowed `rand_b` bits.\n // Borrowing the next millisecond keeps ids ordered and unique rather than wrapping into\n // values this millisecond has already issued.\n if (counterHi > 0x3ff) {\n // At the ceiling there is no next millisecond to borrow: `writeTimestamp` truncates to\n // six bytes, so `lastMs + 1` wraps to 0 and the generator restarts in 1970 — ordering\n // broken permanently, and silently, from that call onward. Unreachable on a real clock\n // until the year 10889; reachable now from any clock that lands near the ceiling, which\n // is why refusing is not theoretical.\n if (lastMs >= MAX_TIMESTAMP)\n return new UuidSlugError(\n \"invalid_timestamp\",\n `Sequence exhausted at the last representable millisecond (${MAX_TIMESTAMP}).`,\n );\n const failed = reseed(lastMs + 1);\n if (failed) return failed;\n } else {\n const failed = fillRandomBytes(fill, random);\n if (failed) return failed;\n }\n }\n ms = lastMs;\n sequenceHi = counterHi;\n sequenceLo = counterLo;\n }\n // The checked offset applies to every store. Write directly into the target so callers\n // reusing an output buffer also avoid allocating a temporary typed-array view.\n writeTimestamp(target, ms, offset);\n writeCounter(target, sequenceHi, sequenceLo, offset);\n for (let i = 12; i < 16; i += 1) target[offset + i] = random[i] as number;\n return target;\n }\n\n return {\n uuidV7() {\n const formatted = formatUuidV7(bytes());\n // Throws rather than returns, because this signature promises a string: the two ways it can\n // fail — entropy, and a `clock` that returns something the format cannot carry — are both\n // configuration the caller cannot act on per call. `uuidV7At` returns its Error instead,\n // because there the failure is a value the caller passed in at the call site.\n if (formatted instanceof Error) throw formatted;\n return formatted;\n },\n uuidV7At: (timestamp) => formatUuidV7(bytes(undefined, 0, timestamp, true)),\n uuidV7Bytes: (out, offset) => bytes(out, offset),\n uuidV7BytesAt: (timestamp, out, offset) => bytes(out, offset, timestamp, true),\n };\n}\n\nexport function createRuntimeGenerator(runtime: Runtime): UuidV7Generator {\n const fallback = createUuidV7Generator({ fillRandom: runtime.fillRandom });\n return {\n uuidV7() {\n if (!runtime.uuidV7) return fallback.uuidV7();\n try {\n return runtime.uuidV7();\n } catch {\n return fallback.uuidV7();\n }\n },\n // The range is checked BEFORE delegating for the same reason the instant is: a native writer\n // is handed the caller's buffer and offset directly, and answers differently from the portable\n // path. Measured on Bun 1.3.14, `out.set(bytes, offset)` coerces a NaN offset to 0 and writes\n // at the wrong place reporting success, while a fractional one throws a RangeError that the\n // catch below would relabel `rng_unavailable` — blaming the entropy source for a caller's\n // argument. Checking here is what makes every runtime give the one answer.\n uuidV7Bytes(out?: Uint8Array, offset = 0) {\n // Guarded only on the branch that leaves this package: the fallback checks the same range\n // itself, so checking before the branch would pay for it twice on every Node call.\n if (!runtime.uuidV7Bytes) return fallback.uuidV7Bytes(out, offset);\n const badRange = checkRange(out?.length ?? 16, offset, 16);\n if (badRange) return badRange;\n try {\n return runtime.uuidV7Bytes(out, offset);\n } catch (cause) {\n return new UuidSlugError(\"rng_unavailable\", \"Runtime UUIDv7 byte generation failed.\", {\n cause,\n });\n }\n },\n // Both timestamped paths reject the instant BEFORE reaching the platform, because a native\n // generator that accepts it may answer wrongly instead of failing: measured 2026-08-12,\n // `Bun.randomUUIDv7(\"hex\", NaN)` and the same call at 2^48 both return the 1970 prefix\n // `000000000000` silently, while -1 and 1.5 throw. Each then mirrors its untimestamped\n // sibling on a platform failure — fall back for the string form, report for the byte form —\n // so the four entry points behave predictably in pairs.\n uuidV7At(timestamp: number) {\n if (!runtime.uuidV7At) return fallback.uuidV7At(timestamp);\n const invalid = rejectInstant(timestamp);\n if (invalid) return invalid;\n try {\n return runtime.uuidV7At(timestamp);\n } catch {\n return fallback.uuidV7At(timestamp);\n }\n },\n uuidV7BytesAt(timestamp: number, out?: Uint8Array, offset = 0) {\n if (!runtime.uuidV7BytesAt) return fallback.uuidV7BytesAt(timestamp, out, offset);\n const invalid = rejectInstant(timestamp);\n if (invalid) return invalid;\n const badRange = checkRange(out?.length ?? 16, offset, 16);\n if (badRange) return badRange;\n try {\n return runtime.uuidV7BytesAt(timestamp, out, offset);\n } catch (cause) {\n return new UuidSlugError(\"rng_unavailable\", \"Runtime UUIDv7 byte generation failed.\", {\n cause,\n });\n }\n },\n };\n}\n"],"mappings":";;;;;AAYA,SAAS,eAAe,OAAmB,IAAY,QAAgB;CACrE,IAAI,QAAQ,KAAK,MAAM,EAAE;CACzB,KAAK,IAAI,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG;EAC9B,MAAM,SAAS,KAAK,QAAQ;EAC5B,QAAQ,KAAK,MAAM,QAAQ,GAAG;CAChC;AACF;;;;;;;;;;AAWA,SAAS,aAAa,OAAmB,IAAY,IAAY,QAAgB;CAC/E,MAAM,SAAS,KAAK,MAAS,OAAO,IAAK;CACzC,MAAM,SAAS,OAAQ,KAAK,OAAS,IAAM,OAAO,MAAO;CACzD,MAAM,SAAS,KAAK,MAAS,OAAO,KAAM;CAC1C,MAAM,SAAS,KAAM,OAAO,KAAM;CAClC,MAAM,SAAS,MAAO,OAAO,IAAK;CAClC,MAAM,SAAS,MAAM,KAAK;AAC5B;;AAGA,MAAM,gBAAgB;;;;;;;;;AAUtB,MAAM,0BAA0B,OAC9B,OAAO,UAAU,EAAE,KAAK,MAAM,KAAK,MAAM;;;;;;AAO3C,MAAM,iBAAiB,OACrB,uBAAuB,EAAE,IACrB,KAAA,IACA,IAAI,cACF,qBACA,iEAAiE,cAAc,EACjF;;;;;;;AAQN,MAAM,gBAAgB,WACpB,kBAAkB,QAAQ,SAAU,WAAW,MAAM;;;;;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AK,UAAU,IAAI,QAAQ,EAAE;GACzD,IAAI,UAAU,OAAO;GACrB,IAAI;IACF,OAAO,QAAQ,YAAY,KAAK,MAAM;GACxC,SAAS,OAAO;IACd,OAAO,IAAI,cAAc,mBAAmB,0CAA0C,EACpF,MACF,CAAC;GACH;EACF;EAOA,SAAS,WAAmB;GAC1B,IAAI,CAAC,QAAQ,UAAU,OAAO,SAAS,SAAS,SAAS;GACzD,MAAM,UAAU,cAAc,SAAS;GACvC,IAAI,SAAS,OAAO;GACpB,IAAI;IACF,OAAO,QAAQ,SAAS,SAAS;GACnC,QAAQ;IACN,OAAO,SAAS,SAAS,SAAS;GACpC;EACF;EACA,cAAc,WAAmB,KAAkB,SAAS,GAAG;GAC7D,IAAI,CAAC,QAAQ,eAAe,OAAO,SAAS,cAAc,WAAW,KAAK,MAAM;GAChF,MAAM,UAAU,cAAc,SAAS;GACvC,IAAI,SAAS,OAAO;GACpB,MAAM,WAAW,WAAW,KAAK,UAAU,IAAI,QAAQ,EAAE;GACzD,IAAI,UAAU,OAAO;GACrB,IAAI;IACF,OAAO,QAAQ,cAAc,WAAW,KAAK,MAAM;GACrD,SAAS,OAAO;IACd,OAAO,IAAI,cAAc,mBAAmB,0CAA0C,EACpF,MACF,CAAC;GACH;EACF;CACF;AACF"}
|
package/dist/yield.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
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 };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=yield.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"yield.js","names":[],"sources":["../src/yield.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nconst host = globalThis as {\n setImmediate?: (callback: () => void) => unknown;\n};\nconst immediate = host.setImmediate?.bind(host);\n\n/** Yield to a host task so timers, input and cancellation can run; a microtask would starve them. */\nexport function yieldToHost(): Promise<void> {\n // Prioritized scheduler continuations can overtake queued cancellation tasks in browsers.\n if (immediate) return new Promise((resolve) => immediate(resolve));\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n // eslint-disable-next-line unicorn/prefer-add-event-listener -- this private port has one handler; assignment also starts delivery\n channel.port1.onmessage = () => {\n channel.port1.close();\n channel.port2.close();\n resolve();\n };\n channel.port2.postMessage(null);\n });\n}\n"],"mappings":";;;AAEA,MAAM,OAAO;AAGb,MAAM,YAAY,KAAK,cAAc,KAAK,IAAI;;AAG9C,SAAgB,cAA6B;CAE3C,IAAI,WAAW,OAAO,IAAI,SAAS,YAAY,UAAU,OAAO,CAAC;CACjE,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,UAAU,IAAI,eAAe;EAEnC,QAAQ,MAAM,kBAAkB;GAC9B,QAAQ,MAAM,MAAM;GACpB,QAAQ,MAAM,MAAM;GACpB,QAAQ;EACV;EACA,QAAQ,MAAM,YAAY,IAAI;CAChC,CAAC;AACH"}
|