@anizoptera/uuid-slug 0.5.0 → 0.6.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.
Files changed (125) hide show
  1. package/README.md +51 -139
  2. package/dist/alphabet.d.ts +1 -3
  3. package/dist/alphabet.d.ts.map +1 -1
  4. package/dist/alphabet.js +32 -90
  5. package/dist/alphabet.js.map +1 -1
  6. package/dist/base64url-name.d.ts +1 -3
  7. package/dist/base64url-name.d.ts.map +1 -1
  8. package/dist/base64url-name.js +2 -3
  9. package/dist/errors.d.ts +1 -3
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +7 -24
  12. package/dist/errors.js.map +1 -1
  13. package/dist/feistel.js +1 -2
  14. package/dist/generation-options.js +2 -3
  15. package/dist/index.d.ts +10 -10
  16. package/dist/index.js +21 -21
  17. package/dist/instant.js +2 -3
  18. package/dist/mask-handle.d.ts +1 -3
  19. package/dist/mask-handle.d.ts.map +1 -1
  20. package/dist/mask-handle.js +19 -17
  21. package/dist/mask-handle.js.map +1 -1
  22. package/dist/mask.d.ts +1 -3
  23. package/dist/mask.d.ts.map +1 -1
  24. package/dist/mask.js +23 -24
  25. package/dist/mask.js.map +1 -1
  26. package/dist/masked-bytes.js +74 -0
  27. package/dist/masked-bytes.js.map +1 -0
  28. package/dist/masking-codec-protocol.js +2 -3
  29. package/dist/masking-codec-types.d.ts +60 -19
  30. package/dist/masking-codec-types.d.ts.map +1 -1
  31. package/dist/masking-codec.d.ts +1 -3
  32. package/dist/masking-codec.d.ts.map +1 -1
  33. package/dist/masking-codec.js +115 -111
  34. package/dist/masking-codec.js.map +1 -1
  35. package/dist/migration.js +39 -40
  36. package/dist/migration.js.map +1 -1
  37. package/dist/node/runtime.js +2 -3
  38. package/dist/payload.d.ts +1 -3
  39. package/dist/payload.d.ts.map +1 -1
  40. package/dist/payload.js +65 -64
  41. package/dist/payload.js.map +1 -1
  42. package/dist/runtime/pool.js +2 -3
  43. package/dist/runtime/portable.js +2 -3
  44. package/dist/runtime/portable.js.map +1 -1
  45. package/dist/sentinel.js +2 -3
  46. package/dist/siphash.js +1 -2
  47. package/dist/slug.d.ts +14 -13
  48. package/dist/slug.d.ts.map +1 -1
  49. package/dist/slug.js +144 -152
  50. package/dist/slug.js.map +1 -1
  51. package/dist/timestamp.d.ts +1 -3
  52. package/dist/timestamp.d.ts.map +1 -1
  53. package/dist/timestamp.js +2 -3
  54. package/dist/types.d.ts +38 -16
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +2 -3
  57. package/dist/types.js.map +1 -1
  58. package/dist/uuid-value-protocol.js +2 -3
  59. package/dist/uuid-value.d.ts +3 -5
  60. package/dist/uuid-value.d.ts.map +1 -1
  61. package/dist/uuid-value.js +74 -78
  62. package/dist/uuid-value.js.map +1 -1
  63. package/dist/uuid.d.ts +6 -8
  64. package/dist/uuid.d.ts.map +1 -1
  65. package/dist/uuid.js +34 -45
  66. package/dist/uuid.js.map +1 -1
  67. package/dist/v4-slug.d.ts +2 -4
  68. package/dist/v4-slug.d.ts.map +1 -1
  69. package/dist/v4-slug.js +6 -7
  70. package/dist/v4.d.ts +8 -6
  71. package/dist/v4.d.ts.map +1 -1
  72. package/dist/v4.js +3 -9
  73. package/dist/v4.js.map +1 -1
  74. package/dist/v7-bounds.d.ts +3 -5
  75. package/dist/v7-bounds.d.ts.map +1 -1
  76. package/dist/v7-bounds.js +8 -9
  77. package/dist/v7-bounds.js.map +1 -1
  78. package/dist/v7-generator-input.js +10 -11
  79. package/dist/v7-generator-input.js.map +1 -1
  80. package/dist/v7-generator.d.ts +1 -3
  81. package/dist/v7-generator.d.ts.map +1 -1
  82. package/dist/v7-generator.js +13 -14
  83. package/dist/v7-keyless.d.ts +12 -4
  84. package/dist/v7-keyless.d.ts.map +1 -1
  85. package/dist/v7-keyless.js +2 -3
  86. package/dist/v7-keyless.js.map +1 -1
  87. package/dist/v7-payload.js +2 -3
  88. package/dist/v7-slug.d.ts +8 -5
  89. package/dist/v7-slug.d.ts.map +1 -1
  90. package/dist/v7-slug.js +28 -29
  91. package/dist/v7-slug.js.map +1 -1
  92. package/dist/v7-timestamp.js +2 -3
  93. package/dist/v7-value-options.js +2 -3
  94. package/dist/v7-value.d.ts +5 -8
  95. package/dist/v7-value.d.ts.map +1 -1
  96. package/dist/v7-value.js +10 -11
  97. package/dist/v7-value.js.map +1 -1
  98. package/dist/v7.js +16 -17
  99. package/dist/v7.js.map +1 -1
  100. package/package.json +2 -2
  101. package/src/alphabet.ts +82 -237
  102. package/src/errors.ts +27 -40
  103. package/src/feistel.ts +3 -3
  104. package/src/index.ts +3 -0
  105. package/src/mask-handle.ts +7 -11
  106. package/src/mask.ts +16 -14
  107. package/src/masked-bytes.ts +203 -0
  108. package/src/masking-codec-types.ts +124 -24
  109. package/src/masking-codec.ts +43 -42
  110. package/src/migration.ts +8 -7
  111. package/src/payload.ts +69 -51
  112. package/src/runtime/portable.ts +2 -2
  113. package/src/runtime/types.ts +2 -4
  114. package/src/slug.ts +39 -48
  115. package/src/types.ts +108 -17
  116. package/src/uuid-value.ts +2 -9
  117. package/src/uuid.ts +19 -33
  118. package/src/v4.ts +12 -9
  119. package/src/v7-bounds.ts +4 -2
  120. package/src/v7-generator-input.ts +2 -5
  121. package/src/v7-generator.ts +2 -2
  122. package/src/v7-keyless.ts +29 -0
  123. package/src/v7-slug.ts +20 -1
  124. package/src/v7-value.ts +9 -4
  125. package/src/v7.ts +26 -0
@@ -0,0 +1,203 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import {
4
+ checkByteRange,
5
+ checkRange,
6
+ INVALID_MASK,
7
+ INVALID_OPTIONS,
8
+ INVALID_UUID_SLUG,
9
+ INVALID_UUID_VERSION,
10
+ isSuccessfulUuidBytes,
11
+ isUint8Array,
12
+ isUuidSlugError,
13
+ UuidSlugError,
14
+ } from "./errors.ts";
15
+ import { maskUuidV7Block, unmix } from "./payload.ts";
16
+ import type { UuidV7MaskRange } from "./payload.ts";
17
+ import {
18
+ exactUuidByteView,
19
+ formatUuidBytesUnchecked,
20
+ isUuidV7Bytes,
21
+ resolveUuidTextCase,
22
+ } from "./uuid.ts";
23
+ import { UUID_TEXT_LOWERCASE } from "./types.ts";
24
+ import type {
25
+ MaskedOrSentinelUuidV7Bytes,
26
+ UuidByteInput,
27
+ UuidInput,
28
+ UuidOutput,
29
+ UuidTextCase,
30
+ UuidTextCaseArguments,
31
+ UuidV7Bytes,
32
+ UuidV7StringFor,
33
+ UuidV7ValueInput,
34
+ } from "./types.ts";
35
+ import type { UuidV7MaskingCodec } from "./masking-codec-types.ts";
36
+
37
+ type BinaryMethods = Pick<
38
+ UuidV7MaskingCodec,
39
+ "uuidToMaskedBytes" | "maskedBytesToUuidBytes" | "maskedBytesToUuidString"
40
+ >;
41
+
42
+ function readMaskedByteSource(value: unknown, byteOffset?: number): Uint8Array | UuidSlugError {
43
+ if (byteOffset === undefined) return exactUuidByteView(value);
44
+ if (isUint8Array(value)) return checkRange(value.length, byteOffset, 16) ?? value;
45
+ if (isUuidSlugError(value)) return value;
46
+ // Zero has the same meaning as omission on standalone byte forms, as on UUID readers.
47
+ if (byteOffset === 0) return exactUuidByteView(value);
48
+ return new UuidSlugError(INVALID_OPTIONS, "A non-zero byteOffset requires Uint8Array input.");
49
+ }
50
+
51
+ /** Keep binary provenance explicit: raw UUID bytes and mixed bytes have the same runtime shape. */
52
+ export function createMaskedByteMethods(
53
+ decodeUuid: (uuid: unknown) => Uint8Array | UuidSlugError,
54
+ current: UuidV7MaskRange,
55
+ previous: readonly UuidV7MaskRange[],
56
+ sentinels: readonly { readonly bytes: Uint8Array }[],
57
+ ): BinaryMethods {
58
+ function sentinel(bytes: Uint8Array, byteOffset = 0): Uint8Array | undefined {
59
+ // Raw sentinels must win before a probabilistic key check, including outside the masked range.
60
+ for (const entry of sentinels) {
61
+ let index = 0;
62
+ while (index < 16 && entry.bytes[index] === bytes[byteOffset + index]) index += 1;
63
+ if (index === 16) return entry.bytes;
64
+ }
65
+ return undefined;
66
+ }
67
+
68
+ function uuidToMaskedBytes<Input extends UuidInput>(
69
+ uuid: UuidV7ValueInput<Input>,
70
+ ): MaskedOrSentinelUuidV7Bytes | UuidSlugError;
71
+ function uuidToMaskedBytes<Input extends UuidInput, Output extends Uint8Array>(
72
+ uuid: UuidV7ValueInput<Input>,
73
+ output: Output,
74
+ outputOffset?: number,
75
+ ): UuidOutput<Output> | UuidSlugError;
76
+ function uuidToMaskedBytes(
77
+ uuid: unknown,
78
+ output?: Uint8Array,
79
+ outputOffset = 0,
80
+ ): Uint8Array | UuidSlugError {
81
+ const source = decodeUuid(uuid);
82
+ if (!isSuccessfulUuidBytes(source)) return source;
83
+ if (output !== undefined) {
84
+ const invalid = checkByteRange(output, outputOffset, 16);
85
+ if (invalid) return invalid;
86
+ }
87
+ if (!isUuidV7Bytes(source))
88
+ return new UuidSlugError(INVALID_UUID_VERSION, "Masking requires an RFC-variant UUIDv7.");
89
+ // Mutation is private until masking and collision checks succeed; output may alias input.
90
+ const bytes = new Uint8Array(source);
91
+ if (!sentinel(source)) {
92
+ const tail = maskUuidV7Block(bytes, current.mask, current.timestampRangeStartUnixMs);
93
+ if (typeof tail !== "number") return tail;
94
+ // Binary has no outer text nibble to distinguish a reserved raw sentinel from this block.
95
+ if (sentinel(bytes))
96
+ return new UuidSlugError(
97
+ INVALID_MASK,
98
+ "Masked output collides with a reserved sentinel. Configure a different mask or sentinel set.",
99
+ );
100
+ }
101
+ if (!output) return bytes;
102
+ output.set(bytes, outputOffset);
103
+ return output;
104
+ }
105
+
106
+ function read(source: Uint8Array, byteOffset?: number): Uint8Array | UuidSlugError {
107
+ const reserved = sentinel(source, byteOffset);
108
+ if (reserved) return new Uint8Array(reserved);
109
+ // Snapshot once before callbacks: a callback may mutate the caller's original ciphertext.
110
+ // Offset reads copy only their payload directly into owned scratch, not a temporary view.
111
+ // Keep the native whole-array copy for the standalone path; no packet scan is needed.
112
+ const bytes = byteOffset === undefined ? new Uint8Array(source) : new Uint8Array(16);
113
+ if (byteOffset !== undefined)
114
+ for (let index = 0; index < 16; index += 1) bytes[index] = source[byteOffset + index]!;
115
+ const ciphertext = previous.length ? bytes.slice() : undefined;
116
+ let candidate = unmix(bytes, undefined, current);
117
+ if (candidate !== undefined) return candidate;
118
+ if (ciphertext) {
119
+ for (const range of previous) {
120
+ bytes.set(ciphertext);
121
+ candidate = unmix(bytes, undefined, range);
122
+ if (candidate !== undefined) return candidate;
123
+ }
124
+ }
125
+ return new UuidSlugError(
126
+ INVALID_UUID_SLUG,
127
+ "No configured mask and timestamp range accepts these masked bytes; use the codec configuration that issued them.",
128
+ );
129
+ }
130
+
131
+ function maskedBytesToUuidBytes(
132
+ maskedUuidBytes: UuidByteInput | UuidSlugError,
133
+ ): UuidV7Bytes | UuidSlugError;
134
+ function maskedBytesToUuidBytes<Output extends Uint8Array>(
135
+ maskedUuidBytes: UuidByteInput | UuidSlugError,
136
+ output: Output,
137
+ outputOffset?: number,
138
+ ): UuidOutput<Output> | UuidSlugError;
139
+ function maskedBytesToUuidBytes(
140
+ maskedUuidBytes: Uint8Array | UuidSlugError,
141
+ byteOffset: number,
142
+ ): UuidV7Bytes | UuidSlugError;
143
+ function maskedBytesToUuidBytes<Output extends Uint8Array>(
144
+ maskedUuidBytes: Uint8Array | UuidSlugError,
145
+ byteOffset: number,
146
+ output: Output,
147
+ outputOffset?: number,
148
+ ): UuidOutput<Output> | UuidSlugError;
149
+ function maskedBytesToUuidBytes(
150
+ maskedUuidBytes: unknown,
151
+ outputOrByteOffset?: Uint8Array | number,
152
+ outputOrOutputOffset?: Uint8Array | number,
153
+ offsetAfterOutput = 0,
154
+ ): Uint8Array | UuidSlugError {
155
+ // The named reader supplies source meaning; a prior shape check does not exclude masking.
156
+ // Recognize a preceding error before output validation or invoking any key callback.
157
+ const readsAtOffset = typeof outputOrByteOffset === "number";
158
+ const byteOffset = readsAtOffset ? outputOrByteOffset : undefined;
159
+ const source = readMaskedByteSource(maskedUuidBytes, byteOffset);
160
+ if (!isSuccessfulUuidBytes(source)) return source;
161
+ const output = (readsAtOffset ? outputOrOutputOffset : outputOrByteOffset) as
162
+ | Uint8Array
163
+ | undefined;
164
+ const outputOffset = readsAtOffset
165
+ ? offsetAfterOutput
166
+ : ((outputOrOutputOffset as number | undefined) ?? 0);
167
+ if (output !== undefined) {
168
+ const invalid = checkByteRange(output, outputOffset, 16);
169
+ if (invalid) return invalid;
170
+ }
171
+ const bytes = read(source, byteOffset);
172
+ if (bytes instanceof Error) return bytes;
173
+ if (!output) return bytes;
174
+ output.set(bytes, outputOffset);
175
+ return output;
176
+ }
177
+
178
+ function maskedBytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
179
+ maskedUuidBytes: UuidByteInput | UuidSlugError,
180
+ ...textCase: UuidTextCaseArguments<Case>
181
+ ): UuidV7StringFor<Case> | UuidSlugError;
182
+ function maskedBytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
183
+ maskedUuidBytes: Uint8Array | UuidSlugError,
184
+ byteOffset: number,
185
+ ...textCase: UuidTextCaseArguments<Case>
186
+ ): UuidV7StringFor<Case> | UuidSlugError;
187
+ function maskedBytesToUuidString(
188
+ maskedUuidBytes: unknown,
189
+ offsetOrCase: number | UuidTextCase = UUID_TEXT_LOWERCASE,
190
+ textCaseAfterOffset: UuidTextCase = UUID_TEXT_LOWERCASE,
191
+ ): string | UuidSlugError {
192
+ const readsAtOffset = typeof offsetOrCase === "number";
193
+ const byteOffset = readsAtOffset ? offsetOrCase : undefined;
194
+ const source = readMaskedByteSource(maskedUuidBytes, byteOffset);
195
+ if (!isSuccessfulUuidBytes(source)) return source;
196
+ const selectedCase = resolveUuidTextCase(readsAtOffset ? textCaseAfterOffset : offsetOrCase);
197
+ if (selectedCase instanceof Error) return selectedCase;
198
+ const bytes = read(source, byteOffset);
199
+ return bytes instanceof Error ? bytes : formatUuidBytesUnchecked(bytes, 0, selectedCase);
200
+ }
201
+
202
+ return { uuidToMaskedBytes, maskedBytesToUuidBytes, maskedBytesToUuidString };
203
+ }
@@ -10,6 +10,7 @@ import type {
10
10
  GenerateUuidV7WithMaskedSlugOptions,
11
11
  MaskingCodecUuidInput,
12
12
  MaskedOrSentinelUuidV7Slug,
13
+ MaskedOrSentinelUuidV7Bytes,
13
14
  PlainUuidSlug,
14
15
  PlainUuidSlugResult,
15
16
  PlainUuidV7Slug,
@@ -18,6 +19,7 @@ import type {
18
19
  SlugStringInput,
19
20
  Uuid,
20
21
  UuidBytesResult,
22
+ UuidByteInput,
21
23
  UuidInput,
22
24
  UuidSlugMigrationDecoder,
23
25
  UuidSlugMigrationOptions,
@@ -25,6 +27,8 @@ import type {
25
27
  UuidOutput,
26
28
  UuidTextCase,
27
29
  UuidTextCaseArguments,
30
+ UuidGenerationTextCase,
31
+ UuidGenerationInput,
28
32
  UuidV7Bytes,
29
33
  UuidV7Mask,
30
34
  UuidV7MaskOptions,
@@ -36,6 +40,7 @@ import type {
36
40
  UuidV7StringFor,
37
41
  UuidV7TimestampWindow,
38
42
  UuidV7ValueInput,
43
+ UnmaskedUuidInput,
39
44
  } from "./types.ts";
40
45
 
41
46
  /** Key rotation, sentinel, and output options shared by both ways of supplying the writer mask. */
@@ -51,7 +56,8 @@ export interface UuidV7MaskingCodecSharedOptions {
51
56
  /**
52
57
  * Decode-only masks tried after the writer mask, in caller order. Each item accepts a mask or its
53
58
  * derivation options. A returned `UuidSlugError` passes through unchanged. Keep the list short:
54
- * every mask adds decoding work and another chance for a random input to pass its 16-bit check.
59
+ * every mask adds decoding work and another chance for a random input to pass its check
60
+ * (16 bits for text, 12 for binary).
55
61
  *
56
62
  * @defaultValue No previous masks.
57
63
  */
@@ -128,7 +134,7 @@ export interface UuidV7MaskingCodec {
128
134
  /** Parse any accepted UUID form, retain this codec and preserve an existing payload layout. A plain-v4 slug brand cannot exclude a masked-v7 reading. */
129
135
  parseUuid<Input extends UuidInput>(
130
136
  this: void,
131
- uuid: Input,
137
+ uuid: UnmaskedUuidInput<Input>,
132
138
  ): ParsedUuidResult<Input, true> | UuidSlugError;
133
139
  /**
134
140
  * Convert any accepted UUID form to normalized UUID text. A 22-character slug is read as masked
@@ -137,17 +143,21 @@ export interface UuidV7MaskingCodec {
137
143
  */
138
144
  uuidToString<Input extends UuidInput, Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
139
145
  this: void,
140
- uuid: Input,
146
+ uuid: UnmaskedUuidInput<Input>,
141
147
  ...textCase: UuidTextCaseArguments<Case>
142
148
  ): UuidStringResult<MaskingCodecUuidInput<Input>, Case>;
143
149
  /**
144
- * Read one UUID out of a larger array as normalized UUID text. Bytes carry no masked spelling.
150
+ * Read raw UUID bytes out of a larger array as normalized UUID text.
151
+ * Decode masked bytes with `maskedBytesToUuidString` instead.
145
152
  *
146
153
  * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
147
154
  */
148
- uuidToString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
155
+ uuidToString<
156
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
157
+ Input extends Uint8Array = Uint8Array,
158
+ >(
149
159
  this: void,
150
- uuid: Uint8Array,
160
+ uuid: UnmaskedUuidInput<Input>,
151
161
  byteOffset: number,
152
162
  ...textCase: UuidTextCaseArguments<Case>
153
163
  ): UuidStringResult<Uint8Array, Case>;
@@ -158,25 +168,29 @@ export interface UuidV7MaskingCodec {
158
168
  */
159
169
  uuidToBytes<Input extends UuidInput>(
160
170
  this: void,
161
- uuid: Input,
171
+ uuid: UnmaskedUuidInput<Input>,
162
172
  ): UuidBytesResult<MaskingCodecUuidInput<Input>>;
163
173
  /** Convert any accepted UUID form into caller-owned storage after complete validation. */
164
- uuidToBytes<Output extends Uint8Array>(
174
+ uuidToBytes<Output extends Uint8Array, Input extends UuidInput = UuidInput>(
165
175
  this: void,
166
- uuid: UuidInput,
176
+ uuid: UnmaskedUuidInput<Input>,
167
177
  output: Output,
168
178
  outputOffset?: number,
169
179
  ): UuidOutput<Output> | UuidSlugError;
170
180
  /**
171
- * Copy one UUID out of a larger array. Bytes carry no masked spelling.
181
+ * Copy raw UUID bytes out of a larger array. Decode masked bytes with `maskedBytesToUuidBytes` instead.
172
182
  *
173
183
  * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
174
184
  */
175
- uuidToBytes(this: void, uuid: Uint8Array, byteOffset: number): UuidBytesResult<Uint8Array>;
185
+ uuidToBytes<Input extends Uint8Array>(
186
+ this: void,
187
+ uuid: UnmaskedUuidInput<Input>,
188
+ byteOffset: number,
189
+ ): UuidBytesResult<Uint8Array>;
176
190
  /** Copy one UUID out of a larger array into caller-owned storage. */
177
- uuidToBytes<Output extends Uint8Array>(
191
+ uuidToBytes<Output extends Uint8Array, Input extends Uint8Array = Uint8Array>(
178
192
  this: void,
179
- uuid: Uint8Array,
193
+ uuid: UnmaskedUuidInput<Input>,
180
194
  byteOffset: number,
181
195
  output: Output,
182
196
  outputOffset?: number,
@@ -188,17 +202,18 @@ export interface UuidV7MaskingCodec {
188
202
  */
189
203
  uuidToPlainSlug<Input extends UuidInput>(
190
204
  this: void,
191
- uuid: Input,
205
+ uuid: UnmaskedUuidInput<Input>,
192
206
  alphabet?: SlugAlphabet,
193
207
  ): PlainUuidSlugResult<MaskingCodecUuidInput<Input>>;
194
208
  /**
195
- * Read one UUID out of a larger array as a plain UUID slug. Bytes carry no masked spelling.
209
+ * Read raw UUID bytes out of a larger array as a plain UUID slug.
210
+ * Decode masked bytes with `maskedBytesToUuidBytes` before plain-slug conversion.
196
211
  *
197
212
  * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
198
213
  */
199
- uuidToPlainSlug(
214
+ uuidToPlainSlug<Input extends Uint8Array>(
200
215
  this: void,
201
- uuid: Uint8Array,
216
+ uuid: UnmaskedUuidInput<Input>,
202
217
  byteOffset: number,
203
218
  alphabet?: SlugAlphabet,
204
219
  ): PlainUuidSlugResult<Uint8Array>;
@@ -210,15 +225,14 @@ export interface UuidV7MaskingCodec {
210
225
  *
211
226
  * @param options - Old formats this application has actually issued. Omit for current formats only.
212
227
  */
213
- createUuidSlugMigrationDecoder(
214
- this: void,
215
- options?: undefined,
216
- ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
228
+ createUuidSlugMigrationDecoder(this: void): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
217
229
  /** Create a reusable reader with explicitly enabled old formats; check configuration failure once. */
218
- createUuidSlugMigrationDecoder<const Options extends UuidSlugMigrationOptions>(
230
+ createUuidSlugMigrationDecoder<const Options extends UuidSlugMigrationOptions | undefined>(
219
231
  this: void,
220
- options: Options | undefined,
221
- ): UuidSlugMigrationDecoder<EnabledMigrationFormat<Options>> | UuidSlugError;
232
+ options: Options,
233
+ ):
234
+ | UuidSlugMigrationDecoder<EnabledMigrationFormat<NonNullable<Options>>>
235
+ | (Options extends undefined ? never : UuidSlugError);
222
236
  /**
223
237
  * Generate and encode a UUIDv7 as a masked slug or its registered raw sentinel slug.
224
238
  * Options may select an explicit time and a generator whose sequence this call joins.
@@ -249,6 +263,19 @@ export interface UuidV7MaskingCodec {
249
263
  this: void,
250
264
  options: GenerateUuidV7WithMaskedSlugOptions<Case>,
251
265
  ): GeneratedUuidV7<MaskedOrSentinelUuidV7Slug, Case> | UuidSlugError;
266
+ /** Forward a text-case preset or optional settings with this masking codec retained. */
267
+ generateUuidV7WithMaskedSlug<
268
+ const Input extends
269
+ | UuidTextCase
270
+ | GenerateUuidV7WithMaskedSlugOptions<UuidTextCase>
271
+ | undefined,
272
+ >(
273
+ this: void,
274
+ textCaseOrOptions: UuidGenerationInput<
275
+ Input,
276
+ GenerateUuidV7WithMaskedSlugOptions<UuidTextCase>
277
+ >,
278
+ ): GeneratedUuidV7<MaskedOrSentinelUuidV7Slug, UuidGenerationTextCase<Input>> | UuidSlugError;
252
279
  /**
253
280
  * Convert UUID text, 16 UUID bytes, a plain slug, or a masked slug to this masking codec's
254
281
  * current masked spelling. A 22-character slug is read as masked when it passes this codec's
@@ -265,6 +292,79 @@ export interface UuidV7MaskingCodec {
265
292
  this: void,
266
293
  uuid: UuidV7ValueInput<Input>,
267
294
  ): MaskedOrSentinelUuidV7Slug | UuidSlugError;
295
+ /**
296
+ * Convert UUIDv7 text, raw bytes, a parsed UUID, or a plain or masked slug to 16 masked bytes.
297
+ * Registered sentinels retain raw UUID bytes and their full timestamp range. Binary carries 12 inner check bits;
298
+ * current masked text carries four more. Returns owned plain bytes or an unchanged prior error.
299
+ * Range, version and mask failures follow masked-slug conversion. A mixed block matching a
300
+ * registered raw sentinel returns `invalid_mask` instead of losing the original UUID.
301
+ */
302
+ uuidToMaskedBytes<Input extends UuidInput>(
303
+ this: void,
304
+ uuid: UuidV7ValueInput<Input>,
305
+ ): MaskedOrSentinelUuidV7Bytes | UuidSlugError;
306
+ /** Write 16 masked bytes at `outputOffset` (default zero); preserve output identity and all bytes on failure. */
307
+ uuidToMaskedBytes<Input extends UuidInput, Output extends Uint8Array>(
308
+ this: void,
309
+ uuid: UuidV7ValueInput<Input>,
310
+ output: Output,
311
+ outputOffset?: number,
312
+ ): UuidOutput<Output> | UuidSlugError;
313
+ /**
314
+ * Read exactly 16 masked bytes using registered-sentinel priority and current-first key order.
315
+ * A 12-bit check can accept a wrong key by chance; it is not authorization. Input remains unchanged
316
+ * unless it is also the supplied output storage.
317
+ * A preceding error propagates unchanged; malformed storage or no passing key returns a package error.
318
+ */
319
+ maskedBytesToUuidBytes(
320
+ this: void,
321
+ maskedUuidBytes: UuidByteInput | UuidSlugError,
322
+ ): UuidV7Bytes | UuidSlugError;
323
+ /** Write the decoded UUID at `outputOffset` (default zero), preserving output identity and bytes on failure. */
324
+ maskedBytesToUuidBytes<Output extends Uint8Array>(
325
+ this: void,
326
+ maskedUuidBytes: UuidByteInput | UuidSlugError,
327
+ output: Output,
328
+ outputOffset?: number,
329
+ ): UuidOutput<Output> | UuidSlugError;
330
+ /**
331
+ * Read 16 masked bytes at `byteOffset` from a larger array. Uses the same keys, checks and failures
332
+ * as the standalone reader; an invalid range returns `invalid_buffer`.
333
+ * @param byteOffset - Zero-based index where the masked UUID starts. Omit for a standalone value.
334
+ */
335
+ maskedBytesToUuidBytes(
336
+ this: void,
337
+ maskedUuidBytes: Uint8Array | UuidSlugError,
338
+ byteOffset: number,
339
+ ): UuidV7Bytes | UuidSlugError;
340
+ /**
341
+ * Decode 16 masked bytes at `byteOffset` into caller storage at `outputOffset` (default zero).
342
+ * Input and output may overlap; return output by identity and leave it unchanged on failure.
343
+ */
344
+ maskedBytesToUuidBytes<Output extends Uint8Array>(
345
+ this: void,
346
+ maskedUuidBytes: Uint8Array | UuidSlugError,
347
+ byteOffset: number,
348
+ output: Output,
349
+ outputOffset?: number,
350
+ ): UuidOutput<Output> | UuidSlugError;
351
+ /** Read masked bytes as UUIDv7 text; `textCase` defaults to lowercase. Uses the same keys, checks and failures as the byte reader. */
352
+ maskedBytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
353
+ this: void,
354
+ maskedUuidBytes: UuidByteInput | UuidSlugError,
355
+ ...textCase: UuidTextCaseArguments<Case>
356
+ ): UuidV7StringFor<Case> | UuidSlugError;
357
+ /**
358
+ * Read 16 masked bytes at `byteOffset` from a larger array as UUIDv7 text; lowercase is the default.
359
+ * Uses the standalone reader's keys, checks and failures; an invalid range returns `invalid_buffer`.
360
+ * @param byteOffset - Zero-based index where the masked UUID starts. Omit for a standalone value.
361
+ */
362
+ maskedBytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
363
+ this: void,
364
+ maskedUuidBytes: Uint8Array | UuidSlugError,
365
+ byteOffset: number,
366
+ ...textCase: UuidTextCaseArguments<Case>
367
+ ): UuidV7StringFor<Case> | UuidSlugError;
268
368
  /**
269
369
  * Convert either plain UUIDv7 slug spelling to this codec's current masked or sentinel spelling.
270
370
  * TypeScript rejects known UUIDv4 slugs. Other UUIDv4 input returns `invalid_uuid_version`;
@@ -28,8 +28,11 @@ import {
28
28
  noMaskedSlugMatch,
29
29
  unmaskSlug,
30
30
  } from "./payload.ts";
31
+ import type { UuidV7MaskRange } from "./payload.ts";
32
+ import { MAX_UUID_V7_UNIX_MS } from "./v7-timestamp.ts";
31
33
  import { createMigration } from "./migration.ts";
32
34
  import { findSentinel } from "./sentinel.ts";
35
+ import { createMaskedByteMethods } from "./masked-bytes.ts";
33
36
  import { registerMaskingCodec } from "./masking-codec-protocol.ts";
34
37
  import { isMaskHandle } from "./mask-handle.ts";
35
38
  import { deriveUuidV7Mask } from "./mask.ts";
@@ -91,7 +94,7 @@ import {
91
94
  } from "./uuid.ts";
92
95
  import type { UuidV7TimestampWindow, UuidV7SentinelConfig } from "./types.ts";
93
96
  import type { SlugAlphabet } from "./slug.ts";
94
- import { createUuidValue, parseUuidWithCodec } from "./uuid-value.ts";
97
+ import { createUuidValue, parseUuid } from "./uuid-value.ts";
95
98
  import { generateUuidV7ValueWithGenerator, readUuidV7ValueOptions } from "./v7-value-options.ts";
96
99
  import { generateUuidV7BytesWithGenerator, readUuidV7Generator } from "./v7-generator-input.ts";
97
100
  import { readGenerationOptions } from "./generation-options.ts";
@@ -124,8 +127,7 @@ const SENTINEL_OPTIONS = {
124
127
  uuid: true,
125
128
  } as const satisfies Record<keyof UuidV7SentinelConfig, true>;
126
129
  const MASKED_PAIR_GENERATION_OPTIONS = {
127
- at: true,
128
- generator: true,
130
+ ...UUID_V7_MASKING_CODEC_VALUE_OPTIONS,
129
131
  textCase: true,
130
132
  } as const satisfies Record<keyof GenerateUuidV7WithMaskedSlugOptions, true>;
131
133
  type EncodedSentinelIndex = {
@@ -167,8 +169,7 @@ const EMPTY_SENTINEL_STATE: SentinelState = Object.freeze({
167
169
  function maskFromOption(
168
170
  mask: UuidV7Mask | UuidV7MaskOptions | UuidSlugError,
169
171
  ): UuidV7Mask | UuidSlugError {
170
- if (isUuidSlugError(mask)) return mask;
171
- if (isMaskHandle(mask)) return mask;
172
+ if (isUuidSlugError(mask) || isMaskHandle(mask)) return mask;
172
173
  if (typeof mask !== "object" || mask === null)
173
174
  return new UuidSlugError(
174
175
  INVALID_MASK,
@@ -177,7 +178,6 @@ function maskFromOption(
177
178
  return deriveUuidV7Mask(mask);
178
179
  }
179
180
 
180
- const MAX_UUID_V7_UNIX_MS = 2 ** 48 - 1;
181
181
  const MAX_TIMESTAMP_RANGE_START_UNIX_MS =
182
182
  MAX_UUID_V7_UNIX_MS - MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS;
183
183
 
@@ -340,13 +340,9 @@ function createSentinels(
340
340
  export function createUuidV7MaskingCodec(
341
341
  options: UuidV7MaskingCodecOptions,
342
342
  ): UuidV7MaskingCodec | UuidSlugError {
343
- try {
344
- // Codec generation keeps every failure as a value: a configured timestamp range can reject
345
- // the current time, so no codec generation call is free of fallible input.
346
- return buildUuidSlugCodec(options, generateDefaultUuidV7Bytes);
347
- } catch (cause) {
348
- return new UuidSlugError(INVALID_MASK, CODEC_CONSTRUCTION_FAILED, { cause });
349
- }
343
+ // Codec generation keeps every failure as a value: a configured timestamp range can reject
344
+ // the current time, so no codec generation call is free of fallible input.
345
+ return createUuidV7MaskingCodecWithGenerator(options, generateDefaultUuidV7Bytes);
350
346
  }
351
347
 
352
348
  /** Internal seam for exercising generator failures without weakening public generation. */
@@ -396,7 +392,7 @@ function buildUuidSlugCodec(
396
392
  const current = { mask: handle, timestampRangeStartUnixMs: currentTimestampRangeStart };
397
393
  // Decode tries exactly the caller's masks in order. Every added mask increases false
398
394
  // acceptance, and the first passing mask decides the result, so no fallback is added here.
399
- const previousMasks: { mask: UuidV7Mask; timestampRangeStartUnixMs: number }[] = [];
395
+ const previousMasks: UuidV7MaskRange[] = [];
400
396
  const previousMaskOptions = options.previousMasks ?? [];
401
397
  if (!Array.isArray(previousMaskOptions))
402
398
  return new UuidSlugError(
@@ -497,17 +493,12 @@ function buildUuidSlugCodec(
497
493
  }
498
494
  // Branch after common validation so ordinary callers retain one plain borrowed-byte route.
499
495
  // Split guard helpers slowed that Bun route; reconsider only with packed mixed-workload evidence.
500
- if (owned)
501
- return ownedUuidV7BytesToMaskedSlug(
502
- bytes,
503
- handle,
504
- maskedSlugAlphabet,
505
- sentinels.bySlug,
506
- currentTimestampRangeStart,
507
- );
508
- encodeScratch.set(bytes);
496
+ if (!owned) {
497
+ encodeScratch.set(bytes);
498
+ bytes = encodeScratch;
499
+ }
509
500
  return ownedUuidV7BytesToMaskedSlug(
510
- encodeScratch,
501
+ bytes,
511
502
  handle,
512
503
  maskedSlugAlphabet,
513
504
  sentinels.bySlug,
@@ -600,14 +591,13 @@ function buildUuidSlugCodec(
600
591
  // stays here: sending a masked slug to the keyless reader would decode a different UUID.
601
592
  const readsAtOffset = typeof outputOrByteOffset === "number";
602
593
  if (readsAtOffset && (isUint8Array(uuid) || outputOrByteOffset !== 0))
603
- return outputOrOutputOffset === undefined
604
- ? keylessUuidToBytes(uuid as Uint8Array, outputOrByteOffset)
605
- : keylessUuidToBytes(
606
- uuid as Uint8Array,
607
- outputOrByteOffset,
608
- outputOrOutputOffset as Uint8Array,
609
- offsetAfterOutput,
610
- );
594
+ // The keyless reader treats an undefined output like an omitted one, so one call covers both.
595
+ return keylessUuidToBytes(
596
+ uuid as Uint8Array,
597
+ outputOrByteOffset,
598
+ outputOrOutputOffset as Uint8Array,
599
+ offsetAfterOutput,
600
+ );
611
601
  const output = readsAtOffset ? outputOrOutputOffset : outputOrByteOffset;
612
602
  const outputOffset = readsAtOffset
613
603
  ? offsetAfterOutput
@@ -846,14 +836,16 @@ function buildUuidSlugCodec(
846
836
  return bytes instanceof Error ? bytes : extractUuidV7Payload(bytes, layout);
847
837
  }
848
838
 
849
- function createUuidSlugMigrationDecoder(
850
- migrationOptions?: undefined,
851
- ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
839
+ function createUuidSlugMigrationDecoder(): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
852
840
  // Structural typing permits extra keys and accessors; createMigration can reject either even
853
841
  // when boolean fields type-check. Only omission removes that configuration failure boundary.
854
- function createUuidSlugMigrationDecoder<const Options extends UuidSlugMigrationOptions>(
855
- migrationOptions: Options | undefined,
856
- ): UuidSlugMigrationDecoder<EnabledMigrationFormat<Options>> | UuidSlugError;
842
+ function createUuidSlugMigrationDecoder<
843
+ const Options extends UuidSlugMigrationOptions | undefined,
844
+ >(
845
+ migrationOptions: Options,
846
+ ):
847
+ | UuidSlugMigrationDecoder<EnabledMigrationFormat<NonNullable<Options>>>
848
+ | (Options extends undefined ? never : UuidSlugError);
857
849
  function createUuidSlugMigrationDecoder(
858
850
  migrationOptions?: UuidSlugMigrationOptions,
859
851
  ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT> | UuidSlugError {
@@ -892,18 +884,27 @@ function buildUuidSlugCodec(
892
884
  const generator = readUuidV7Generator(values.generator);
893
885
  if (generator instanceof Error) return generator;
894
886
  if (generator) return generateUuidV7ValueWithGenerator(generator, values, maskingCodec);
895
- const generated = !Object.hasOwn(values, AT_OPTION)
896
- ? generateDefaultUuidV7Bytes()
897
- : generateDefaultUuidV7Bytes({ at: values.at as UuidV7Instant });
887
+ // Public codecs inject the package default, whose bytes and failures every module-level route
888
+ // already returns directly; the shared helper's generator re-read, try/catch and validation
889
+ // measured slower on every engine (`bench/decisions.md` §Default value generation). Injected
890
+ // generators keep its containment of thrown and malformed results. Remeasure if the helper
891
+ // loses its try/catch or validation.
892
+ const generated =
893
+ generateBytes !== generateDefaultUuidV7Bytes
894
+ ? generateCodecBytesFromValues(values)
895
+ : !Object.hasOwn(values, AT_OPTION)
896
+ ? generateBytes()
897
+ : generateBytes({ at: values.at as UuidV7Instant });
898
898
  return generated instanceof Error
899
899
  ? generated
900
900
  : createUuidValue<7, true, true>(generated, maskingCodec, uuidV7DefaultPayloadLayout());
901
901
  }
902
902
 
903
903
  const maskingCodec: UuidV7MaskingCodec = {
904
+ ...createMaskedByteMethods(decodeUuid, current, previousMasks, sentinels.encoded),
904
905
  sentinels: sentinels.sentinels,
905
906
  generateUuidV7Value,
906
- parseUuid: (uuid) => parseUuidWithCodec(uuid, maskingCodec),
907
+ parseUuid: (uuid) => parseUuid(uuid, maskingCodec),
907
908
  uuidToString,
908
909
  uuidToBytes,
909
910
  uuidToPlainSlug,