@anizoptera/uuid-slug 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -1062
- package/dist/alphabet.d.ts +1 -3
- package/dist/alphabet.d.ts.map +1 -1
- package/dist/alphabet.js +32 -90
- package/dist/alphabet.js.map +1 -1
- package/dist/base64url-name.d.ts +1 -3
- package/dist/base64url-name.d.ts.map +1 -1
- package/dist/base64url-name.js +2 -3
- package/dist/errors.d.ts +1 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +7 -24
- package/dist/errors.js.map +1 -1
- package/dist/feistel.js +1 -2
- package/dist/generation-options.js +2 -3
- package/dist/index.d.ts +10 -10
- package/dist/index.js +21 -21
- package/dist/instant.js +2 -3
- package/dist/mask-handle.d.ts +1 -3
- package/dist/mask-handle.d.ts.map +1 -1
- package/dist/mask-handle.js +19 -17
- package/dist/mask-handle.js.map +1 -1
- package/dist/mask.d.ts +1 -3
- package/dist/mask.d.ts.map +1 -1
- package/dist/mask.js +23 -24
- package/dist/mask.js.map +1 -1
- package/dist/masked-bytes.js +74 -0
- package/dist/masked-bytes.js.map +1 -0
- package/dist/masking-codec-protocol.js +2 -3
- package/dist/masking-codec-types.d.ts +60 -19
- package/dist/masking-codec-types.d.ts.map +1 -1
- package/dist/masking-codec.d.ts +1 -3
- package/dist/masking-codec.d.ts.map +1 -1
- package/dist/masking-codec.js +115 -111
- package/dist/masking-codec.js.map +1 -1
- package/dist/migration.js +39 -40
- package/dist/migration.js.map +1 -1
- package/dist/node/runtime.js +2 -3
- package/dist/payload.d.ts +1 -3
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +65 -64
- package/dist/payload.js.map +1 -1
- package/dist/runtime/pool.js +2 -3
- package/dist/runtime/portable.js +2 -3
- package/dist/runtime/portable.js.map +1 -1
- package/dist/sentinel.js +2 -3
- package/dist/siphash.js +1 -2
- package/dist/slug.d.ts +14 -13
- package/dist/slug.d.ts.map +1 -1
- package/dist/slug.js +144 -152
- package/dist/slug.js.map +1 -1
- package/dist/timestamp.d.ts +1 -3
- package/dist/timestamp.d.ts.map +1 -1
- package/dist/timestamp.js +2 -3
- package/dist/types.d.ts +38 -16
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -3
- package/dist/types.js.map +1 -1
- package/dist/uuid-value-protocol.js +2 -3
- package/dist/uuid-value.d.ts +3 -5
- package/dist/uuid-value.d.ts.map +1 -1
- package/dist/uuid-value.js +74 -78
- package/dist/uuid-value.js.map +1 -1
- package/dist/uuid.d.ts +6 -8
- package/dist/uuid.d.ts.map +1 -1
- package/dist/uuid.js +34 -45
- package/dist/uuid.js.map +1 -1
- package/dist/v4-slug.d.ts +2 -4
- package/dist/v4-slug.d.ts.map +1 -1
- package/dist/v4-slug.js +6 -7
- package/dist/v4.d.ts +8 -6
- package/dist/v4.d.ts.map +1 -1
- package/dist/v4.js +3 -9
- package/dist/v4.js.map +1 -1
- package/dist/v7-bounds.d.ts +3 -5
- package/dist/v7-bounds.d.ts.map +1 -1
- package/dist/v7-bounds.js +8 -9
- package/dist/v7-bounds.js.map +1 -1
- package/dist/v7-generator-input.js +10 -11
- package/dist/v7-generator-input.js.map +1 -1
- package/dist/v7-generator.d.ts +1 -3
- package/dist/v7-generator.d.ts.map +1 -1
- package/dist/v7-generator.js +13 -14
- package/dist/v7-keyless.d.ts +12 -4
- package/dist/v7-keyless.d.ts.map +1 -1
- package/dist/v7-keyless.js +2 -3
- package/dist/v7-keyless.js.map +1 -1
- package/dist/v7-payload.js +2 -3
- package/dist/v7-slug.d.ts +8 -5
- package/dist/v7-slug.d.ts.map +1 -1
- package/dist/v7-slug.js +28 -29
- package/dist/v7-slug.js.map +1 -1
- package/dist/v7-timestamp.js +2 -3
- package/dist/v7-value-options.js +2 -3
- package/dist/v7-value.d.ts +5 -8
- package/dist/v7-value.d.ts.map +1 -1
- package/dist/v7-value.js +10 -11
- package/dist/v7-value.js.map +1 -1
- package/dist/v7.js +16 -17
- package/dist/v7.js.map +1 -1
- package/package.json +6 -4
- package/src/alphabet.ts +84 -239
- package/src/errors.ts +30 -43
- package/src/feistel.ts +4 -4
- package/src/generation-options.ts +1 -1
- package/src/index.ts +3 -0
- package/src/mask-handle.ts +7 -11
- package/src/mask.ts +16 -14
- package/src/masked-bytes.ts +203 -0
- package/src/masking-codec-protocol.ts +1 -1
- package/src/masking-codec-types.ts +124 -24
- package/src/masking-codec.ts +44 -43
- package/src/migration.ts +8 -7
- package/src/payload.ts +71 -53
- package/src/runtime/bun.ts +1 -1
- package/src/runtime/node.ts +2 -2
- package/src/runtime/pool.ts +1 -1
- package/src/runtime/portable.ts +3 -3
- package/src/runtime/types.ts +2 -4
- package/src/slug.ts +45 -54
- package/src/types.ts +108 -17
- package/src/uuid-value-protocol.ts +1 -1
- package/src/uuid-value.ts +3 -10
- package/src/uuid.ts +27 -41
- package/src/v4.ts +14 -11
- package/src/v7-bounds.ts +7 -5
- package/src/v7-generator-input.ts +4 -7
- package/src/v7-generator.ts +2 -2
- package/src/v7-keyless.ts +35 -6
- package/src/v7-payload.ts +1 -1
- package/src/v7-slug.ts +21 -2
- package/src/v7-value.ts +9 -4
- package/src/v7.ts +27 -1
package/README.md
CHANGED
|
@@ -1,1209 +1,379 @@
|
|
|
1
1
|
# @anizoptera/uuid-slug
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
[](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml)
|
|
5
|
-
[](package.json)
|
|
6
|
-
[](package.json)
|
|
7
|
-
[](LICENSE)
|
|
8
|
-
|
|
9
|
-
## TL;DR
|
|
10
|
-
|
|
11
|
-
**Zero-dependency UUIDv4/v7 generation, lossless base64url and base32hex slugs for any UUID, and reversible UUIDv7 masking for databases, URLs, and files.**
|
|
12
|
-
|
|
13
|
-
- Encode any UUID as short `base64url` or lowercase `base32hex`.
|
|
14
|
-
- Use optional reversible masking to hide the timestamp and structure of UUIDv7 slugs.
|
|
15
|
-
- Keep one ID across all representations, with no lost bits or mapping table.
|
|
16
|
-
- Write directly into your buffers without intermediate text or new output arrays.
|
|
17
|
-
- Read the time directly from UUIDv7 when it is the timestamp your application needs.
|
|
18
|
-
- Use native runtime APIs with matching portable fallbacks.
|
|
19
|
-
- Failures return typed errors. Built-in generation never falls back to weaker randomness.
|
|
20
|
-
- Unused features tree-shake away with any modern bundler.
|
|
21
|
-
|
|
22
|
-
[Install](#install) · [Quick start](#quick-start) · [Contents](#contents) · [API](#api) · [Performance](#measured-performance)
|
|
23
|
-
|
|
24
|
-
### TypeScript API map
|
|
25
|
-
|
|
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.
|
|
31
|
-
|
|
32
|
-
```text
|
|
33
|
-
UUID text ─┐
|
|
34
|
-
UUID bytes ├── keyless conversion ── UUID text / bytes / plain slug
|
|
35
|
-
plain slug ┘
|
|
36
|
-
|
|
37
|
-
UUIDv7 text / bytes / plain slug ── masking codec ── masked slug / sentinel / decoded UUID
|
|
38
|
-
│
|
|
39
|
-
├── current + previous masks
|
|
40
|
-
└── opt-in migration reader
|
|
41
|
-
```
|
|
3
|
+
Fastest UUIDv4/v7 generation and handling for TS, Rust, and WASM, short base64/base32 plain and masked slugs. Zero runtime deps, tree-shakable, and optimised for your runtime. One efficient ID for databases, URLs and files.
|
|
42
4
|
|
|
43
|
-
|
|
44
|
-
`ch` means text characters and `B` means bytes.
|
|
5
|
+
[](https://www.npmjs.com/package/@anizoptera/uuid-slug) [](https://github.com/Anizoptera/uuid-slug/actions/workflows/check.yml) [](package.json) [](#runtime) [](#runtime) [](#runtime) [](#runtime) [](LICENSE)
|
|
45
6
|
|
|
46
|
-
|
|
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.
|
|
7
|
+
[](https://raw.githubusercontent.com/Anizoptera/uuid-slug/main/docs/assets/uuid-representations.svg)
|
|
65
8
|
|
|
66
|
-
|
|
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` |
|
|
9
|
+
<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>
|
|
82
10
|
|
|
83
|
-
|
|
84
|
-
|
|
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
|
|
120
|
-
```
|
|
11
|
+
- **Benchmark-leading UUIDv7 text generation on Node, Bun, Deno and browsers!**
|
|
12
|
+
- 6+ distinct UUID representations are supported!
|
|
121
13
|
|
|
122
|
-
|
|
14
|
+
- **[Leading performance](bench/results/competitors.md)**, low memory and resource allocation!
|
|
15
|
+
- Same API across Node, Bun, Deno, browsers and cloud workers. Native fast paths and portable fallbacks are used automatically.
|
|
16
|
+
- _IDs can be generated or decoded [directly into your buffers](#work-with-uuid-bytes); failed validation leaves them unchanged._
|
|
123
17
|
|
|
124
|
-
|
|
18
|
+
- **Zero runtime dependencies.** Small [runtime-optimised](#runtime) bundles on Node, Bun, Deno and browsers.
|
|
125
19
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
20
|
+
- **One UUID for storage, URLs and files, each in its [most compact form](#representations)!**
|
|
21
|
+
- 16-byte binary UUID for storage or transport.
|
|
22
|
+
- **Short 22-character base64url slug for URLs** (39% shorter than a naive UUID text).
|
|
23
|
+
- 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.
|
|
24
|
+
- Optional **[UUIDv7 masked slug](#masked-slugs) form that hides timestamp and UUID structure.** Expose your IDs without revealing their creation time or nature!
|
|
25
|
+
- _Any UUID converts to a lossless plain slug and back. Existing database keys stay unchanged; no mapping table is needed._
|
|
26
|
+
- _Plain slugs decode with any standard base64url or base32hex decoder, without this library. Masked slugs need your key and settings._
|
|
130
27
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
- [Install](#install)
|
|
141
|
-
- [Quick start](#quick-start)
|
|
142
|
-
- [Keep your existing UUIDs](#keep-your-existing-uuids)
|
|
143
|
-
- [Assign IDs before saving or syncing](#assign-ids-before-saving-or-syncing)
|
|
144
|
-
- [Generate at a recorded time](#generate-at-a-recorded-time)
|
|
145
|
-
- [Use the UUID as the timestamp source](#use-the-uuid-as-the-timestamp-source)
|
|
146
|
-
- [Representations](#representations)
|
|
147
|
-
- [Work with UUID bytes](#work-with-uuid-bytes)
|
|
148
|
-
- [Two kinds of slug](#two-kinds-of-slug)
|
|
149
|
-
- [Plain slugs](#plain-slugs) · [Masked slugs](#masked-slugs) · [Sentinels](#sentinels)
|
|
150
|
-
- [Ordering and key distribution](#ordering-and-key-distribution)
|
|
151
|
-
- [What masking is not](#what-masking-is-not)
|
|
152
|
-
- [Handling errors](#handling-errors)
|
|
153
|
-
- [Types](#types)
|
|
154
|
-
- [API](#api)
|
|
155
|
-
- [Generate IDs](#generate-ids) · [Convert and inspect IDs](#convert-and-inspect-ids)
|
|
156
|
-
- [Use a masking codec](#use-a-masking-codec) · [Constructors and guards](#constructors-and-guards)
|
|
157
|
-
- [Masking codec options](#masking-codec-options)
|
|
158
|
-
- [Changing an existing ID format](#changing-an-existing-id-format)
|
|
159
|
-
- [Reading original slugs during migration](#reading-original-slugs-during-migration)
|
|
160
|
-
- [Validating timestamp windows](#validating-timestamp-windows)
|
|
161
|
-
- [Measured performance](#measured-performance)
|
|
162
|
-
- [Guarantees](#guarantees)
|
|
163
|
-
- [Runtime](#runtime)
|
|
164
|
-
- [License](#license)
|
|
165
|
-
|
|
166
|
-
## Keep your existing UUIDs
|
|
28
|
+
- **UUIDv4/v7 generation, conversion and inspection, configurable UUIDv7 masking, and plain conversion for any UUID!**
|
|
29
|
+
- **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).
|
|
30
|
+
- IDs and relationships can be [created offline](#assign-ids-before-saving-or-syncing), before saving or syncing, without a central allocator or worker number.
|
|
31
|
+
- Masking [key rotation and format migration](docs/api.md#changing-an-existing-id-format) keep old IDs readable while new IDs use current settings.
|
|
32
|
+
- [Async key derivation](docs/api.md#masking-codec-options) yields during long work and can be cancelled.
|
|
33
|
+
- [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.
|
|
34
|
+
- Optional [sentinel IDs](#sentinels): reserved values for tests, debugging and tracing that stay recognizable in logs, even after key rotation.
|
|
35
|
+
- Optimal, **safe and most efficient defaults!**
|
|
167
36
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
37
|
+
- **Intuitive, ergonomic, agent-friendly manually tailored API.**
|
|
38
|
+
- Strict types, validation, typed errors, safe buffer writes and one-check composition to prevent integration mistakes.
|
|
39
|
+
- Types catch UUID-version and plain/masked mix-ups before execution. Compatible conversions chain with one error check; failures have stable codes.
|
|
40
|
+
- **Named imports let supported bundlers [remove unused features](#guarantees), including masking and key derivation.**
|
|
172
41
|
|
|
173
|
-
|
|
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.
|
|
42
|
+
- TypeScript and Rust implementations that encode and decode the same formats, including masked IDs with matching key settings.
|
|
177
43
|
|
|
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
44
|
|
|
183
|
-
|
|
184
|
-
same millisecond follow their generator's payload rules; UUIDv7 alone does not promise their order.
|
|
45
|
+
[Install](#install) · [Quick start](#quick-start) · [Contents](#contents) · [API](#api) · [Performance](bench/results/competitors.md)
|
|
185
46
|
|
|
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
47
|
|
|
194
|
-
|
|
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.
|
|
48
|
+
## Install
|
|
197
49
|
|
|
198
|
-
Use
|
|
199
|
-
|
|
50
|
+
Use your favorite TS/JS package manager (npm/bun/pnpm/yarn/..), e.g.:
|
|
51
|
+
```
|
|
52
|
+
bun install @anizoptera/uuid-slug
|
|
53
|
+
```
|
|
200
54
|
|
|
201
|
-
|
|
55
|
+
Rust: `cargo add uuid-slug`. Build browser WASM from the Rust crate with `wasm-js`.
|
|
202
56
|
|
|
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
57
|
|
|
208
|
-
##
|
|
58
|
+
## Quick start
|
|
209
59
|
|
|
210
|
-
|
|
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.
|
|
60
|
+
One call returns the same ID as `uuid` for storage and `slug` for URLs:
|
|
219
61
|
|
|
220
62
|
```ts
|
|
221
|
-
import {
|
|
63
|
+
import { generateUuidV7WithPlainSlug } from "@anizoptera/uuid-slug";
|
|
64
|
+
import type { GeneratedUuidV7, PlainUuidV7Slug } from "@anizoptera/uuid-slug";
|
|
222
65
|
|
|
223
|
-
|
|
224
|
-
return generatePlainUuidV7Slug({ at: recordedAt, alphabet: BASE32HEX });
|
|
225
|
-
}
|
|
66
|
+
const { uuid, slug }: GeneratedUuidV7<PlainUuidV7Slug> = generateUuidV7WithPlainSlug();
|
|
226
67
|
```
|
|
227
68
|
|
|
228
|
-
|
|
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`.
|
|
69
|
+
`uuid` has type `UuidV7String`; `slug` has type `PlainUuidV7Slug`. These are ordinary strings at runtime; TypeScript retains their UUID version and representation. Unchecked external IDs remain `string` inputs; conversion and parsing validate them.
|
|
258
70
|
|
|
259
|
-
|
|
71
|
+
Use `generateUuidV4()` for random IDs, `generateUuidV7()` for timestamped IDs, or `generatePlainUuidV7Slug()` for just the slug. Default generation returns the ID and throws `rng_unavailable` only without secure randomness. [Conversions return errors as values](#handling-errors).
|
|
260
72
|
|
|
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:
|
|
263
73
|
|
|
264
|
-
|
|
265
|
-
import { extractUuidV7UnixMs, isUuidSlugError } from "@anizoptera/uuid-slug";
|
|
74
|
+
## Contents
|
|
266
75
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
76
|
+
- [Performance](bench/results/competitors.md) · [Install](#install) · [Quick start](#quick-start)
|
|
77
|
+
- [Convert existing IDs](#keep-your-existing-uuids) · [Representations](#representations)
|
|
78
|
+
- [Plain slugs](#plain-slugs) · [Masking](#masked-slugs) · [Sentinels](#sentinels) · [Bytes](#work-with-uuid-bytes)
|
|
79
|
+
- [Parse once](#parse-once-for-repeated-work) · [Offline IDs](#assign-ids-before-saving-or-syncing)
|
|
80
|
+
- [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)
|
|
81
|
+
- [Errors](#handling-errors) · [Types](docs/api.md#types)
|
|
82
|
+
- [API](#api) · [TypeScript API map](#typescript-api-map)
|
|
83
|
+
- [Codec options](docs/api.md#masking-codec-options) · [Migration](docs/api.md#reading-original-slugs-during-migration)
|
|
84
|
+
- [Guarantees](#guarantees)
|
|
85
|
+
- [Runtime](#runtime)
|
|
86
|
+
- [Upgrades and support](#upgrades-and-support)
|
|
87
|
+
- [License](#license)
|
|
272
88
|
|
|
273
|
-
|
|
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.
|
|
89
|
+
## Keep your existing UUIDs
|
|
276
90
|
|
|
277
|
-
|
|
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:
|
|
91
|
+
Encode stored UUIDs; decode incoming slugs before querying the same keys. Plain encoding preserves every bit. Standard encodings let you decode plain slugs without this library; **masked slugs need the matching key and settings**.
|
|
280
92
|
|
|
281
93
|
```ts
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
counterBits: 14,
|
|
285
|
-
});
|
|
286
|
-
```
|
|
94
|
+
import { isUuidSlugError, plainSlugToUuidString, uuidStringToPlainSlug } from "@anizoptera/uuid-slug";
|
|
95
|
+
import type { PlainUuidSlug, UuidSlugError, UuidString } from "@anizoptera/uuid-slug";
|
|
287
96
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
Use `maskingCodec.extractMaskedUuidV7Payload(slug, layout)` for masked slugs and sentinels.
|
|
97
|
+
const slug: PlainUuidSlug | UuidSlugError = uuidStringToPlainSlug("0198abcd-1234-7abc-9def-0123456789ab");
|
|
98
|
+
if (typeof slug === "string") console.log(slug);
|
|
99
|
+
else console.error(slug.message);
|
|
292
100
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
Keep a separate field for other dates, finer precision, editable times, or date queries your UUID
|
|
296
|
-
index cannot serve. Changing the timestamp inside a UUID changes the ID.
|
|
297
|
-
|
|
298
|
-
## Representations
|
|
101
|
+
// Alternative to the typeof check: the helper recognizes returned error values.
|
|
102
|
+
if (!isUuidSlugError(slug)) console.log(slug);
|
|
299
103
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
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
|
|
104
|
+
const uuid: UuidString | UuidSlugError = plainSlugToUuidString("AZirzRI0eryd7wEjRWeJqw");
|
|
105
|
+
if (typeof uuid === "string") console.log(uuid); // The database key for this incoming URL slug.
|
|
106
|
+
else console.error(uuid.message);
|
|
320
107
|
```
|
|
321
108
|
|
|
322
|
-
|
|
109
|
+
## Representations
|
|
323
110
|
|
|
324
|
-
|
|
111
|
+
A masking codec holds the keys and settings to encode and decode UUIDv7 slugs and masked bytes.
|
|
325
112
|
|
|
326
|
-
|
|
113
|
+
All examples encode the same UUIDv7; sizes are characters except for bytes.
|
|
327
114
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
115
|
+
| Representation | Size | Example | Meaning and use |
|
|
116
|
+
| --- | ---: | --- | --- |
|
|
117
|
+
| UUID text | 36 | `0198abcd-1234-7abc-9def-0123456789ab` | Lowercase hyphenated output; uppercase optional |
|
|
118
|
+
| 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 |
|
|
119
|
+
| Plain base64url slug | 22 | `AZirzRI0eryd7wEjRWeJqw` | 39% shorter than UUID text; lossless for any UUID; case-sensitive; almost time-ordered for UUIDv7 |
|
|
120
|
+
| Plain base32hex slug | 26 | `06canj8i6htbp7ff04hkaps9lc` | 28% shorter than UUID text; keyless, lossless; writes lowercase, accepts mixed case; UUIDv7 sorts by timestamp in ASCII order |
|
|
121
|
+
| Masked base64url UUIDv7 slug | 22 | `ap225Qa_y6wN5LQCJgwH0z` | 39% shorter than UUID text; opaque, case-sensitive, unordered; 16-bit check; requires its codec to decode |
|
|
122
|
+
| Masked base32hex UUIDv7 slug | 27 | `daerdp86nv5qo3f4mg12c307qco` | 25% shorter than UUID text; opaque, unordered; writes lowercase, accepts mixed case; requires its codec to decode |
|
|
123
|
+
| Masked UUIDv7 bytes | 16 | `6a 9d b6 e5 06 bf cb ac 0d e4 b4 02 26 0c 07 d3` | The same mixed block without text encoding; 12-bit check; requires its codec to decode |
|
|
335
124
|
|
|
336
|
-
|
|
125
|
+
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). Masked examples use the public `UUID_V7_TEST_MASK`; use a private seed for your IDs.
|
|
337
126
|
|
|
338
|
-
|
|
339
|
-
import { uuidStringToBytes } from "@anizoptera/uuid-slug";
|
|
127
|
+
Plain and masked base64url slugs can look identical but decode to different UUIDs. 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.
|
|
340
128
|
|
|
341
|
-
|
|
342
|
-
const record = new Uint8Array(32);
|
|
343
|
-
return uuidStringToBytes("01990d4d-e600-7000-8000-000000000000", record, 8);
|
|
344
|
-
}
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
`uuidStringToBytes` accepts mixed-case canonical or compact UUID text, UUID URNs, and canonical text
|
|
348
|
-
enclosed by braces. It either allocates a plain
|
|
349
|
-
`Uint8Array` or writes 16 bytes at the requested offset. `bytesToUuidString` reads 16 bytes at an
|
|
350
|
-
optional offset and returns lowercase hyphenated text by default. Pass `UUID_TEXT_UPPERCASE` or
|
|
351
|
-
`"uppercase"` for uppercase output, or `UUID_TEXT_LOWERCASE` when the default must be an explicit
|
|
352
|
-
reusable choice.
|
|
353
|
-
The same optional preset works on every operation that returns UUID text, including generators,
|
|
354
|
-
plain and masked decoders, timestamp validation, and migration readers. It changes only UUID text;
|
|
355
|
-
slug alphabets and accepted input stay independent.
|
|
356
|
-
`Buffer` works because it is a `Uint8Array`. A standalone `ArrayBuffer` must contain exactly 16
|
|
357
|
-
bytes. A `DataView` must declare an exact 16-byte range, which can select a UUID inside a larger
|
|
358
|
-
buffer without copying. Offsets apply only to `Uint8Array`; other typed arrays and array-like values
|
|
359
|
-
are rejected. Use `isUuidBytes`, `isUuidV4Bytes`, or `isUuidV7Bytes` when unknown binary input must
|
|
360
|
-
be narrowed before storage or version-specific work.
|
|
361
|
-
|
|
362
|
-
For a binary database key or protocol field, use `uuidBytesToPlainSlug(record, offset)` and
|
|
363
|
-
`plainSlugToUuidBytes(slug, record, offset)` to avoid UUID text and temporary slices. Use
|
|
364
|
-
`maskingCodec.uuidToBytes(slug, record, offset)` for masked IDs. These writes return the original
|
|
365
|
-
array, not a view of the UUID. Read it back at the same offset. Copy bytes you need to keep before
|
|
366
|
-
reusing the buffer.
|
|
129
|
+
Generate bytes once when you need several representations, then convert only those you use. Use paired generation when you need UUID text plus one slug.
|
|
367
130
|
|
|
368
131
|
## Two kinds of slug
|
|
369
132
|
|
|
370
133
|
### Plain slugs
|
|
371
134
|
|
|
372
|
-
|
|
373
|
-
`uuidStringToPlainSlug` and `uuidToString` preserve the UUID value, and anyone can convert either way. Use it
|
|
374
|
-
when you only want the identifier shorter.
|
|
375
|
-
|
|
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.
|
|
135
|
+
_Examples: `AZirzRI0eryd7wEjRWeJqw` (base64url), `06canj8i6htbp7ff04hkaps9lc` (base32hex)_
|
|
380
136
|
|
|
381
|
-
|
|
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.
|
|
137
|
+
A plain slug is the UUID's 16 bytes in base64url (22 characters) or base32hex (26), with no key. Use `uuidStringToPlainSlug` to encode a UUID and `plainSlugToUuidString` to recover it. Decoders reject `=` padding and nonzero unused bits in the last character. `isPlainUuidSlug` checks canonical spelling and returns a boolean.
|
|
384
138
|
|
|
385
|
-
|
|
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.
|
|
139
|
+
Pass `BASE32HEX` to a plain-slug writer, for example `generatePlainUuidV7Slug(BASE32HEX)`; see [ordering](#ordering-and-key-distribution).
|
|
388
140
|
|
|
389
|
-
`uuidToString` infers the alphabet from the length, 22 or 26, so
|
|
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.
|
|
141
|
+
`uuidToString` infers the alphabet from the length automatically, 22 or 26, so old slugs survive alphabet changes. It returns lowercase UUID text by default. Decode before comparing IDs or building cache keys: different spellings can identify the same record. Preserve base64url case; lowercasing changes the value.
|
|
394
142
|
|
|
395
143
|
### Masked slugs
|
|
396
144
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
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).
|
|
145
|
+
_Examples: `ap225Qa_y6wN5LQCJgwH0z` (base64url), `daerdp86nv5qo3f4mg12c307qco` (base32hex)_
|
|
146
|
+
|
|
147
|
+
Hide UUIDv7 timestamps and other standard fields with a reusable masking codec. Codecs default to base64url; set `maskedSlugAlphabet: BASE32HEX` for lowercase filenames.
|
|
403
148
|
|
|
404
|
-
Use a
|
|
149
|
+
Supply either `maskSeed` or `mask`; neither or both returns `invalid_mask`. 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
150
|
|
|
406
151
|
```ts
|
|
407
152
|
import {
|
|
408
153
|
createUuidV7MaskingCodec,
|
|
409
154
|
isUuidSlugError,
|
|
155
|
+
UUID_V7_TEST_MASK,
|
|
410
156
|
} from "@anizoptera/uuid-slug";
|
|
157
|
+
import type { MaskedOrSentinelUuidV7Slug, UuidSlugError, UuidV7MaskingCodec } from "@anizoptera/uuid-slug";
|
|
411
158
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
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`:
|
|
159
|
+
const maskingCodec: UuidV7MaskingCodec | UuidSlugError = createUuidV7MaskingCodec({
|
|
160
|
+
mask: UUID_V7_TEST_MASK,
|
|
161
|
+
});
|
|
472
162
|
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
});
|
|
481
|
-
return isUuidSlugError(maskingCodec) ? maskingCodec : maskingCodec.sentinels;
|
|
163
|
+
if (isUuidSlugError(maskingCodec)) {
|
|
164
|
+
console.error(maskingCodec.message);
|
|
165
|
+
} else {
|
|
166
|
+
const storedUuid = "0198abcd-1234-7abc-9def-0123456789ab";
|
|
167
|
+
const slug: MaskedOrSentinelUuidV7Slug | UuidSlugError = maskingCodec.uuidToMaskedSlug(storedUuid);
|
|
168
|
+
if (typeof slug === "string") console.log(slug);
|
|
169
|
+
else console.error(slug.message);
|
|
482
170
|
}
|
|
483
171
|
```
|
|
484
172
|
|
|
485
|
-
|
|
486
|
-
unique. Its input accepts every UUID text spelling above; `maskingCodec.sentinels` exposes normalized lowercase text.
|
|
487
|
-
|
|
488
|
-
Sentinels keep their spelling across seed rotation when the alphabet and reserved UUIDs stay the
|
|
489
|
-
same. This lets reserved identities remain recognizable while ordinary IDs use the new mask.
|
|
490
|
-
The example named `nil` is an application sentinel, not the all-zero UUID; that UUID
|
|
491
|
-
is not UUIDv7 and cannot be a masking-codec sentinel.
|
|
492
|
-
|
|
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.
|
|
173
|
+
Construct and check the codec once; reuse it to avoid per-ID key derivation. Its methods need no `bind`. The public test mask makes this example reproducible; production codecs need a private seed. Masking accepts UUIDv7s from other generators and preserves all their payload bits. For new IDs, `maskingCodec.generateUuidV7WithMaskedSlug()` returns the UUID and slug together; `maskingCodec.generateMaskedUuidV7Slug()` returns just the slug. Both can return `UuidSlugError`. [Async mask derivation](docs/api.md#masking-codec-options) lets other work run during long setup and supports cancellation.
|
|
497
174
|
|
|
498
|
-
|
|
175
|
+
Generate a random seed, for example with `openssl rand -base64 32`, and keep it outside source control. Seeds need at least 16 bytes; length alone does not prevent offline guessing from known UUID/slug pairs.
|
|
499
176
|
|
|
500
|
-
|
|
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.
|
|
177
|
+
Changing the seed or `keyDerivationIterations` changes keys. Keep old mask settings and range starts in `previousMasks` while old slugs must work. Retain each live format's sentinel definitions too. New slugs use current keys. Deploy both readers before switching writers; bookmarks still need their old decoder. See [migration](docs/api.md#changing-an-existing-id-format). `keyDerivationIterations` defaults to `1`. More iterations increase setup and guessing costs; they do not make a human-chosen seed suitable.
|
|
546
178
|
|
|
547
|
-
|
|
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
|
-
```
|
|
179
|
+
Masking covers roughly 139 years from `timestampRangeStartUnixMs`. The default starts at the Unix epoch and ends in May 2109. Outside that range, masking returns `invalid_timestamp` rather than lose timestamp bits. Plain slugs and sentinels retain the full UUIDv7 range. See [exact bounds and range configuration](docs/design.md#representations-and-bit-budget).
|
|
563
180
|
|
|
564
|
-
|
|
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.
|
|
181
|
+
### Sentinels
|
|
571
182
|
|
|
572
|
-
|
|
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.
|
|
183
|
+
Reserve UUIDv7 values that stay recognizable in logs: codecs write them as plain slugs, even after key rotation. Codecs have none by default. Keep their definitions unchanged while their slugs remain in use. See [sentinel setup and collision handling](docs/api.md#sentinels).
|
|
575
184
|
|
|
576
|
-
##
|
|
185
|
+
## Work with UUID bytes
|
|
577
186
|
|
|
578
|
-
|
|
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.
|
|
187
|
+
Generation can write an ID into an existing binary record:
|
|
583
188
|
|
|
584
189
|
```ts
|
|
585
|
-
import {
|
|
190
|
+
import { generateUuidV7Bytes, isUuidSlugError } from "@anizoptera/uuid-slug";
|
|
191
|
+
import type { UuidSlugError } from "@anizoptera/uuid-slug";
|
|
586
192
|
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
}
|
|
193
|
+
const record: Uint8Array = new Uint8Array(32);
|
|
194
|
+
const result: Uint8Array | UuidSlugError = generateUuidV7Bytes(record, 8);
|
|
195
|
+
if (isUuidSlugError(result)) console.error(result.message);
|
|
196
|
+
else console.log(result); // The same record, with its ID at bytes 8 through 23.
|
|
592
197
|
```
|
|
593
198
|
|
|
594
|
-
|
|
595
|
-
intermediate result only when the caller also needs that intermediate successful value.
|
|
199
|
+
Write directly into your database or protocol buffer with `uuidStringToBytes`, `plainSlugToUuidBytes` or `maskingCodec.maskedSlugToUuidBytes`. Pass the array and offset; the call returns your array and leaves other bytes unchanged. Failed validation leaves the buffer unchanged. See [buffer examples and accepted byte forms](docs/api.md#work-with-uuid-bytes).
|
|
596
200
|
|
|
597
|
-
|
|
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`.
|
|
201
|
+
For client-visible binary IDs, use `maskingCodec.uuidToMaskedBytes(uuid, record, offset)` or omit storage for an owned 16-byte result. Read directly from a packet with `maskingCodec.maskedBytesToUuidString(record, offset)` or `maskedBytesToUuidBytes(record, offset, output, outputOffset)`. Omit the input offset for a standalone value and output storage for owned bytes. Raw and masked bytes can represent different UUIDs, so ordinary UUID readers never infer masking. Binary preserves the slug's UUID payload and settings, with a 12-bit check instead of text's 16-bit check; neither authorizes access. Registered sentinels retain their raw UUID bytes.
|
|
602
202
|
|
|
603
|
-
|
|
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.
|
|
203
|
+
## Parse once for repeated work
|
|
607
204
|
|
|
608
|
-
|
|
609
|
-
import { BASE32HEX, uuidBytesToPlainSlug } from "@anizoptera/uuid-slug";
|
|
205
|
+
`parseUuid` validates and decodes an ID once for repeated conversion and inspection. It returns an immutable `Uuid` object, not a string. Changes to its byte outputs leave the retained UUID unchanged.
|
|
610
206
|
|
|
611
|
-
|
|
612
|
-
|
|
207
|
+
```ts
|
|
208
|
+
import { isUuidSlugError, parseUuid } from "@anizoptera/uuid-slug";
|
|
209
|
+
import type { PlainUuidSlug, Uuid, UuidBytes, UuidInspection, UuidSlugError } from "@anizoptera/uuid-slug";
|
|
210
|
+
|
|
211
|
+
const input = "0198abcd-1234-7abc-9def-0123456789ab";
|
|
212
|
+
const uuid: Uuid | UuidSlugError = parseUuid(input);
|
|
213
|
+
if (isUuidSlugError(uuid)) {
|
|
214
|
+
console.error(uuid.message);
|
|
215
|
+
} else {
|
|
216
|
+
const bytes: UuidBytes = uuid.toBytes();
|
|
217
|
+
const slug: PlainUuidSlug = uuid.toPlainSlug();
|
|
218
|
+
const details: UuidInspection = uuid.inspect();
|
|
219
|
+
console.log(bytes, slug, details);
|
|
613
220
|
}
|
|
614
221
|
```
|
|
615
222
|
|
|
616
|
-
##
|
|
223
|
+
## Assign IDs before saving or syncing
|
|
617
224
|
|
|
618
|
-
|
|
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.
|
|
225
|
+
Create IDs before saving, even offline. Related records can reference them without a database round trip and keep them after synchronization. No central allocator or worker number is needed. Any generator works, e.g. `generateUuidV7()`, wherever the record is created.
|
|
623
226
|
|
|
624
|
-
|
|
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.
|
|
227
|
+
## Generate at a recorded time
|
|
628
228
|
|
|
629
|
-
|
|
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.
|
|
229
|
+
Set `at` on UUIDv7 generation calls to encode a record's time instead of now. It accepts a `Date`, Unix milliseconds, zoned ISO text, Temporal-style instants and `{ seconds, nanoseconds }` timestamps without manual conversion. See [accepted time forms and configured fractional precision](docs/api.md#supplied-time).
|
|
634
230
|
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
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.
|
|
231
|
+
```ts
|
|
232
|
+
import { BASE32HEX, generatePlainUuidV7Slug } from "@anizoptera/uuid-slug";
|
|
233
|
+
import type { PlainUuidV7Slug, UuidSlugError } from "@anizoptera/uuid-slug";
|
|
677
234
|
|
|
678
|
-
|
|
235
|
+
const recordedAt = "2026-01-01T12:00:00Z"; // Also accepts Date or Unix milliseconds.
|
|
236
|
+
const slug: PlainUuidV7Slug | UuidSlugError = generatePlainUuidV7Slug({ at: recordedAt, alphabet: BASE32HEX });
|
|
237
|
+
if (typeof slug === "string") console.log(slug);
|
|
238
|
+
else console.error(slug.message);
|
|
239
|
+
```
|
|
679
240
|
|
|
680
|
-
|
|
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.
|
|
241
|
+
Use one `createUuidV7Generator` generator across output forms to share a sequence, including `at` calls. Module-level calls remain independent.
|
|
685
242
|
|
|
686
|
-
|
|
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.
|
|
243
|
+
Calls use fresh randomness even at identical timestamps. For retries, retain the first ID or use a deduplication key; existing records keep their UUIDs. Masked IDs need a [timestamp range](#masked-slugs) covering the recorded time.
|
|
689
244
|
|
|
690
|
-
|
|
245
|
+
To keep IDs in order, a generator may encode a time slightly after the one you supplied.
|
|
691
246
|
|
|
692
|
-
|
|
693
|
-
independent generator; UUIDv4 and plain-slug generation remain module-level.
|
|
247
|
+
## Use the UUID as the timestamp source
|
|
694
248
|
|
|
695
|
-
|
|
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.
|
|
249
|
+
Read UUIDv7's millisecond timestamp without a database lookup or UUID-text conversion. If it is the time you need, omit a separate field:
|
|
730
250
|
|
|
731
251
|
```ts
|
|
732
|
-
|
|
733
|
-
|
|
252
|
+
import { extractUuidV7UnixMs } from "@anizoptera/uuid-slug";
|
|
253
|
+
import type { UuidSlugError } from "@anizoptera/uuid-slug";
|
|
734
254
|
|
|
735
|
-
const
|
|
736
|
-
const
|
|
737
|
-
|
|
255
|
+
const incomingId = "AZirzRI0eryd7wEjRWeJqw";
|
|
256
|
+
const unixMs: number | UuidSlugError = extractUuidV7UnixMs(incomingId);
|
|
257
|
+
if (typeof unixMs === "number") console.log(unixMs);
|
|
258
|
+
else console.error(unixMs.message);
|
|
738
259
|
```
|
|
739
260
|
|
|
740
|
-
|
|
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.
|
|
261
|
+
`extractUuidV7UnixMs(bytes, offset)` reads from a larger buffer. `maskingCodec.extractMaskedUuidV7UnixMs(slug)` recovers a masked timestamp with the codec's keys. UUIDv4 has no timestamp and is rejected.
|
|
745
262
|
|
|
746
|
-
|
|
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";
|
|
263
|
+
For known fraction and counter layouts, use [payload extraction](docs/api.md#uuidv7-payload-fields).
|
|
784
264
|
|
|
785
|
-
|
|
786
|
-
return createUuidV7Generator({ readUnixMs });
|
|
787
|
-
}
|
|
788
|
-
```
|
|
265
|
+
Keep separate fields for other dates, finer precision, editable times or queries the UUID index cannot serve. Changing the timestamp changes the ID.
|
|
789
266
|
|
|
790
|
-
|
|
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
|
|
841
|
-
|
|
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.
|
|
267
|
+
## Ordering and key distribution
|
|
859
268
|
|
|
860
|
-
|
|
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.
|
|
269
|
+
Base64url UUIDv7 slugs are almost time-ordered: nearby timestamps have similar prefixes. ASCII sorting can reverse them: `AAAAAAAz` and `AAAAAAA0` encode consecutive milliseconds, but the second prefix sorts first.
|
|
867
270
|
|
|
868
|
-
|
|
869
|
-
import {
|
|
870
|
-
createCustomUuidV7Mask,
|
|
871
|
-
createUuidV7MaskingCodec,
|
|
872
|
-
isUuidSlugError,
|
|
873
|
-
} from "@anizoptera/uuid-slug";
|
|
271
|
+
Base32hex preserves UUID byte order: its alphabet, `0-9a-v`, follows numeric order, with the most significant bits first. Equal-length slugs sort by timestamp even across field boundaries. Clocks can move backwards, and UUIDv7 does not promise creation order within a millisecond. Compare one spelling at a time; database collations and natural file sorting can differ from ASCII.
|
|
874
272
|
|
|
875
|
-
|
|
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
|
-
```
|
|
273
|
+
`uuidV7StringBounds(startMs, endMs)` builds inclusive bounds for time-range queries on UUID keys. The bounds cover every UUIDv7 in the interval, regardless of its payload. For one millisecond, use `uuidV7StringBounds(ms)`. Compare in UUID wire-byte order; SQL Server's `uniqueidentifier` uses a different order.
|
|
889
274
|
|
|
890
|
-
|
|
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.
|
|
275
|
+
Decode masked filenames or store dates separately to sort them chronologically.
|
|
893
276
|
|
|
894
|
-
|
|
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.
|
|
277
|
+
Changing public URLs leaves the UUID index unchanged. For hash partitioning, hash the UUID so a spelling change does not move the record.
|
|
897
278
|
|
|
898
|
-
|
|
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.
|
|
279
|
+
With unchanged settings, built-in masking gives the same UUID the same slug: URLs and filenames stay stable, and repeated uses are recognizable. Rotation can change the slug; compare decoded UUIDs to identify the same record.
|
|
901
280
|
|
|
902
|
-
|
|
281
|
+
## Masking security
|
|
903
282
|
|
|
904
|
-
|
|
905
|
-
import {
|
|
906
|
-
deriveUuidV7MaskAsync,
|
|
907
|
-
createUuidV7MaskingCodec,
|
|
908
|
-
isUuidSlugError,
|
|
909
|
-
} from "@anizoptera/uuid-slug";
|
|
283
|
+
Masking hides UUIDv7 fields; the matching key restores them. Its cryptographic strength is not established, including against attacks using known UUID/slug pairs. See the [design](docs/design.md) and [security limits](docs/security.md).
|
|
910
284
|
|
|
911
|
-
|
|
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
|
-
```
|
|
285
|
+
An incorrect key can pass the 16-bit check and return the wrong UUID. Keep the rotation list short and confirm decoded IDs against your records; see the [record lookup example](docs/security.md#masking).
|
|
920
286
|
|
|
921
|
-
|
|
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.
|
|
287
|
+
A browser can use your service's masked IDs without the seed. Keep private masking and decoding on the service; client code exposes the seed. Plain generation and conversion need no seed.
|
|
926
288
|
|
|
927
|
-
|
|
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.
|
|
289
|
+
## Handling errors
|
|
932
290
|
|
|
933
|
-
`
|
|
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.
|
|
291
|
+
Conversions return `T | UuidSlugError` and pass errors through unchanged. Async mask construction resolves to the same union. Compatible chains need one final check. For string results, `typeof result === "string"` keeps the branded string type; the other branch is `UuidSlugError`. Use `isUuidSlugError` for object results or unknown input. It recognizes package errors across realms and package copies.
|
|
937
292
|
|
|
938
293
|
```ts
|
|
939
|
-
import {
|
|
294
|
+
import { isUuidSlugError, uuidStringToBytes } from "@anizoptera/uuid-slug";
|
|
295
|
+
import type { UuidBytes, UuidSlugError } from "@anizoptera/uuid-slug";
|
|
940
296
|
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
previousMasks: [{ mask: { seed: previousSeed }, timestampRangeStartUnixMs: 0 }],
|
|
945
|
-
});
|
|
946
|
-
}
|
|
297
|
+
const bytes: UuidBytes | UuidSlugError = uuidStringToBytes("0198abcd-1234-7abc-9def-0123456789ab");
|
|
298
|
+
if (isUuidSlugError(bytes)) console.error(bytes.code, bytes.message);
|
|
299
|
+
else console.log(bytes);
|
|
947
300
|
```
|
|
948
301
|
|
|
949
|
-
|
|
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.
|
|
302
|
+
Check intermediate results only when you also need their values.
|
|
960
303
|
|
|
961
|
-
|
|
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.
|
|
304
|
+
Handle errors by `code`, with constants such as `INVALID_BUFFER` and the `UuidSlugErrorCode` type. Use `message` for diagnostics; wording can change while codes stay stable. Failed entropy draws, clock readings and custom transforms retain their exception as `cause`.
|
|
965
305
|
|
|
966
|
-
|
|
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.
|
|
969
|
-
|
|
970
|
-
### Reading original slugs during migration
|
|
306
|
+
## API
|
|
971
307
|
|
|
972
|
-
|
|
308
|
+
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). Each export also documents its accepted input, result and failures in JSDoc.
|
|
973
309
|
|
|
974
|
-
|
|
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
|
-
```
|
|
310
|
+
## TypeScript API map
|
|
987
311
|
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
312
|
+
| Job | Main TypeScript API |
|
|
313
|
+
| --- | --- |
|
|
314
|
+
| Generate UUIDv4 | `generateUuidV4`, `generateUuidV4Bytes`, `generatePlainUuidV4Slug`, `generateUuidV4WithRandomFill` |
|
|
315
|
+
| Generate UUIDv7 | `generateUuidV7`, `generateUuidV7Bytes`, `generatePlainUuidV7Slug` |
|
|
316
|
+
| Generate one UUIDv7 with its slug | `generateUuidV7WithPlainSlug`, `maskingCodec.generateUuidV7WithMaskedSlug` |
|
|
317
|
+
| Generate an immutable UUIDv7 value | `generateUuidV7Value`, or its generator and masking-codec methods |
|
|
318
|
+
| Control UUIDv7 time, sequence, rollback, or entropy | `createUuidV7Generator`, `createUuidV7GeneratorWithRandomFill` |
|
|
319
|
+
| Convert UUID text, bytes, and plain slugs | `uuidToString`, `uuidToBytes`, `uuidToPlainSlug`, plus source-specific converters |
|
|
320
|
+
| Parse once for repeated work | [`parseUuid`](#parse-once-for-repeated-work) returns an immutable `Uuid` object |
|
|
321
|
+
| Inspect version, variant, timestamp, or payload | `Uuid.inspect`, `extractUuidVersion`, `extractUuidV7UnixMs`, `extractUuidV7Payload` |
|
|
322
|
+
| Narrow untrusted input | `isUuidText`, `isUuidString`, `isUuidBytes`, `isPlainUuidSlug`, their v4/v7 guards, and `isUuidSlugError` |
|
|
323
|
+
| Build UUIDv7 database range keys | `uuidV7StringBounds`, `uuidV7ByteBounds` |
|
|
324
|
+
| Validate a UUIDv7 timestamp window | `validateUuidV7StringUnixMs` and the plain or masked slug equivalents |
|
|
325
|
+
| Derive UUIDv7 masks, with optional async cancellation | `deriveUuidV7Mask`, `deriveUuidV7MaskAsync` |
|
|
326
|
+
| Use an application-defined reversible masking transform | [`createCustomUuidV7Mask`](docs/api.md#masking-codec-options) |
|
|
327
|
+
| Mask, unmask, rotate keys, or reserve sentinels | `createUuidV7MaskingCodec` and its methods |
|
|
328
|
+
| Transfer masked UUIDv7 as 16 bytes | `maskingCodec.uuidToMaskedBytes`, `maskedBytesToUuidBytes`, `maskedBytesToUuidString` |
|
|
329
|
+
| Read explicitly enabled old formats | `maskingCodec.createUuidSlugMigrationDecoder` |
|
|
996
330
|
|
|
997
|
-
|
|
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.
|
|
331
|
+
Types catch UUID-version and plain/masked mix-ups; results retain text case and buffer ownership. Generator, masking-codec and migration methods need no `this` binding.
|
|
1000
332
|
|
|
1001
|
-
|
|
333
|
+
## Guarantees
|
|
1002
334
|
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
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
|
-
```
|
|
335
|
+
- Generated IDs have RFC 9562 version and variant bits.
|
|
336
|
+
- 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.
|
|
337
|
+
- 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.
|
|
338
|
+
- Default calls retain the selected native generator's ordering and clock behavior. Use a created generator to control ordering and clock rollback. Native failures fall back to the package's generator; if both fail, the error retains both causes.
|
|
339
|
+
- UUIDv7 starts with a 48-bit millisecond timestamp, so UUID strings sort by encoded time across different milliseconds. Backfills and clock adjustments can differ from generation order.
|
|
340
|
+
- Successful current-time calls on one created generator strictly increase in UUID byte order under the default `clockRollback` policy, `"preserve"`; `at` calls share its sequence state. Module-level generation and `"reset"` calls beyond their tolerance do not guarantee this order. Independent generators, package copies, workers and processes have separate state; use a sequence column for ordering across them.
|
|
341
|
+
- Plain slugs preserve all UUID bits. Base32hex UUIDv7 slugs sort by timestamp across different milliseconds under ASCII comparison. Base64url UUIDv7 slugs are almost time-ordered; [ASCII sorting can reverse them](#ordering-and-key-distribution). Masked slugs have no chronological order.
|
|
342
|
+
- Byte generators return a new plain `Uint8Array` or your supplied array, writing only the requested range.
|
|
343
|
+
- `uuidStringToBytes` and `plainSlugToUuidBytes` validate the whole identifier before writing. Invalid text or destination ranges return an error without changing caller storage.
|
|
344
|
+
- Named root imports let supported bundlers remove the cipher, key derivation, sentinel table, and unrelated generation code.
|
|
345
|
+
- A UUIDv7 masking codec requires explicit private mask options or a package-produced mask. Use `UUID_V7_TEST_MASK` explicitly for the public test key; omission does not select it.
|
|
1019
346
|
|
|
1020
|
-
|
|
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.
|
|
347
|
+
## Runtime
|
|
1026
348
|
|
|
1027
|
-
|
|
349
|
+
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
350
|
|
|
1029
|
-
|
|
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
|
-
```
|
|
351
|
+
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
352
|
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
353
|
+
| Runtime | Package code |
|
|
354
|
+
| --- | --- |
|
|
355
|
+
| Node 20 and newer (also works from 16.20) | Uses compiled JavaScript |
|
|
356
|
+
| Bun 1.0.8 and newer | Uses TypeScript source |
|
|
357
|
+
| Deno 1.29 and newer | Compiled JavaScript; no flag or import map needed |
|
|
358
|
+
| Cloudflare Workers, browsers and other compatible runtimes | Compiled JavaScript over Web Crypto |
|
|
1053
359
|
|
|
1054
|
-
|
|
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.
|
|
360
|
+
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
361
|
|
|
1061
|
-
|
|
362
|
+
Conversion and timestamp extraction need no randomness, so read-only tools and static builds can use them. Generation needs secure randomness.
|
|
1062
363
|
|
|
1063
|
-
```ts
|
|
1064
|
-
import { validateUuidV7StringUnixMs } from "@anizoptera/uuid-slug";
|
|
1065
364
|
|
|
1066
|
-
|
|
1067
|
-
return validateUuidV7StringUnixMs(uuid, { maxTimestampDeltaMs: 60_000 });
|
|
1068
|
-
}
|
|
1069
|
-
```
|
|
365
|
+
## Upgrades and support
|
|
1070
366
|
|
|
1071
|
-
|
|
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.
|
|
367
|
+
Check the [changelog](CHANGELOG.md) and the [release policy](docs/release.md) before upgrading.
|
|
1117
368
|
|
|
1118
|
-
|
|
369
|
+
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
370
|
|
|
1120
|
-
|
|
1121
|
-
passing them proves none of this. See [security boundaries](docs/security.md) for entropy failures
|
|
1122
|
-
and masking limits.
|
|
371
|
+
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
372
|
|
|
1124
|
-
-
|
|
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.
|
|
373
|
+
The built-in [wire format](docs/design.md) is documented for independent decoders.
|
|
1159
374
|
|
|
1160
|
-
|
|
375
|
+
Report bugs through [GitHub issues](https://github.com/Anizoptera/uuid-slug/issues).
|
|
1161
376
|
|
|
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
377
|
|
|
1208
378
|
## License
|
|
1209
379
|
|