@anizoptera/uuid-slug 0.3.0 → 0.4.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 (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1052 -261
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +14 -9
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
package/src/errors.ts CHANGED
@@ -1,48 +1,311 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- /** Consumers can enumerate error codes at runtime without duplicating the type's vocabulary. */
4
- export const UUID_SLUG_ERROR_CODES = [
5
- "aborted",
6
- "invalid_base32",
7
- "invalid_base64url",
8
- "invalid_buffer",
9
- "invalid_mask_schema",
10
- "invalid_timestamp",
11
- "invalid_uuid",
12
- "invalid_uuid_slug",
13
- "invalid_uuid_version",
14
- "rng_unavailable",
15
- "stale_uuid",
16
- ] as const;
17
-
18
- export type UuidSlugErrorCode = (typeof UUID_SLUG_ERROR_CODES)[number];
3
+ /** The operation was cancelled through its `AbortSignal`. */
4
+ export const ABORTED = "aborted";
5
+ /** The input is not a canonical base32hex UUID slug. */
6
+ export const INVALID_BASE32HEX = "invalid_base32hex";
7
+ /** The input is not a canonical base64url UUID slug. */
8
+ export const INVALID_BASE64URL = "invalid_base64url";
9
+ /** A byte buffer or offset cannot satisfy the requested operation. */
10
+ export const INVALID_BUFFER = "invalid_buffer";
11
+ /** A mask is missing, malformed, or failed its reversible transform. */
12
+ export const INVALID_MASK = "invalid_mask";
13
+ /** An options object or one of its values is invalid. */
14
+ export const INVALID_OPTIONS = "invalid_options";
15
+ /** A sentinel definition is invalid or conflicts with another sentinel. */
16
+ export const INVALID_SENTINEL = "invalid_sentinel";
17
+ /** A timestamp is invalid or outside the selected operation's range. */
18
+ export const INVALID_TIMESTAMP = "invalid_timestamp";
19
+ /** The input is not valid UUID text or a valid UUID byte payload. */
20
+ export const INVALID_UUID = "invalid_uuid";
21
+ /** The input is not a canonical plain or codec-owned UUID slug. */
22
+ export const INVALID_UUID_SLUG = "invalid_uuid_slug";
23
+ /** The UUID version does not satisfy the requested operation. */
24
+ export const INVALID_UUID_VERSION = "invalid_uuid_version";
25
+ /** The runtime could not provide cryptographically secure random bytes. */
26
+ export const RNG_UNAVAILABLE = "rng_unavailable";
27
+ /** The UUIDv7 timestamp falls outside the caller's validation window. */
28
+ export const TIMESTAMP_OUTSIDE_WINDOW = "timestamp_outside_window";
19
29
 
30
+ /** One stable `UuidSlugError.code`; branch on this value and use `message` for diagnostics. */
31
+ export type UuidSlugErrorCode =
32
+ | typeof ABORTED
33
+ | typeof INVALID_BASE32HEX
34
+ | typeof INVALID_BASE64URL
35
+ | typeof INVALID_BUFFER
36
+ | typeof INVALID_MASK
37
+ | typeof INVALID_OPTIONS
38
+ | typeof INVALID_SENTINEL
39
+ | typeof INVALID_TIMESTAMP
40
+ | typeof INVALID_UUID
41
+ | typeof INVALID_UUID_SLUG
42
+ | typeof INVALID_UUID_VERSION
43
+ | typeof RNG_UNAVAILABLE
44
+ | typeof TIMESTAMP_OUTSIDE_WINDOW;
45
+
46
+ export const ERROR_CODES: readonly UuidSlugErrorCode[] = /*#__PURE__*/ Object.freeze([
47
+ ABORTED,
48
+ INVALID_BASE32HEX,
49
+ INVALID_BASE64URL,
50
+ INVALID_BUFFER,
51
+ INVALID_MASK,
52
+ INVALID_OPTIONS,
53
+ INVALID_SENTINEL,
54
+ INVALID_TIMESTAMP,
55
+ INVALID_UUID,
56
+ INVALID_UUID_SLUG,
57
+ INVALID_UUID_VERSION,
58
+ RNG_UNAVAILABLE,
59
+ TIMESTAMP_OUTSIDE_WINDOW,
60
+ ]);
61
+
62
+ const ERROR_CODE_SET: ReadonlySet<unknown> = /*#__PURE__*/ new Set(ERROR_CODES);
63
+ const ERROR_NAME = "UuidSlugError";
64
+ // Internal consumers share the protocol key without exporting it from the package root.
65
+ export const ERROR_MARKER = "__failure";
66
+ const OBJECT_TYPE = "object";
67
+ const ERROR_TAG = "[object Error]";
68
+ const ARRAY_BUFFER_TAG = "[object ArrayBuffer]";
69
+ const DATA_VIEW_TAG = "[object DataView]";
70
+ const BYTE_LENGTH_PROPERTY = "byteLength";
71
+ const BUFFER_TYPE_MESSAGE = "Buffer must be a Uint8Array.";
72
+ const RANDOM_FAILURE_MESSAGE = "Random byte generation failed.";
73
+ const nativeIsError = (Error as { isError?: (value: unknown) => boolean }).isError;
74
+
75
+ const typedArrayTagDescriptor = /*#__PURE__*/ Object.getOwnPropertyDescriptor(
76
+ Object.getPrototypeOf(Uint8Array.prototype) as object,
77
+ Symbol.toStringTag,
78
+ );
79
+ const dataViewByteLengthDescriptor = /*#__PURE__*/ Object.getOwnPropertyDescriptor(
80
+ DataView.prototype,
81
+ BYTE_LENGTH_PROPERTY,
82
+ );
83
+ const dataViewByteOffsetDescriptor = /*#__PURE__*/ Object.getOwnPropertyDescriptor(
84
+ DataView.prototype,
85
+ "byteOffset",
86
+ );
87
+ const dataViewBufferDescriptor = /*#__PURE__*/ Object.getOwnPropertyDescriptor(
88
+ DataView.prototype,
89
+ "buffer",
90
+ );
91
+ const arrayBufferByteLengthDescriptor = /*#__PURE__*/ Object.getOwnPropertyDescriptor(
92
+ ArrayBuffer.prototype,
93
+ BYTE_LENGTH_PROPERTY,
94
+ );
95
+
96
+ /**
97
+ * An expected failure returned by package operations. Branch on `code`; `message` explains the
98
+ * failed input or operation, and `cause` retains an underlying runtime or callback failure.
99
+ */
20
100
  export class UuidSlugError extends Error {
101
+ /** Stable cross-realm marker used by `isUuidSlugError` and composable package operations. */
102
+ declare readonly __failure: true;
103
+ /** Stable recovery category; use `message` and `cause` for diagnostics. */
21
104
  readonly code: UuidSlugErrorCode;
22
105
 
106
+ /**
107
+ * Create an expected package error.
108
+ *
109
+ * @param code - Stable recovery category.
110
+ * @param message - Input- or operation-specific diagnostic.
111
+ * @param options - Standard error options; use `cause` to retain the underlying failure.
112
+ */
23
113
  constructor(code: UuidSlugErrorCode, message: string, options?: ErrorOptions) {
24
114
  super(message, options);
25
- this.name = "UuidSlugError";
115
+ this.name = ERROR_NAME;
26
116
  this.code = code;
27
117
  }
28
118
  }
29
119
 
30
- export class UuidRuntimeError extends UuidSlugError {
31
- constructor(message: string, options?: ErrorOptions) {
32
- super("rng_unavailable", message, options);
33
- this.name = "UuidRuntimeError";
120
+ // One immutable prototype property avoids adding storage to every error while preserving the same
121
+ // marker across realms and duplicate package copies. Remeasure if supported engines change their
122
+ // prototype-property access or Error layout; benchmark evidence belongs in bench/PERFORMANCE.md.
123
+ Object.defineProperty(UuidSlugError.prototype, ERROR_MARKER, { value: true });
124
+
125
+ // Keep local identity before the costlier cross-realm capability, but isolate the probes: a proxy
126
+ // that blocks one operation must not suppress a later independent one. Remeasure if Error branding
127
+ // or inlining changes in a supported engine; results and statistical limits live in PERFORMANCE.md.
128
+ /*#__NO_SIDE_EFFECTS__*/
129
+ function hasErrorBrand(candidate: object): boolean {
130
+ try {
131
+ if (candidate instanceof Error) return true;
132
+ } catch {
133
+ // A proxy may block local identity while a native cross-realm check can still recognize it.
134
+ }
135
+ try {
136
+ return nativeIsError
137
+ ? nativeIsError(candidate)
138
+ : Object.prototype.toString.call(candidate) === ERROR_TAG;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Narrow a returned value to `UuidSlugError`, including errors from another realm or package copy.
146
+ * The package marker is the primary protocol. Existing unmarked package errors use local Error
147
+ * identity before native or portable cross-realm recognition. This does not authenticate data.
148
+ */
149
+ /*#__NO_SIDE_EFFECTS__*/
150
+ export function isUuidSlugError(value: unknown): value is UuidSlugError {
151
+ if (typeof value !== OBJECT_TYPE || value === null) return false;
152
+ const candidate = value as object;
153
+ try {
154
+ if ((candidate as { readonly __failure?: unknown })[ERROR_MARKER] === true) return true;
155
+ } catch {
156
+ // A hostile marker does not suppress the independent Error-brand fallback.
157
+ }
158
+ if (!hasErrorBrand(candidate)) return false;
159
+ try {
160
+ return (
161
+ Reflect.get(candidate, "name") === ERROR_NAME &&
162
+ ERROR_CODE_SET.has(Reflect.get(candidate, "code"))
163
+ );
164
+ } catch {
165
+ return false;
34
166
  }
35
167
  }
36
168
 
37
169
  /**
38
- * The bridge from this package's `Error | T` return convention to the generator convention, where
39
- * a failure throws. Shared rather than repeated because every module that has both conventions
40
- * meeting in it needs exactly this, and a local copy is one `instanceof` away from being written
41
- * as a truthiness test that swallows a legitimate falsy result.
170
+ * Universal conversions otherwise recognize the same local bytes before and after dispatch. Keep
171
+ * this shortcut exact; views and cross-realm arrays need the general path. Remeasure if dispatch
172
+ * stops repeating byte recognition.
42
173
  */
43
- export function errorOrThrow<T>(value: UuidSlugError | T): T {
44
- if (value instanceof Error) throw value;
45
- return value;
174
+ /*#__NO_SIDE_EFFECTS__*/
175
+ export function exactLocalUuidBytes(value: unknown): Uint8Array | undefined {
176
+ try {
177
+ return value instanceof Uint8Array && value.length === 16 ? value : undefined;
178
+ } catch {
179
+ return undefined;
180
+ }
181
+ }
182
+
183
+ /** Recognize local Errors first, then use native or portable cross-realm recognition. */
184
+ /*#__NO_SIDE_EFFECTS__*/
185
+ export function isError(value: unknown): value is Error {
186
+ if (typeof value !== OBJECT_TYPE || value === null) return false;
187
+ return hasErrorBrand(value as object);
188
+ }
189
+
190
+ // A slot probe is the only proof of a genuine buffer, but calling one on anything else
191
+ // throws, and building that native TypeError costs three orders of magnitude more than the checks
192
+ // below (bench/PERFORMANCE.md). For buffers, local identity answers the common case without reading
193
+ // the tag at all; the tag then recognizes another realm's value. The tag is caller-visible, so a value
194
+ // carrying its own Symbol.toStringTag still reaches the probe and keeps its acceptance, and that
195
+ // own-property lookup runs only after the tag misses. Only a value whose realm re-tagged the
196
+ // prototype itself is lost, and a tag getter that throws lands in the catch the probe already
197
+ // needed. Every clause is ordered by measured cost; remeasure if a probe stops throwing.
198
+ /*#__NO_SIDE_EFFECTS__*/
199
+ function isTagged(value: unknown, tag: string): boolean {
200
+ return (
201
+ Object.prototype.toString.call(value) === tag ||
202
+ // The literal is required: TypeScript narrows from `typeof x === "object"`, not from a constant.
203
+ (typeof value === "object" && value !== null && Object.hasOwn(value, Symbol.toStringTag))
204
+ );
205
+ }
206
+
207
+ /** Read primitive or genuine boxed text without invoking caller-defined coercion hooks. */
208
+ /*#__NO_SIDE_EFFECTS__*/
209
+ export function stringInput(value: unknown): string | undefined {
210
+ if (typeof value === "string") return value;
211
+ if (typeof value !== "object" || value === null) return undefined;
212
+ try {
213
+ // The intrinsic checks the string slot across realms. A tag or prototype precheck can invoke
214
+ // caller getters, reject retagged wrappers, or reenter a conversion using shared scratch.
215
+ return String.prototype.valueOf.call(value);
216
+ } catch {
217
+ return undefined;
218
+ }
219
+ }
220
+
221
+ /** Normalize UUID string input while preserving a preceding package failure. */
222
+ export function normalizeUuidStringInput(value: unknown): string | UuidSlugError {
223
+ if (typeof value === "string") return value;
224
+ return stringInput(value) ?? invalidUuidStringInput(value);
225
+ }
226
+
227
+ /** Normalize slug input while preserving a preceding package failure. */
228
+ export function normalizeUuidSlugInput(value: unknown): string | UuidSlugError {
229
+ if (typeof value === "string") return value;
230
+ return stringInput(value) ?? invalidUuidSlugInput(value);
231
+ }
232
+
233
+ /** Describe rejected values without executing object coercion or inspecting caller properties. */
234
+ export function diagnosticValue(value: unknown): string {
235
+ if (typeof value === "string") return value;
236
+ if (
237
+ typeof value === "number" ||
238
+ typeof value === "bigint" ||
239
+ typeof value === "boolean" ||
240
+ typeof value === "symbol"
241
+ )
242
+ return String(value);
243
+ return value === null ? "null" : typeof value;
244
+ }
245
+
246
+ /** Accept cross-realm and null-prototype records; callers contain proxy failures at their boundary. */
247
+ export function isPlainRecord(value: object): boolean {
248
+ if (Array.isArray(value)) return false;
249
+ const prototype = Object.getPrototypeOf(value);
250
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
251
+ }
252
+
253
+ /** Use fast local identity, then an unspoofable intrinsic brand for cross-realm Uint8Array values. */
254
+ /*#__NO_SIDE_EFFECTS__*/
255
+ export function isUint8Array(value: unknown): value is Uint8Array {
256
+ return (
257
+ ArrayBuffer.isView(value) &&
258
+ (value instanceof Uint8Array || typedArrayTagDescriptor?.get?.call(value) === "Uint8Array")
259
+ );
260
+ }
261
+
262
+ // A validated draw returns Uint8Array or a recognized failure, so a view check is sufficient:
263
+ // unmarked Errors cannot be views, and marked views remain failures. Rechecking the element brand
264
+ // adds work without narrowing this union. Arbitrary public input still needs its owning validator.
265
+ export function isSuccessfulUuidBytes(value: Uint8Array | UuidSlugError): value is Uint8Array {
266
+ if (!ArrayBuffer.isView(value)) return false;
267
+ try {
268
+ return (value as Uint8Array & { readonly __failure?: unknown })[ERROR_MARKER] !== true;
269
+ } catch {
270
+ // A validated view cannot be an unmarked native Error when its marker is inaccessible.
271
+ return true;
272
+ }
273
+ }
274
+
275
+ /** Borrow bytes from supported local or cross-realm input without copying or accepting other views. */
276
+ export function uuidByteView(value: unknown): Uint8Array | undefined {
277
+ if (isUint8Array(value)) return value;
278
+ try {
279
+ if (
280
+ ArrayBuffer.isView(value) &&
281
+ (value instanceof DataView || isTagged(value, DATA_VIEW_TAG)) &&
282
+ dataViewByteLengthDescriptor?.get?.call(value) !== undefined
283
+ ) {
284
+ return new Uint8Array(
285
+ dataViewBufferDescriptor?.get?.call(value) as ArrayBuffer,
286
+ dataViewByteOffsetDescriptor?.get?.call(value) as number,
287
+ dataViewByteLengthDescriptor.get.call(value) as number,
288
+ );
289
+ }
290
+ if (
291
+ (value instanceof ArrayBuffer || isTagged(value, ARRAY_BUFFER_TAG)) &&
292
+ arrayBufferByteLengthDescriptor?.get?.call(value) !== undefined
293
+ )
294
+ return new Uint8Array(value as ArrayBuffer);
295
+ } catch {
296
+ // Detached buffers and hostile objects are invalid byte inputs.
297
+ }
298
+ return undefined;
299
+ }
300
+
301
+ /** Return the first unsupported enumerable own string key in a package-owned options object. */
302
+ /*#__NO_SIDE_EFFECTS__*/
303
+ export function findUnknownOption(
304
+ options: object,
305
+ accepted: Readonly<Record<string, true>>,
306
+ ): string | undefined {
307
+ for (const option of Object.keys(options)) if (!Object.hasOwn(accepted, option)) return option;
308
+ return undefined;
46
309
  }
47
310
 
48
311
  /**
@@ -59,6 +322,7 @@ export function errorOrThrow<T>(value: UuidSlugError | T): T {
59
322
  * Seven near-identical copies of that test existed across this package and not one checked
60
323
  * integrality — the copying is why. One copy is what stops the class returning.
61
324
  */
325
+ /*#__NO_SIDE_EFFECTS__*/
62
326
  export function checkRange(
63
327
  capacity: number,
64
328
  offset: number,
@@ -66,35 +330,107 @@ export function checkRange(
66
330
  ): undefined | UuidSlugError {
67
331
  if (!Number.isInteger(offset))
68
332
  return new UuidSlugError(
69
- "invalid_buffer",
70
- `Buffer offset must be a whole number, got ${typeof offset} ${String(offset)}.`,
333
+ INVALID_BUFFER,
334
+ `Buffer offset must be a whole number, got ${typeof offset} ${diagnosticValue(offset)}.`,
71
335
  );
72
336
  if (offset < 0 || offset + need > capacity)
73
337
  return new UuidSlugError(
74
- "invalid_buffer",
338
+ INVALID_BUFFER,
75
339
  `Buffer needs ${need} bytes at offset ${offset}, but holds ${capacity}.`,
76
340
  );
77
341
  return undefined;
78
342
  }
79
343
 
344
+ /** Reject alien views and objects before range checks can mistake them for byte storage. */
345
+ /*#__NO_SIDE_EFFECTS__*/
346
+ export function checkByteRange(
347
+ bytes: unknown,
348
+ offset: number,
349
+ need: number,
350
+ ): undefined | UuidSlugError {
351
+ if (!isUint8Array(bytes)) {
352
+ if (isUuidSlugError(bytes)) return bytes;
353
+ return new UuidSlugError(INVALID_BUFFER, BUFFER_TYPE_MESSAGE);
354
+ }
355
+ return checkRange(bytes.length, offset, need);
356
+ }
357
+
358
+ /** Preserve a preceding failure or reject an untyped value that is not UUID text. */
359
+ /*#__NO_SIDE_EFFECTS__*/
360
+ export function invalidUuidStringInput(value: unknown): UuidSlugError {
361
+ return isUuidSlugError(value) ? value : new UuidSlugError(INVALID_UUID, "UUID must be text.");
362
+ }
363
+
364
+ /** Preserve a preceding failure or reject an untyped value that is not a UUID slug. */
365
+ /*#__NO_SIDE_EFFECTS__*/
366
+ export function invalidUuidSlugInput(value: unknown): UuidSlugError {
367
+ return isUuidSlugError(value)
368
+ ? value
369
+ : new UuidSlugError(INVALID_UUID_SLUG, "UUID slug must be a string.");
370
+ }
371
+
80
372
  /** Preserve failures from an injected or platform entropy source without changing successful draws. */
373
+ export const randomFailure = /* @__NO_SIDE_EFFECTS__ */ (
374
+ value: unknown,
375
+ ): undefined | UuidSlugError => {
376
+ if (value === undefined) return undefined;
377
+ if (isUuidSlugError(value)) return value;
378
+ return isError(value)
379
+ ? new UuidSlugError(RNG_UNAVAILABLE, RANDOM_FAILURE_MESSAGE, { cause: value })
380
+ : undefined;
381
+ };
382
+
81
383
  export function fillRandomBytes(
82
- fill: (bytes: Uint8Array<ArrayBuffer>) => void,
384
+ fill: (bytes: Uint8Array<ArrayBuffer>) => unknown,
83
385
  bytes: Uint8Array<ArrayBuffer>,
84
- ): UuidRuntimeError | undefined {
386
+ ): undefined | UuidSlugError {
85
387
  try {
86
- fill(bytes);
87
- return undefined;
388
+ return randomFailure(fill(bytes));
88
389
  } catch (cause) {
89
- return new UuidRuntimeError("Random byte generation failed.", { cause });
390
+ return new UuidSlugError(RNG_UNAVAILABLE, RANDOM_FAILURE_MESSAGE, { cause });
90
391
  }
91
392
  }
92
393
 
394
+ /**
395
+ * Generation whose typed inputs cannot fail declares no error union, so a failure reaching this
396
+ * point is an environment defect such as a missing secure random source and is thrown. Callers
397
+ * with fallible input never route through here; they keep the error value.
398
+ */
399
+ export function generatedOrThrow<Value>(result: Value | UuidSlugError): Value {
400
+ if (result instanceof Error) throw result;
401
+ return result;
402
+ }
403
+
404
+ /** Keep both failed implementations inspectable when an optional native shortcut also fails. */
405
+ /*#__NO_SIDE_EFFECTS__*/
406
+ export function failedFallback(
407
+ nativeCause: unknown,
408
+ fallback: UuidSlugError,
409
+ message: string,
410
+ ): UuidSlugError {
411
+ return new UuidSlugError(fallback.code, fallback.message, {
412
+ cause: new AggregateError([nativeCause, fallback], message),
413
+ });
414
+ }
415
+
416
+ /** Run the portable generator once after native generation failed; dual failures keep both causes. */
417
+ export function portableAfterNative<FallbackArgument>(
418
+ nativeCause: unknown,
419
+ fallback: (argument: FallbackArgument) => string | UuidSlugError,
420
+ fallbackArgument: FallbackArgument,
421
+ operation: string,
422
+ ): string | UuidSlugError {
423
+ const result = fallback(fallbackArgument);
424
+ return result instanceof Error
425
+ ? failedFallback(nativeCause, result, `Native and portable ${operation} failed.`)
426
+ : result;
427
+ }
428
+
93
429
  /** Read once so a failing clock keeps its original cause and successful clocks have one observation. */
94
430
  export function readClock(clock: () => number): number | UuidSlugError {
95
431
  try {
96
432
  return clock();
97
433
  } catch (cause) {
98
- return new UuidSlugError("invalid_timestamp", "Clock reading failed.", { cause });
434
+ return new UuidSlugError(INVALID_TIMESTAMP, "Clock reading failed.", { cause });
99
435
  }
100
436
  }
package/src/feistel.ts CHANGED
@@ -1,51 +1,14 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { halfSipHash } from "./siphash";
4
-
5
3
  /**
6
- * A 4-round Feistel network over the 16 UUID bytes, used as the mask's mixing step.
7
- *
8
- * Why a Feistel rather than the byte permutation plus XOR it replaces: that construction is a
9
- * monoalphabetic substitution — one output byte per input byte — so bytes the inputs share, the
10
- * outputs share too. Measured over 3000 ids, masked slugs of UUIDv7s created in the same second
11
- * held 4 of 16 bytes constant, the same hour 3, the same day 2. The timestamp the mask exists to
12
- * hide was still legible in the output. A Feistel diffuses every input bit across the whole
13
- * block, so no output byte is a function of one input byte: the same measurement yields 0 of 16.
14
- *
15
- * The bijection is the property being bought, and it holds whatever the round function does: 16
16
- * bytes map to 16 bytes and the inverse is the same routine with the round keys reversed, so
17
- * `mask` and `unmask` cannot drift apart.
18
- *
19
- * The round function is HalfSipHash-2-4 keyed per round. What that fixes: the previous round
20
- * function was `mix32(word ^ roundKey)` — a FIXED, PUBLIC, UNKEYED bijection with the key merely
21
- * XORed in front, so an attacker inverts it and reads `word ^ roundKey` directly. Luby-Rackoff
22
- * makes a four-round Feistel a strong pseudorandom permutation only when the round functions are
23
- * pseudorandom functions, which `mix32` is not, so the theorem said nothing about what shipped and
24
- * an earlier version of this comment cited it wrongly. A keyed PRF meets that hypothesis in kind,
25
- * which is what makes ROUNDS = 4 a justified number rather than an unexamined margin. It is still
26
- * NOT a proof about what ships: the theorem wants four INDEPENDENTLY sampled round functions, and
27
- * `schema.ts` derives all four key pairs from one 128-bit key. Read it as the design rationale it
28
- * is, and see `docs/design.md` for what masking does and does not promise.
29
- *
30
- * Measured 2026-08-12 on Bun, both directions, medians of 9: the swap costs 2.5x on the mixing step
31
- * alone (30.85M -> 12.43M mixes/s) and about a quarter of end-to-end masking throughput, because
32
- * mixing is roughly a fifth of a mask. HalfSipHash is FASTER per round than `mix32` — pure
33
- * add/xor/rotate against two `Math.imul` calls — and loses only by doing 14 rounds where the old
34
- * function did the equivalent of 4.
35
- *
36
- * Nor does any measurement in this repository grade the round count or the round function. Strict
37
- * avalanche across all input/output bit pairs, a same-millisecond burst where only a 12-bit counter
38
- * varies, and a single-difference differential all PASS a TWO-round network, so none of them can
39
- * separate a weak setting from a strong one. Their agreement is evidence about the instruments.
40
- * `test/siphash.test.ts` is the exception and the reason a published primitive was worth taking:
41
- * it checks the round function against 64 vectors somebody else computed, and that CAN fail.
4
+ * A four-round Feistel network gives masking an exact inverse while spreading each UUID change
5
+ * across the block. HalfSipHash-2-4 supplies the keyed round function. This is reversible
6
+ * obfuscation, not authenticated encryption; `docs/design.md` defines the security boundary.
42
7
  */
43
8
 
44
9
  /**
45
10
  * Round count. Wire-format-bearing: changing it changes every masked slug this package has ever
46
- * issued, so it moves only alongside a deliberate format change. Four is Luby-Rackoff's number,
47
- * which the round function now makes relevant — see the note above for why that is a rationale
48
- * rather than a proof.
11
+ * issued, so it moves only alongside a deliberate format change.
49
12
  */
50
13
  const ROUNDS = 4;
51
14
 
@@ -57,6 +20,7 @@ export const FEISTEL_KEY_WORDS = ROUNDS * 2;
57
20
  * round function — see above — but still what `mask.ts` derives its check tag with, where the input
58
21
  * is public and an unkeyed mixer is the right tool.
59
22
  */
23
+ /*#__NO_SIDE_EFFECTS__*/
60
24
  export function mix32(value: number): number {
61
25
  let x = (value ^ (value >>> 16)) >>> 0;
62
26
  x = Math.imul(x, 0x7feb352d);
@@ -66,6 +30,7 @@ export function mix32(value: number): number {
66
30
  }
67
31
 
68
32
  /** Big-endian on purpose: the wire format must not depend on the host's byte order. */
33
+ /*#__NO_SIDE_EFFECTS__*/
69
34
  export function read32(bytes: Uint8Array, offset: number): number {
70
35
  return (
71
36
  ((bytes[offset] as number) << 24) |
@@ -83,23 +48,17 @@ function write32(bytes: Uint8Array, offset: number, value: number) {
83
48
  bytes[offset + 3] = value & 0xff;
84
49
  }
85
50
 
86
- // Scratch for the round function, at module scope because allocating two 2-word arrays per call
87
- // dominated the mix. Safe because nothing here is reentrant: `feistel16` is synchronous, calls only
88
- // `halfSipHash`, and that calls nothing.
89
- const roundInput = new Int32Array(2);
90
- const roundOutput = new Int32Array(2);
91
-
92
51
  /**
93
52
  * Transform 16 bytes from `input` into `output`, which may be the same array.
94
53
  *
95
- * `forward: false` is the exact inverse — the rounds are identical and only the key order
96
- * differs, which is why the final swap below is undone rather than performed.
54
+ * Unmasking is the exact inverse: the rounds are identical and only the key order differs, which
55
+ * is why the final swap below is undone rather than performed.
97
56
  */
98
57
  export function feistel16(
99
58
  input: Uint8Array,
100
59
  inputOffset: number,
101
60
  keys: Int32Array,
102
- forward: boolean,
61
+ direction: "mask" | "unmask",
103
62
  output: Uint8Array,
104
63
  outputOffset: number,
105
64
  ) {
@@ -108,12 +67,66 @@ export function feistel16(
108
67
  let right0 = read32(input, inputOffset + 8);
109
68
  let right1 = read32(input, inputOffset + 12);
110
69
  for (let round = 0; round < ROUNDS; round += 1) {
111
- const key = (forward ? round : ROUNDS - 1 - round) * 2;
112
- roundInput[0] = right0;
113
- roundInput[1] = right1;
114
- halfSipHash(keys[key] as number, keys[key + 1] as number, roundInput, 8, roundOutput);
115
- const next0 = left0 ^ (roundOutput[0] as number);
116
- const next1 = left1 ^ (roundOutput[1] as number);
70
+ const key = (direction === "mask" ? round : ROUNDS - 1 - round) * 2;
71
+ // The round function is `halfSipHash(keys[key], keys[key + 1], [right0, right1], 8)`, written
72
+ // out for its fixed two-word message: the call through word arrays cost about a fifth more of
73
+ // the network on Node and Bun (bench/PERFORMANCE.md). The fixed vector in `feistel.test.ts`
74
+ // and the wire-format vectors hold it to issued slugs.
75
+ const key0 = keys[key] as number;
76
+ const key1 = keys[key + 1] as number;
77
+ let v0 = key0 | 0;
78
+ let v1 = (key1 ^ 0xee) | 0;
79
+ let v2 = (key0 ^ 0x6c796765) | 0;
80
+ let v3 = (key1 ^ 0x74656462) | 0;
81
+ // Absorb both message words, then the length block for 8 bytes, with two rounds each.
82
+ for (let block = 0; block < 3; block += 1) {
83
+ const m = block === 0 ? right0 : block === 1 ? right1 : 8 << 24;
84
+ v3 ^= m;
85
+ for (let sipRound = 0; sipRound < 2; sipRound += 1) {
86
+ v0 = (v0 + v1) | 0;
87
+ v1 = (v1 << 5) | (v1 >>> 27);
88
+ v1 ^= v0;
89
+ v0 = (v0 << 16) | (v0 >>> 16);
90
+ v2 = (v2 + v3) | 0;
91
+ v3 = (v3 << 8) | (v3 >>> 24);
92
+ v3 ^= v2;
93
+ v0 = (v0 + v3) | 0;
94
+ v3 = (v3 << 7) | (v3 >>> 25);
95
+ v3 ^= v0;
96
+ v2 = (v2 + v1) | 0;
97
+ v1 = (v1 << 13) | (v1 >>> 19);
98
+ v1 ^= v2;
99
+ v2 = (v2 << 16) | (v2 >>> 16);
100
+ }
101
+ v0 ^= m;
102
+ }
103
+ // Two four-round squeezes yield the two output words.
104
+ v2 ^= 0xee;
105
+ let hash0 = 0;
106
+ for (let half = 0; half < 2; half += 1) {
107
+ for (let sipRound = 0; sipRound < 4; sipRound += 1) {
108
+ v0 = (v0 + v1) | 0;
109
+ v1 = (v1 << 5) | (v1 >>> 27);
110
+ v1 ^= v0;
111
+ v0 = (v0 << 16) | (v0 >>> 16);
112
+ v2 = (v2 + v3) | 0;
113
+ v3 = (v3 << 8) | (v3 >>> 24);
114
+ v3 ^= v2;
115
+ v0 = (v0 + v3) | 0;
116
+ v3 = (v3 << 7) | (v3 >>> 25);
117
+ v3 ^= v0;
118
+ v2 = (v2 + v1) | 0;
119
+ v1 = (v1 << 13) | (v1 >>> 19);
120
+ v1 ^= v2;
121
+ v2 = (v2 << 16) | (v2 >>> 16);
122
+ }
123
+ if (half === 0) {
124
+ hash0 = v1 ^ v3;
125
+ v1 ^= 0xdd;
126
+ }
127
+ }
128
+ const next0 = left0 ^ hash0;
129
+ const next1 = left1 ^ v1 ^ v3;
117
130
  left0 = right0;
118
131
  left1 = right1;
119
132
  right0 = next0;