@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/keyless.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
// @anizoptera/uuid-slug 0.3.0 | https://github.com/Anizoptera/uuid-slug#readme
|
|
3
|
+
import { UuidRuntimeError, checkRange, errorOrThrow, fillRandomBytes } from "./errors.js";
|
|
4
|
+
import { runtime } from "./runtime/web.js";
|
|
5
|
+
import { formatUuid, formatUuidSlug } from "./uuid.js";
|
|
6
|
+
import { createRuntimeGenerator } from "./v7.js";
|
|
7
|
+
//#region src/keyless.ts
|
|
8
|
+
/**
|
|
9
|
+
* The operations that need no key, built WITHOUT a codec.
|
|
10
|
+
*
|
|
11
|
+
* Generating an id and re-encoding one are keyless: the result is the same value whoever asks, so
|
|
12
|
+
* a bare function is an honest shape for them. Reaching them through a codec is what made them
|
|
13
|
+
* expensive — a codec carries a mask schema, a cipher and a sentinel table, none of which a caller
|
|
14
|
+
* who never masks will ever execute, and all of which a bundler must keep once the graph reaches
|
|
15
|
+
* them. Measured 2026-08-12 on the built package: an entry importing only `uuidV7Slug` minified to
|
|
16
|
+
* 12,735 bytes through the codec and 4,559 from a bare generator; `uuidToSlug` alone, 12,725
|
|
17
|
+
* against 2,188. `defaultCodec` still exists and still works — it is simply no longer on the path
|
|
18
|
+
* every consumer walks.
|
|
19
|
+
*
|
|
20
|
+
* NOTHING KEYED MAY BE ADDED HERE (Art's ruling, 2026-08-12). The only key a bare function could
|
|
21
|
+
* carry is `DEFAULT_MASK_SCHEMA`'s, whose seed is a string literal in this published package, so a
|
|
22
|
+
* masked operation exported this way would be the shortest spelling of the headline feature and
|
|
23
|
+
* the one that obfuscates nothing. Masking is reached through a codec built with your own seed.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Built on first use, and the laziness is what the measurement above depends on: a module-scope
|
|
27
|
+
* CONSTRUCTION call is a side effect a bundler may not remove, so an eager one would pin the
|
|
28
|
+
* generator, the runtime adapter and the entropy pool into a bundle that only ever re-encodes a
|
|
29
|
+
* UUID. Measured the same day, the eager spelling cost 5,130 bytes for `uuidToSlug` alone against
|
|
30
|
+
* 2,188 here.
|
|
31
|
+
*
|
|
32
|
+
* It also keeps import-time work at zero, which `test/entropy.test.ts` gates for a different
|
|
33
|
+
* reason — a heap snapshot taken at module load must capture no drawn randomness.
|
|
34
|
+
*/
|
|
35
|
+
let generator;
|
|
36
|
+
const v7 = () => generator ??= createRuntimeGenerator(runtime);
|
|
37
|
+
/**
|
|
38
|
+
* Randomness is drawn into a private buffer and copied out instead of filled through a view of the
|
|
39
|
+
* caller's array: `fillRandom` requires a plain `ArrayBuffer` because Web Crypto rejects a
|
|
40
|
+
* `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee. Reused rather
|
|
41
|
+
* than allocated per call, matching the v7 generator, so the cost is one 16-byte copy.
|
|
42
|
+
*/
|
|
43
|
+
const v4Random = /* @__PURE__ */ new Uint8Array(16);
|
|
44
|
+
/** Shared with `createUuidSlugCodec`, so a v4 has one implementation however it is reached. */
|
|
45
|
+
function uuidV4Bytes(out, offset = 0) {
|
|
46
|
+
const target = out ?? /* @__PURE__ */ new Uint8Array(16);
|
|
47
|
+
const badRange = checkRange(target.length, offset, 16);
|
|
48
|
+
if (badRange) return badRange;
|
|
49
|
+
const failed = fillRandomBytes(runtime.fillRandom, v4Random);
|
|
50
|
+
if (failed) return failed;
|
|
51
|
+
target.set(v4Random, offset);
|
|
52
|
+
target[offset + 6] = (target[offset + 6] ?? 0) & 15 | 64;
|
|
53
|
+
target[offset + 8] = (target[offset + 8] ?? 0) & 63 | 128;
|
|
54
|
+
return target;
|
|
55
|
+
}
|
|
56
|
+
function uuidV4() {
|
|
57
|
+
try {
|
|
58
|
+
const native = runtime.uuidV4?.();
|
|
59
|
+
if (native) return native;
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
throw new UuidRuntimeError("Runtime UUIDv4 generation failed.", { cause });
|
|
62
|
+
}
|
|
63
|
+
return errorOrThrow(formatUuid(errorOrThrow(uuidV4Bytes())));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Takes the alphabet for the same reason `uuidV7Slug` does, and NOT because a v4 slug sorts — it
|
|
67
|
+
* does not. The alphabet is a choice of representation, so a project that has standardised on the
|
|
68
|
+
* 26-character lowercase form for its public ids needs its v4 slugs in it too; the pair differing
|
|
69
|
+
* would be an asymmetry with nothing behind it.
|
|
70
|
+
*/
|
|
71
|
+
function uuidV4Slug(alphabet = "base64url") {
|
|
72
|
+
return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, alphabet));
|
|
73
|
+
}
|
|
74
|
+
const uuidV7 = () => v7().uuidV7();
|
|
75
|
+
const uuidV7Bytes = (out, offset) => v7().uuidV7Bytes(out, offset);
|
|
76
|
+
const uuidV7At = (timestamp) => v7().uuidV7At(timestamp);
|
|
77
|
+
const uuidV7BytesAt = (timestamp, out, offset) => v7().uuidV7BytesAt(timestamp, out, offset);
|
|
78
|
+
/**
|
|
79
|
+
* The alphabet is an argument here, exactly as it is on `uuidToSlug(uuid, alphabet)`, because
|
|
80
|
+
* choosing it needs no key: without it the only way to GENERATE a base32hex slug was to build a
|
|
81
|
+
* codec, so the sortable form cost the whole masking machinery while the unsortable one was free.
|
|
82
|
+
* Positional and last, matching `uuidToSlug`, so the two spellings of "encode in this alphabet"
|
|
83
|
+
* do not diverge.
|
|
84
|
+
*/
|
|
85
|
+
function uuidV7Slug(alphabet = "base64url") {
|
|
86
|
+
const native = alphabet === "base64url" ? runtime.uuidV7Slug : void 0;
|
|
87
|
+
if (native) return native();
|
|
88
|
+
return errorOrThrow(formatUuidSlug(errorOrThrow(v7().uuidV7Bytes()), 0, alphabet));
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
export { uuidV4, uuidV4Bytes, uuidV4Slug, uuidV7, uuidV7At, uuidV7Bytes, uuidV7BytesAt, uuidV7Slug };
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=keyless.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keyless.js","names":[],"sources":["../src/keyless.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * The operations that need no key, built WITHOUT a codec.\n *\n * Generating an id and re-encoding one are keyless: the result is the same value whoever asks, so\n * a bare function is an honest shape for them. Reaching them through a codec is what made them\n * expensive — a codec carries a mask schema, a cipher and a sentinel table, none of which a caller\n * who never masks will ever execute, and all of which a bundler must keep once the graph reaches\n * them. Measured 2026-08-12 on the built package: an entry importing only `uuidV7Slug` minified to\n * 12,735 bytes through the codec and 4,559 from a bare generator; `uuidToSlug` alone, 12,725\n * against 2,188. `defaultCodec` still exists and still works — it is simply no longer on the path\n * every consumer walks.\n *\n * NOTHING KEYED MAY BE ADDED HERE (Art's ruling, 2026-08-12). The only key a bare function could\n * carry is `DEFAULT_MASK_SCHEMA`'s, whose seed is a string literal in this published package, so a\n * masked operation exported this way would be the shortest spelling of the headline feature and\n * the one that obfuscates nothing. Masking is reached through a codec built with your own seed.\n */\nimport { runtime } from \"#runtime\";\nimport {\n checkRange,\n errorOrThrow,\n fillRandomBytes,\n UuidRuntimeError,\n UuidSlugError,\n} from \"./errors\";\nimport type { UuidV4Slug, UuidV4String, UuidV7Generator, UuidV7Slug, UuidV7String } from \"./types\";\nimport { formatUuid, formatUuidSlug } from \"./uuid\";\nimport type { SlugAlphabet } from \"./uuid\";\nimport { createRuntimeGenerator } from \"./v7\";\n\n/**\n * Built on first use, and the laziness is what the measurement above depends on: a module-scope\n * CONSTRUCTION call is a side effect a bundler may not remove, so an eager one would pin the\n * generator, the runtime adapter and the entropy pool into a bundle that only ever re-encodes a\n * UUID. Measured the same day, the eager spelling cost 5,130 bytes for `uuidToSlug` alone against\n * 2,188 here.\n *\n * It also keeps import-time work at zero, which `test/entropy.test.ts` gates for a different\n * reason — a heap snapshot taken at module load must capture no drawn randomness.\n */\nlet generator: UuidV7Generator | undefined;\nconst v7 = () => (generator ??= createRuntimeGenerator(runtime));\n\n/**\n * Randomness is drawn into a private buffer and copied out instead of filled through a view of the\n * caller's array: `fillRandom` requires a plain `ArrayBuffer` because Web Crypto rejects a\n * `SharedArrayBuffer` view, and a caller-supplied `out` carries no such guarantee. Reused rather\n * than allocated per call, matching the v7 generator, so the cost is one 16-byte copy.\n */\nconst v4Random = new Uint8Array(16);\n\n/** Shared with `createUuidSlugCodec`, so a v4 has one implementation however it is reached. */\nexport function uuidV4Bytes(out?: Uint8Array, offset = 0): UuidSlugError | Uint8Array {\n const target = out ?? new Uint8Array(16);\n const badRange = checkRange(target.length, offset, 16);\n if (badRange) return badRange;\n const failed = fillRandomBytes(runtime.fillRandom, v4Random);\n if (failed) return failed;\n target.set(v4Random, offset);\n target[offset + 6] = ((target[offset + 6] ?? 0) & 0x0f) | 0x40;\n target[offset + 8] = ((target[offset + 8] ?? 0) & 0x3f) | 0x80;\n return target;\n}\n\nexport function uuidV4(): UuidV4String {\n try {\n const native = runtime.uuidV4?.();\n if (native) return native;\n } catch (cause) {\n throw new UuidRuntimeError(\"Runtime UUIDv4 generation failed.\", { cause });\n }\n return errorOrThrow(formatUuid(errorOrThrow(uuidV4Bytes()))) as UuidV4String;\n}\n\n/**\n * Takes the alphabet for the same reason `uuidV7Slug` does, and NOT because a v4 slug sorts — it\n * does not. The alphabet is a choice of representation, so a project that has standardised on the\n * 26-character lowercase form for its public ids needs its v4 slugs in it too; the pair differing\n * would be an asymmetry with nothing behind it.\n */\nexport function uuidV4Slug(alphabet: SlugAlphabet = \"base64url\"): UuidV4Slug {\n // The bytes came from `uuidV4Bytes`, which stamps version 4; the encoder sees only bytes and\n // cannot carry that through, which is what the assertion stands in for.\n return errorOrThrow(formatUuidSlug(errorOrThrow(uuidV4Bytes()), 0, alphabet)) as UuidV4Slug;\n}\n\n/*\n * Return types are DECLARED, not inferred, on all four. Inference reads them off the generator, so\n * a widened method there silently widens the package's public surface — and this package has\n * already been bitten by exactly that: `uuidV7Slug` once inferred `string | UuidSlug`, which\n * collapses to `string` because `Brand`'s marker is optional, so a branded return was promised that\n * nothing checked. A declared type turns that into a compile error at the one site that is wrong.\n */\nexport const uuidV7 = (): UuidV7String => v7().uuidV7();\n\nexport const uuidV7Bytes = (out?: Uint8Array, offset?: number): UuidSlugError | Uint8Array =>\n v7().uuidV7Bytes(out, offset);\n\nexport const uuidV7At = (timestamp: number): UuidSlugError | UuidV7String =>\n v7().uuidV7At(timestamp);\n\nexport const uuidV7BytesAt = (\n timestamp: number,\n out?: Uint8Array,\n offset?: number,\n): UuidSlugError | Uint8Array => v7().uuidV7BytesAt(timestamp, out, offset);\n\n/**\n * The alphabet is an argument here, exactly as it is on `uuidToSlug(uuid, alphabet)`, because\n * choosing it needs no key: without it the only way to GENERATE a base32hex slug was to build a\n * codec, so the sortable form cost the whole masking machinery while the unsortable one was free.\n * Positional and last, matching `uuidToSlug`, so the two spellings of \"encode in this alphabet\"\n * do not diverge.\n */\nexport function uuidV7Slug(alphabet: SlugAlphabet = \"base64url\"): UuidV7Slug {\n // Gated on the ALPHABET, not merely on the hook's presence. The runtime's slug generator emits\n // base64url and nothing else, so an ungated branch answers a base32hex request with a 22-char\n // base64url string — and only Bun defines the hook, so vitest on Node cannot reach the branch at\n // all and the entire suite stays green. `test/runtime.bun.test.ts` is what actually covers it.\n // Probed per call rather than resolved once: resolving at module scope would reintroduce the\n // eager work the lazy cell above exists to avoid.\n //\n // The gate is also where the two alphabets stop costing the same, which is worth knowing before\n // standardising on the sortable one: measured on Bun 2026-08-12, base64url runs 17.0M/s and\n // base32hex 4.2M/s. Not an encoder deficiency -- base64url is handed straight to the engine's\n // own slug generator here, while base32hex must draw bytes and encode them in JavaScript. 4M\n // ids/sec is ample for identifier issuance; the number is recorded so the 4x is not rediscovered\n // as a mystery.\n const native = alphabet === \"base64url\" ? runtime.uuidV7Slug : undefined;\n if (native) return native();\n // Asserted for the same reason `uuidV4Slug` asserts: the bytes come from a v7 generator and the\n // encoder sees only bytes, so it returns the version-agnostic brand.\n return errorOrThrow(formatUuidSlug(errorOrThrow(v7().uuidV7Bytes()), 0, alphabet)) as UuidV7Slug;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,IAAI;AACJ,MAAM,WAAY,cAAc,uBAAuB,OAAO;;;;;;;AAQ9D,MAAM,2BAAW,IAAI,WAAW,EAAE;;AAGlC,SAAgB,YAAY,KAAkB,SAAS,GAA+B;CACpF,MAAM,SAAS,uBAAO,IAAI,WAAW,EAAE;CACvC,MAAM,WAAW,WAAW,OAAO,QAAQ,QAAQ,EAAE;CACrD,IAAI,UAAU,OAAO;CACrB,MAAM,SAAS,gBAAgB,QAAQ,YAAY,QAAQ;CAC3D,IAAI,QAAQ,OAAO;CACnB,OAAO,IAAI,UAAU,MAAM;CAC3B,OAAO,SAAS,MAAO,OAAO,SAAS,MAAM,KAAK,KAAQ;CAC1D,OAAO,SAAS,MAAO,OAAO,SAAS,MAAM,KAAK,KAAQ;CAC1D,OAAO;AACT;AAEA,SAAgB,SAAuB;CACrC,IAAI;EACF,MAAM,SAAS,QAAQ,SAAS;EAChC,IAAI,QAAQ,OAAO;CACrB,SAAS,OAAO;EACd,MAAM,IAAI,iBAAiB,qCAAqC,EAAE,MAAM,CAAC;CAC3E;CACA,OAAO,aAAa,WAAW,aAAa,YAAY,CAAC,CAAC,CAAC;AAC7D;;;;;;;AAQA,SAAgB,WAAW,WAAyB,aAAyB;CAG3E,OAAO,aAAa,eAAe,aAAa,YAAY,CAAC,GAAG,GAAG,QAAQ,CAAC;AAC9E;AASA,MAAa,eAA6B,GAAG,CAAC,CAAC,OAAO;AAEtD,MAAa,eAAe,KAAkB,WAC5C,GAAG,CAAC,CAAC,YAAY,KAAK,MAAM;AAE9B,MAAa,YAAY,cACvB,GAAG,CAAC,CAAC,SAAS,SAAS;AAEzB,MAAa,iBACX,WACA,KACA,WAC+B,GAAG,CAAC,CAAC,cAAc,WAAW,KAAK,MAAM;;;;;;;;AAS1E,SAAgB,WAAW,WAAyB,aAAyB;CAc3E,MAAM,SAAS,aAAa,cAAc,QAAQ,aAAa,KAAA;CAC/D,IAAI,QAAQ,OAAO,OAAO;CAG1B,OAAO,aAAa,eAAe,aAAa,GAAG,CAAC,CAAC,YAAY,CAAC,GAAG,GAAG,QAAQ,CAAC;AACnF"}
|
|
@@ -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
|
+
import { UuidSlugError } from "./errors.js";
|
|
4
|
+
//#region src/legacy-mask.ts
|
|
5
|
+
const PERMUTE = [
|
|
6
|
+
9,
|
|
7
|
+
13,
|
|
8
|
+
3,
|
|
9
|
+
8,
|
|
10
|
+
14,
|
|
11
|
+
0,
|
|
12
|
+
11,
|
|
13
|
+
7,
|
|
14
|
+
6,
|
|
15
|
+
1,
|
|
16
|
+
15,
|
|
17
|
+
4,
|
|
18
|
+
2,
|
|
19
|
+
5,
|
|
20
|
+
10,
|
|
21
|
+
12
|
|
22
|
+
];
|
|
23
|
+
const XOR = [
|
|
24
|
+
162,
|
|
25
|
+
112,
|
|
26
|
+
50,
|
|
27
|
+
127,
|
|
28
|
+
152,
|
|
29
|
+
184,
|
|
30
|
+
155,
|
|
31
|
+
94,
|
|
32
|
+
27,
|
|
33
|
+
38,
|
|
34
|
+
182,
|
|
35
|
+
22,
|
|
36
|
+
150,
|
|
37
|
+
249,
|
|
38
|
+
234,
|
|
39
|
+
62
|
|
40
|
+
];
|
|
41
|
+
/** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */
|
|
42
|
+
function decodeOriginalMask(mixed) {
|
|
43
|
+
if (mixed.length !== 16) return new UuidSlugError("invalid_buffer", "Original masked slugs require 16 decoded bytes.");
|
|
44
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
45
|
+
for (let i = 0; i < 16; i++) bytes[PERMUTE[i]] = mixed[i] ^ XOR[i];
|
|
46
|
+
const found = bytes[6] >>> 4;
|
|
47
|
+
bytes[6] = bytes[6] & 15 | 112;
|
|
48
|
+
let checksum = 0;
|
|
49
|
+
for (const byte of bytes) checksum ^= byte;
|
|
50
|
+
return (checksum >>> 4 ^ checksum & 15) === found ? bytes : void 0;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { decodeOriginalMask };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=legacy-mask.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"legacy-mask.js","names":[],"sources":["../src/legacy-mask.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { UuidSlugError } from \"./errors\";\n\n// These tables and the four-bit checksum define the original wire format.\n// Changing them would change the UUID recovered from an existing slug.\nconst PERMUTE = [9, 13, 3, 8, 14, 0, 11, 7, 6, 1, 15, 4, 2, 5, 10, 12] as const;\nconst XOR = [\n 0xa2, 0x70, 0x32, 0x7f, 0x98, 0xb8, 0x9b, 0x5e, 0x1b, 0x26, 0xb6, 0x16, 0x96, 0xf9, 0xea, 0x3e,\n] as const;\n\n/** Return a matching candidate or undefined; callers resolve sentinels before trying masks. */\nexport function decodeOriginalMask(mixed: Uint8Array): Uint8Array | UuidSlugError | undefined {\n if (mixed.length !== 16)\n return new UuidSlugError(\"invalid_buffer\", \"Original masked slugs require 16 decoded bytes.\");\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++)\n bytes[PERMUTE[i] as number] = (mixed[i] as number) ^ (XOR[i] as number);\n const found = (bytes[6] as number) >>> 4;\n bytes[6] = ((bytes[6] as number) & 15) | 0x70;\n let checksum = 0;\n for (const byte of bytes) checksum ^= byte;\n // A mismatch is expected while trying formats; allocate diagnostics only if the reader fails.\n return ((checksum >>> 4) ^ (checksum & 15)) === found ? bytes : undefined;\n}\n"],"mappings":";;;;AAMA,MAAM,UAAU;CAAC;CAAG;CAAI;CAAG;CAAG;CAAI;CAAG;CAAI;CAAG;CAAG;CAAG;CAAI;CAAG;CAAG;CAAG;CAAI;AAAE;AACrE,MAAM,MAAM;CACV;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;AAC5F;;AAGA,SAAgB,mBAAmB,OAA2D;CAC5F,IAAI,MAAM,WAAW,IACnB,OAAO,IAAI,cAAc,kBAAkB,iDAAiD;CAC9F,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KACtB,MAAM,QAAQ,MAAiB,MAAM,KAAiB,IAAI;CAC5D,MAAM,QAAS,MAAM,OAAkB;CACvC,MAAM,KAAO,MAAM,KAAgB,KAAM;CACzC,IAAI,WAAW;CACf,KAAK,MAAM,QAAQ,OAAO,YAAY;CAEtC,QAAS,aAAa,IAAM,WAAW,QAAS,QAAQ,QAAQ,KAAA;AAClE"}
|
package/dist/mask.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
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 { BASE64URL, decodeInto, encode, spareBits } from "./alphabet.js";
|
|
5
|
+
import { formatUuid } from "./uuid.js";
|
|
6
|
+
import { mix32, read32 } from "./feistel.js";
|
|
7
|
+
//#region src/mask.ts
|
|
8
|
+
/** Custom callbacks can fail after construction; preserve their cause in the public error contract. */
|
|
9
|
+
function applyMix(schema, input, output, forward) {
|
|
10
|
+
try {
|
|
11
|
+
schema.mix(input, output, forward);
|
|
12
|
+
return;
|
|
13
|
+
} catch (cause) {
|
|
14
|
+
return new UuidSlugError("invalid_mask_schema", `Mask schema "${schema.id}" failed ${forward ? "encoding" : "decoding"}.`, { cause });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The check must fail a wrong key with probability 2^-width, which holds only if the function
|
|
19
|
+
* spreads its input across its whole output — so this is an avalanche mixer, not a sum. Measured
|
|
20
|
+
* over 100,000 draws: uniform to chi-squared/df 0.999 across all 65,536 buckets of its top 16 bits.
|
|
21
|
+
*
|
|
22
|
+
* Taken from the TOP so that widening the check never renumbers the bits below it.
|
|
23
|
+
*/
|
|
24
|
+
function tagFor(bytes, width) {
|
|
25
|
+
let acc = 0;
|
|
26
|
+
for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));
|
|
27
|
+
return acc >>> 32 - width;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The 12 check bits a UUIDv7 can hold inside the block, because it spends them on nothing: bits
|
|
31
|
+
* 0-3 in byte 6's version nibble, 4-5 in byte 8's variant bits, 6-11 in byte 0's top six — the
|
|
32
|
+
* high end of the 48-bit timestamp, zero for every instant before 2109. The rest of the check
|
|
33
|
+
* rides outside the block, in whatever the encoding has spare.
|
|
34
|
+
*
|
|
35
|
+
* Claiming byte 0 is why encoding must REFUSE an instant at or past 2^42 ms rather than truncate.
|
|
36
|
+
*/
|
|
37
|
+
function injectTag(bytes, tag) {
|
|
38
|
+
bytes[6] = (tag & 15) << 4 | (bytes[6] ?? 0) & 15;
|
|
39
|
+
bytes[8] = (tag & 48) << 2 | (bytes[8] ?? 0) & 63;
|
|
40
|
+
bytes[0] = (tag >>> 6 & 63) << 2 | (bytes[0] ?? 0) & 3;
|
|
41
|
+
}
|
|
42
|
+
function extractTag(bytes) {
|
|
43
|
+
return (bytes[6] ?? 0) >>> 4 | (bytes[8] ?? 0) >>> 6 << 4 | (bytes[0] ?? 0) >>> 2 << 6;
|
|
44
|
+
}
|
|
45
|
+
/** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
|
|
46
|
+
function restoreV7(bytes) {
|
|
47
|
+
bytes[6] = (bytes[6] ?? 0) & 15 | 112;
|
|
48
|
+
bytes[8] = (bytes[8] ?? 0) & 63 | 128;
|
|
49
|
+
bytes[0] = (bytes[0] ?? 0) & 3;
|
|
50
|
+
}
|
|
51
|
+
/** The 12 check bits that fit inside the block; the rest ride in the encoding's spare bits. */
|
|
52
|
+
const INNER_TAG_BITS = 12;
|
|
53
|
+
/**
|
|
54
|
+
* A masked slug is always 22 base64url characters (Art's ruling, 2026-08-12), so the outer half of
|
|
55
|
+
* the check is a constant 4 bits. Derived rather than written as `4` because the derivation IS the
|
|
56
|
+
* rule — the check is whatever the encoding has left over, never a number somebody chose.
|
|
57
|
+
*/
|
|
58
|
+
const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
|
|
59
|
+
const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
|
|
60
|
+
function uuidV7BytesToMaskedSlug(raw, schema) {
|
|
61
|
+
if ((raw[0] ?? 0) > 3) return new UuidSlugError("invalid_timestamp", "Masking requires a UUIDv7 timestamped before 2^42 ms (year 2109); its top six bits carry the check.");
|
|
62
|
+
const tag = tagFor(raw, TAG_BITS);
|
|
63
|
+
const tagged = new Uint8Array(raw);
|
|
64
|
+
injectTag(tagged, tag >>> OUTER_TAG_BITS);
|
|
65
|
+
const mixed = /* @__PURE__ */ new Uint8Array(16);
|
|
66
|
+
const failed = applyMix(schema, tagged, mixed, true);
|
|
67
|
+
if (failed) return failed;
|
|
68
|
+
return encode(mixed, BASE64URL, tag & (1 << OUTER_TAG_BITS) - 1, OUTER_TAG_BITS);
|
|
69
|
+
}
|
|
70
|
+
function decodeMaskedSlug(slug, schema, previous = []) {
|
|
71
|
+
const mixed = /* @__PURE__ */ new Uint8Array(16);
|
|
72
|
+
const outerTag = decodeInto(slug, BASE64URL, mixed, 0, 16, OUTER_TAG_BITS);
|
|
73
|
+
if (outerTag instanceof Error) return outerTag;
|
|
74
|
+
const primary = unmix(previous.length ? mixed.slice() : mixed, outerTag, schema);
|
|
75
|
+
if (primary && !(primary instanceof Error)) return primary;
|
|
76
|
+
for (const older of previous) {
|
|
77
|
+
const decoded = unmix(mixed.slice(), outerTag, older);
|
|
78
|
+
if (decoded && !(decoded instanceof Error)) return decoded;
|
|
79
|
+
}
|
|
80
|
+
return primary ?? new UuidSlugError("invalid_uuid_slug", "Masked UUID slug failed schema validation.");
|
|
81
|
+
}
|
|
82
|
+
/** Append distinct UUIDs directly to the result, before another callback can mutate their bytes. */
|
|
83
|
+
function decodeMaskedCandidates(mixed, outerTag, schemas, firstOnly = false, candidates = []) {
|
|
84
|
+
for (const schema of schemas) {
|
|
85
|
+
const decoded = unmix(mixed.slice(), outerTag, schema);
|
|
86
|
+
if (decoded instanceof Error) return decoded;
|
|
87
|
+
if (decoded) {
|
|
88
|
+
const uuid = formatUuid(decoded);
|
|
89
|
+
if (uuid instanceof Error) return uuid;
|
|
90
|
+
if (!candidates.includes(uuid)) candidates.push(uuid);
|
|
91
|
+
if (firstOnly) break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return candidates;
|
|
95
|
+
}
|
|
96
|
+
function unmix(mixed, outerTag, schema) {
|
|
97
|
+
const unmixed = /* @__PURE__ */ new Uint8Array(16);
|
|
98
|
+
const failed = applyMix(schema, mixed, unmixed, false);
|
|
99
|
+
if (failed) return failed;
|
|
100
|
+
const foundTag = extractTag(unmixed) << OUTER_TAG_BITS | outerTag;
|
|
101
|
+
restoreV7(unmixed);
|
|
102
|
+
if (tagFor(unmixed, TAG_BITS) !== foundTag) return void 0;
|
|
103
|
+
return unmixed;
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
export { decodeMaskedCandidates, decodeMaskedSlug, uuidV7BytesToMaskedSlug };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=mask.js.map
|
package/dist/mask.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mask.js","names":[],"sources":["../src/mask.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { BASE64URL, decodeInto, encode, spareBits } from \"./alphabet\";\nimport { UuidSlugError } from \"./errors\";\nimport { mix32, read32 } from \"./feistel\";\nimport { formatUuid } from \"./uuid\";\nimport type { MaskSchema, MaskedUuidV7Slug, UuidString } from \"./types\";\n\n/** Custom callbacks can fail after construction; preserve their cause in the public error contract. */\nfunction applyMix(\n schema: MaskSchema,\n input: Uint8Array,\n output: Uint8Array,\n forward: boolean,\n): UuidSlugError | undefined {\n try {\n schema.mix(input, output, forward);\n return undefined;\n } catch (cause) {\n return new UuidSlugError(\n \"invalid_mask_schema\",\n `Mask schema \"${schema.id}\" failed ${forward ? \"encoding\" : \"decoding\"}.`,\n { cause },\n );\n }\n}\n\n/**\n * The check must fail a wrong key with probability 2^-width, which holds only if the function\n * spreads its input across its whole output — so this is an avalanche mixer, not a sum. Measured\n * over 100,000 draws: uniform to chi-squared/df 0.999 across all 65,536 buckets of its top 16 bits.\n *\n * Taken from the TOP so that widening the check never renumbers the bits below it.\n */\nfunction tagFor(bytes: Uint8Array, width: number) {\n let acc = 0;\n for (let offset = 0; offset < 16; offset += 4) acc = mix32(acc ^ read32(bytes, offset));\n return acc >>> (32 - width);\n}\n\n/**\n * The 12 check bits a UUIDv7 can hold inside the block, because it spends them on nothing: bits\n * 0-3 in byte 6's version nibble, 4-5 in byte 8's variant bits, 6-11 in byte 0's top six — the\n * high end of the 48-bit timestamp, zero for every instant before 2109. The rest of the check\n * rides outside the block, in whatever the encoding has spare.\n *\n * Claiming byte 0 is why encoding must REFUSE an instant at or past 2^42 ms rather than truncate.\n */\nfunction injectTag(bytes: Uint8Array, tag: number) {\n bytes[6] = ((tag & 0x0f) << 4) | ((bytes[6] ?? 0) & 0x0f);\n bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] ?? 0) & 0x3f);\n bytes[0] = (((tag >>> 6) & 0x3f) << 2) | ((bytes[0] ?? 0) & 0x03);\n}\n\nfunction extractTag(bytes: Uint8Array) {\n return ((bytes[6] ?? 0) >>> 4) | (((bytes[8] ?? 0) >>> 6) << 4) | (((bytes[0] ?? 0) >>> 2) << 6);\n}\n\n/** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */\nfunction restoreV7(bytes: Uint8Array) {\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n bytes[0] = (bytes[0] ?? 0) & 0x03;\n}\n\n/** The 12 check bits that fit inside the block; the rest ride in the encoding's spare bits. */\nconst INNER_TAG_BITS = 12;\n\n/**\n * A masked slug is always 22 base64url characters (Art's ruling, 2026-08-12), so the outer half of\n * the check is a constant 4 bits. Derived rather than written as `4` because the derivation IS the\n * rule — the check is whatever the encoding has left over, never a number somebody chose.\n */\nconst OUTER_TAG_BITS = spareBits(BASE64URL, 16);\nconst TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;\n\nexport function uuidV7BytesToMaskedSlug(\n raw: Uint8Array,\n schema: MaskSchema,\n): UuidSlugError | MaskedUuidV7Slug {\n // Truncating instead would make encoding non-injective — two UUIDs would share one slug, and no\n // decoder could ever tell which was meant. Refusing is the only recoverable answer.\n if ((raw[0] ?? 0) > 0x03)\n return new UuidSlugError(\n \"invalid_timestamp\",\n \"Masking requires a UUIDv7 timestamped before 2^42 ms (year 2109); its top six bits carry the check.\",\n );\n const tag = tagFor(raw, TAG_BITS);\n const tagged = new Uint8Array(raw);\n injectTag(tagged, tag >>> OUTER_TAG_BITS);\n const mixed = new Uint8Array(16);\n const failed = applyMix(schema, tagged, mixed, true);\n if (failed) return failed;\n return encode(mixed, BASE64URL, tag & ((1 << OUTER_TAG_BITS) - 1), OUTER_TAG_BITS);\n}\n\nexport function decodeMaskedSlug(\n slug: string,\n schema: MaskSchema,\n previous: readonly MaskSchema[] = [],\n): UuidSlugError | Uint8Array {\n const mixed = new Uint8Array(16);\n const outerTag = decodeInto(slug, BASE64URL, mixed, 0, 16, OUTER_TAG_BITS);\n if (outerTag instanceof Error) return outerTag;\n // A callback may mutate or retain its input. Each attempted key must receive fresh original\n // ciphertext, as it would when decoding the text again; only the text validation is shared.\n const primary = unmix(previous.length ? mixed.slice() : mixed, outerTag, schema);\n if (primary && !(primary instanceof Error)) return primary;\n for (const older of previous) {\n const decoded = unmix(mixed.slice(), outerTag, older);\n if (decoded && !(decoded instanceof Error)) return decoded;\n }\n // A key mismatch is ordinary rotation control flow. Allocate its diagnostic only if no key\n // succeeds, while keeping the primary callback's error and cause when that was the failure.\n return (\n primary ?? new UuidSlugError(\"invalid_uuid_slug\", \"Masked UUID slug failed schema validation.\")\n );\n}\n\n/** Append distinct UUIDs directly to the result, before another callback can mutate their bytes. */\nexport function decodeMaskedCandidates(\n mixed: Uint8Array,\n outerTag: number,\n schemas: readonly MaskSchema[],\n firstOnly = false,\n candidates: UuidString[] = [],\n): UuidSlugError | UuidString[] {\n for (const schema of schemas) {\n // Custom callbacks may mutate their input; no key may alter what the next one sees.\n const decoded = unmix(mixed.slice(), outerTag, schema);\n // A failed callback means the candidate list is incomplete, not that its key mismatched.\n if (decoded instanceof Error) return decoded;\n if (decoded) {\n const uuid = formatUuid(decoded);\n if (uuid instanceof Error) return uuid;\n if (!candidates.includes(uuid)) candidates.push(uuid);\n if (firstOnly) break;\n }\n }\n return candidates;\n}\n\nfunction unmix(\n mixed: Uint8Array,\n outerTag: number,\n schema: MaskSchema,\n): UuidSlugError | Uint8Array | undefined {\n const unmixed = new Uint8Array(16);\n const failed = applyMix(schema, mixed, unmixed, false);\n if (failed) return failed;\n // Both halves come out of the same decryption, so a wrong key garbles the observed check as\n // thoroughly as the payload: the tag needs no key of its own to tell keys apart.\n const foundTag = (extractTag(unmixed) << OUTER_TAG_BITS) | outerTag;\n restoreV7(unmixed);\n if (tagFor(unmixed, TAG_BITS) !== foundTag) return undefined;\n return unmixed;\n}\n"],"mappings":";;;;;;;;AASA,SAAS,SACP,QACA,OACA,QACA,SAC2B;CAC3B,IAAI;EACF,OAAO,IAAI,OAAO,QAAQ,OAAO;EACjC;CACF,SAAS,OAAO;EACd,OAAO,IAAI,cACT,uBACA,gBAAgB,OAAO,GAAG,WAAW,UAAU,aAAa,WAAW,IACvE,EAAE,MAAM,CACV;CACF;AACF;;;;;;;;AASA,SAAS,OAAO,OAAmB,OAAe;CAChD,IAAI,MAAM;CACV,KAAK,IAAI,SAAS,GAAG,SAAS,IAAI,UAAU,GAAG,MAAM,MAAM,MAAM,OAAO,OAAO,MAAM,CAAC;CACtF,OAAO,QAAS,KAAK;AACvB;;;;;;;;;AAUA,SAAS,UAAU,OAAmB,KAAa;CACjD,MAAM,MAAO,MAAM,OAAS,KAAO,MAAM,MAAM,KAAK;CACpD,MAAM,MAAO,MAAM,OAAS,KAAO,MAAM,MAAM,KAAK;CACpD,MAAM,MAAQ,QAAQ,IAAK,OAAS,KAAO,MAAM,MAAM,KAAK;AAC9D;AAEA,SAAS,WAAW,OAAmB;CACrC,QAAS,MAAM,MAAM,OAAO,KAAQ,MAAM,MAAM,OAAO,KAAM,KAAQ,MAAM,MAAM,OAAO,KAAM;AAChG;;AAGA,SAAS,UAAU,OAAmB;CACpC,MAAM,MAAO,MAAM,MAAM,KAAK,KAAQ;CACtC,MAAM,MAAO,MAAM,MAAM,KAAK,KAAQ;CACtC,MAAM,MAAM,MAAM,MAAM,KAAK;AAC/B;;AAGA,MAAM,iBAAiB;;;;;;AAOvB,MAAM,iBAAiB,UAAU,WAAW,EAAE;AAC9C,MAAM,WAAW,iBAAiB;AAElC,SAAgB,wBACd,KACA,QACkC;CAGlC,KAAK,IAAI,MAAM,KAAK,GAClB,OAAO,IAAI,cACT,qBACA,qGACF;CACF,MAAM,MAAM,OAAO,KAAK,QAAQ;CAChC,MAAM,SAAS,IAAI,WAAW,GAAG;CACjC,UAAU,QAAQ,QAAQ,cAAc;CACxC,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,MAAM,SAAS,SAAS,QAAQ,QAAQ,OAAO,IAAI;CACnD,IAAI,QAAQ,OAAO;CACnB,OAAO,OAAO,OAAO,WAAW,OAAQ,KAAK,kBAAkB,GAAI,cAAc;AACnF;AAEA,SAAgB,iBACd,MACA,QACA,WAAkC,CAAC,GACP;CAC5B,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,MAAM,WAAW,WAAW,MAAM,WAAW,OAAO,GAAG,IAAI,cAAc;CACzE,IAAI,oBAAoB,OAAO,OAAO;CAGtC,MAAM,UAAU,MAAM,SAAS,SAAS,MAAM,MAAM,IAAI,OAAO,UAAU,MAAM;CAC/E,IAAI,WAAW,EAAE,mBAAmB,QAAQ,OAAO;CACnD,KAAK,MAAM,SAAS,UAAU;EAC5B,MAAM,UAAU,MAAM,MAAM,MAAM,GAAG,UAAU,KAAK;EACpD,IAAI,WAAW,EAAE,mBAAmB,QAAQ,OAAO;CACrD;CAGA,OACE,WAAW,IAAI,cAAc,qBAAqB,4CAA4C;AAElG;;AAGA,SAAgB,uBACd,OACA,UACA,SACA,YAAY,OACZ,aAA2B,CAAC,GACE;CAC9B,KAAK,MAAM,UAAU,SAAS;EAE5B,MAAM,UAAU,MAAM,MAAM,MAAM,GAAG,UAAU,MAAM;EAErD,IAAI,mBAAmB,OAAO,OAAO;EACrC,IAAI,SAAS;GACX,MAAM,OAAO,WAAW,OAAO;GAC/B,IAAI,gBAAgB,OAAO,OAAO;GAClC,IAAI,CAAC,WAAW,SAAS,IAAI,GAAG,WAAW,KAAK,IAAI;GACpD,IAAI,WAAW;EACjB;CACF;CACA,OAAO;AACT;AAEA,SAAS,MACP,OACA,UACA,QACwC;CACxC,MAAM,0BAAU,IAAI,WAAW,EAAE;CACjC,MAAM,SAAS,SAAS,QAAQ,OAAO,SAAS,KAAK;CACrD,IAAI,QAAQ,OAAO;CAGnB,MAAM,WAAY,WAAW,OAAO,KAAK,iBAAkB;CAC3D,UAAU,OAAO;CACjB,IAAI,OAAO,SAAS,QAAQ,MAAM,UAAU,OAAO,KAAA;CACnD,OAAO;AACT"}
|
|
@@ -0,0 +1,66 @@
|
|
|
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 { BASE32HEX, BASE64URL, decodeInto, encode } from "./alphabet.js";
|
|
5
|
+
import { formatUuid } from "./uuid.js";
|
|
6
|
+
import { decodeMaskedCandidates } from "./mask.js";
|
|
7
|
+
import { decodeOriginalMask } from "./legacy-mask.js";
|
|
8
|
+
//#region src/migration.ts
|
|
9
|
+
/** Read old IDs with the codec's keys and sentinels; never change how new IDs are written. */
|
|
10
|
+
function createMigration(schemas, sentinels, options = {}) {
|
|
11
|
+
const original = options.original === true;
|
|
12
|
+
const plain = options.plain === true;
|
|
13
|
+
function read(slug, format, firstOnly) {
|
|
14
|
+
if (format !== void 0 && format !== "current" && format !== "original" && format !== "plain" || format === "original" && !original || format === "plain" && !plain) return new UuidSlugError("invalid_uuid_slug", "Enable the requested format when creating the migration reader.");
|
|
15
|
+
const sentinel = sentinels.get(slug);
|
|
16
|
+
if (sentinel) return [sentinel.uuid];
|
|
17
|
+
const useCurrent = format === void 0 || format === "current";
|
|
18
|
+
const useOriginal = original && (format === void 0 || format === "original");
|
|
19
|
+
const usePlain = plain && (format === void 0 || format === "plain");
|
|
20
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
21
|
+
const base32 = slug.length === 26 && usePlain;
|
|
22
|
+
const tail = decodeInto(slug, base32 ? BASE32HEX : BASE64URL, bytes, 0, 16, base32 ? 0 : 4);
|
|
23
|
+
if (tail instanceof Error) return tail;
|
|
24
|
+
const reserved = (useOriginal || usePlain) && sentinels.get(base32 ? encode(bytes, BASE64URL) : tail === 0 ? slug : slug.slice(0, 21) + BASE64URL.chars[(bytes[15] & 3) << 4]);
|
|
25
|
+
if (reserved && firstOnly) return [reserved.uuid];
|
|
26
|
+
const candidates = reserved ? [reserved.uuid] : [];
|
|
27
|
+
function add(value) {
|
|
28
|
+
const uuid = formatUuid(value);
|
|
29
|
+
if (uuid instanceof Error) return uuid;
|
|
30
|
+
if (!candidates.includes(uuid)) candidates.push(uuid);
|
|
31
|
+
}
|
|
32
|
+
if (useCurrent && !base32) {
|
|
33
|
+
const matches = decodeMaskedCandidates(bytes, tail, schemas, firstOnly, candidates);
|
|
34
|
+
if (matches instanceof Error) return matches;
|
|
35
|
+
if (firstOnly && candidates.length) return candidates;
|
|
36
|
+
}
|
|
37
|
+
if (reserved) return candidates;
|
|
38
|
+
if (useOriginal && slug.length === 22) {
|
|
39
|
+
const match = decodeOriginalMask(bytes);
|
|
40
|
+
if (match instanceof Error) return match;
|
|
41
|
+
if (match) {
|
|
42
|
+
const failed = add(match);
|
|
43
|
+
if (failed) return failed;
|
|
44
|
+
if (firstOnly) return candidates;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (usePlain) {
|
|
48
|
+
const failed = add(bytes);
|
|
49
|
+
if (failed) return failed;
|
|
50
|
+
}
|
|
51
|
+
return candidates;
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
decode(slug, format) {
|
|
55
|
+
const result = read(slug, format, true);
|
|
56
|
+
return result instanceof Error ? result : result[0] ?? new UuidSlugError("invalid_uuid_slug", "Slug does not match an enabled format.");
|
|
57
|
+
},
|
|
58
|
+
candidates(slug, format) {
|
|
59
|
+
return read(slug, format, false);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { createMigration };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=migration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration.js","names":[],"sources":["../src/migration.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport { BASE32HEX, BASE64URL, decodeInto, encode } from \"./alphabet\";\nimport { UuidSlugError } from \"./errors\";\nimport { decodeOriginalMask } from \"./legacy-mask\";\nimport { decodeMaskedCandidates } from \"./mask\";\nimport type {\n MaskSchema,\n MigrationFormat,\n UuidSlugMigration,\n UuidSlugMigrationOptions,\n UuidString,\n UuidV7String,\n} from \"./types\";\nimport { formatUuid } from \"./uuid\";\n\n/** Read old IDs with the codec's keys and sentinels; never change how new IDs are written. */\nexport function createMigration(\n schemas: readonly MaskSchema[],\n sentinels: ReadonlyMap<string, { uuid: UuidV7String }>,\n options: UuidSlugMigrationOptions = {},\n): UuidSlugMigration {\n const original = options.original === true;\n const plain = options.plain === true;\n\n function read(slug: string, format: MigrationFormat | undefined, firstOnly: boolean) {\n if (\n (format !== undefined &&\n format !== \"current\" &&\n format !== \"original\" &&\n format !== \"plain\") ||\n (format === \"original\" && !original) ||\n (format === \"plain\" && !plain)\n )\n return new UuidSlugError(\n \"invalid_uuid_slug\",\n \"Enable the requested format when creating the migration reader.\",\n );\n\n const sentinel = sentinels.get(slug);\n if (sentinel) return [sentinel.uuid];\n const useCurrent = format === undefined || format === \"current\";\n const useOriginal = original && (format === undefined || format === \"original\");\n const usePlain = plain && (format === undefined || format === \"plain\");\n const bytes = new Uint8Array(16);\n // Original readers ignored the four trailing bits. Keep those aliases confined to migration.\n const base32 = slug.length === 26 && usePlain;\n const tail = decodeInto(slug, base32 ? BASE32HEX : BASE64URL, bytes, 0, 16, base32 ? 0 : 4);\n if (tail instanceof Error) return tail;\n // A base64 alias differs only in its final four bits; reuse the validated text instead of\n // encoding all sixteen bytes again. Base32 input still needs the sentinel's base64 spelling.\n const reserved =\n (useOriginal || usePlain) &&\n sentinels.get(\n base32\n ? encode(bytes, BASE64URL)\n : tail === 0\n ? slug\n : slug.slice(0, 21) + BASE64URL.chars[((bytes[15] as number) & 3) << 4],\n );\n if (reserved && firstOnly) return [reserved.uuid];\n const candidates: UuidString[] = reserved ? [reserved.uuid] : [];\n function add(value: Uint8Array) {\n const uuid = formatUuid(value);\n if (uuid instanceof Error) return uuid;\n if (!candidates.includes(uuid)) candidates.push(uuid);\n return undefined;\n }\n if (useCurrent && !base32) {\n const matches = decodeMaskedCandidates(bytes, tail, schemas, firstOnly, candidates);\n if (matches instanceof Error) return matches;\n if (firstOnly && candidates.length) return candidates;\n }\n // Legacy aliases reserve the raw identity, but their check bits can also encode a current ID.\n if (reserved) return candidates;\n if (useOriginal && slug.length === 22) {\n const match = decodeOriginalMask(bytes);\n if (match instanceof Error) return match;\n if (match) {\n const failed = add(match);\n if (failed) return failed;\n if (firstOnly) return candidates;\n }\n }\n if (usePlain) {\n const failed = add(bytes);\n if (failed) return failed;\n }\n return candidates;\n }\n\n return {\n decode(slug, format) {\n const result = read(slug, format, true);\n return result instanceof Error\n ? result\n : (result[0] ??\n new UuidSlugError(\"invalid_uuid_slug\", \"Slug does not match an enabled format.\"));\n },\n candidates(slug, format) {\n return read(slug, format, false);\n },\n };\n}\n"],"mappings":";;;;;;;;;AAiBA,SAAgB,gBACd,SACA,WACA,UAAoC,CAAC,GAClB;CACnB,MAAM,WAAW,QAAQ,aAAa;CACtC,MAAM,QAAQ,QAAQ,UAAU;CAEhC,SAAS,KAAK,MAAc,QAAqC,WAAoB;EACnF,IACG,WAAW,KAAA,KACV,WAAW,aACX,WAAW,cACX,WAAW,WACZ,WAAW,cAAc,CAAC,YAC1B,WAAW,WAAW,CAAC,OAExB,OAAO,IAAI,cACT,qBACA,iEACF;EAEF,MAAM,WAAW,UAAU,IAAI,IAAI;EACnC,IAAI,UAAU,OAAO,CAAC,SAAS,IAAI;EACnC,MAAM,aAAa,WAAW,KAAA,KAAa,WAAW;EACtD,MAAM,cAAc,aAAa,WAAW,KAAA,KAAa,WAAW;EACpE,MAAM,WAAW,UAAU,WAAW,KAAA,KAAa,WAAW;EAC9D,MAAM,wBAAQ,IAAI,WAAW,EAAE;EAE/B,MAAM,SAAS,KAAK,WAAW,MAAM;EACrC,MAAM,OAAO,WAAW,MAAM,SAAS,YAAY,WAAW,OAAO,GAAG,IAAI,SAAS,IAAI,CAAC;EAC1F,IAAI,gBAAgB,OAAO,OAAO;EAGlC,MAAM,YACH,eAAe,aAChB,UAAU,IACR,SACI,OAAO,OAAO,SAAS,IACvB,SAAS,IACP,OACA,KAAK,MAAM,GAAG,EAAE,IAAI,UAAU,OAAQ,MAAM,MAAiB,MAAM,EAC3E;EACF,IAAI,YAAY,WAAW,OAAO,CAAC,SAAS,IAAI;EAChD,MAAM,aAA2B,WAAW,CAAC,SAAS,IAAI,IAAI,CAAC;EAC/D,SAAS,IAAI,OAAmB;GAC9B,MAAM,OAAO,WAAW,KAAK;GAC7B,IAAI,gBAAgB,OAAO,OAAO;GAClC,IAAI,CAAC,WAAW,SAAS,IAAI,GAAG,WAAW,KAAK,IAAI;EAEtD;EACA,IAAI,cAAc,CAAC,QAAQ;GACzB,MAAM,UAAU,uBAAuB,OAAO,MAAM,SAAS,WAAW,UAAU;GAClF,IAAI,mBAAmB,OAAO,OAAO;GACrC,IAAI,aAAa,WAAW,QAAQ,OAAO;EAC7C;EAEA,IAAI,UAAU,OAAO;EACrB,IAAI,eAAe,KAAK,WAAW,IAAI;GACrC,MAAM,QAAQ,mBAAmB,KAAK;GACtC,IAAI,iBAAiB,OAAO,OAAO;GACnC,IAAI,OAAO;IACT,MAAM,SAAS,IAAI,KAAK;IACxB,IAAI,QAAQ,OAAO;IACnB,IAAI,WAAW,OAAO;GACxB;EACF;EACA,IAAI,UAAU;GACZ,MAAM,SAAS,IAAI,KAAK;GACxB,IAAI,QAAQ,OAAO;EACrB;EACA,OAAO;CACT;CAEA,OAAO;EACL,OAAO,MAAM,QAAQ;GACnB,MAAM,SAAS,KAAK,MAAM,QAAQ,IAAI;GACtC,OAAO,kBAAkB,QACrB,SACC,OAAO,MACN,IAAI,cAAc,qBAAqB,wCAAwC;EACvF;EACA,WAAW,MAAM,QAAQ;GACvB,OAAO,KAAK,MAAM,QAAQ,KAAK;EACjC;CACF;AACF"}
|
|
@@ -0,0 +1,130 @@
|
|
|
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
|
+
//#region src/alphabet.ts
|
|
5
|
+
function alphabet(name, chars, code) {
|
|
6
|
+
const bitsPerChar = Math.log2(chars.length);
|
|
7
|
+
if (!Number.isInteger(bitsPerChar)) throw new Error(`${name} alphabet must be a power of two.`);
|
|
8
|
+
const decode = (/* @__PURE__ */ new Int16Array(128)).fill(-1);
|
|
9
|
+
for (let i = 0; i < chars.length; i += 1) decode[chars.charCodeAt(i)] = i;
|
|
10
|
+
return {
|
|
11
|
+
bitsPerChar,
|
|
12
|
+
chars,
|
|
13
|
+
code,
|
|
14
|
+
decode,
|
|
15
|
+
name,
|
|
16
|
+
invalidChars: new RegExp(`[^${chars.replaceAll("-", "\\-")}]`)
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
const BASE64URL = alphabet("base64url", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", "invalid_base64url");
|
|
20
|
+
/**
|
|
21
|
+
* The RFC 4648 §7 extended-hex digit values, not the §6 alphabet and not Crockford. Chosen because
|
|
22
|
+
* its characters are in ASCII order, so encoded values sort the same way the underlying bytes do —
|
|
23
|
+
* the one property base64url cannot offer, and the reason a second alphabet exists at all.
|
|
24
|
+
*
|
|
25
|
+
* Spelled LOWERCASE where the RFC writes `0-9A-V`, matching how this package renders UUIDs, and
|
|
26
|
+
* decoding accepts only that spelling so an id has exactly one form. The cost is interop: verified
|
|
27
|
+
* 2026-08-12 against CPython, `base64.b32hexdecode` rejects these slugs unless called with
|
|
28
|
+
* `casefold=True`. Upper-case them at the boundary if a strict RFC decoder has to read them.
|
|
29
|
+
*/
|
|
30
|
+
const BASE32HEX = alphabet("base32hex", "0123456789abcdefghijklmnopqrstuv", "invalid_base32");
|
|
31
|
+
const nativeToBase64 = Uint8Array.prototype.toBase64;
|
|
32
|
+
const BASE64_OPTIONS = {
|
|
33
|
+
alphabet: "base64url",
|
|
34
|
+
omitPadding: true
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Bits left over when `byteLength` bytes are written in this alphabet. A slug rounds up to whole
|
|
38
|
+
* characters, so the final character has spare low bits that carry no data: 4 for 16 bytes in
|
|
39
|
+
* base64url (22 chars = 132 bits), 2 in base32hex (26 chars = 130 bits). Callers may spend them
|
|
40
|
+
* on a trailing value at zero cost in length — see `encode`.
|
|
41
|
+
*/
|
|
42
|
+
function spareBits(alpha, byteLength) {
|
|
43
|
+
const bits = byteLength * 8;
|
|
44
|
+
return (alpha.bitsPerChar - bits % alpha.bitsPerChar) % alpha.bitsPerChar;
|
|
45
|
+
}
|
|
46
|
+
/** Boolean validation needs no output buffer or diagnostic allocation. */
|
|
47
|
+
function isEncoded(value, alpha, byteLength) {
|
|
48
|
+
if (value.length !== Math.ceil(byteLength * 8 / alpha.bitsPerChar) || alpha.invalidChars.test(value)) return false;
|
|
49
|
+
const spare = spareBits(alpha, byteLength);
|
|
50
|
+
return spare === 0 || (alpha.decode[value.charCodeAt(value.length - 1)] & (1 << spare) - 1) === 0;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Pack bytes, optionally followed by `tailBits` low bits of `tail`, into `alpha`.
|
|
54
|
+
*
|
|
55
|
+
* `tailBits` MUST NOT exceed `spareBits`, otherwise the result grows a character. Passing
|
|
56
|
+
* `tail = 0` reproduces a plain encoding byte for byte, which is what keeps identifiers issued
|
|
57
|
+
* before the tail existed valid afterwards.
|
|
58
|
+
*/
|
|
59
|
+
function encode(bytes, alpha, tail = 0, tailBits = 0) {
|
|
60
|
+
if (nativeToBase64 && alpha === BASE64URL && tailBits >= 0 && tailBits <= spareBits(alpha, bytes.length)) {
|
|
61
|
+
const encoded = nativeToBase64.call(bytes, BASE64_OPTIONS);
|
|
62
|
+
if (tailBits === 0) return encoded;
|
|
63
|
+
const last = encoded.length - 1;
|
|
64
|
+
const digit = alpha.decode[encoded.charCodeAt(last)];
|
|
65
|
+
const trailing = (tail & (1 << tailBits) - 1) << spareBits(alpha, bytes.length) - tailBits;
|
|
66
|
+
return encoded.slice(0, last) + alpha.chars[digit | trailing];
|
|
67
|
+
}
|
|
68
|
+
const { bitsPerChar, chars } = alpha;
|
|
69
|
+
const mask = (1 << bitsPerChar) - 1;
|
|
70
|
+
let out = "";
|
|
71
|
+
let acc = 0;
|
|
72
|
+
let bits = 0;
|
|
73
|
+
for (let i = 0; i < bytes.length; i += 1) {
|
|
74
|
+
acc = acc << 8 | bytes[i];
|
|
75
|
+
bits += 8;
|
|
76
|
+
while (bits >= bitsPerChar) {
|
|
77
|
+
bits -= bitsPerChar;
|
|
78
|
+
out += chars[acc >>> bits & mask];
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (tailBits > 0) {
|
|
82
|
+
acc = acc << tailBits | tail & (1 << tailBits) - 1;
|
|
83
|
+
bits += tailBits;
|
|
84
|
+
while (bits >= bitsPerChar) {
|
|
85
|
+
bits -= bitsPerChar;
|
|
86
|
+
out += chars[acc >>> bits & mask];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (bits > 0) out += chars[acc << bitsPerChar - bits & mask];
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Inverse of `encode`, writing into a caller-owned buffer so the slug paths need no intermediate
|
|
94
|
+
* allocation. Returns the trailing value (0 when `tailBits` is 0), or an Error.
|
|
95
|
+
*
|
|
96
|
+
* Rejects any character outside the alphabet, and any padding bit that is not zero. Without that
|
|
97
|
+
* last check one identifier would have several valid spellings, so a corrupted slug could decode
|
|
98
|
+
* successfully instead of being refused.
|
|
99
|
+
*/
|
|
100
|
+
function decodeInto(value, alpha, out, offset, byteLength, tailBits = 0) {
|
|
101
|
+
const { bitsPerChar, decode: table, code, name } = alpha;
|
|
102
|
+
const expected = Math.ceil((byteLength * 8 + tailBits) / bitsPerChar);
|
|
103
|
+
if (value.length !== expected) return new UuidSlugError(code, `Expected ${expected} ${name} characters, got ${value.length}.`);
|
|
104
|
+
const badRange = checkRange(out.length, offset, byteLength);
|
|
105
|
+
if (badRange) return badRange;
|
|
106
|
+
let acc = 0;
|
|
107
|
+
let bits = 0;
|
|
108
|
+
let written = 0;
|
|
109
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
110
|
+
const charCode = value.charCodeAt(i);
|
|
111
|
+
const digit = charCode < 128 ? table[charCode] : -1;
|
|
112
|
+
if (digit < 0) return new UuidSlugError(code, `Invalid ${name} character at offset ${i}.`);
|
|
113
|
+
acc = acc << bitsPerChar | digit;
|
|
114
|
+
bits += bitsPerChar;
|
|
115
|
+
while (bits >= 8 && written < byteLength) {
|
|
116
|
+
bits -= 8;
|
|
117
|
+
out[offset + written] = acc >>> bits & 255;
|
|
118
|
+
written += 1;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
let tail = 0;
|
|
122
|
+
if (tailBits > 0) {
|
|
123
|
+
bits -= tailBits;
|
|
124
|
+
tail = acc >>> bits & (1 << tailBits) - 1;
|
|
125
|
+
}
|
|
126
|
+
if (bits > 0 && (acc & (1 << bits) - 1) !== 0) return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);
|
|
127
|
+
return tail;
|
|
128
|
+
}
|
|
129
|
+
//#endregion
|
|
130
|
+
export { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded, spareBits };
|
|
@@ -0,0 +1,31 @@
|
|
|
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 { BASE64URL, decodeInto, encode, isEncoded } from "./alphabet.js";
|
|
5
|
+
//#region src/base64url.ts
|
|
6
|
+
function encodeBase64Url(bytes) {
|
|
7
|
+
return encode(bytes, BASE64URL);
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Decodes into `out` at `offset` when given one, otherwise into a fresh array.
|
|
11
|
+
*
|
|
12
|
+
* Returns a view over EXACTLY the bytes decoded, in both cases. The two used to disagree: without
|
|
13
|
+
* `out` the result was `byteLength`-exact, with `out` it was the caller's entire buffer at its full
|
|
14
|
+
* size, with the data at `offset` and no way to learn how many bytes had been written short of
|
|
15
|
+
* recomputing `floor(value.length * 6 / 8)` by hand. One rule — "the bytes this call produced" —
|
|
16
|
+
* makes the length usable and leaves the caller's own buffer reachable, since they own it.
|
|
17
|
+
*/
|
|
18
|
+
function decodeBase64Url(value, out, offset = 0) {
|
|
19
|
+
if (value.includes("=")) return new UuidSlugError("invalid_base64url", "Base64url value must be unpadded.");
|
|
20
|
+
const byteLength = Math.floor(value.length * BASE64URL.bitsPerChar / 8);
|
|
21
|
+
const target = out ?? new Uint8Array(byteLength);
|
|
22
|
+
const result = decodeInto(value, BASE64URL, target, offset, byteLength);
|
|
23
|
+
if (result instanceof Error) return result;
|
|
24
|
+
return target.subarray(offset, offset + byteLength);
|
|
25
|
+
}
|
|
26
|
+
function isBase64Url(value) {
|
|
27
|
+
if (!value) return false;
|
|
28
|
+
return isEncoded(value, BASE64URL, Math.floor(value.length * BASE64URL.bitsPerChar / 8));
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { decodeBase64Url, encodeBase64Url, isBase64Url };
|