@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/README.md CHANGED
@@ -1,282 +1,954 @@
1
1
  # @anizoptera/uuid-slug
2
2
 
3
- Use shorter UUIDs in URLs, with optional masking of UUIDv7 timestamps.
4
-
5
3
  [![npm version](https://img.shields.io/npm/v/@anizoptera/uuid-slug?label=npm)](https://www.npmjs.com/package/@anizoptera/uuid-slug)
6
4
  [![CI](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml/badge.svg?branch=main)](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml)
7
5
  [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
8
6
  [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
9
7
  [![License](https://img.shields.io/github/license/Anizoptera/uuid-slug)](LICENSE)
10
8
 
11
- A UUID in a URL is 36 characters of hex and dashes. The same 16 bytes written as base64url
12
- are 22 characters, and nothing is lost: it is the same identifier in a shorter alphabet.
9
+ ## TL;DR
10
+
11
+ **Zero-dependency UUIDv4/v7 generation, lossless base64url and base32hex slugs for any UUID, and reversible UUIDv7 masking for databases, URLs, and files.**
12
+
13
+ - Encode any UUID as short `base64url` or lowercase `base32hex`.
14
+ - Use optional reversible masking to hide the timestamp and structure of UUIDv7 slugs.
15
+ - Keep one ID across all representations, with no lost bits or mapping table.
16
+ - Write directly into your buffers without intermediate text or new output arrays.
17
+ - Read the time directly from UUIDv7 when it is the timestamp your application needs.
18
+ - Use native runtime APIs with matching portable fallbacks.
19
+ - Failures return typed errors. Built-in generation never falls back to weaker randomness.
20
+ - Unused features tree-shake away with any modern bundler.
21
+
22
+ [Install](#install) · [Quick start](#quick-start) · [Contents](#contents) · [API](#api) · [Performance](#measured-performance)
13
23
 
14
- UUIDv7 adds a second problem. It begins with a millisecond timestamp, which is exactly
15
- what you want in a database index and rarely what you want in public. A v7 id tells anyone
16
- who reads it when the record was created, and two of them tell them how fast you are
17
- creating records. Masking removes that directly readable structure from public identifiers,
18
- then recovers the UUID for a lookup. It is obfuscation, not an authorization boundary.
24
+ ### TypeScript API map
19
25
 
20
- It defines no new identifier scheme. Everything here is a UUID underneath.
26
+ A UUID is a 128-bit identifier. UUIDv4 is random; UUIDv7 starts with a Unix-millisecond timestamp
27
+ so values from different milliseconds sort by time in UUID byte order. A slug is the same UUID in
28
+ shorter text. A plain slug needs no key. A masked slug hides UUIDv7 fields with a secret held by a
29
+ reusable masking codec. A sentinel is an application-reserved UUIDv7 that the codec deliberately
30
+ leaves as a recognizable plain slug.
21
31
 
22
- ## Install
32
+ ```text
33
+ UUID text ─┐
34
+ UUID bytes ├── keyless conversion ── UUID text / bytes / plain slug
35
+ plain slug ┘
36
+
37
+ UUIDv7 text / bytes / plain slug ── masking codec ── masked slug / sentinel / decoded UUID
38
+ │
39
+ ├── current + previous masks
40
+ └── opt-in migration reader
41
+ ```
42
+
43
+ The concrete examples encode the same UUIDv7; the sentinel row describes a separately configured value.
44
+ `ch` means text characters and `B` means bytes.
45
+
46
+ | Representation | Size (ch/B) | Example | Meaning and use |
47
+ | --- | ---: | --- | --- |
48
+ | Compact UUID text | 32 | `0198abcd12347abc9def0123456789ab` | Input; hexadecimal may use mixed case |
49
+ | Canonical UUID text | 36 | `0198abcd-1234-7abc-9def-0123456789ab` | Input and the only emitted UUID text; lowercase by default or uppercase on request |
50
+ | Brace-wrapped UUID text | 38 | `{0198abcd-1234-7abc-9def-0123456789ab}` | Input; braces require canonical text and hexadecimal may use mixed case |
51
+ | UUID URN | 45 | `urn:uuid:0198abcd-1234-7abc-9def-0123456789ab` | Input; prefix is case-insensitive and requires canonical text; hexadecimal may use mixed case |
52
+ | UUID bytes | 16 | `01 98 ab cd 12 34 7a bc 9d ef 01 23 45 67 89 ab` | Compact storage; output can use a new array or caller-owned storage; URLs need text encoding |
53
+ | Plain base64url slug | 22 | `AZirzRI0eryd7wEjRWeJqw` | Shortest keyless lossless form for any UUID; case-sensitive and not lexically ordered |
54
+ | Plain base32hex slug | 26 | `06canj8i6htbp7ff04hkaps9lc` | Keyless and lossless; output is lowercase, input may use mixed case, and UUIDv7 values sort by timestamp |
55
+ | Masked base64url UUIDv7 slug | 22 | `ap225Qa_y6wN5LQCJgwH0z` | Short opaque form with a 16-bit check; case-sensitive, unordered, and decoding requires its codec |
56
+ | Masked base32hex UUIDv7 slug | 27 | `daerdp86nv5qo3f4mg12c307qco` | Opaque and unordered; output is lowercase, input may use mixed case, and decoding requires its codec |
57
+ | Sentinel UUIDv7 slug | 22/26 | Configured | A recognizable plain slug reserved by a codec; size follows its selected alphabet |
58
+
59
+ Plain and masked slugs work in URLs and filenames. Alphabet and masking are independent choices.
60
+
61
+ The four concrete slug examples recover the UUIDv7 shown above. Masking makes UUIDv7 fields
62
+ unrecognizable; encoding and decoding require the codec that holds your secret. Plain base64url
63
+ keeps similar timestamps visually grouped but does not sort chronologically as text. Plain
64
+ base32hex does. Masked slugs expose no useful time order.
65
+
66
+ | Job | Main TypeScript API |
67
+ | --- | --- |
68
+ | Generate UUIDv4 | `generateUuidV4`, `generateUuidV4Bytes`, `generatePlainUuidV4Slug`, `generateUuidV4WithRandomFill` |
69
+ | Generate UUIDv7 | `generateUuidV7`, `generateUuidV7Bytes`, `generatePlainUuidV7Slug` |
70
+ | Generate one UUIDv7 with its slug | `generateUuidV7WithPlainSlug`, `maskingCodec.generateUuidV7WithMaskedSlug` |
71
+ | Generate an immutable UUIDv7 value | `generateUuidV7Value`, or its generator and masking-codec methods |
72
+ | Control UUIDv7 time, sequence, rollback, or entropy | `createUuidV7Generator`, `createUuidV7GeneratorWithRandomFill` |
73
+ | Convert UUID text, bytes, and plain slugs | `uuidToString`, `uuidToBytes`, `uuidToPlainSlug`, plus source-specific converters |
74
+ | Parse once for repeated work | `parseUuid` returns an immutable `Uuid` value |
75
+ | Inspect version, variant, timestamp, or payload | `Uuid.inspect`, `extractUuidVersion`, `extractUuidV7UnixMs`, `extractUuidV7Payload` |
76
+ | Narrow untrusted input | `isUuidText`, `isUuidString`, `isUuidBytes`, `isPlainUuidSlug`, their v4/v7 guards, and `isUuidSlugError` |
77
+ | Build UUIDv7 database range keys | `uuidV7StringBounds`, `uuidV7ByteBounds` |
78
+ | Validate a UUIDv7 timestamp window | `validateUuidV7StringUnixMs` and the plain or masked slug equivalents |
79
+ | Create UUIDv7 masking | `deriveUuidV7Mask`, `deriveUuidV7MaskAsync`, `createCustomUuidV7Mask` |
80
+ | Mask, unmask, rotate keys, or reserve sentinels | `createUuidV7MaskingCodec` and its methods |
81
+ | Read explicitly enabled old formats | `maskingCodec.createUuidSlugMigrationDecoder` |
82
+
83
+ The TypeScript types preserve known UUID versions, text case, slug kind, and caller-owned buffer
84
+ types. Expected failures return `UuidSlugError`; invalid writes leave caller storage unchanged.
85
+ Generation with no arguments or only a spelling preset returns its value directly and throws only
86
+ when generation cannot obtain secure randomness.
87
+ Generator, masking-codec, and migration methods can be detached without binding `this`.
88
+ Stable error codes distinguish malformed encodings, UUIDs, buffers, options, masks, sentinels and
89
+ timestamps from unavailable entropy, cancellation, wrong UUID versions, and timestamps outside a window.
90
+
91
+ Operational contracts:
92
+
93
+ - A created UUIDv7 generator owns its clock and sequence. Its successful current-time values
94
+ strictly increase in UUID byte order; sequence exhaustion advances logical time instead of failing or wrapping.
95
+ - Module-level UUIDv7 calls share no sequence state. Supply one generator when calls must share ordering.
96
+ - A masking codec is immutable. Writers use its current mask; readers also try previous masks in order.
97
+ - Caller-owned buffer writes are transactional. Invalid input or output ranges leave the buffer unchanged.
98
+ - Async mask derivation is cooperatively cancellable. Migration readers accept only enabled old formats
99
+ and can return every distinct UUID candidate when one slug has several meanings.
100
+
101
+ Critical boundaries:
102
+
103
+ - A 22-character base64url value can be a plain slug and a masked slug for different UUIDs.
104
+ A masking codec uses the first passing mask, then tries plain decoding if every mask rejects it.
105
+ Use a source-specific converter when you know the slug is plain or masked.
106
+ - Masking hides recognizable UUIDv7 fields. It is not encryption, authentication, authorization,
107
+ proof of issuance, or a replacement for record lookup and access checks.
108
+ - Mask checks can accept a wrong key by chance. Readers try only the configured current and previous masks;
109
+ record lookup must decide whether the decoded UUID exists.
110
+ - Sentinels remain recognizable plain slugs and bypass the masking codec's timestamp range.
111
+ - Plain base32hex UUIDv7 slugs preserve timestamp order. Base64url and masked slugs do not.
112
+ - Generated UUID collisions remain possible. Use a uniqueness constraint wherever a duplicate can cause harm.
113
+
114
+ ## Install (use your favorite package manager)
23
115
 
24
116
  ```bash
117
+ bun add @anizoptera/uuid-slug
25
118
  pnpm add @anizoptera/uuid-slug
119
+ npm add @anizoptera/uuid-slug
26
120
  ```
27
121
 
28
- Requires TypeScript 5.7 or newer for `Uint8Array<ArrayBuffer>` declarations.
29
- Custom `fillRandom` callbacks receive an ordinary `ArrayBuffer` view, which Web Crypto accepts.
30
-
31
122
  ## Quick start
32
123
 
124
+ When you need both a database UUID and a public slug, generate both from one byte draw:
125
+
33
126
  ```ts
34
- import { createUuidSlugCodec } from "@anizoptera/uuid-slug";
127
+ import {
128
+ generateUuidV7WithPlainSlug,
129
+ } from "@anizoptera/uuid-slug";
130
+
131
+ function createShortId() {
132
+ return generateUuidV7WithPlainSlug();
133
+ }
134
+ ```
35
135
 
36
- const seed = process.env.ID_MASK_SEED;
37
- if (!seed) throw new Error("Set ID_MASK_SEED to a stable, randomly generated secret.");
136
+ If you only need the slug, call `generatePlainUuidV7Slug()` directly.
137
+
138
+ ## Contents
139
+
140
+ - [Install](#install)
141
+ - [Quick start](#quick-start)
142
+ - [Keep your existing UUIDs](#keep-your-existing-uuids)
143
+ - [Assign IDs before saving or syncing](#assign-ids-before-saving-or-syncing)
144
+ - [Generate at a recorded time](#generate-at-a-recorded-time)
145
+ - [Use the UUID as the timestamp source](#use-the-uuid-as-the-timestamp-source)
146
+ - [Representations](#representations)
147
+ - [Work with UUID bytes](#work-with-uuid-bytes)
148
+ - [Two kinds of slug](#two-kinds-of-slug)
149
+ - [Plain slugs](#plain-slugs) · [Masked slugs](#masked-slugs) · [Sentinels](#sentinels)
150
+ - [Ordering and key distribution](#ordering-and-key-distribution)
151
+ - [What masking is not](#what-masking-is-not)
152
+ - [Handling errors](#handling-errors)
153
+ - [Types](#types)
154
+ - [API](#api)
155
+ - [Generate IDs](#generate-ids) · [Convert and inspect IDs](#convert-and-inspect-ids)
156
+ - [Use a masking codec](#use-a-masking-codec) · [Constructors and guards](#constructors-and-guards)
157
+ - [Masking codec options](#masking-codec-options)
158
+ - [Changing an existing ID format](#changing-an-existing-id-format)
159
+ - [Reading original slugs during migration](#reading-original-slugs-during-migration)
160
+ - [Validating timestamp windows](#validating-timestamp-windows)
161
+ - [Measured performance](#measured-performance)
162
+ - [Guarantees](#guarantees)
163
+ - [Runtime](#runtime)
164
+ - [License](#license)
165
+
166
+ ## Keep your existing UUIDs
167
+
168
+ Encode your stored UUID; decode incoming slugs before querying that same key. Plain encoding
169
+ accepts every UUID version, including IDs from databases and other libraries. It preserves all
170
+ bits, so shortening adds no collisions and needs no mapping table. Masked UUIDv7 slugs also
171
+ recover the original UUID, but need the matching masking codec.
172
+
173
+ UUIDv4 uses 122 bits for random data. UUIDv7 uses 48 bits for its millisecond timestamp. RFC 9562
174
+ allows the remaining 74 bits to hold random data, a counter, or both. Use UUIDv4 when the timestamp
175
+ has no value. Use UUIDv7 when you need timestamp sorting or extraction. Neither requires masking.
176
+ Anyone can decode a plain slug, including its UUIDv7 timestamp.
177
+
178
+ This package accepts every RFC 9562 UUIDv7. Conversion and masking preserve the 74 payload bits
179
+ without interpreting them. Payload extraction interprets only the layout supplied by the caller.
180
+ A UUID alone cannot prove which library generated it or whether those bits contain random data, a
181
+ counter, sub-millisecond time, or a combination.
182
+
183
+ UUIDv7 values from different milliseconds sort by timestamp in UUID byte order. Values from the
184
+ same millisecond follow their generator's payload rules; UUIDv7 alone does not promise their order.
185
+
186
+ | Operation | UUID bits recoverable from the result | Other effect |
187
+ | --- | --- | --- |
188
+ | UUID to plain slug and back | All 128 | Needs no key or codec |
189
+ | UUIDv7 to masked slug and back | All 128 | Needs the matching codec configuration; encoding returns `invalid_timestamp` outside its inclusive range and never truncates |
190
+ | Registered sentinel through a masking codec | All 128 | Remains a plain slug and bypasses the masked timestamp range |
191
+ | Accepted UUID text to bytes or slug | All 128 | Text output uses canonical hyphens and the requested case |
192
+ | UUIDv7 timestamp extraction | 48 | Returns Unix milliseconds; does not return the other 80 UUID bits |
193
+
194
+ Payload patterns may suggest a generator or ordering policy, but the UUID alone cannot prove one.
195
+ Generation is limited to UUIDv4 and UUIDv7. Other versions remain accepted by version-neutral
196
+ parsing, inspection, and plain-slug conversion without version-specific package machinery.
197
+
198
+ Use this package for short public IDs, binary storage, typed validation, and the same API across
199
+ runtimes. Named root imports let you use UUID generation alone without bundling the other features.
200
+
201
+ ## Assign IDs before saving or syncing
202
+
203
+ Create IDs before saving records, including in an offline client. Related records can refer to
204
+ those UUIDs before a database round trip, then keep the same IDs when synchronized. No central
205
+ ID allocator or worker number is required. Validate client-supplied IDs and check ownership on
206
+ the server; generating a valid UUID does not grant permission to create or replace a record.
207
+
208
+ ## Generate at a recorded time
209
+
210
+ When importing records that do not yet have IDs, encode their recorded time instead of the import
211
+ time. Pass `at` to the UUIDv7 text, byte, plain-slug, paired, or immutable-value generator. It
212
+ accepts a Unix-millisecond `number` or `bigint`, a `Date`, zoned ISO timestamp text, a
213
+ Temporal-style `epochMilliseconds` or `epochNanoseconds` object, or a `{ seconds, nanoseconds }`
214
+ timestamp. Text must include a time zone. The 48-bit UUID timestamp stores the containing Unix
215
+ millisecond. A configured generator also stores the best fraction its selected payload bits can
216
+ represent; the default layout assigns no payload bits to fractions. A created generator mixes that
217
+ fraction with its counter and applies its rollback policy, so `at` calls join the same sequence.
218
+ Module-level calls remain independent.
38
219
 
39
- // Reuse the codec: the seed is expanded once, at construction.
40
- export const ids = createUuidSlugCodec({ mask: { seed } });
220
+ ```ts
221
+ import { BASE32HEX, generatePlainUuidV7Slug } from "@anizoptera/uuid-slug";
41
222
 
42
- const publicId = ids.uuidV7MaskedSlug();
43
- const uuid = ids.maskedSlugToUuidV7(publicId);
44
- if (uuid instanceof Error) throw uuid;
45
- // Look up uuid in your store and apply the caller's authorization policy.
223
+ function idForImportedRecord(recordedAt: Date) {
224
+ return generatePlainUuidV7Slug({ at: recordedAt, alphabet: BASE32HEX });
225
+ }
46
226
  ```
47
227
 
48
- **Generate the seed; do not think one up.** For example, run `openssl rand -base64 32` and
49
- store the result outside your source repository. Seeds shorter than 16 bytes are rejected, but
50
- length alone does not make a seed unpredictable: a known UUID/slug pair allows offline guesses.
228
+ Pass the same created generator to any UUIDv7 representation call when its result must join one
229
+ sequence. The representation call generates and formats once; callers do not unwrap bytes first.
230
+
231
+ Each call uses fresh randomness, even at the same timestamp. For retries, keep the first ID or
232
+ use your application's deduplication key. Existing records should keep their UUIDs.
233
+ By default, masking accepts UUIDv7 timestamps from Unix millisecond `0` through `2^42 - 1`,
234
+ inclusive. Set `timestampRangeStartUnixMs` on the masking codec to move that fixed-size range.
235
+
236
+ Use `createUuidV7Generator({ readUnixMs })` for an application clock or time-dependent tests.
237
+ Each generator has its own sequence state. A fixed clock does not make IDs repeatable:
238
+ randomness still comes from the runtime.
239
+
240
+ Set `subMillisecondFractionBits` from 1 through 12 to encode the clock fraction before the
241
+ generator's random-start counter. `payloadLayout` exposes the exact split for later extraction.
242
+ Without `readUnixMs`, this mode uses the runtime's high-resolution clock when available and falls
243
+ back to `Date.now()`. The selected width states the UUID layout, not the clock's real accuracy.
244
+ If another reading lands in the same fraction bucket, the generator increments the counter. If the
245
+ counter fills, it advances the logical fraction and then the millisecond timestamp. The default
246
+ preserve policy applies the same rule when the clock moves backward, so extracted time can be later
247
+ than the supplied instant. A reset policy may move backward after its tolerance. Explicit `at`
248
+ calls on the generator join this sequence; module-level `at` calls use independent randomness.
249
+
250
+ With the default preserve policy, successful current-time calls on one generator strictly increase
251
+ in UUID byte order, including calls made within one millisecond. Module-level generation uses the
252
+ fastest validated secure path for each output form and does not promise ordering across calls.
253
+ Created generators do not coordinate with reset-policy calls after their tolerance, other
254
+ generators, package copies, workers, or processes. Set `clockRollback` to reset or
255
+ return `invalid_timestamp` when total skew exceeds an inclusive tolerance. Use
256
+ `createUuidV7GeneratorWithRandomFill` only when the application must own entropy; its callback must
257
+ fill every requested byte or return `UuidSlugError`.
258
+
259
+ ## Use the UUID as the timestamp source
260
+
261
+ UUIDv7 already stores a millisecond timestamp. If that is the time your application needs,
262
+ you can omit a separate timestamp field. Read it without a database lookup or conversion to UUID text:
51
263
 
52
- Keep the seed and `keyIterations` stable for as long as issued slugs must remain readable.
53
- Changing either derives different keys; retain the old settings in `previousMasks` during
54
- rotation. `keyIterations` defaults to `1`; increasing it adds construction and guessing cost,
55
- but does not turn a human-chosen seed into a suitable secret.
264
+ ```ts
265
+ import { extractUuidV7UnixMs, isUuidSlugError } from "@anizoptera/uuid-slug";
266
+
267
+ function dateFromId(uuidOrPlainSlug: string) {
268
+ const unixMs = extractUuidV7UnixMs(uuidOrPlainSlug);
269
+ return isUuidSlugError(unixMs) ? unixMs : new Date(unixMs);
270
+ }
271
+ ```
272
+
273
+ `extractUuidV7UnixMs(bytes, offset)` reads a UUID inside a larger buffer.
274
+ `maskingCodec.extractMaskedUuidV7UnixMs(slug)` reads the same timestamp from a masked slug using the
275
+ masking codec's keys. Masking preserves it. UUIDv4 has no timestamp and is rejected.
276
+
277
+ The other 74 UUIDv7 bits have no self-describing layout. A generator may use them for random data,
278
+ a fixed counter, a changing random value, a sub-millisecond fraction, or a fraction followed by a
279
+ counter. Use `extractUuidV7Payload(value, layout)` only when you know that generator's layout:
280
+
281
+ ```ts
282
+ const payload = extractUuidV7Payload(uuid, {
283
+ subMillisecondFractionBits: 12,
284
+ counterBits: 14,
285
+ });
286
+ ```
287
+
288
+ The result keeps each value with its bit width and returns every undeclared low bit in `remaining`.
289
+ A fraction value `n` stored in `b` bits places creation within
290
+ `[unixMs + n / 2**b, unixMs + (n + 1) / 2**b)` milliseconds. It does not recover a more exact time.
291
+ Use `maskingCodec.extractMaskedUuidV7Payload(slug, layout)` for masked slugs and sentinels.
292
+
293
+ Choose what the timestamp means when assigning the ID: generation time, or a supplied time for
294
+ imports. It has millisecond precision and does not prove when an external event happened.
295
+ Keep a separate field for other dates, finer precision, editable times, or date queries your UUID
296
+ index cannot serve. Changing the timestamp inside a UUID changes the ID.
297
+
298
+ ## Representations
299
+
300
+ A UUID contains 128 bits: 36 characters as canonical text or 16 bytes in binary form.
301
+
302
+ Plain slugs need no key and preserve every UUID version, variant, and timestamp bit without a
303
+ timestamp limit. A masking codec owns the key used to mask and unmask UUIDv7. A sentinel is an
304
+ ordinary plain UUIDv7 slug reserved by the application; registering it makes masked writers leave
305
+ that plain spelling unchanged.
306
+
307
+ No operation eagerly returns every representation. Generate bytes once when one caller genuinely
308
+ needs several outputs, then derive only the text, plain slug, or masked slug it will use. This keeps
309
+ one UUID identity without paying for unused strings. The paired generation methods cover the common
310
+ case that needs UUID text plus one selected slug.
311
+
312
+ ```mermaid
313
+ flowchart LR
314
+ T["Canonical UUID text<br>36 characters"] <--> B["UUID bytes<br>16 bytes"]
315
+ T <--> S["Plain slug<br>22 base64url or 26 base32hex<br>any UUID version, no key"]
316
+ B <--> S
317
+ B -- "masking codec, UUIDv7 only" --> M["Masked slug<br>22 base64url or 27 base32hex"]
318
+ M -- "masking codec, check must pass" --> B
319
+ N["Sentinel<br>a reserved UUIDv7"] -- "masking codec writes it as a plain slug" --> S
320
+ ```
321
+
322
+ Choose masking to hide recognizable UUID fields; choose base32hex to avoid case collisions.
323
+
324
+ ## Work with UUID bytes
325
+
326
+ Decode a masked public ID directly into your database or protocol buffer using your masking codec:
327
+
328
+ ```ts
329
+ import type { UuidV7MaskingCodec } from "@anizoptera/uuid-slug";
330
+
331
+ function decodePublicId(maskingCodec: UuidV7MaskingCodec, publicId: string, record: Uint8Array, offset: number) {
332
+ return maskingCodec.uuidToBytes(publicId, record, offset);
333
+ }
334
+ ```
335
+
336
+ Write a UUID directly into a binary record, leaving its other fields untouched:
337
+
338
+ ```ts
339
+ import { uuidStringToBytes } from "@anizoptera/uuid-slug";
340
+
341
+ function convertUuid() {
342
+ const record = new Uint8Array(32);
343
+ return uuidStringToBytes("01990d4d-e600-7000-8000-000000000000", record, 8);
344
+ }
345
+ ```
346
+
347
+ `uuidStringToBytes` accepts mixed-case canonical or compact UUID text, UUID URNs, and canonical text
348
+ enclosed by braces. It either allocates a plain
349
+ `Uint8Array` or writes 16 bytes at the requested offset. `bytesToUuidString` reads 16 bytes at an
350
+ optional offset and returns lowercase hyphenated text by default. Pass `UUID_TEXT_UPPERCASE` or
351
+ `"uppercase"` for uppercase output, or `UUID_TEXT_LOWERCASE` when the default must be an explicit
352
+ reusable choice.
353
+ The same optional preset works on every operation that returns UUID text, including generators,
354
+ plain and masked decoders, timestamp validation, and migration readers. It changes only UUID text;
355
+ slug alphabets and accepted input stay independent.
356
+ `Buffer` works because it is a `Uint8Array`. A standalone `ArrayBuffer` must contain exactly 16
357
+ bytes. A `DataView` must declare an exact 16-byte range, which can select a UUID inside a larger
358
+ buffer without copying. Offsets apply only to `Uint8Array`; other typed arrays and array-like values
359
+ are rejected. Use `isUuidBytes`, `isUuidV4Bytes`, or `isUuidV7Bytes` when unknown binary input must
360
+ be narrowed before storage or version-specific work.
361
+
362
+ For a binary database key or protocol field, use `uuidBytesToPlainSlug(record, offset)` and
363
+ `plainSlugToUuidBytes(slug, record, offset)` to avoid UUID text and temporary slices. Use
364
+ `maskingCodec.uuidToBytes(slug, record, offset)` for masked IDs. These writes return the original
365
+ array, not a view of the UUID. Read it back at the same offset. Copy bytes you need to keep before
366
+ reusing the buffer.
56
367
 
57
368
  ## Two kinds of slug
58
369
 
59
- **Direct slug.** The 16 UUID bytes as unpadded base64url, 22 characters. Pure re-encoding:
60
- `uuidToSlug` and `slugToUuid` preserve the UUID value, and anyone can convert either way. Use it
370
+ ### Plain slugs
371
+
372
+ A plain slug holds the 16 UUID bytes as 22-character unpadded base64url by default:
373
+ `uuidStringToPlainSlug` and `uuidToString` preserve the UUID value, and anyone can convert either way. Use it
61
374
  when you only want the identifier shorter.
62
375
 
63
- Pass `"base32hex"` to get 26 characters instead, and gain one thing: **base32hex slugs of UUIDv7s
64
- sort by creation time as plain strings.** A v7 starts with its timestamp, and base32hex writes
65
- its digits in the same order as their values, so comparing two slugs compares two instants. That
66
- makes them usable directly as an ordered database key. base64url cannot do it — its alphabet runs
376
+ Pass `"base32hex"` to get 26 lowercase characters that sort by UUIDv7 millisecond timestamp.
377
+ A v7 starts with its timestamp, and base32hex writes its digits in the same order as their values. That
378
+ makes them usable directly as an ordered database key. base64url cannot do it: its alphabet runs
67
379
  `A-Za-z0-9-_`, so `0` stands for a larger value than `A` but sorts before it.
68
380
 
69
- base32hex is also the safer of the two for a **filename**: it is lowercase throughout, so it
70
- survives a case-insensitive filesystem unchanged, and a directory listing comes back in creation
71
- order for free. `uuidV7Slug("base32hex")` generates one directly; the alphabet is an argument on
72
- every keyless entry point that produces a slug, so nothing about choosing it requires a codec.
381
+ Use bytewise or ASCII ordering for those keys. A database collation or a file manager's natural
382
+ sort can order text differently. Compare one representation at a time: mixing UUID text, both
383
+ slug alphabets, or masked slugs does not preserve timestamp order.
384
+
385
+ base32hex also avoids case collisions in filenames. A directory listing sorted bytewise follows
386
+ the encoded timestamps across different milliseconds. `generatePlainUuidV7Slug(BASE32HEX)` produces
387
+ one directly; every keyless slug writer accepts the alphabet without requiring a masking codec.
388
+
389
+ `uuidToString` infers the alphabet from the length, 22 or 26, so both spellings remain readable
390
+ after you switch output. It accepts uppercase base32hex and returns lowercase UUID text by default.
391
+ Decode to a UUID before comparing identities or building a cache key:
392
+ different spellings can identify the same record. Preserve base64url case; lowercasing it changes
393
+ the value. Choose base32hex when storage cannot preserve case distinctions.
73
394
 
74
- You never say which alphabet you are reading. The two lengths are different, 22 and 26, so
75
- `slugToUuid` works out the encoding from the slug itself — which means switching alphabet leaves
76
- every slug you have already handed out working.
395
+ ### Masked slugs
77
396
 
78
- **Masked slug.** A UUIDv7 payload and check passed through a small block cipher keyed by your
79
- seed, then base64url-encoded. Also 22 characters. Use it when the identifier is public and you
80
- would rather not publish creation times. The exact steps are in
81
- [how masking works](https://github.com/Anizoptera/uuid-slug/blob/main/docs/design.md).
397
+ Masking supports UUIDv7 only. Its compact payload and check pass through a small
398
+ block cipher keyed by your seed, then encoded as 22 base64url characters by default, or 27
399
+ lowercase base32hex characters with `maskedSlugAlphabet: BASE32HEX`. Both preserve the same payload
400
+ and check. Use it when the identifier is public and you want an opaque, hash-like spelling instead
401
+ of recognizable UUID fields. Masked slugs are reversible and therefore are not hashes. The exact steps are in
402
+ [how masking works](docs/design.md).
82
403
 
83
- A supported UUIDv7 carries 116 bits that the masked format must preserve — the version and
84
- variant are fixed, and the top six bits of the timestamp stay zero until the year 2109. 22 base64url characters hold 132
85
- bits, so the spare 16 carry a check for incorrect decoding. Two things follow, and both are
86
- part of the contract rather than implementation detail:
404
+ Use a masking codec only when IDs must hide their UUIDv7 layout:
405
+
406
+ ```ts
407
+ import {
408
+ createUuidV7MaskingCodec,
409
+ isUuidSlugError,
410
+ } from "@anizoptera/uuid-slug";
411
+
412
+ function createPublicIdGenerator(seed: string) {
413
+ const maskingCodec = createUuidV7MaskingCodec({ maskSeed: seed });
414
+ if (isUuidSlugError(maskingCodec)) return maskingCodec;
415
+ return maskingCodec.generateMaskedUuidV7Slug;
416
+ }
417
+ ```
418
+
419
+ Call `createPublicIdGenerator(seed)` at startup and check its result. Keep the returned function
420
+ and call it for each new ID; key derivation runs once. Masking-codec methods need no `bind`.
421
+
422
+ **Generate the seed; do not think one up.** For example, run `openssl rand -base64 32` and
423
+ store the result outside your source repository. Seeds shorter than 16 bytes are rejected, but
424
+ length alone does not make a seed unpredictable: a known UUID/slug pair allows offline guesses.
425
+
426
+ Keep the seed and `keyDerivationIterations` stable for as long as issued slugs must remain readable.
427
+ Changing either derives different keys; retain the old settings in `previousMasks` during
428
+ rotation. `keyDerivationIterations` defaults to `1`; increasing it adds construction and guessing cost,
429
+ but does not turn a human-chosen seed into a suitable secret.
430
+
431
+ The application creates one UUIDv7 masking codec from a stable secret seed. Encoding compresses the UUIDv7's
432
+ fixed fields, adds a 16-bit check, applies the keyed reversible transform, then writes the selected
433
+ slug alphabet. Decoding reverses those steps and rejects a value when its check does not match.
434
+ Create the masking codec once and reuse it; changing its seed changes the mapping.
435
+
436
+ A supported UUIDv7 carries 116 bits that the masked format must preserve: the version and
437
+ variant are fixed, and the timestamp is stored as a 42-bit offset from the codec's configured
438
+ start. 22 base64url
439
+ characters hold 132 bits, so the spare 16 carry a check for incorrect decoding. Two things follow,
440
+ and both are part of the contract rather than implementation detail:
87
441
 
88
442
  - **A decoded slug is a candidate, not a proof.** Roughly one random 22-character string in
89
- 65,536 passes the check and decodes to a well-formed, possibly unissued UUID. Look the result
90
- up in your own store; a wrong candidate is then a miss rather than a wrong answer. Every extra
91
- distinct schema you try adds another opportunity for false acceptance; the combined rate is
443
+ 65,536 passes the check and decodes to a well-formed, possibly unissued UUID. When accessing a
444
+ stored record, check that it exists and that the caller may access it. A wrong candidate can name
445
+ an existing record: a lookup alone does not prove correct decoding. Every extra
446
+ mask you try adds another opportunity for false acceptance; the combined rate is
92
447
  at most the sum of the individual rates. Keep the rotation list short.
93
- - **Masking refuses a timestamp at or past 2^42 ms** — the year 2109 — with `invalid_timestamp`,
94
- because those six bits are spent on the check. Truncating instead would let two UUIDs share one
95
- slug, which nothing could recover from. Direct slugs have no such limit.
448
+ - **Masking keeps the UUIDv7 timestamp and accepts a configurable range of `2^42`
449
+ milliseconds.** `timestampRangeStartUnixMs` sets the inclusive first millisecond; the inclusive
450
+ last is `timestampRangeStartUnixMs + MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS`. The default start is `0`, which
451
+ preserves existing slugs. Masking returns `invalid_timestamp` outside the selected range.
452
+ Truncating instead would let
453
+ two UUIDs share one slug, which nothing could recover from. Plain slugs have no such limit;
454
+ registered sentinels are always plain slugs and therefore retain the full UUIDv7 timestamp range.
455
+
456
+ Set `timestampRangeStartUnixMs` to the earliest timestamp your application needs to mask. Omit it
457
+ to preserve the default range and existing slugs.
96
458
 
97
- **Sentinels** are reserved UUIDs that skip masking on purpose, so they stay recognisable in
98
- logs and support tickets. The defaults always encode to these fixed slugs:
459
+ ### Sentinels
460
+
461
+ Sentinels are application-selected UUIDv7 values that are never masked, so they stay
462
+ recognisable in logs and support tickets. Codecs default to no sentinels; configure only identities
463
+ your application has reserved:
99
464
 
100
465
  | Name | UUID | Slug |
101
466
  | --------------- | -------------------------------------- | ------------------------ |
102
467
  | `nil` | `00000000-0000-7000-8000-000000000000` | `AAAAAAAAcACAAAAAAAAAAA` |
103
- | `anonymousUser` | `00000000-0001-7000-8000-000000000000` | `AAAAAAABcACAAAAAAAAAAA` |
104
- | `unknownUser` | `00000000-0002-7000-8000-000000000000` | `AAAAAAACcACAAAAAAAAAAA` |
468
+ | `anonymous` | `00000000-0001-7000-8000-000000000000` | `AAAAAAABcACAAAAAAAAAAA` |
469
+ | `unknown` | `00000000-0002-7000-8000-000000000000` | `AAAAAAACcACAAAAAAAAAAA` |
105
470
 
106
- Read the names, UUIDs and slugs from `codec.sentinels`. Pass your own list as `sentinels` to replace the defaults:
471
+ Read the validated names, UUIDs, and slugs from `maskingCodec.sentinels`:
107
472
 
108
473
  ```ts
109
- const ids = createUuidSlugCodec({
110
- mask: { seed },
111
- sentinels: [{ name: "unknownUser", uuid: "00000000-0002-7000-8000-000000000000" }],
112
- });
113
- console.table(ids.sentinels);
474
+ import { createUuidV7MaskingCodec, isUuidSlugError } from "@anizoptera/uuid-slug";
475
+
476
+ function createSentinels(seed: string) {
477
+ const maskingCodec = createUuidV7MaskingCodec({
478
+ maskSeed: seed,
479
+ sentinels: [{ name: "unknownUser", uuid: "00000000-0002-7000-8000-000000000000" }],
480
+ });
481
+ return isUuidSlugError(maskingCodec) ? maskingCodec : maskingCodec.sentinels;
482
+ }
114
483
  ```
115
484
 
485
+ Each sentinel name must be nonempty and unique within the masking codec. Each sentinel UUID must also be
486
+ unique. Its input accepts every UUID text spelling above; `maskingCodec.sentinels` exposes normalized lowercase text.
487
+
488
+ Sentinels keep their spelling across seed rotation when the alphabet and reserved UUIDs stay the
489
+ same. This lets reserved identities remain recognizable while ordinary IDs use the new mask.
490
+ The example named `nil` is an application sentinel, not the all-zero UUID; that UUID
491
+ is not UUIDv7 and cannot be a masking-codec sentinel.
492
+
116
493
  Keep sentinel definitions stable while their slugs are in use. Decoding checks sentinels first, so they
117
494
  are reserved even if a mask could produce the same text. Encoding rejects a non-sentinel UUID
118
- whose masked output collides with a reserved slug, using `invalid_mask_schema`; it never returns
495
+ whose masked output collides with a reserved slug, using `invalid_mask`; it never returns
119
496
  a slug that would decode to the wrong sentinel.
120
497
 
498
+ ## Ordering and key distribution
499
+
500
+ Both plain alphabets keep the timestamp at the start. UUIDv7s from the same millisecond share
501
+ that prefix; nearby milliseconds can share much of it. Base64url retains this grouping but can
502
+ reverse time order: the prefixes `AAAAAAAz` and `AAAAAAA0` encode consecutive milliseconds,
503
+ yet ASCII sorting puts the second first.
504
+
505
+ Base32hex preserves UUID byte order because its alphabet, `0-9a-v`, follows numeric order and
506
+ the most significant bits come first. Equal-length slugs sort by timestamp even when a character
507
+ spans two UUID fields. This is timestamp order, not event order: clocks can move backwards, and
508
+ UUIDv7 does not promise creation order within a millisecond.
509
+
510
+ `uuidV7StringBounds(ms)` returns two search keys because one millisecond identifies a set, not one UUID:
511
+ the timestamp fixes the first 48 bits while 74 payload bits can differ. The first key sets those
512
+ payload bits to zero and the second sets them to one. Pass an inclusive end millisecond to cover a
513
+ longer interval. Use these bounds only where comparison follows UUID wire-byte order; SQL Server's
514
+ `uniqueidentifier` order does not.
515
+
516
+ Use plain slugs to keep time grouping, and base32hex for chronological text sorting.
517
+ Masking scrambles the timestamp with the other fields. It can suit storage that benefits from
518
+ spreading new keys across text ranges instead of grouping them by time.
519
+
520
+ Plain UUIDv7 base32hex filenames sort chronologically without decoding. Masked filenames need
521
+ decoding or separate dates for that view. Plain URLs need no secret; masked URLs require you to
522
+ keep the mask as long as the links must work. Neither grants access to the record.
523
+
524
+ Masking does not guarantee even key distribution or faster database writes. Measure with your
525
+ storage's sorting and partition rules. If you partition by hash, hash the UUID rather than its
526
+ slug so a change of spelling does not move the record. Changing only public URLs does not change
527
+ an index on the original UUID.
528
+ Sentinels remain plain slugs and keep their original grouping.
529
+
530
+ With unchanged settings, built-in masking gives the same UUID the same slug. URLs and filenames
531
+ stay stable, but anyone can recognize repeated uses of that slug. Key rotation can give the
532
+ record a different slug; compare decoded UUIDs to check whether two slugs identify the same record.
533
+
121
534
  ## What masking is not
122
535
 
123
536
  Masking uses a four-round Feistel network with HalfSipHash-2-4 round functions and a
124
- seed-derived key schedule. It removes a directly readable timestamp; this package does not
125
- establish a confidentiality strength for that construction or resistance to known-pair attacks.
126
- A reference-vector test for the round function does not establish those properties for the
127
- whole construction. See [the mechanism and its limits](docs/design.md).
537
+ seed-derived key schedule. It removes the directly recognizable UUIDv7 field layout. The package makes no
538
+ claim about how hard the mask is to break, with or without known UUID and slug pairs. The round
539
+ function is tested against reference vectors; that says nothing about the whole construction. See
540
+ [the mechanism and its limits](docs/design.md).
128
541
 
129
542
  Masked slugs are not authentication tokens or capabilities. The check detects many incorrect
130
543
  decodes; it is not a message authentication code. Confirm decoded candidates against your store
131
- and enforce authorization separately. Supplying a custom `mix` still leaves the same short check
544
+ and enforce authorization separately. Supplying a custom transform still leaves the same short check
132
545
  and does not turn the API into an authenticated-token system.
133
546
 
134
- **Supply your own secret seed for real identifiers.** Omitting `mask` uses the published default
135
- seed, so anyone can decode the result. Reserve that default for tests and demos.
136
- Masked operations are codec methods; `defaultCodec` uses the same public seed.
547
+ ```ts
548
+ import { isUuidSlugError } from "@anizoptera/uuid-slug";
549
+ import type { UuidV7MaskingCodec, UuidV7String } from "@anizoptera/uuid-slug";
550
+
551
+ async function findAuthorizedRecord<Record>(
552
+ maskingCodec: UuidV7MaskingCodec,
553
+ slug: string,
554
+ findByUuid: (uuid: UuidV7String) => Promise<Record | undefined>,
555
+ canRead: (record: Record) => boolean,
556
+ ) {
557
+ const uuid = maskingCodec.uuidToString(slug);
558
+ if (isUuidSlugError(uuid)) return uuid;
559
+ const record = await findByUuid(uuid);
560
+ return record !== undefined && canRead(record) ? record : undefined;
561
+ }
562
+ ```
563
+
564
+ **Supply your own secret seed for real identifiers.** Masking-codec construction fails with
565
+ `invalid_mask` when neither `maskSeed` nor `mask` is supplied, and when both are supplied. Pass
566
+ `maskSeed` for a plain secret. Pass `mask` for a mask you derived separately, for
567
+ `UUID_V7_TEST_MASK`, or for seed material that also needs a label or a key-derivation work factor.
568
+ For tests and demos that need stable public bytes,
569
+ select `UUID_V7_TEST_MASK` explicitly; anyone can decode identifiers produced with it.
570
+ The masked examples in the TL;DR use this test mask; every row there identifies the same UUIDv7.
571
+
572
+ A browser can use a masked ID returned by your service without knowing the seed. Keep private
573
+ masking and decoding on a trusted service; shipping the seed in client code makes it public.
574
+ Plain-slug generation and conversion need no seed and can run entirely in the client.
137
575
 
138
576
  ## Handling errors
139
577
 
140
- Parsing, decoding, formatting, conversion, byte generation, and explicit-timestamp generation
141
- return `UuidSlugError | T`. Check `instanceof Error` before using the value. String-only
142
- generators return a value directly and throw on failure; constructing an invalid codec throws too.
578
+ Fallible synchronous operations return `T | UuidSlugError`; async mask construction resolves to
579
+ the same union. Pass that union directly into the next compatible operation and use
580
+ `isUuidSlugError` once at the boundary. The guard checks the `__failure` protocol marker first,
581
+ then recognizes unmarked package errors from older copies across realms. The marker is a routing
582
+ protocol, not proof of origin; untrusted data still belongs in the documented parser or validator.
583
+
584
+ ```ts
585
+ import { isUuidSlugError, plainSlugToUuidBytes, uuidStringToPlainSlug } from "@anizoptera/uuid-slug";
586
+
587
+ function saveUuid(uuidText: string, save: (bytes: Uint8Array) => void) {
588
+ const bytes = plainSlugToUuidBytes(uuidStringToPlainSlug(uuidText));
589
+ if (isUuidSlugError(bytes)) return bytes;
590
+ save(bytes);
591
+ }
592
+ ```
593
+
594
+ The inner conversion's failure passes through the outer conversion unchanged. Check an
595
+ intermediate result only when the caller also needs that intermediate successful value.
596
+
597
+ Use the error's `code` for handling and its `message` for diagnostics. `UuidSlugErrorCode` is the
598
+ exported code type. Each code has a named constant such as `INVALID_BUFFER`, so callers never need
599
+ to copy a code string or recover one from a collection. Do not parse messages; they can add details
600
+ without changing the code. Errors wrapping failed entropy draws, clock readings, and custom
601
+ transform calls preserve the original exception as `cause`.
143
602
 
144
- Use the error's `code` for handling and its `message` for diagnostics. `UuidSlugErrorCode` and
145
- `UUID_SLUG_ERROR_CODES` are the exported type and runtime list of codes. Errors wrapping failed
146
- entropy draws, clock readings, and custom `mix` calls preserve the original exception as `cause`.
603
+ `uuidBytesToPlainSlug` and `plainSlugToUuidBytes` convert one 16-byte UUID, not arbitrary binary data. Without an
604
+ offset, `uuidBytesToPlainSlug` requires exactly 16 bytes; an explicit offset selects 16 bytes from a larger
605
+ array. `plainSlugToUuidBytes` accepts mixed-case base32hex and rejects nonzero padding bits.
606
+ `isPlainUuidSlug` checks canonical output spelling and returns a boolean, not an error.
607
+
608
+ ```ts
609
+ import { BASE32HEX, uuidBytesToPlainSlug } from "@anizoptera/uuid-slug";
610
+
611
+ function encodeStoredUuid(bytes: Uint8Array) {
612
+ return uuidBytesToPlainSlug(bytes, BASE32HEX);
613
+ }
614
+ ```
147
615
 
148
616
  ## Types
149
617
 
150
- Branded types distinguish the values returned by this library. Their marker is optional:
151
- assigning a string does not validate it. Use guards to check format and your store to check issuance.
152
-
153
- - Strings: `UuidString`, `UuidV4String`, `UuidV7String`, `Base64UrlString`.
154
- - Slugs: `UuidSlug` (either alphabet), `UuidV4Slug`, `UuidV7Slug`; masked ones are base64url only
155
- — `MaskedUuidSlug`, `MaskedUuidV7Slug`, `SentinelUuidV7Slug`, and `PublicUuidV7Slug` for
156
- "masked or sentinel", which is what a masking call returns. `SlugAlphabet` names the two
157
- alphabets, and `UuidBytes` brands 16 raw bytes — for annotating storage of your own, which is why
158
- it appears in no signature here: a byte writer returns the caller's output array, which can be
159
- longer than the UUID range it writes.
160
- - Shapes: `UuidSlugCodec` and `UuidSlugCodecOptions`, `MaskSchema`, `MaskSchemaOptions` and `AsyncMaskSchemaOptions`,
161
- `UuidV7Sentinel` and `UuidV7SentinelDefinition`, `UuidV7Generator` and
162
- `UuidV7GeneratorOptions`, `FreshValidationOptions`, `UuidSlugErrorCode`.
163
-
164
- **Some masked slugs also pass direct-slug guards.** Canonical trailing bits, version, and variant
618
+ Branded types distinguish values this library has validated or produced. Plain strings and byte
619
+ arrays are not assignable to them; pass raw input directly to package operations or use a guard when
620
+ you need to retain the narrowed type. A brand proves format, not issuance or permission to access a record.
621
+ JavaScript consumers do not need TypeScript. The shipped declarations compile with TypeScript 5.0
622
+ and newer.
623
+
624
+ Public identifier, configuration, and selector string inputs accept primitive JavaScript strings
625
+ and genuine `String` objects. This includes identifiers, output selectors, timestamp text, mask seeds and labels, sentinel names,
626
+ and migration formats. The package reads a wrapper's intrinsic value without invoking custom
627
+ coercion; TypeScript callers use primitive strings.
628
+
629
+ Use `BASE64URL`, `BASE32HEX`, `UUID_TEXT_LOWERCASE`, `UUID_TEXT_UPPERCASE`, `NIL_UUID`, `MAX_UUID`,
630
+ `MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS`, and the named error-code constants instead of copying their values.
631
+ `NIL_UUID` and `MAX_UUID` are canonical generic UUID text; they do not claim a UUID version.
632
+ Migration readers accept `SEEDED_MASK_FORMAT`, `FIXED_MASK_FORMAT`, or `PLAIN_SLUG_FORMAT`;
633
+ their TypeScript type permits only formats enabled when the reader was created.
634
+
635
+ | Type | What the value is |
636
+ | --- | --- |
637
+ | `UuidText`, `UuidV4Text`, `UuidV7Text` | Valid UUID text in any accepted spelling; the version is known where the name says so. |
638
+ | `UuidString`, `UuidV4String`, `UuidV7String` | Canonical UUID text; the version is known where the name says so. |
639
+ | `UppercaseUuidString`, `UppercaseUuidV4String`, `UppercaseUuidV7String` | Uppercase UUID text; the version is known where the name says so. |
640
+ | `UuidTextCase`, `UuidStringFor`, `UuidV4StringFor`, `UuidV7StringFor` | A preset choice and the UUID text type selected by it. |
641
+ | `UuidVersion` | The complete four-bit version field: `0` through `15`. |
642
+ | `PlainUuidSlug`, `PlainUuidV4Slug`, `PlainUuidV7Slug` | A plain slug in either alphabet; the version is known where the name says so. |
643
+ | `MaskedUuidV7Slug` | A masked UUIDv7 slug; its check bits require masking-codec decoding. |
644
+ | `SentinelUuidV7Slug` | A reserved plain UUIDv7 slug, also usable wherever `PlainUuidV7Slug` is accepted. |
645
+ | `MaskedOrSentinelUuidV7Slug` | Masked or sentinel: what a masking call returns. |
646
+ | `UuidBytes`, `UuidV4Bytes`, `UuidV7Bytes` | `UuidBytes` proves the 16-byte shape; v4/v7 brands also prove version and variant bits. |
647
+ | `UuidByteInput`, `UuidInput` | The byte forms and complete keyless input domain accepted by generic conversion helpers. |
648
+ | `SlugAlphabet` | `"base64url"` or `"base32hex"`. |
649
+ | `GeneratedUuidV7`, `UuidStringResult`, `UuidBytesResult`, `PlainUuidSlugResult` | The paired generation result and version-preserving result types for typed wrapper functions. |
650
+ | `Uuid`, `UuidInspection`, `UuidV7Bounds`, `UuidV7Payload`, `UuidV7PayloadLayout` | An immutable parsed UUID and the typed inspection, search-bound, and caller-declared UUIDv7 payload results it exposes. |
651
+ | `UuidV7Instant` | A supported host time accepted by UUIDv7 generation, including exact epoch nanoseconds. |
652
+ | `UuidV7MaskingCodec`, `UuidV7MaskingCodecOptions`, `UuidV7PreviousMask`, `UuidV7Mask`, `UuidV7MaskOptions`, `AsyncUuidV7MaskOptions`, `CustomUuidV7MaskOptions`, `UuidV7Sentinel`, `UuidV7SentinelConfig` | The masking codec, what `createUuidV7MaskingCodec` takes, and the retained mask and sentinel shapes it accepts and exposes. |
653
+ | `UuidV7Generator`, `UuidV7GeneratorOptions`, `UuidV7ClockRollbackPolicy`, `UuidRandomFill`, `UuidV7TimestampWindow`, `UuidSlugMigrationDecoder`, `UuidSlugMigrationOptions`, `UuidSlugMigrationFormat`, `UuidSlugErrorCode` | A generator, its clock and rollback choices, an explicit custom-entropy callback, timestamp validation, migration controls, and error codes. |
654
+ | `GenerateUuidV7Options`, `GeneratePlainUuidV7SlugOptions`, `GenerateUuidV7BytesOptions`, `GenerateUuidV7BytesIntoOptions`, `GenerateUuidV7WithPlainSlugOptions`, `GenerateUuidV7WithMaskedSlugOptions` | Reusable option shapes for each UUIDv7 output job. |
655
+
656
+ A brand narrows what a call accepts at compile time. A value already typed as the wrong kind is
657
+ rejected before it runs, with or without an output buffer:
658
+
659
+ | Value typed as | Rejected by | Why |
660
+ | --- | --- | --- |
661
+ | Masked or possibly masked (`MaskedUuidV7Slug`, `MaskedOrSentinelUuidV7Slug`) | Root conversion and plain-slug readers | A masked value needs its masking codec; a sentinel alone remains a plain slug. |
662
+ | UUID text (`UuidString` and its versions) | Source-specific slug readers and migration readers | Those methods require encoded slug input. |
663
+ | Known v4 (`UuidV4String`, `PlainUuidV4Slug`, `UuidV4Bytes`) | UUIDv7 timestamp validation and masking | UUIDv4 has no UUIDv7 timestamp or masked form. |
664
+ | `unknown` | All conversion signatures | Narrow untyped data before calling; JavaScript values are still checked safely at runtime. |
665
+
666
+ Parsers accept ordinary strings and validate them at runtime. Choose the decoder from your ID
667
+ format: plain and masked base64url spellings overlap. A masking codec reads a 22-character slug as
668
+ masked when it passes the codec's check and as plain otherwise; keyless root readers always read
669
+ it as plain. UUID values with an unknown version also receive runtime version checks.
670
+ Lossless conversion preserves a known UUID version in its result type. Byte conversion returns an
671
+ owned branded array when it allocates and the caller's exact array subtype when it writes into
672
+ supplied storage.
673
+
674
+ **Some masked slugs also pass plain-slug guards.** Canonical trailing bits, version, and variant
165
675
  can all match by chance. A guard answers "is this well formed", never "is this mine". Decode with
166
- the matching API and look up the candidate; a brand or guard cannot establish issuance.
676
+ the matching API. For access to stored records, check existence and authorization separately.
167
677
 
168
678
  ## API
169
679
 
170
- The **Where** column tells you whether to import a function or call a codec method.
171
-
172
- - **codec + top level.** Keyless generation is available directly, for example `import { uuidV7 }`.
173
- A codec can use your supplied v7 generator; top-level generation uses the platform adapter.
174
- - **codec only.** Uses your configured keys or sentinels.
175
- - **module only.** Import these functions directly. Codec settings do not affect them.
176
-
177
- | Method | Where | Returns | What it does |
178
- | ------------------------------------------------------- | ----------------- | ----------------------------- | ---------------------------------------- |
179
- | `uuidV4()` / `uuidV7()` | codec + top level | UUID string | Generate. |
180
- | `uuidV4Bytes(out?, offset?)` / `uuidV7Bytes(...)` | codec + top level | `UuidSlugError \| Uint8Array` | Generate into a buffer you own. |
181
- | `uuidV7At(ms)` / `uuidV7BytesAt(ms, out?, offset?)` | codec + top level | `UuidSlugError \| ...` | Generate at an instant you name. |
182
- | `uuidV4Slug(alphabet?)` / `uuidV7Slug(alphabet?)` | top level | direct slug | Generate and encode in one step. |
183
- | `codec.uuidV4Slug()` / `codec.uuidV7Slug()` | codec | direct slug | Same, in the codec's `slugAlphabet`. |
184
- | `uuidV7MaskedSlug()` | codec only | `PublicUuidV7Slug` | Generate a masked or sentinel slug. |
185
- | `uuidV7ToMaskedSlug(uuid)` / `maskedSlugToUuidV7(slug)` | codec only | `UuidSlugError \| ...` | Masked slug, both ways; v7 only. |
186
- | `maskedSlugToUuid(slug)` | codec only | `UuidSlugError \| ...` | Unmask, accepting any UUID version. |
187
- | `validateMaskedSlugFresh(slug, opts?)` | codec only | `UuidSlugError \| ...` | Unmask, then check the freshness window. |
188
- | `sentinels` | codec only | array | The reserved values this codec knows. |
189
- | `migration(options?)` | codec only | migration reader | Read selected old formats without changing new output. |
190
- | `uuidToSlug(uuid, alphabet?)` / `slugToUuid(slug)` | module only | `UuidSlugError \| ...` | Direct slug, both ways. |
191
- | `parseUuid` / `formatUuid` | module only | `UuidSlugError \| ...` | UUID string to bytes and back. |
192
- | `parseUuidSlug` / `formatUuidSlug` | module only | `UuidSlugError \| ...` | Slug to bytes and back. |
193
-
194
- There is no `uuidToMaskedSlug`: masking is defined for UUIDv7 only, because a v7 is the version
195
- that leaks a creation time and 22 characters have no room for a version tag as well as the check.
196
-
197
- The `At` pair supports backfilling with a known timestamp. It takes the instant first and returns
198
- an error unless it is a whole number of Unix milliseconds in 0..2^48-1. Its interaction with
199
- current-time generation is runtime-specific; within-millisecond ordering is not promised.
680
+ Generation, conversion, and validation return the result below or `UuidSlugError`. Generation with
681
+ no arguments or only a spelling preset returns its result directly; it throws `UuidSlugError` with
682
+ code `rng_unavailable` when generation cannot obtain secure randomness. When you supply
683
+ an output array, the exact array and its type are preserved; otherwise byte outputs are new plain
684
+ `Uint8Array` values. Invalid input leaves caller storage unchanged.
685
+
686
+ Generator, masking-codec, and migration methods do not depend on `this`; they can be passed as callbacks
687
+ without binding them first. Each export's full contract, accepted input, result, and errors, is in
688
+ its declaration comment; your editor shows it on hover.
689
+
690
+ ### Generate IDs
691
+
692
+ Import these functions from the package root. UUIDv7 text and byte methods also exist on an
693
+ independent generator; UUIDv4 and plain-slug generation remain module-level.
694
+
695
+ | Call | Successful result |
696
+ | --- | --- |
697
+ | `generateUuidV4(textCase?)` / `generateUuidV7(textCaseOrOptions?)` | UUID text in the selected case, typed with its version. UUIDv7 options may set `at` and `generator`. |
698
+ | `generateUuidV4WithRandomFill(fill, textCase?)` | UUIDv4 text from an explicit synchronous entropy source. |
699
+ | `generatePlainUuidV4Slug(alphabet?)` / `generatePlainUuidV7Slug(alphabetOrOptions?)` | A plain slug in the chosen alphabet, typed with its UUID version. UUIDv7 options may set `at` or select a generator. |
700
+ | `generateUuidV7WithPlainSlug(alphabetOrTextCaseOrOptions?, textCase?)` | UUIDv7 text and its plain slug from one generated value; options may set `at` or select a generator. |
701
+ | `generateUuidV4Bytes()` / `generateUuidV7Bytes(options?)` | A new 16-byte array, typed with its UUID version. UUIDv7 options may set `at` and `generator`. |
702
+ | `generateUuidV4Bytes(out, offset?)` / `generateUuidV7Bytes(out, offset?)` | Your output array, with the UUID written at the offset. UUIDv7 also accepts `{ at, generator, output, outputOffset }`. |
703
+ | `generateUuidV7Value(options?)` | An immutable UUIDv7; options may set `at`, select a generator, or retain a masking codec. |
704
+ | `uuidV7StringBounds(ms, textCase?)` / `uuidV7StringBounds(startMs, endMs, textCase?)` | Inclusive canonical UUID bounds for one millisecond or an inclusive interval. |
705
+ | `uuidV7ByteBounds(startMs, endMs?)` | The same inclusive bounds as two owned byte arrays. |
706
+ | `createUuidV7Generator(options?)` | An independent UUIDv7 sequence using platform cryptographic entropy; invalid numeric ranges or clock policies return `UuidSlugError`. |
707
+ | `createUuidV7GeneratorWithRandomFill(fill, options?)` | An independent UUIDv7 generator using an explicit synchronous entropy source. |
708
+
709
+ ### Convert and inspect IDs
710
+
711
+ Root functions need no key. They accept UUID text, UUID bytes, and both plain-slug alphabets. A
712
+ known UUID version remains in the result type.
713
+
714
+ | Call | Successful result |
715
+ | --- | --- |
716
+ | `uuidToString(uuid, textCase?)` / `(bytes, byteOffset, textCase?)` | Canonical UUID text from UUID text, bytes, or a plain slug, or from one UUID inside a larger array. |
717
+ | `uuidToBytes(uuid, output?, outputOffset?)` / `(bytes, byteOffset, output?, outputOffset?)` | New UUID bytes or the exact supplied output array, read from a standalone array or from one UUID inside a larger array. |
718
+ | `uuidToPlainSlug(uuid, alphabet?)` / `(bytes, byteOffset, alphabet?)` | A plain slug from UUID text, bytes, or a plain slug, or from one UUID inside a larger array. |
719
+ | `parseUuid(uuid, maskingCodec?)` | An immutable UUID for repeated inspection and conversion; the optional codec also accepts masked input and stays available to the value. |
720
+ | `extractUuidVersion(uuid)` | The UUID version nibble from UUID text, exact bytes, or a plain slug. |
721
+ | `extractUuidV7UnixMs(value, offset?)` | Unix milliseconds from UUIDv7 text, a plain slug, or bytes. |
722
+ | `extractUuidV7Payload(value, layout, offset?)` | Timestamp and caller-declared payload fields, with all other payload bits unchanged. |
723
+ | `validateUuidV7StringUnixMs(uuid, window, textCase?)` / `validatePlainUuidV7SlugUnixMs(slug, window)` | UUIDv7 text in the selected case, or a canonical plain slug, after checking its timestamp. Base32hex results are lowercase. |
724
+
725
+ Use `parseUuid` when one UUID needs several operations. It validates and copies the input once.
726
+ Serialization returns canonical UUID text and intentionally drops the codec and payload layout.
727
+ Mixed-version parsed values support text, byte, plain-slug and inspection calls without narrowing.
728
+ When only some values retain a codec or payload layout, pass that configuration explicitly.
729
+ Each preset is independent; binding its method to the UUID preserves the corresponding default.
200
730
 
201
- Both masking entry points return a raw sentinel slug when the UUID is registered as a sentinel.
202
- Their result type is `PublicUuidV7Slug`, the union of masked and sentinel slugs.
203
-
204
- Also exported, all module-level:
205
-
206
- - Type guards: `isUuidString`, `isUuidV4String`, `isUuidV7String`, `isUuidSlug`, `isUuidV4Slug`,
207
- `isUuidV7Slug`, and `isUuidV7Bytes` for 16 bytes you already hold.
208
- - base64url helpers: `encodeBase64Url`, `decodeBase64Url`, `isBase64Url`. `decodeBase64Url` returns
209
- a view over exactly the bytes it decoded — with or without an `out` buffer — so `.length` is the
210
- decoded length, never the buffer's. Given `out`, that view shares your buffer's memory.
211
- - `extractUuidV7Timestamp` — the instant a v7 was minted at, and an error for anything that is
212
- not a v7, because a v4's first six bytes are random and would otherwise read back as a
213
- plausible date. `hasUuidV7Entropy` answers whether the 74 random bits are anything but
214
- all-zero or all-one. This rejects obvious degeneracy; it does not measure unpredictability.
215
- - `createMaskSchema` builds a schema from a seed; `createMaskSchemaAsync` adds cooperative cancellation; `DEFAULT_MASK_SCHEMA` is the one a codec uses
216
- when you pass no `mask`, exported so `mask: DEFAULT_MASK_SCHEMA` can be a visible choice rather
217
- than an omission. `UUID_V7_SENTINEL_DEFINITIONS` is the default sentinel list.
218
- - `createUuidV7Generator(options)` builds a generator from your own `clock` and `fillRandom`, for
219
- a `generator:` codec option. Its options type is `UuidV7GeneratorOptions`.
220
- - `UuidSlugError` and its subclass `UuidRuntimeError`, which is what the generators throw when the
221
- runtime has no usable randomness. `UuidSlugErrorCode` types the `code` property.
222
-
223
- ### Codec options
731
+ ```ts
732
+ const uuid = parseUuid(input, codec);
733
+ if (uuid instanceof Error) return uuid;
734
+
735
+ const facts = uuid.inspect();
736
+ const stored = uuid.toBytes();
737
+ const publicId = uuid.toMaskedSlug();
738
+ ```
739
+
740
+ ### Use a masking codec
741
+
742
+ A masking codec holds immutable masking keys, sentinels, rotation, and writer settings.
743
+ These methods use that configuration. New output uses its current mask;
744
+ readers also try its configured previous masks.
745
+
746
+ | Member | Successful result |
747
+ | --- | --- |
748
+ | `generateUuidV7Value(options?)` | An immutable UUIDv7 with this codec retained; options may set `at` or select a generator. |
749
+ | `generateMaskedUuidV7Slug(options?)` | A new `MaskedOrSentinelUuidV7Slug`; options may set `at` or select a generator. |
750
+ | `generateUuidV7WithMaskedSlug(textCaseOrOptions?)` | UUIDv7 text and its masked or sentinel slug from one generated value; options may set `at`, select a generator, or select UUID text case. |
751
+ | `parseUuid(uuid)` | The same parsed value as top-level `parseUuid(uuid, codec)`, with this codec retained. |
752
+ | `uuidToString(uuid, textCase?)` / `(bytes, byteOffset, textCase?)` | UUID text from any supported UUID form, or from one UUID inside a larger array. |
753
+ | `uuidToBytes(uuid, output?, outputOffset?)` / `(bytes, byteOffset, output?, outputOffset?)` | UUID bytes from any supported UUID form, or from one UUID inside a larger array. |
754
+ | `uuidToPlainSlug(uuid, alphabet?)` / `(bytes, byteOffset, alphabet?)` | A plain slug from any supported UUID form, or from one UUID inside a larger array. |
755
+ | `uuidToMaskedSlug(uuid)` | A masked or sentinel slug from any supported UUIDv7 form. |
756
+ | `plainToMaskedUuidSlug(plainUuidSlug)` | A `MaskedOrSentinelUuidV7Slug` from either plain UUIDv7 slug spelling. |
757
+ | `maskedToPlainUuidSlug(maskedUuidSlug, alphabet?)` | A plain UUIDv7 slug from a masked slug or registered sentinel. |
758
+ | `maskedSlugToUuidString(maskedUuidSlug, textCase?)` | UUIDv7 text when the caller knows the slug is masked. |
759
+ | `maskedSlugToUuidBytes(maskedUuidSlug, output?, outputOffset?)` | UUIDv7 bytes when the caller knows the slug is masked. |
760
+ | `extractMaskedUuidV7UnixMs(maskedUuidSlug)` | Unix milliseconds from a masked slug or sentinel. |
761
+ | `extractMaskedUuidV7Payload(maskedUuidSlug, layout)` | Timestamp and caller-declared payload fields from a masked slug or sentinel. |
762
+ | `validateMaskedUuidV7SlugUnixMs(maskedUuidSlug, window)` | A canonical slug, narrowed to `MaskedOrSentinelUuidV7Slug` after checking its timestamp. Base32hex results are lowercase. |
763
+ | `sentinels` | Readonly reserved names, UUIDs, and slugs. |
764
+ | `createUuidSlugMigrationDecoder(options?)` | A reader for the old formats you enable; new output stays unchanged. |
765
+
766
+ The universal methods read a 22-character base64url slug as masked when it passes the codec's
767
+ check and as plain otherwise. The source-specific methods apply the meaning the caller states
768
+ instead, because that string cannot identify its meaning itself.
769
+
770
+ A byte offset is the zero-based index where one 16-byte UUID starts inside a larger `Uint8Array`.
771
+ Omit it for a standalone 16-byte array. Output offsets select where a method writes; input offsets
772
+ select where it reads. Bytes outside that 16-byte range stay unchanged. An offset of `0` always means
773
+ the same as omitting it. Only `Uint8Array` input accepts a non-zero input offset: every other
774
+ accepted form holds exactly one UUID, with no surrounding bytes to skip.
775
+
776
+ Masking is possible for any UUID version, but this library supports it only for UUIDv7.
777
+ Its fixed version, variant, and 42-bit timestamp offset leave room for a 16-bit check without
778
+ lengthening the default 22-character slug. Plain slugs support every UUID version.
779
+
780
+ Use an independent generator when the application owns the clock:
224
781
 
225
782
  ```ts
226
- createUuidSlugCodec({
227
- mask: { seed: "…", keyIterations: 1 }, // or your own { id, mix } schema
228
- sentinels: [{ name: "nil", uuid: "…" }],
229
- previousMasks: [{ seed: "…previous seed…" }],
230
- acceptUnmaskedSlugs: false,
231
- slugAlphabet: "base32hex", // plain slugs only; masked slugs and sentinels stay base64url
232
- generator: myUuidV7Generator,
233
- });
783
+ import { createUuidV7Generator } from "@anizoptera/uuid-slug";
784
+
785
+ function createEventGenerator(readUnixMs: () => number) {
786
+ return createUuidV7Generator({ readUnixMs });
787
+ }
234
788
  ```
235
789
 
236
- The current masked format is fixed: 22 base64url characters, including a 16-bit check.
237
- Changing `slugAlphabet` affects plain slugs only.
790
+ Both masking entry points return a raw sentinel slug when the UUID is registered as a sentinel.
791
+ Their result type is `MaskedOrSentinelUuidV7Slug`, the union of masked and sentinel slugs.
792
+
793
+ The byte decoder returns a new plain `Uint8Array` branded as `UuidV7Bytes` when storage is omitted.
794
+ When storage is supplied, it validates and decodes before writing, then returns that exact array;
795
+ an error leaves the array unchanged.
796
+
797
+ Each decoder accepts every value that a supported matching encoder can produce. Masked decoding
798
+ always accepts both alphabets, sentinels, and current or previous masks. Migration adds only
799
+ the old formats you enable. Forms no supported encoder produces are invalid.
800
+
801
+ ### Constructors and guards
802
+
803
+ Also exported from the package root:
804
+
805
+ - Permissive type guards: `isUuidText`, `isUuidV4Text`, and `isUuidV7Text` accept mixed case,
806
+ canonical or compact text, UUID URNs, and brace-wrapped canonical text.
807
+ - Normalized type guards: `isUuidString`, `isUuidV4String`, and `isUuidV7String` accept lowercase
808
+ hyphenated text. Slug and byte guards are `isPlainUuidSlug`, `isPlainUuidV4Slug`,
809
+ `isPlainUuidV7Slug`, `isUuidBytes`, `isUuidV4Bytes`, and `isUuidV7Bytes`.
810
+ - `extractUuidV7UnixMs` reads Unix milliseconds from UUIDv7 text, either plain-slug alphabet,
811
+ or bytes. Use `maskingCodec.extractMaskedUuidV7UnixMs` for masked slugs and sentinels because their decoding
812
+ keys belong to the masking codec. Both return an error for other UUID versions; a v4's first six bytes
813
+ are random and must not be presented as a timestamp.
814
+ - `extractUuidVersion` reads the four-bit version field from UUID text, either plain-slug alphabet,
815
+ or bytes. It does not prove the RFC variant or that another version-specific operation accepts it.
816
+ - `deriveUuidV7Mask` builds a mask from a seed; `deriveUuidV7MaskAsync` adds cooperative
817
+ cancellation; `createCustomUuidV7Mask` adapts separate forward and reverse callbacks.
818
+ `UUID_V7_TEST_MASK` is the explicit, published-key choice for deterministic examples.
819
+ - `createUuidV7Generator(options?)` builds a generator with its own sequence state, your `readUnixMs`
820
+ or `Date.now` when omitted, and platform cryptographic entropy. Preserve-order rollback is the
821
+ default; reset and error policies require an inclusive total-skew tolerance. Invalid numeric
822
+ ranges, clock policies, and untyped malformed options return `invalid_options`. Every method on
823
+ the generator generates in its sequence: `generateUuidV7`, `generateUuidV7Bytes`,
824
+ `generatePlainUuidV7Slug`, `generateUuidV7WithPlainSlug`, and `generateUuidV7Value`. Each takes
825
+ the same spellings and `at` as its root function, without the `generator` option. The root
826
+ functions reach the same sequence by taking `{ generator }`.
827
+ - `generateUuidV4WithRandomFill` and `createUuidV7GeneratorWithRandomFill` are the explicit
828
+ custom-entropy paths. Their callback owns entropy quality and must fill every requested byte or
829
+ return `UuidSlugError`; weak or partial successful fills cannot be detected.
830
+ - `UuidSlugError`, including code `rng_unavailable` when the runtime has no usable randomness;
831
+ generation with no arguments or only a spelling preset throws that error instead of returning it.
832
+ `UuidSlugErrorCode` types the `code` property; `isUuidSlugError` recognizes package errors across
833
+ JavaScript realms and duplicate package copies.
834
+ - `BASE64URL` and `BASE32HEX` select slug output without copying string literals.
835
+
836
+ When forwarding optional settings to `generateUuidV7Value` or `generatePlainUuidV7Slug`,
837
+ an undefined value uses default generation and may throw `rng_unavailable`.
838
+ Configured branches return failures as values; handle both effects when the settings can be absent.
839
+
840
+ ### Masking codec options
238
841
 
239
- To supply a different mixing implementation, pass a `MaskSchema`: an `id` and
240
- `mix(input, output, forward)`, where `forward: false` must reverse `forward: true` for every
241
- 16-byte input. Construction runs round-trip smoke tests and throws if they fail. Passing them
242
- is not a proof of invertibility; the caller remains responsible for the complete domain.
842
+ ```ts
843
+ import { BASE32HEX, createUuidV7MaskingCodec } from "@anizoptera/uuid-slug";
844
+
845
+ function configureCodec(seed: string, previousSeed: string) {
846
+ return createUuidV7MaskingCodec({
847
+ mask: { seed, keyDerivationIterations: 1 },
848
+ sentinels: [{ name: "nil", uuid: "00000000-0000-7000-8000-000000000000" }],
849
+ previousMasks: [{ seed: previousSeed }],
850
+ maskedSlugAlphabet: BASE32HEX,
851
+ });
852
+ }
853
+ ```
243
854
 
244
- `createMaskSchema({ seed, keyIterations })` returns an error for invalid seed options.
245
- `createUuidSlugCodec` throws for invalid options, including a supplied schema that fails its
246
- smoke tests. Build a seed schema first when you want to inspect its returned error.
855
+ The masked payload is fixed at 132 bits, including a 16-bit check. `maskedSlugAlphabet` defaults to
856
+ `"base64url"`. Readers accept either masked spelling without an alphabet argument. With
857
+ `maskedSlugAlphabet: BASE32HEX`, sentinels are written as 26-character base32hex slugs; their
858
+ 22-character base64url spelling still decodes.
247
859
 
248
- For expensive derivation, await `createMaskSchemaAsync` and pass the completed schema to the codec:
860
+ To supply a different mixing implementation, call
861
+ `createCustomUuidV7Mask({ diagnosticLabel, mask, unmask })`. Each callback receives distinct 16-byte input
862
+ bytes and returns either a 16-byte result or `UuidSlugError`; `unmask` must invert `mask` for
863
+ every input. A callback may mutate and return its isolated input. The factory copies callback results
864
+ into package storage, captures the callbacks in an opaque frozen handle, and rejects invalid results
865
+ and failed round-trip probes. Unexpected throws become errors with the thrown value as their cause.
866
+ Finite probes cannot prove invertibility, so the caller remains responsible for the complete domain.
249
867
 
250
868
  ```ts
251
- import { createMaskSchemaAsync, createUuidSlugCodec } from "@anizoptera/uuid-slug";
869
+ import {
870
+ createCustomUuidV7Mask,
871
+ createUuidV7MaskingCodec,
872
+ isUuidSlugError,
873
+ } from "@anizoptera/uuid-slug";
874
+
875
+ function adaptMask(mix: (input: Uint8Array, output: Uint8Array, forward: boolean) => void) {
876
+ const transform = (direction: "mask" | "unmask") => (input: Uint8Array) => {
877
+ const output = new Uint8Array(16);
878
+ mix(input, output, direction === "mask");
879
+ return output;
880
+ };
881
+ const mask = createCustomUuidV7Mask({
882
+ diagnosticLabel: "existing-scheme",
883
+ mask: transform("mask"),
884
+ unmask: transform("unmask"),
885
+ });
886
+ return isUuidSlugError(mask) ? mask : createUuidV7MaskingCodec({ mask });
887
+ }
888
+ ```
252
889
 
253
- const controller = new AbortController();
254
- const schema = await createMaskSchemaAsync({
255
- seed, // the same stored secret used by the synchronous constructor
256
- keyIterations, // preserve the setting used for issued slugs
257
- signal: controller.signal, // optional; call controller.abort(reason) to stop
258
- });
259
- if (schema instanceof Error) throw schema;
260
- const codec = createUuidSlugCodec({ mask: schema });
890
+ Mask, masking-codec, generator, sentinel, migration, and timestamp options reject unknown keys instead of
891
+ silently applying a default. Invalid mask or masking-codec options return an error. Create custom handles
892
+ before passing them; an arbitrary object is not a mask.
893
+
894
+ Share one derived mask between codecs to avoid repeating key derivation, for example when URLs
895
+ use base64url and filenames use base32hex. Each masking codec chooses its alphabet and sentinels; keep
896
+ sentinel definitions the same if the codecs must read each other's output.
897
+
898
+ Diagnostic labels name masks in diagnostics. Slugs contain no diagnosticLabel, so a diagnosticLabel cannot select the decoding
899
+ key. Services must use the same seed bytes and iteration count to derive matching keys.
900
+ String seeds use UTF-8: base64 text and the bytes it encodes are different seeds.
901
+
902
+ For expensive derivation, await `deriveUuidV7MaskAsync` and pass the completed mask to the codec:
903
+
904
+ ```ts
905
+ import {
906
+ deriveUuidV7MaskAsync,
907
+ createUuidV7MaskingCodec,
908
+ isUuidSlugError,
909
+ } from "@anizoptera/uuid-slug";
910
+
911
+ async function createResponsiveCodec(
912
+ seed: string,
913
+ keyDerivationIterations: number,
914
+ signal: AbortSignal,
915
+ ) {
916
+ const mask = await deriveUuidV7MaskAsync({ seed, keyDerivationIterations, signal });
917
+ return isUuidSlugError(mask) ? mask : createUuidV7MaskingCodec({ mask });
918
+ }
261
919
  ```
262
920
 
263
921
  The async form derives the same keys and accepts the same seed settings. It splits encoding,
264
922
  packing and hashing into cooperative work slices, allowing host tasks to run during long
265
- construction. Cancellation stops derivation and returns `UuidSlugError` with code `aborted` and
266
- `signal.reason` as its cause. Invalid options return `invalid_mask_schema`; unexpected construction
267
- failures retain their cause. No partially derived schema is returned.
923
+ construction. UuidV7MaskDerivationCancellation stops derivation and returns `UuidSlugError` with code `aborted` and
924
+ `signal.reason` as its cause. Invalid options return `invalid_mask`; unexpected construction
925
+ failures retain their cause. No partially derived mask is returned.
268
926
 
269
927
  Options are captured when called. Byte seeds are copied before the first suspension, so later
270
928
  caller mutation cannot change the key; synchronize concurrent writes to shared backing memory.
271
- The initial copy of a very large byte seed, allocation, GC and host scheduling can exceed the
272
- responsiveness target. Small derivations need no host yield. Construct once and reuse the schema;
929
+ Copying a very large byte seed, plus allocation, GC, and host scheduling, can still block longer
930
+ than one work slice. Small derivations need no host yield. Construct once and reuse the mask;
273
931
  passing seed options to each new codec would repeat derivation.
274
932
 
275
- `previousMasks` is how you rotate a seed. Decoding tries `mask` first, then each entry in the
276
- order you list them, and the first whose check passes wins — so put the newest first, and keep
277
- the list short. Nothing else is ever tried: a codec decodes with the schemas you gave it and no
933
+ `previousMasks` is how you rotate a seed or timestamp range. Decoding tries `mask` first, then each entry in the
934
+ order you list them, and the first whose check passes wins. Put the newest first, and keep the
935
+ list short. Nothing else is ever tried: a masking codec decodes with the masks you gave it and no
278
936
  others.
279
937
 
938
+ ```ts
939
+ import { createUuidV7MaskingCodec } from "@anizoptera/uuid-slug";
940
+
941
+ function createRotatedCodec(currentSeed: string, previousSeed: string) {
942
+ return createUuidV7MaskingCodec({
943
+ maskSeed: currentSeed,
944
+ previousMasks: [{ mask: { seed: previousSeed }, timestampRangeStartUnixMs: 0 }],
945
+ });
946
+ }
947
+ ```
948
+
949
+ Writers use `currentSeed`; readers also accept `previousSeed`. Remove the old seed only after its
950
+ IDs no longer need to decode.
951
+
280
952
  ### Changing an existing ID format
281
953
 
282
954
  Preserve the UUID; change only how it is encoded. Do not generate a replacement UUID when
@@ -291,128 +963,247 @@ Remove compatibility only when the old IDs in those places no longer need to wor
291
963
  No recent legacy traffic does not prove that old links are gone. To keep old URLs after removing
292
964
  their decoder, retain an application-owned mapping from each supported old slug to its UUID.
293
965
 
294
- Keep keys and sentinel definitions stable throughout the rollout. Non-v7 UUIDs and UUIDv7s
295
- timestamped at or beyond 2^42 ms cannot use the current masked format; preserve them as UUIDs
296
- or direct slugs. Never truncate the timestamp or substitute a new identity to make masking pass.
966
+ Keep keys, timestamp-range starts, and sentinel definitions with every format still in use.
967
+ Preserve UUIDs outside the configured masked range as UUID text or plain slugs. Never truncate a
968
+ timestamp or substitute a new identity to make masking pass.
297
969
 
298
970
  ### Reading original slugs during migration
299
971
 
300
972
  Create a migration reader from your codec. Enable only the old formats your application issued:
301
973
 
302
974
  ```ts
303
- const reader = ids.migration({ original: true, plain: true });
304
- const uuid = reader.decode(incomingSlug);
305
- if (uuid instanceof Error) throw uuid;
306
- // Look up uuid and check the caller's access to the record.
975
+ import { isUuidSlugError } from "@anizoptera/uuid-slug";
976
+ import type { UuidV7MaskingCodec } from "@anizoptera/uuid-slug";
977
+
978
+ function createLegacyReader(maskingCodec: UuidV7MaskingCodec) {
979
+ const migrationDecoder = maskingCodec.createUuidSlugMigrationDecoder({
980
+ acceptFixedMask: true,
981
+ acceptPlainSlug: true,
982
+ });
983
+ if (isUuidSlugError(migrationDecoder)) return migrationDecoder;
984
+ return (incomingSlug: string) => migrationDecoder.uuidSlugToUuidString(incomingSlug);
985
+ }
307
986
  ```
308
987
 
309
- `original` accepts the original fixed permutation/XOR format with its 4-bit checksum.
310
- It does **not** accept the different masked format from package version 0.2.0.
311
- `plain` accepts direct UUID slugs of any version, including old base64url spellings whose
312
- last four bits were ignored. Ordinary `slugToUuid` remains strict about those trailing bits.
988
+ `acceptFixedMask` accepts the fixed-key permutation/XOR format with a 4-bit check that predates
989
+ seeded masking, from before package 0.2.0. Releases from 0.2.0 on write different formats, and the
990
+ 0.2.0 masked format itself is not readable.
991
+ `acceptPlainSlug` accepts plain UUID slugs of any version, including old base64url spellings whose
992
+ last four bits were ignored. Ordinary `uuidToString` remains strict about those trailing bits.
993
+ Create and check the reader once, then reuse it for incoming slugs. Both options must be booleans.
994
+ Unknown keys and inaccessible properties return `invalid_options`, including on typed objects.
313
995
  Neither option changes generation, ordinary codec methods, keys or sentinels.
314
996
 
315
- `decode` returns one UUID or `UuidSlugError`: sentinels first, then current keys, then enabled
997
+ `uuidSlugToUuidString` returns one UUID or `UuidSlugError`: sentinels first, then current keys, then enabled
316
998
  original and plain formats. A successful decode still needs a record lookup. The same slug can
317
999
  decode to different UUIDs in different formats; the original check has only four bits.
318
1000
 
319
1001
  When you know the input format, name it to avoid trying unrelated formats:
320
1002
 
321
1003
  ```ts
322
- const uuid = reader.decode(oldSlug, "original"); // "plain" or "current" also works
323
- if (uuid instanceof Error) throw uuid;
324
- const replacement = ids.uuidV7ToMaskedSlug(uuid);
325
- if (replacement instanceof Error) throw replacement;
326
- // Keep uuid in the database; use replacement in new links.
1004
+ import { isUuidSlugError, FIXED_MASK_FORMAT } from "@anizoptera/uuid-slug";
1005
+ import type { UuidSlugMigrationDecoder, UuidV7MaskingCodec } from "@anizoptera/uuid-slug";
1006
+
1007
+ function replaceOriginalSlug(
1008
+ maskingCodec: UuidV7MaskingCodec,
1009
+ migrationDecoder: UuidSlugMigrationDecoder<typeof FIXED_MASK_FORMAT>,
1010
+ oldSlug: string,
1011
+ ) {
1012
+ const uuid = migrationDecoder.uuidSlugToUuidString(oldSlug, FIXED_MASK_FORMAT);
1013
+ if (isUuidSlugError(uuid)) return uuid;
1014
+ const replacement = maskingCodec.uuidToMaskedSlug(uuid);
1015
+ if (isUuidSlugError(replacement)) return replacement;
1016
+ return { uuid, replacement }; // Keep uuid in the database; use replacement in new links.
1017
+ }
327
1018
  ```
328
1019
 
329
1020
  Enable an old format before selecting it. Recognized sentinels always return their reserved UUID,
330
1021
  including old trailing-bit aliases when reading original or plain slugs.
1022
+ With literal options, TypeScript offers only `SEEDED_MASK_FORMAT` and the formats enabled with `true`;
1023
+ options whose values are dynamic remain selectable because they may be enabled at runtime.
1024
+ Pass a UUID text-case preset after the slug when the format is unknown, or after the format when it
1025
+ is known. Candidate arrays use the same selected case; lowercase remains the default.
331
1026
 
332
- For unknown formats, use `candidates` to find the matching record without guessing:
1027
+ For unknown formats, use `uuidSlugToUuidStringCandidates` to find the matching record without guessing:
333
1028
 
334
1029
  ```ts
335
- const candidates = reader.candidates(incomingSlug);
336
- if (candidates instanceof Error) throw candidates;
337
- const matches = candidates.length ? await findRecordsByUuids(candidates) : [];
338
- if (matches.length === 0) throw new Error("ID not found");
339
- if (matches.length !== 1) throw new Error("ID matches multiple records; supply its original format");
340
- const record = matches[0];
341
- // Check access to record before returning it.
1030
+ import { isUuidSlugError } from "@anizoptera/uuid-slug";
1031
+ import type { UuidSlugMigrationDecoder, UuidString } from "@anizoptera/uuid-slug";
1032
+
1033
+ async function findMigratedRecord(
1034
+ migrationDecoder: UuidSlugMigrationDecoder,
1035
+ incomingSlug: string,
1036
+ findRecordsByUuids: (uuids: readonly UuidString[]) => Promise<readonly unknown[]>,
1037
+ ) {
1038
+ const candidates = migrationDecoder.uuidSlugToUuidStringCandidates(incomingSlug);
1039
+ if (isUuidSlugError(candidates)) return candidates;
1040
+ const matches = candidates.length ? await findRecordsByUuids(candidates) : [];
1041
+ if (matches.length !== 1)
1042
+ return new Error(matches.length ? "ID matches multiple records" : "ID not found");
1043
+ return matches[0]; // Check access before returning the record to the caller.
1044
+ }
342
1045
  ```
343
1046
 
344
- `findRecordsByUuids` is your database query. Return distinct records by UUID. `candidates`
1047
+ `findRecordsByUuids` is your database query. Return distinct records by UUID. `uuidSlugToUuidStringCandidates`
345
1048
  returns distinct UUIDs in decoding order, or an empty array if none match. Malformed input and
346
1049
  failed mask callbacks return an error. Callback errors keep their cause; they never produce a
347
1050
  successful but incomplete list.
348
- An old sentinel alias can also be a current masked ID. `candidates` retains both UUIDs;
349
- `decode` keeps sentinel priority.
350
-
351
- Keep this reader while old inputs must work. Replace it with `ids.migration({ plain: true })`
352
- to stop trying the original mask, or `ids.migration({ original: true })` to stop plain decoding.
353
- `ids.migration()` tries only current keys and sentinels. Removing the migration reader entirely
354
- leaves ordinary codec decoding unchanged. Neither method can identify the issuing format from
1051
+ An old sentinel alias can also be a seeded masked ID. `uuidSlugToUuidStringCandidates` retains both UUIDs;
1052
+ `uuidSlugToUuidString` keeps sentinel priority.
1053
+
1054
+ Keep this reader while old inputs must work. Replace it with
1055
+ `maskingCodec.createUuidSlugMigrationDecoder({ acceptPlainSlug: true })` to stop trying the fixed mask, or
1056
+ `maskingCodec.createUuidSlugMigrationDecoder({ acceptFixedMask: true })` to stop plain-slug decoding.
1057
+ `maskingCodec.createUuidSlugMigrationDecoder()` tries only current keys and sentinels. Removing the migration reader entirely
1058
+ leaves ordinary masking-codec decoding unchanged. Neither method can identify the issuing format from
355
1059
  the slug alone, so successful decoding is not a reliable count of legacy traffic.
356
1060
 
357
- ### Rejecting stale ids
1061
+ ### Validating timestamp windows
358
1062
 
359
1063
  ```ts
360
- import { validateUuidV7Fresh } from "@anizoptera/uuid-slug";
1064
+ import { validateUuidV7StringUnixMs } from "@anizoptera/uuid-slug";
361
1065
 
362
- const ok = validateUuidV7Fresh(uuid, { windowMs: 60_000 });
1066
+ function validateRecentUuid(uuid: string) {
1067
+ return validateUuidV7StringUnixMs(uuid, { maxTimestampDeltaMs: 60_000 });
1068
+ }
363
1069
  ```
364
1070
 
365
- The timestamp must be inside the inclusive interval `now() - windowMs` through
366
- `now() + windowMs`; the default radius is 24 hours. `windowMs` must be finite and nonnegative;
367
- zero and finite fractions are valid. `now` defaults to `Date.now`, must return finite Unix
368
- milliseconds, and is read once per validation. Invalid settings return an error instead of
369
- disabling the check. Degenerate all-zero or all-one random bits are also rejected.
1071
+ The timestamp must be inside the inclusive interval `referenceUnixMs - maxTimestampDeltaMs`
1072
+ through `referenceUnixMs + maxTimestampDeltaMs`. The maximum delta is required, finite, and
1073
+ nonnegative; zero and finite fractions are valid. `referenceUnixMs` defaults to one `Date.now()`
1074
+ reading and must be finite when supplied. Invalid settings return an error instead of disabling
1075
+ the check.
370
1076
 
371
- `validateUuidV7SlugFresh` starts from a plain slug; `codec.validateMaskedSlugFresh` starts from
372
- a slug decoded with that codec. This is a symmetric timestamp sanity check, not past-only expiry,
1077
+ `validatePlainUuidV7SlugUnixMs` starts from a plain slug; `maskingCodec.validateMaskedUuidV7SlugUnixMs` starts from
1078
+ a slug decoded with that masking codec. Success returns the same spelling with its UUIDv7 slug type.
1079
+ The window accepts timestamps on either side of the reference time; it does not enforce expiry,
373
1080
  authentication, or replay prevention. Use ordinary decoding for permanent identifiers. For links
374
1081
  with expiration or one-time use, check the stored expiry and consumption state as well.
375
1082
 
376
- ## Guarantees
1083
+ ## Measured performance
1084
+
1085
+ Choose the output your application needs directly: UUID text, slug, or bytes. Caller-buffer
1086
+ methods reuse your storage; named imports let bundlers remove unused features. Reuse codecs
1087
+ to pay key derivation once. These choices avoid conversions, allocations, and setup on each call.
1088
+
1089
+ The comparisons time complete calls, including validation and error handling, against native APIs
1090
+ and competing packages on Node, Bun, Deno, and Chromium. Portable fallbacks are measured separately.
1091
+ The ranking excludes insecure randomness and timestamp extraction without UUID-version checks;
1092
+ counter layouts and clock advancement are measured differences, not exclusions.
377
1093
 
378
- These are API contracts. Runtime measurements and their exercised conditions belong in
379
- [`bench/README.md`](bench/README.md); a benchmark pass is not proof of every guarantee.
1094
+ The [performance study](bench/PERFORMANCE.md) also measures CPU use, allocations, retained memory,
1095
+ and responsiveness on those runtimes. Guards avoid decoded arrays and error objects; measured caller-buffer
1096
+ paths avoid temporary byte views. Key rotation decodes input text once, and pooled randomness
1097
+ reduces calls to the platform RNG. Node and Bun regression checks enforce these limits.
380
1098
 
381
- - **Conformance.** Generated ids have RFC 9562 version and variant bits. A custom generator is
382
- responsible for honoring its declared contract.
383
- - **Randomness.** Built-in portable generation draws from Web Crypto or `node:crypto`, never
384
- `Math.random`. Native generation delegates to the platform; a caller-supplied `fillRandom`
385
- controls its own entropy. Collisions are possible: enforce uniqueness in storage when required.
386
- - **Time ordering, to the millisecond.** A v7 carries a 48-bit millisecond timestamp in its
387
- leading bits, so UUID strings sort by their encoded timestamps across different milliseconds.
1099
+ Those checks cannot see every engine allocation or prove lower memory use than every competitor.
1100
+ Memory remaining after GC is not total memory allocated.
1101
+
1102
+ These results come from repeated runs on one machine. Workload, hardware, and engine version can
1103
+ change the ranking. Browser competitor comparisons use Chromium; UUID text and slug comparisons and correctness checks also cover Firefox and WebKit.
1104
+
1105
+ | Evidence | Scope | Current result |
1106
+ | --- | --- | --- |
1107
+ | UUIDv7 text | Node, Bun, Deno, Chromium | Leads the compared packages, including `fastv7`. Module calls have no cross-form ordering; created generators add an explicit ordering contract and clock controls. |
1108
+ | UUIDv4 text | Node, Bun, Deno, Chromium | Uses native generation on Bun, Deno and Node without JIT compilation; uses pooled entropy on Node with JIT compilation and Chromium. Leads the compared packages on Chromium; trails the fastest compared package on Bun. |
1109
+ | UUIDv4/v7 bytes | New arrays and caller buffers on Node, Bun, Deno, Chromium | Leads the compared packages on Node and Chromium. On Bun, caller-buffer writes trail `uuid`; owned UUIDv7 byte comparisons are unresolved. On Deno, both UUIDv7 byte forms are unresolved against `uuidv7` and `uniku`. |
1110
+ | Plain-slug generation | UUIDv4/v7 base64url | Retained Bun measurements favor native Web Crypto with reusable storage for UUIDv4 slugs; resource parity remains unresolved. Bun UUIDv7 slugs retain native delegation. |
1111
+ | Conversion | UUID text, bytes, both plain-slug alphabets, timestamp extraction | Text timestamp extraction leads `uuidv7-js` on Node, Bun, Deno, and Chromium. The study has no comparable package for extraction from bytes or slugs. |
1112
+ | Bundling | Bun, esbuild, Parcel, Rollup, Rolldown, Rspack, webpack | A named root import keeps only the code it needs. |
1113
+
1114
+ See the [performance study](bench/PERFORMANCE.md) for measurements, competitors, and rejected
1115
+ optimizations. Raw results are in [competitors.md](bench/results/competitors.md) and
1116
+ [matrix.md](bench/results/matrix.md), including plain-slug generation.
1117
+
1118
+ ## Guarantees
1119
+
1120
+ These are API contracts. The benchmarks in [`bench/README.md`](bench/README.md) measure cost;
1121
+ passing them proves none of this. See [security boundaries](docs/security.md) for entropy failures
1122
+ and masking limits.
1123
+
1124
+ - Generated IDs have RFC 9562 version and variant bits.
1125
+ - Built-in generators use the runtime's cryptographically secure random source. They never fall
1126
+ back to weaker randomness. If secure randomness is unavailable, generation with no arguments or
1127
+ only a spelling preset throws `UuidSlugError` with code `rng_unavailable`, and every generation
1128
+ call with an explicit time, a generator, caller-owned output, or custom entropy returns it.
1129
+ - UUID collisions are possible. Keep a uniqueness constraint where a duplicate could overwrite or
1130
+ misidentify data. On conflict while creating a record, keep the existing record and generate a
1131
+ new ID.
1132
+ - Default generation trusts proper native runtime results and provides no stronger guarantees.
1133
+ Stronger guarantees belong to explicitly configured calls. Native call failures fall back to
1134
+ portable generation; if both fail, the error retains both causes.
1135
+ - A v7 carries a 48-bit millisecond timestamp in its leading bits, so UUID strings sort by their
1136
+ encoded timestamps across different milliseconds.
388
1137
  Backfilled timestamps or a clock adjustment need not reflect generation order.
389
- - **NOT ordered within a millisecond.** Two ids created in the same millisecond may sort in
390
- either order. RFC 9562 §6.2 permits different counter and random-bit strategies. Do not use a v7
391
- to recover the order of events inside a millisecond; use a sequence column.
392
- - **Sortable as a slug only in base32hex.** A 26-character base32hex slug compares as a plain
393
- string in creation order, to the same millisecond granularity as the guarantee above: its digits
394
- are in ASCII order and a v7 leads with its timestamp. That is the whole reason the alphabet is
395
- offered.
396
- - **NOT sortable as a base64url slug.** The default 22-character form is the same 16 bytes in a
397
- shorter alphabet, and the value round-trips exactly — but that alphabet runs `A-Za-z0-9-_`, so
1138
+ - Successful current-time calls on one generator strictly increase in UUID byte order under the
1139
+ default preserve policy, including calls with `at`. Module-level generation does not provide this
1140
+ guarantee. Reset-policy calls after their tolerance, independent generators, package copies, workers,
1141
+ and processes do not share sequence state; use a sequence column when order must cross boundaries.
1142
+ - A 26-character plain UUIDv7 base32hex slug sorts by encoded timestamp across different
1143
+ milliseconds under ASCII comparison. Its digits are in value order and the timestamp comes
1144
+ first. Its lowercase spelling also suits case-insensitive storage.
1145
+ - The default 22-character base64url form preserves all 16 bytes, but its alphabet runs `A-Za-z0-9-_`, so
398
1146
  its character order and its value order disagree. Sort by the UUID, or by a timestamp column. A
399
- masked slug has no chronological ordering; masking always uses base64url.
400
- - **One type for owned bytes.** Without an output buffer, byte generators return a plain
401
- `Uint8Array`, never a platform-specific subclass. With an output buffer, they return that same
1147
+ masked slug has no chronological ordering in either alphabet.
1148
+ - Without an output buffer, byte generators return a plain `Uint8Array`, never a platform-specific
1149
+ subclass. With an output buffer, they return that same
402
1150
  caller-owned array and write only the requested UUID range.
403
- - **You pay for masking only if you mask.** The keyless operations — generating an id, converting
404
- between a UUID and a plain slug — reach no codec, so a bundle that imports only those carries
405
- none of the cipher, key derivation, or sentinel table. Use named imports with a tree-shaking
406
- bundler; loading the complete module namespace does not promise that removal.
1151
+ - `uuidStringToBytes` and `plainSlugToUuidBytes` validate the complete identifier
1152
+ before writing. Invalid text or destination ranges return an error and leave caller storage
1153
+ unchanged.
1154
+ - Named root imports let supported bundlers remove the cipher, key derivation, sentinel table,
1155
+ and unrelated generation code.
1156
+ - A UUIDv7 masking codec requires private mask options or a package-produced mask.
1157
+ The published-key mask is available only as `UUID_V7_TEST_MASK`; omission never
1158
+ selects it.
407
1159
 
408
1160
  ## Runtime
409
1161
 
410
- No runtime dependencies, on any platform.
411
-
412
- - **Bun** uses `Bun.randomUUIDv7`.
413
- - **Node** uses native `crypto.randomUUID`, and native `crypto.randomUUIDv7` where the
414
- version provides it, otherwise the bundled v7 generator.
415
- - **Browsers and Deno** use Web Crypto for randomness plus the bundled v7 generator.
1162
+ The native Rust crate in [`rust/uuid-slug`](rust/uuid-slug) implements the same wire contract: a
1163
+ slug issued by a Node service decodes in a Rust service holding the same seed, and one shared case
1164
+ corpus runs against both implementations in CI. The npm package remains TypeScript/JavaScript-only.
1165
+
1166
+ | Runtime | Loads | Generation |
1167
+ | --- | --- | --- |
1168
+ | Node 20 and newer | compiled JavaScript | native UUIDv4 text without JIT compilation; pooled native entropy for other output |
1169
+ | Bun | published TypeScript | native default UUIDv4 text, UUIDv7 text and UUIDv7 base64url slugs; pooled Web Crypto for other output and configured generators |
1170
+ | Deno | published TypeScript | native UUIDv4 text; pooled Web Crypto for bytes and UUIDv7; no flag or import map needed |
1171
+ | Cloudflare Workers, browsers, other compatible runtimes | compiled JavaScript | the package's own generator over Web Crypto |
1172
+
1173
+ The npm package has no runtime dependencies or native addons to install.
1174
+
1175
+ - Bun loads the published TypeScript source, uses Node-compatible `randomUUID` for UUIDv4 text
1176
+ with Web Crypto as fallback, and uses `Bun.randomUUIDv7` for default UUIDv7 text and base64url slugs.
1177
+ Its logical timestamp can advance ahead of the clock during bursts.
1178
+ Create a generator explicitly when ordering, clock policy or payload
1179
+ layout must be controlled. Other output forms use pooled Web Crypto entropy.
1180
+ If Bun loads the compiled JavaScript directly, it still uses the Bun-specific source and native
1181
+ functions. Tooling that opts into the `development` condition loads the same source.
1182
+ - Node uses native `crypto.randomUUID` for UUIDv4 text without JIT compilation. With JIT
1183
+ compilation, pooled `crypto.randomFillSync` and package formatting are faster. UUIDv7 and byte
1184
+ output use pooled entropy in both modes.
1185
+ - Deno loads the published TypeScript source, uses Web Crypto `randomUUID` for UUIDv4 text,
1186
+ and runs the package's own generator for bytes and UUIDv7. No resolver flag or import map is needed.
1187
+ - Cloudflare Workers, browsers and other compatible runtimes use the portable compiled code over Web Crypto.
1188
+ Local workerd checks run the packed consumer inside a request with and without `nodejs_compat`;
1189
+ deployed Workers verification remains open. See [edge checks](bench/README.md#profiling).
1190
+
1191
+ Capabilities are probed once when the module loads. A missing method is left undefined, so no call
1192
+ pays for a throw and a retry. Native base64url and hex encoders are used where a runtime provides
1193
+ them and they measured faster; on Deno the portable encoder measured faster, so it is kept there.
1194
+ The UUIDv7 generator is created on first use, so conversion-only imports draw no entropy.
1195
+
1196
+ Convert stored UUIDs, decode slugs, and extract timestamps without an entropy source. This suits
1197
+ read-only tools and static builds that never generate IDs. Generation needs secure randomness;
1198
+ conversion does not. The npm package does not load the Rust crate or a WebAssembly module.
1199
+
1200
+ Every change runs a shared runtime contract on the exact Node 20 floor, the latest published patch
1201
+ of every Node major from 20 upward, and unpinned Node Current. Full Node tests also run on each row
1202
+ whose runtime satisfies the development test runner. CI uses the latest Bun and Deno. Packed
1203
+ JavaScript and both WebAssembly profiles run in the Chromium, Firefox, and WebKit revisions pinned
1204
+ by Playwright; dependency updates advance those reproducible browser revisions. The Rust crate builds and tests
1205
+ natively on Linux, macOS, and Windows for x86-64 and Arm64, and its WebAssembly build runs in the
1206
+ same three browser engines.
416
1207
 
417
1208
  ## License
418
1209