@anizoptera/uuid-slug 0.4.0 → 0.5.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 (81) hide show
  1. package/README.md +315 -1057
  2. package/dist/alphabet.d.ts +1 -1
  3. package/dist/alphabet.js +1 -1
  4. package/dist/base64url-name.d.ts +1 -1
  5. package/dist/base64url-name.js +1 -1
  6. package/dist/errors.d.ts +1 -1
  7. package/dist/errors.js +1 -1
  8. package/dist/feistel.js +1 -1
  9. package/dist/generation-options.js +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/instant.js +1 -1
  13. package/dist/mask-handle.d.ts +1 -1
  14. package/dist/mask-handle.js +1 -1
  15. package/dist/mask.d.ts +1 -1
  16. package/dist/mask.js +1 -1
  17. package/dist/masking-codec-protocol.js +1 -1
  18. package/dist/masking-codec-types.d.ts +1 -1
  19. package/dist/masking-codec.d.ts +1 -1
  20. package/dist/masking-codec.js +1 -1
  21. package/dist/migration.js +1 -1
  22. package/dist/node/runtime.js +1 -1
  23. package/dist/payload.d.ts +1 -1
  24. package/dist/payload.js +1 -1
  25. package/dist/runtime/pool.js +1 -1
  26. package/dist/runtime/portable.js +1 -1
  27. package/dist/sentinel.js +1 -1
  28. package/dist/siphash.js +1 -1
  29. package/dist/slug.d.ts +1 -1
  30. package/dist/slug.js +1 -1
  31. package/dist/timestamp.d.ts +1 -1
  32. package/dist/timestamp.js +1 -1
  33. package/dist/types.d.ts +1 -1
  34. package/dist/types.js +1 -1
  35. package/dist/uuid-value-protocol.js +1 -1
  36. package/dist/uuid-value.d.ts +1 -1
  37. package/dist/uuid-value.js +1 -1
  38. package/dist/uuid.d.ts +1 -1
  39. package/dist/uuid.js +1 -1
  40. package/dist/v4-slug.d.ts +1 -1
  41. package/dist/v4-slug.js +1 -1
  42. package/dist/v4.d.ts +1 -1
  43. package/dist/v4.js +1 -1
  44. package/dist/v7-bounds.d.ts +1 -1
  45. package/dist/v7-bounds.js +1 -1
  46. package/dist/v7-generator-input.js +1 -1
  47. package/dist/v7-generator.d.ts +1 -1
  48. package/dist/v7-generator.js +1 -1
  49. package/dist/v7-keyless.d.ts +1 -1
  50. package/dist/v7-keyless.js +1 -1
  51. package/dist/v7-payload.js +1 -1
  52. package/dist/v7-slug.d.ts +1 -1
  53. package/dist/v7-slug.js +1 -1
  54. package/dist/v7-timestamp.js +1 -1
  55. package/dist/v7-value-options.js +1 -1
  56. package/dist/v7-value.d.ts +1 -1
  57. package/dist/v7-value.js +1 -1
  58. package/dist/v7.js +1 -1
  59. package/package.json +5 -3
  60. package/src/alphabet.ts +2 -2
  61. package/src/errors.ts +3 -3
  62. package/src/feistel.ts +1 -1
  63. package/src/generation-options.ts +1 -1
  64. package/src/masking-codec-protocol.ts +1 -1
  65. package/src/masking-codec.ts +1 -1
  66. package/src/payload.ts +2 -2
  67. package/src/runtime/bun.ts +1 -1
  68. package/src/runtime/node.ts +2 -2
  69. package/src/runtime/pool.ts +1 -1
  70. package/src/runtime/portable.ts +1 -1
  71. package/src/slug.ts +6 -6
  72. package/src/uuid-value-protocol.ts +1 -1
  73. package/src/uuid-value.ts +1 -1
  74. package/src/uuid.ts +8 -8
  75. package/src/v4.ts +2 -2
  76. package/src/v7-bounds.ts +3 -3
  77. package/src/v7-generator-input.ts +2 -2
  78. package/src/v7-keyless.ts +6 -6
  79. package/src/v7-payload.ts +1 -1
  80. package/src/v7-slug.ts +1 -1
  81. package/src/v7.ts +1 -1
package/README.md CHANGED
@@ -1,1209 +1,467 @@
1
1
  # @anizoptera/uuid-slug
2
2
 
3
+ High-performance UUIDv4/v7 generation and handling for TS, Rust, and WASM, short base64/base32 plain slugs and configurable masked UUIDv7 slugs. Zero runtime deps, tree-shakable, and optimised for your runtime. One efficient ID for databases, URLs and files.
4
+
3
5
  [![npm version](https://img.shields.io/npm/v/@anizoptera/uuid-slug?label=npm)](https://www.npmjs.com/package/@anizoptera/uuid-slug)
4
6
  [![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)
5
- [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
6
7
  [![Runtime deps](https://img.shields.io/badge/runtime_deps-0-2ea44f)](package.json)
8
+ [![Node >=20](https://img.shields.io/badge/node-%3E%3D20-339933?logo=node.js&logoColor=white)](package.json)
9
+ [![Bun >=1.0](https://img.shields.io/badge/bun-%3E%3D1.0-FBF0DF?logo=bun&logoColor=FBF0DF)](#runtime)
10
+ [![Deno >=1.29](https://img.shields.io/badge/deno-%3E%3D1.29-70FFAF?logo=deno&logoColor=white)](#runtime)
11
+ [![Cloudflare Workers](https://img.shields.io/badge/cloud-workers-F38020?logo=cloudflare&logoColor=white)](#runtime)
7
12
  [![License](https://img.shields.io/github/license/Anizoptera/uuid-slug)](LICENSE)
8
13
 
9
- ## TL;DR
14
+ [![One UUIDv7 shown as UUID text, 16 bytes, plain base64url and base32hex slugs, and masked base64url and base32hex slugs, with colours tracing timestamp, version, variant and payload bits](docs/assets/uuid-representations.svg)](https://raw.githubusercontent.com/Anizoptera/uuid-slug/main/docs/assets/uuid-representations.svg)
10
15
 
11
- **Zero-dependency UUIDv4/v7 generation, lossless base64url and base32hex slugs for any UUID, and reversible UUIDv7 masking for databases, URLs, and files.**
16
+ <p align="center"><sub><em>Open the <a href="https://raw.githubusercontent.com/Anizoptera/uuid-slug/main/docs/assets/uuid-representations.svg">interactive infographic</a>: hover any field to trace it through every form.</em></sub></p>
12
17
 
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.
18
+ - **Benchmark-leading UUIDv7 text generation on Node, Bun, Deno and browsers!**
19
+ - 6+ distinct UUID representations are supported!
21
20
 
22
- [Install](#install) · [Quick start](#quick-start) · [Contents](#contents) · [API](#api) · [Performance](#measured-performance)
21
+ - **[Leading performance](bench/results/competitors.md)**, low memory and resource allocation!
22
+ - Same API across Node, Bun, Deno, browsers and cloud workers. Native fast paths and portable fallbacks are used automatically.
23
+ - _IDs can be generated or decoded [directly into your buffers](#work-with-uuid-bytes); failed validation leaves them unchanged._
23
24
 
24
- ### TypeScript API map
25
+ - **Zero runtime dependencies.** Small [runtime-optimised](#runtime) bundles on Node, Bun, Deno and browsers.
25
26
 
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.
27
+ - **One UUID for storage, URLs and files, each in its [most compact form](#representations)!**
28
+ - 16-byte binary UUID for storage or transport.
29
+ - **Short 22-character base64url slug for URLs** (39% shorter than a naive UUID text).
30
+ - 26-character base32hex lowercase slug suits case-insensitive (e.g., cross-OS) filenames. Plain UUIDv7 slugs in this alphabet sort by timestamp under ASCII comparison.
31
+ - Optional **[UUIDv7 masked slug](#masked-slugs) form that hides timestamp and UUID structure.** Expose your IDs without revealing their creation time or nature!
32
+ - _Any UUID converts to a lossless plain slug and back. Existing database keys stay unchanged; no mapping table is needed._
33
+ - _Plain slugs decode with any standard base64url or base32hex decoder, without this library. Masked slugs need your key and settings._
31
34
 
32
- ```text
33
- UUID text ─┐
34
- UUID bytes ├── keyless conversion ── UUID text / bytes / plain slug
35
- plain slug ┘
35
+ - **UUIDv4/v7 generation, conversion and inspection, configurable UUIDv7 masking, and plain conversion for any UUID!**
36
+ - **Full control of UUIDv7 time and order:** [recorded times](#generate-at-a-recorded-time) or your own clock, clock-rollback policy, custom payload layout, [timestamp extraction](#use-the-uuid-as-the-timestamp-source) and [time-range queries](#ordering-and-key-distribution).
37
+ - IDs and relationships can be [created offline](#assign-ids-before-saving-or-syncing), before saving or syncing, without a central allocator or worker number.
38
+ - Masking [key rotation and format migration](docs/api.md#changing-an-existing-id-format) keep old IDs readable while new IDs use current settings.
39
+ - [Async key derivation](docs/api.md#masking-codec-options) yields during long work and can be cancelled.
40
+ - [Parse once](#parse-once-for-repeated-work): validate and decode an ID one time into the optimized UUID object, then reuse it for every conversion and inspection.
41
+ - Optional [sentinel IDs](#sentinels): reserved values for tests, debugging and tracing that stay recognizable in logs, even after key rotation.
42
+ - Optimal, **safe and most efficient defaults!**
36
43
 
37
- UUIDv7 text / bytes / plain slug ── masking codec ── masked slug / sentinel / decoded UUID
38
- │
39
- ├── current + previous masks
40
- └── opt-in migration reader
41
- ```
44
+ - **Intuitive, ergonomic, agent-friendly manually tailored API.**
45
+ - Strict types, validation, typed errors, safe buffer writes and one-check composition to prevent integration mistakes.
46
+ - Types catch UUID-version and plain/masked mix-ups before execution. Compatible conversions chain with one error check; failures have stable codes.
47
+ - **Named imports let supported bundlers [remove unused features](#guarantees), including masking and key derivation.**
42
48
 
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.
49
+ - TypeScript and Rust implementations that encode and decode the same formats, including masked IDs with matching key settings.
45
50
 
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
51
 
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` |
52
+ [Install](#install) · [Quick start](#quick-start) · [Contents](#contents) · [API](#api) · [Performance](bench/results/competitors.md)
53
+
82
54
 
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)
115
-
116
- ```bash
117
- bun add @anizoptera/uuid-slug
118
- pnpm add @anizoptera/uuid-slug
119
- npm add @anizoptera/uuid-slug
55
+ ## Install
56
+
57
+ Use your favorite TS/JS package manager (npm/bun/pnpm/yarn/..), e.g.:
58
+ ```
59
+ bun install @anizoptera/uuid-slug
120
60
  ```
121
61
 
62
+ _The [Rust crate](rust/uuid-slug) and WASM builds live in this repo but are not yet published._
63
+
64
+
122
65
  ## Quick start
123
66
 
124
- When you need both a database UUID and a public slug, generate both from one byte draw:
67
+ One call returns the same ID as `uuid` for storage and `slug` for URLs:
125
68
 
126
69
  ```ts
127
- import {
128
- generateUuidV7WithPlainSlug,
129
- } from "@anizoptera/uuid-slug";
70
+ import { generateUuidV7WithPlainSlug } from "@anizoptera/uuid-slug";
71
+ import type { GeneratedUuidV7, PlainUuidV7Slug } from "@anizoptera/uuid-slug";
130
72
 
131
- function createShortId() {
132
- return generateUuidV7WithPlainSlug();
133
- }
73
+ const { uuid, slug }: GeneratedUuidV7<PlainUuidV7Slug> = generateUuidV7WithPlainSlug();
134
74
  ```
135
75
 
136
- If you only need the slug, call `generatePlainUuidV7Slug()` directly.
76
+ `uuid` has type `UuidV7String`; `slug` has type `PlainUuidV7Slug`.
77
+ These are ordinary strings at runtime; TypeScript retains their UUID version and representation.
78
+ Unchecked external IDs remain `string` inputs; conversion and parsing validate them.
79
+
80
+ Use `generateUuidV4()` for random IDs, `generateUuidV7()` for timestamped IDs, or
81
+ `generatePlainUuidV7Slug()` for just the slug.
82
+ Default generation returns the ID and throws `rng_unavailable` only without secure randomness.
83
+ [Conversions return errors as values](#handling-errors).
84
+
137
85
 
138
86
  ## Contents
139
87
 
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)
88
+ - [Performance](bench/results/competitors.md) · [Install](#install) · [Quick start](#quick-start)
89
+ - [Convert existing IDs](#keep-your-existing-uuids) · [Representations](#representations)
90
+ - [Plain slugs](#plain-slugs) · [Masking](#masked-slugs) · [Sentinels](#sentinels) · [Bytes](#work-with-uuid-bytes)
91
+ - [Parse once](#parse-once-for-repeated-work) · [Offline IDs](#assign-ids-before-saving-or-syncing)
92
+ - [Recorded time](#generate-at-a-recorded-time) · [Extract time](#use-the-uuid-as-the-timestamp-source) · [Ordering](#ordering-and-key-distribution) · [Security limits](#masking-security)
93
+ - [Errors](#handling-errors) · [Types](docs/api.md#types)
94
+ - [API](#api) · [TypeScript API map](#typescript-api-map)
95
+ - [Codec options](docs/api.md#masking-codec-options) · [Migration](docs/api.md#reading-original-slugs-during-migration)
162
96
  - [Guarantees](#guarantees)
163
97
  - [Runtime](#runtime)
98
+ - [Upgrades and support](#upgrades-and-support)
164
99
  - [License](#license)
165
100
 
166
101
  ## Keep your existing UUIDs
167
102
 
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.
219
-
220
- ```ts
221
- import { BASE32HEX, generatePlainUuidV7Slug } from "@anizoptera/uuid-slug";
222
-
223
- function idForImportedRecord(recordedAt: Date) {
224
- return generatePlainUuidV7Slug({ at: recordedAt, alphabet: BASE32HEX });
225
- }
226
- ```
227
-
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:
103
+ Encode stored UUIDs; decode incoming slugs before querying the same keys.
104
+ Plain encoding preserves every bit. Standard encodings let you decode plain slugs without this library; **masked slugs need the matching key and settings**.
263
105
 
264
106
  ```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
- ```
107
+ import { isUuidSlugError, plainSlugToUuidString, uuidStringToPlainSlug } from "@anizoptera/uuid-slug";
108
+ import type { PlainUuidSlug, UuidSlugError, UuidString } from "@anizoptera/uuid-slug";
272
109
 
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.
110
+ const slug: PlainUuidSlug | UuidSlugError = uuidStringToPlainSlug("0198abcd-1234-7abc-9def-0123456789ab");
111
+ if (typeof slug === "string") console.log(slug);
112
+ else console.error(slug.message);
276
113
 
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:
114
+ // Alternative to the typeof check: the helper recognizes returned error values.
115
+ if (!isUuidSlugError(slug)) console.log(slug);
280
116
 
281
- ```ts
282
- const payload = extractUuidV7Payload(uuid, {
283
- subMillisecondFractionBits: 12,
284
- counterBits: 14,
285
- });
117
+ const uuid: UuidString | UuidSlugError = plainSlugToUuidString("AZirzRI0eryd7wEjRWeJqw");
118
+ if (typeof uuid === "string") console.log(uuid); // The database key for this incoming URL slug.
119
+ else console.error(uuid.message);
286
120
  ```
287
121
 
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
122
  ## Representations
299
123
 
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";
124
+ A masking codec holds the keys and settings to encode and decode UUIDv7 slugs.
330
125
 
331
- function decodePublicId(maskingCodec: UuidV7MaskingCodec, publicId: string, record: Uint8Array, offset: number) {
332
- return maskingCodec.uuidToBytes(publicId, record, offset);
333
- }
334
- ```
126
+ All examples encode the same UUIDv7; sizes are characters except for bytes.
335
127
 
336
- Write a UUID directly into a binary record, leaving its other fields untouched:
128
+ | Representation | Size | Example | Meaning and use |
129
+ | --- | ---: | --- | --- |
130
+ | UUID text | 36 | `0198abcd-1234-7abc-9def-0123456789ab` | Lowercase hyphenated output; uppercase optional |
131
+ | UUID bytes | 16 | `01 98 ab cd 12 34 7a bc 9d ef 01 23 45 67 89 ab` | Compact storage; writes a new or caller-owned array; encode as text for URLs |
132
+ | Plain base64url slug | 22 | `AZirzRI0eryd7wEjRWeJqw` | 39% shorter than UUID text; lossless for any UUID; case-sensitive; almost time-ordered for UUIDv7 |
133
+ | Plain base32hex slug | 26 | `06canj8i6htbp7ff04hkaps9lc` | 28% shorter than UUID text; keyless, lossless; writes lowercase, accepts mixed case; UUIDv7 sorts by timestamp in ASCII order |
134
+ | Masked base64url UUIDv7 slug | 22 | `ap225Qa_y6wN5LQCJgwH0z` | 39% shorter than UUID text; opaque, case-sensitive, unordered; 16-bit check; requires its codec to decode |
135
+ | Masked base32hex UUIDv7 slug | 27 | `daerdp86nv5qo3f4mg12c307qco` | 25% shorter than UUID text; opaque, unordered; writes lowercase, accepts mixed case; requires its codec to decode |
337
136
 
338
- ```ts
339
- import { uuidStringToBytes } from "@anizoptera/uuid-slug";
137
+ Parsers accept mixed-case canonical or compact hexadecimal text, brace-wrapped canonical text and UUID URNs. See [input examples](docs/api.md#uuid-text-input).
138
+ Masked examples use the public `UUID_V7_TEST_MASK`; use a private seed for your IDs.
340
139
 
341
- function convertUuid() {
342
- const record = new Uint8Array(32);
343
- return uuidStringToBytes("01990d4d-e600-7000-8000-000000000000", record, 8);
344
- }
345
- ```
140
+ Plain and masked base64url slugs can look identical but decode to different UUIDs.
141
+ Read known plain IDs with `plainSlugToUuidString` and known masked IDs with `maskingCodec.maskedSlugToUuidString`. General codec readers try masks first, then plain decoding only if every mask rejects the slug.
346
142
 
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.
143
+ Generate bytes once when you need several representations, then convert only those you use.
144
+ Use paired generation when you need UUID text plus one slug.
367
145
 
368
146
  ## Two kinds of slug
369
147
 
370
148
  ### Plain slugs
371
149
 
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
374
- when you only want the identifier shorter.
150
+ _Examples: `AZirzRI0eryd7wEjRWeJqw` (base64url), `06canj8i6htbp7ff04hkaps9lc` (base32hex)_
375
151
 
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
379
- `A-Za-z0-9-_`, so `0` stands for a larger value than `A` but sorts before it.
152
+ A plain slug is the UUID's 16 bytes in base64url (22 characters) or base32hex (26), with no key.
153
+ Use `uuidStringToPlainSlug` to encode a UUID and `plainSlugToUuidString` to recover it.
154
+ Decoders reject `=` padding and nonzero unused bits in the last character.
155
+ `isPlainUuidSlug` checks canonical spelling and returns a boolean.
380
156
 
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.
157
+ Pass `BASE32HEX` to a plain-slug writer, for example `generatePlainUuidV7Slug(BASE32HEX)`; see [ordering](#ordering-and-key-distribution).
384
158
 
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.
159
+ `uuidToString` infers the alphabet from the length automatically, 22 or 26, so old slugs survive alphabet changes.
160
+ It returns lowercase UUID text by default.
161
+ Decode before comparing IDs or building cache keys: different spellings can identify the same record.
162
+ Preserve base64url case; lowercasing changes the value.
394
163
 
395
164
  ### Masked slugs
396
165
 
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).
166
+ _Examples: `ap225Qa_y6wN5LQCJgwH0z` (base64url), `daerdp86nv5qo3f4mg12c307qco` (base32hex)_
167
+
168
+ Hide UUIDv7 timestamps and other standard fields with a reusable masking codec.
169
+ Codecs default to base64url; set `maskedSlugAlphabet: BASE32HEX` for lowercase filenames.
403
170
 
404
- Use a masking codec only when IDs must hide their UUIDv7 layout:
171
+ Supply either `maskSeed` or `mask`; neither or both returns `invalid_mask`.
172
+ Use `maskSeed` for a secret; `mask` accepts a derived mask, derivation options or `UUID_V7_TEST_MASK`. **Anyone can decode IDs made with that public test mask! AVOID USING IT IN PRODUCTION!**
405
173
 
406
174
  ```ts
407
175
  import {
408
176
  createUuidV7MaskingCodec,
409
177
  isUuidSlugError,
178
+ UUID_V7_TEST_MASK,
410
179
  } from "@anizoptera/uuid-slug";
180
+ import type { MaskedOrSentinelUuidV7Slug, UuidSlugError, UuidV7MaskingCodec } from "@anizoptera/uuid-slug";
411
181
 
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:
441
-
442
- - **A decoded slug is a candidate, not a proof.** Roughly one random 22-character string in
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
447
- at most the sum of the individual rates. Keep the rotation list short.
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.
458
-
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:
464
-
465
- | Name | UUID | Slug |
466
- | --------------- | -------------------------------------- | ------------------------ |
467
- | `nil` | `00000000-0000-7000-8000-000000000000` | `AAAAAAAAcACAAAAAAAAAAA` |
468
- | `anonymous` | `00000000-0001-7000-8000-000000000000` | `AAAAAAABcACAAAAAAAAAAA` |
469
- | `unknown` | `00000000-0002-7000-8000-000000000000` | `AAAAAAACcACAAAAAAAAAAA` |
470
-
471
- Read the validated names, UUIDs, and slugs from `maskingCodec.sentinels`:
182
+ const maskingCodec: UuidV7MaskingCodec | UuidSlugError = createUuidV7MaskingCodec({
183
+ mask: UUID_V7_TEST_MASK,
184
+ });
472
185
 
473
- ```ts
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;
186
+ if (isUuidSlugError(maskingCodec)) {
187
+ console.error(maskingCodec.message);
188
+ } else {
189
+ const storedUuid = "0198abcd-1234-7abc-9def-0123456789ab";
190
+ const slug: MaskedOrSentinelUuidV7Slug | UuidSlugError = maskingCodec.uuidToMaskedSlug(storedUuid);
191
+ if (typeof slug === "string") console.log(slug);
192
+ else console.error(slug.message);
482
193
  }
483
194
  ```
484
195
 
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.
196
+ Construct and check the codec once; reuse it to avoid per-ID key derivation.
197
+ Its methods need no `bind`. The public test mask makes this example reproducible; production codecs need a private seed.
198
+ Masking accepts UUIDv7s from other generators and preserves all their payload bits.
199
+ For new IDs, `maskingCodec.generateUuidV7WithMaskedSlug()` returns the UUID and slug together;
200
+ `maskingCodec.generateMaskedUuidV7Slug()` returns just the slug. Both can return `UuidSlugError`.
201
+ [Async mask derivation](docs/api.md#masking-codec-options) lets other work run during long setup and supports cancellation.
492
202
 
493
- Keep sentinel definitions stable while their slugs are in use. Decoding checks sentinels first, so they
494
- are reserved even if a mask could produce the same text. Encoding rejects a non-sentinel UUID
495
- whose masked output collides with a reserved slug, using `invalid_mask`; it never returns
496
- a slug that would decode to the wrong sentinel.
203
+ Generate a random seed, for example with `openssl rand -base64 32`, and keep it outside source control.
204
+ Seeds need at least 16 bytes; length alone does not prevent offline guessing from known UUID/slug pairs.
497
205
 
498
- ## Ordering and key distribution
206
+ Changing the seed or `keyDerivationIterations` changes keys. Keep old mask settings and range starts
207
+ in `previousMasks` while old slugs must work. Retain each live format's sentinel definitions too.
208
+ New slugs use current keys. Deploy both readers before switching writers; bookmarks still need
209
+ their old decoder. See [migration](docs/api.md#changing-an-existing-id-format).
210
+ `keyDerivationIterations` defaults to `1`. More iterations increase setup and guessing costs;
211
+ they do not make a human-chosen seed suitable.
499
212
 
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
-
534
- ## What masking is not
535
-
536
- Masking uses a four-round Feistel network with HalfSipHash-2-4 round functions and a
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).
541
-
542
- Masked slugs are not authentication tokens or capabilities. The check detects many incorrect
543
- decodes; it is not a message authentication code. Confirm decoded candidates against your store
544
- and enforce authorization separately. Supplying a custom transform still leaves the same short check
545
- and does not turn the API into an authenticated-token system.
546
-
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
- ```
213
+ Masking covers roughly 139 years from `timestampRangeStartUnixMs`. The default starts at the
214
+ Unix epoch and ends in May 2109. Outside that range, masking returns `invalid_timestamp` rather
215
+ than lose timestamp bits. Plain slugs and sentinels retain the full UUIDv7 range.
216
+ See [exact bounds and range configuration](docs/design.md#representations-and-bit-budget).
563
217
 
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.
218
+ ### Sentinels
571
219
 
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.
220
+ Reserve UUIDv7 values that stay recognizable in logs: codecs write them as plain slugs,
221
+ even after key rotation. Codecs have none by default. Keep their definitions unchanged while
222
+ their slugs remain in use. See [sentinel setup and collision handling](docs/api.md#sentinels).
575
223
 
576
- ## Handling errors
224
+ ## Work with UUID bytes
577
225
 
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.
226
+ Generation can write an ID into an existing binary record:
583
227
 
584
228
  ```ts
585
- import { isUuidSlugError, plainSlugToUuidBytes, uuidStringToPlainSlug } from "@anizoptera/uuid-slug";
229
+ import { generateUuidV7Bytes, isUuidSlugError } from "@anizoptera/uuid-slug";
230
+ import type { UuidSlugError } from "@anizoptera/uuid-slug";
586
231
 
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
- }
232
+ const record: Uint8Array = new Uint8Array(32);
233
+ const result: Uint8Array | UuidSlugError = generateUuidV7Bytes(record, 8);
234
+ if (isUuidSlugError(result)) console.error(result.message);
235
+ else console.log(result); // The same record, with its ID at bytes 8 through 23.
592
236
  ```
593
237
 
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.
238
+ Write directly into your database or protocol buffer with `uuidStringToBytes`,
239
+ `plainSlugToUuidBytes` or `maskingCodec.maskedSlugToUuidBytes`. Pass the array and offset;
240
+ the call returns your array and leaves other bytes unchanged. Failed validation leaves the buffer unchanged.
241
+ See [buffer examples and accepted byte forms](docs/api.md#work-with-uuid-bytes).
596
242
 
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`.
243
+ ## Parse once for repeated work
602
244
 
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.
245
+ `parseUuid` validates and decodes an ID once for repeated conversion and inspection.
246
+ It returns an immutable `Uuid` object, not a string. Changes to its byte outputs leave the retained UUID unchanged.
607
247
 
608
248
  ```ts
609
- import { BASE32HEX, uuidBytesToPlainSlug } from "@anizoptera/uuid-slug";
610
-
611
- function encodeStoredUuid(bytes: Uint8Array) {
612
- return uuidBytesToPlainSlug(bytes, BASE32HEX);
249
+ import { isUuidSlugError, parseUuid } from "@anizoptera/uuid-slug";
250
+ import type { PlainUuidSlug, Uuid, UuidBytes, UuidInspection, UuidSlugError } from "@anizoptera/uuid-slug";
251
+
252
+ const input = "0198abcd-1234-7abc-9def-0123456789ab";
253
+ const uuid: Uuid | UuidSlugError = parseUuid(input);
254
+ if (isUuidSlugError(uuid)) {
255
+ console.error(uuid.message);
256
+ } else {
257
+ const bytes: UuidBytes = uuid.toBytes();
258
+ const slug: PlainUuidSlug = uuid.toPlainSlug();
259
+ const details: UuidInspection = uuid.inspect();
260
+ console.log(bytes, slug, details);
613
261
  }
614
262
  ```
615
263
 
616
- ## Types
264
+ ## Assign IDs before saving or syncing
617
265
 
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.
266
+ Create IDs before saving, even offline. Related records can reference them without a database round
267
+ trip and keep them after synchronization. No central allocator or worker number is needed.
268
+ Any generator works, e.g. `generateUuidV7()`, wherever the record is created.
623
269
 
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.
270
+ ## Generate at a recorded time
628
271
 
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.
272
+ Set `at` on UUIDv7 generation calls to encode a record's time instead of now.
273
+ It accepts a `Date`, Unix milliseconds, zoned ISO text, Temporal-style instants and
274
+ `{ seconds, nanoseconds }` timestamps without manual conversion.
275
+ See [accepted time forms and configured fractional precision](docs/api.md#supplied-time).
634
276
 
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
675
- can all match by chance. A guard answers "is this well formed", never "is this mine". Decode with
676
- the matching API. For access to stored records, check existence and authorization separately.
277
+ ```ts
278
+ import { BASE32HEX, generatePlainUuidV7Slug } from "@anizoptera/uuid-slug";
279
+ import type { PlainUuidV7Slug, UuidSlugError } from "@anizoptera/uuid-slug";
677
280
 
678
- ## API
281
+ const recordedAt = "2026-01-01T12:00:00Z"; // Also accepts Date or Unix milliseconds.
282
+ const slug: PlainUuidV7Slug | UuidSlugError = generatePlainUuidV7Slug({ at: recordedAt, alphabet: BASE32HEX });
283
+ if (typeof slug === "string") console.log(slug);
284
+ else console.error(slug.message);
285
+ ```
679
286
 
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.
287
+ Use one `createUuidV7Generator` generator across output forms to share a sequence, including `at` calls.
288
+ Module-level calls remain independent.
685
289
 
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.
290
+ Calls use fresh randomness even at identical timestamps. For retries, retain the first ID or
291
+ use a deduplication key; existing records keep their UUIDs. Masked IDs need a
292
+ [timestamp range](#masked-slugs) covering the recorded time.
689
293
 
690
- ### Generate IDs
294
+ To keep IDs in order, a generator may encode a time slightly after the one you supplied.
691
295
 
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.
296
+ ## Use the UUID as the timestamp source
694
297
 
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.
298
+ Read UUIDv7's millisecond timestamp without a database lookup or UUID-text conversion.
299
+ If it is the time you need, omit a separate field:
730
300
 
731
301
  ```ts
732
- const uuid = parseUuid(input, codec);
733
- if (uuid instanceof Error) return uuid;
302
+ import { extractUuidV7UnixMs } from "@anizoptera/uuid-slug";
303
+ import type { UuidSlugError } from "@anizoptera/uuid-slug";
734
304
 
735
- const facts = uuid.inspect();
736
- const stored = uuid.toBytes();
737
- const publicId = uuid.toMaskedSlug();
305
+ const incomingId = "AZirzRI0eryd7wEjRWeJqw";
306
+ const unixMs: number | UuidSlugError = extractUuidV7UnixMs(incomingId);
307
+ if (typeof unixMs === "number") console.log(unixMs);
308
+ else console.error(unixMs.message);
738
309
  ```
739
310
 
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:
781
-
782
- ```ts
783
- import { createUuidV7Generator } from "@anizoptera/uuid-slug";
311
+ `extractUuidV7UnixMs(bytes, offset)` reads from a larger buffer.
312
+ `maskingCodec.extractMaskedUuidV7UnixMs(slug)` recovers a masked timestamp with the codec's keys.
313
+ UUIDv4 has no timestamp and is rejected.
784
314
 
785
- function createEventGenerator(readUnixMs: () => number) {
786
- return createUuidV7Generator({ readUnixMs });
787
- }
788
- ```
315
+ For known fraction and counter layouts, use [payload extraction](docs/api.md#uuidv7-payload-fields).
789
316
 
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
317
+ Keep separate fields for other dates, finer precision, editable times or queries the UUID index
318
+ cannot serve. Changing the timestamp changes the ID.
841
319
 
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
- ```
854
-
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.
320
+ ## Ordering and key distribution
859
321
 
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.
322
+ Base64url UUIDv7 slugs are almost time-ordered: nearby timestamps have similar prefixes.
323
+ ASCII sorting can reverse them: `AAAAAAAz` and `AAAAAAA0` encode consecutive milliseconds,
324
+ but the second prefix sorts first.
867
325
 
868
- ```ts
869
- import {
870
- createCustomUuidV7Mask,
871
- createUuidV7MaskingCodec,
872
- isUuidSlugError,
873
- } from "@anizoptera/uuid-slug";
326
+ Base32hex preserves UUID byte order: its alphabet, `0-9a-v`, follows numeric order, with the
327
+ most significant bits first. Equal-length slugs sort by timestamp even across field boundaries.
328
+ Clocks can move backwards, and UUIDv7 does not promise creation order within a millisecond.
329
+ Compare one spelling at a time; database collations and natural file sorting can differ from ASCII.
874
330
 
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
- ```
331
+ `uuidV7StringBounds(startMs, endMs)` builds inclusive bounds for time-range queries on UUID keys.
332
+ The bounds cover every UUIDv7 in the interval, regardless of its payload.
333
+ For one millisecond, use `uuidV7StringBounds(ms)`. Compare in UUID wire-byte order;
334
+ SQL Server's `uniqueidentifier` uses a different order.
889
335
 
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.
336
+ Decode masked filenames or store dates separately to sort them chronologically.
893
337
 
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.
338
+ Changing public URLs leaves the UUID index unchanged. For hash partitioning, hash the UUID
339
+ so a spelling change does not move the record.
897
340
 
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.
341
+ With unchanged settings, built-in masking gives the same UUID the same slug: URLs and filenames
342
+ stay stable, and repeated uses are recognizable. Rotation can change the slug;
343
+ compare decoded UUIDs to identify the same record.
901
344
 
902
- For expensive derivation, await `deriveUuidV7MaskAsync` and pass the completed mask to the codec:
345
+ ## Masking security
903
346
 
904
- ```ts
905
- import {
906
- deriveUuidV7MaskAsync,
907
- createUuidV7MaskingCodec,
908
- isUuidSlugError,
909
- } from "@anizoptera/uuid-slug";
347
+ Masking hides UUIDv7 fields; the matching key restores them. Its cryptographic strength is not established,
348
+ including against attacks using known UUID/slug pairs. See the [design](docs/design.md)
349
+ and [security limits](docs/security.md).
910
350
 
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
- }
919
- ```
351
+ An incorrect key can pass the 16-bit check and return the wrong UUID.
352
+ Keep the rotation list short and confirm decoded IDs against your records;
353
+ see the [record lookup example](docs/security.md#masking).
920
354
 
921
- The async form derives the same keys and accepts the same seed settings. It splits encoding,
922
- packing and hashing into cooperative work slices, allowing host tasks to run during long
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.
355
+ A browser can use your service's masked IDs without the seed. Keep private masking and decoding
356
+ on the service; client code exposes the seed. Plain generation and conversion need no seed.
926
357
 
927
- Options are captured when called. Byte seeds are copied before the first suspension, so later
928
- caller mutation cannot change the key; synchronize concurrent writes to shared backing memory.
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;
931
- passing seed options to each new codec would repeat derivation.
358
+ ## Handling errors
932
359
 
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
936
- others.
360
+ Conversions return `T | UuidSlugError` and pass errors through unchanged.
361
+ Async mask construction resolves to the same union.
362
+ Compatible chains need one final check. For string results, `typeof result === "string"`
363
+ keeps the branded string type; the other branch is `UuidSlugError`.
364
+ Use `isUuidSlugError` for object results or unknown input. It recognizes package errors
365
+ across realms and package copies.
937
366
 
938
367
  ```ts
939
- import { createUuidV7MaskingCodec } from "@anizoptera/uuid-slug";
368
+ import { isUuidSlugError, uuidStringToBytes } from "@anizoptera/uuid-slug";
369
+ import type { UuidBytes, UuidSlugError } from "@anizoptera/uuid-slug";
940
370
 
941
- function createRotatedCodec(currentSeed: string, previousSeed: string) {
942
- return createUuidV7MaskingCodec({
943
- maskSeed: currentSeed,
944
- previousMasks: [{ mask: { seed: previousSeed }, timestampRangeStartUnixMs: 0 }],
945
- });
946
- }
371
+ const bytes: UuidBytes | UuidSlugError = uuidStringToBytes("0198abcd-1234-7abc-9def-0123456789ab");
372
+ if (isUuidSlugError(bytes)) console.error(bytes.code, bytes.message);
373
+ else console.log(bytes);
947
374
  ```
948
375
 
949
- Writers use `currentSeed`; readers also accept `previousSeed`. Remove the old seed only after its
950
- IDs no longer need to decode.
951
-
952
- ### Changing an existing ID format
953
-
954
- Preserve the UUID; change only how it is encoded. Do not generate a replacement UUID when
955
- converting an existing ID: references and stored records must still identify the same object.
956
-
957
- Deploy readers that accept both formats before any writer issues the new format. Include
958
- background jobs, cached clients and extensions in that rollout. After switching writers, keep
959
- compatible readers available for rollback: an old-only reader cannot read newly issued IDs.
960
-
961
- Updating the database does not update bookmarks, shared links, cookies or client storage.
962
- Remove compatibility only when the old IDs in those places no longer need to work.
963
- No recent legacy traffic does not prove that old links are gone. To keep old URLs after removing
964
- their decoder, retain an application-owned mapping from each supported old slug to its UUID.
376
+ Check intermediate results only when you also need their values.
965
377
 
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.
378
+ Handle errors by `code`, with constants such as `INVALID_BUFFER` and the `UuidSlugErrorCode` type.
379
+ Use `message` for diagnostics; wording can change while codes stay stable.
380
+ Failed entropy draws, clock readings and custom transforms retain their exception as `cause`.
969
381
 
970
- ### Reading original slugs during migration
382
+ ## API
971
383
 
972
- Create a migration reader from your codec. Enable only the old formats your application issued:
384
+ Use the [TypeScript reference](docs/api.md) for [types](docs/api.md#types), [call signatures](docs/api.md#api), [codec options](docs/api.md#masking-codec-options), [migration](docs/api.md#reading-original-slugs-during-migration) and [timestamp windows](docs/api.md#validating-timestamp-windows).
385
+ Each export also documents its accepted input, result and failures in JSDoc.
973
386
 
974
- ```ts
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
- }
986
- ```
387
+ ## TypeScript API map
987
388
 
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.
995
- Neither option changes generation, ordinary codec methods, keys or sentinels.
389
+ | Job | Main TypeScript API |
390
+ | --- | --- |
391
+ | Generate UUIDv4 | `generateUuidV4`, `generateUuidV4Bytes`, `generatePlainUuidV4Slug`, `generateUuidV4WithRandomFill` |
392
+ | Generate UUIDv7 | `generateUuidV7`, `generateUuidV7Bytes`, `generatePlainUuidV7Slug` |
393
+ | Generate one UUIDv7 with its slug | `generateUuidV7WithPlainSlug`, `maskingCodec.generateUuidV7WithMaskedSlug` |
394
+ | Generate an immutable UUIDv7 value | `generateUuidV7Value`, or its generator and masking-codec methods |
395
+ | Control UUIDv7 time, sequence, rollback, or entropy | `createUuidV7Generator`, `createUuidV7GeneratorWithRandomFill` |
396
+ | Convert UUID text, bytes, and plain slugs | `uuidToString`, `uuidToBytes`, `uuidToPlainSlug`, plus source-specific converters |
397
+ | Parse once for repeated work | [`parseUuid`](#parse-once-for-repeated-work) returns an immutable `Uuid` object |
398
+ | Inspect version, variant, timestamp, or payload | `Uuid.inspect`, `extractUuidVersion`, `extractUuidV7UnixMs`, `extractUuidV7Payload` |
399
+ | Narrow untrusted input | `isUuidText`, `isUuidString`, `isUuidBytes`, `isPlainUuidSlug`, their v4/v7 guards, and `isUuidSlugError` |
400
+ | Build UUIDv7 database range keys | `uuidV7StringBounds`, `uuidV7ByteBounds` |
401
+ | Validate a UUIDv7 timestamp window | `validateUuidV7StringUnixMs` and the plain or masked slug equivalents |
402
+ | Derive UUIDv7 masks, with optional async cancellation | `deriveUuidV7Mask`, `deriveUuidV7MaskAsync` |
403
+ | Use an application-defined reversible masking transform | [`createCustomUuidV7Mask`](docs/api.md#masking-codec-options) |
404
+ | Mask, unmask, rotate keys, or reserve sentinels | `createUuidV7MaskingCodec` and its methods |
405
+ | Read explicitly enabled old formats | `maskingCodec.createUuidSlugMigrationDecoder` |
996
406
 
997
- `uuidSlugToUuidString` returns one UUID or `UuidSlugError`: sentinels first, then current keys, then enabled
998
- original and plain formats. A successful decode still needs a record lookup. The same slug can
999
- decode to different UUIDs in different formats; the original check has only four bits.
407
+ Types catch UUID-version and plain/masked mix-ups; results retain text case and buffer ownership.
408
+ Generator, masking-codec and migration methods need no `this` binding.
1000
409
 
1001
- When you know the input format, name it to avoid trying unrelated formats:
410
+ ## Guarantees
1002
411
 
1003
- ```ts
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
- }
1018
- ```
412
+ - Generated IDs have RFC 9562 version and variant bits.
413
+ - Built-in generators use cryptographically secure runtime randomness without weaker fallbacks. If it is unavailable, generation with no arguments or only a text-case or alphabet argument throws `UuidSlugError` with code `rng_unavailable`. Calls with explicit time, a generator, caller output or custom entropy return it.
414
+ - UUIDs **can** still collide even with a very low probability. Use a uniqueness constraint where duplicates could overwrite or misidentify critical data. On conflict creating a record, keep the existing record and generate a new ID.
415
+ - Default calls retain the selected native generator's ordering and clock behavior.
416
+ Use a created generator to control ordering and clock rollback. Native failures fall back to
417
+ the package's generator; if both fail, the error retains both causes.
418
+ - UUIDv7 starts with a 48-bit millisecond timestamp, so UUID strings sort by encoded time across
419
+ different milliseconds. Backfills and clock adjustments can differ from generation order.
420
+ - Successful current-time calls on one created generator strictly increase in UUID byte order
421
+ under the default `clockRollback` policy, `"preserve"`; `at` calls share its sequence state. Module-level
422
+ generation and `"reset"` calls beyond their tolerance do not guarantee this order. Independent generators,
423
+ package copies, workers and processes have separate state; use a sequence column for ordering across them.
424
+ - Plain slugs preserve all UUID bits. Base32hex UUIDv7 slugs sort by timestamp across different
425
+ milliseconds under ASCII comparison. Base64url UUIDv7 slugs are almost time-ordered;
426
+ [ASCII sorting can reverse them](#ordering-and-key-distribution). Masked slugs have no chronological order.
427
+ - Byte generators return a new plain `Uint8Array` or your supplied array, writing only the requested range.
428
+ - `uuidStringToBytes` and `plainSlugToUuidBytes` validate the whole identifier before writing.
429
+ Invalid text or destination ranges return an error without changing caller storage.
430
+ - Named root imports let supported bundlers remove the cipher, key derivation, sentinel table,
431
+ and unrelated generation code.
432
+ - A UUIDv7 masking codec requires explicit private mask options or a package-produced mask.
433
+ Use `UUID_V7_TEST_MASK` explicitly for the public test key; omission does not select it.
1019
434
 
1020
- Enable an old format before selecting it. Recognized sentinels always return their reserved UUID,
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.
435
+ ## Runtime
1026
436
 
1027
- For unknown formats, use `uuidSlugToUuidStringCandidates` to find the matching record without guessing:
437
+ The npm package uses ES modules. Native APIs and portable TypeScript are selected automatically for each runtime and output, so the caller code does not need to choose or coordinate the implementations. When the runtime supports it, the implementation is chosen statically through the `package.json` exports.
1028
438
 
1029
- ```ts
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
- }
1045
- ```
439
+ The [Rust crate](rust/uuid-slug) uses the same identifier formats. Cross-language masked reads require matching seeds, iteration counts and timestamp ranges; see [cross-language contracts](docs/cross-language.md).
1046
440
 
1047
- `findRecordsByUuids` is your database query. Return distinct records by UUID. `uuidSlugToUuidStringCandidates`
1048
- returns distinct UUIDs in decoding order, or an empty array if none match. Malformed input and
1049
- failed mask callbacks return an error. Callback errors keep their cause; they never produce a
1050
- successful but incomplete list.
1051
- An old sentinel alias can also be a seeded masked ID. `uuidSlugToUuidStringCandidates` retains both UUIDs;
1052
- `uuidSlugToUuidString` keeps sentinel priority.
441
+ | Runtime | Package code |
442
+ | --- | --- |
443
+ | Node 20 and newer (also works from 16.20) | Uses compiled JavaScript |
444
+ | Bun 1.0.8 and newer | Uses TypeScript source |
445
+ | Deno 1.29 and newer | Compiled JavaScript; no flag or import map needed |
446
+ | Cloudflare Workers, browsers and other compatible runtimes | Compiled JavaScript over Web Crypto |
1053
447
 
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
1059
- the slug alone, so successful decoding is not a reliable count of legacy traffic.
448
+ Bun's native UUIDv7 timestamp can advance ahead of the clock during bursts. Create a generator to control ordering, clock policy or payload layout.
1060
449
 
1061
- ### Validating timestamp windows
450
+ Conversion and timestamp extraction need no randomness, so read-only tools and static builds can use them. Generation needs secure randomness.
1062
451
 
1063
- ```ts
1064
- import { validateUuidV7StringUnixMs } from "@anizoptera/uuid-slug";
1065
452
 
1066
- function validateRecentUuid(uuid: string) {
1067
- return validateUuidV7StringUnixMs(uuid, { maxTimestampDeltaMs: 60_000 });
1068
- }
1069
- ```
453
+ ## Upgrades and support
1070
454
 
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.
1076
-
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,
1080
- authentication, or replay prevention. Use ordinary decoding for permanent identifiers. For links
1081
- with expiration or one-time use, check the stored expiry and consumption state as well.
1082
-
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.
1093
-
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.
1098
-
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.
455
+ Check the [changelog](CHANGELOG.md) and the [release policy](docs/release.md) before upgrading.
1117
456
 
1118
- ## Guarantees
457
+ Supported identifier formats remain readable across upgrades. Retain the [matching mask settings and migration readers](docs/api.md#changing-an-existing-id-format) for stored masked IDs.
1119
458
 
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.
459
+ Plain slugs recover standard UUIDs without keys or this library. Masked IDs need their keys, range settings and sentinel definitions; custom masks also need their transform implementation.
1123
460
 
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.
1137
- Backfilled timestamps or a clock adjustment need not reflect generation order.
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
1146
- its character order and its value order disagree. Sort by the UUID, or by a timestamp column. A
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
1150
- caller-owned array and write only the requested UUID range.
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.
461
+ The built-in [wire format](docs/design.md) is documented for independent decoders.
1159
462
 
1160
- ## Runtime
463
+ Report bugs through [GitHub issues](https://github.com/Anizoptera/uuid-slug/issues).
1161
464
 
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.
1207
465
 
1208
466
  ## License
1209
467