1.0.2 • Published 2 months ago

@theedoran/uuidv7 v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

@theedoran/uuidv7 - UUIDv7 generator library for Node.js

This library follows the draft-ietf-uuidrev-rfc4122bis-11 draft to generate UUIDv7.

It uses method 2 of "Monotonicity and Counters" section of the draft to generate monotonic UUIDv7 when the timestamp is the same.

Usage

import { UUIDv7 } from "@theedoran/uuidv7";

// Initialize a new UUIDv7 generator.
// You can pass a custom encoding alphabet here.
const uuidv7 = new UUIDv7();

// You can pass a custom timestamp to the `gen()` method,
// to generate a UUIDv7 for a specific timestamp.
const id = uuidv7.gen(); // 018ef3e8-90e2-7be4-b4ea-4be3bf8803b7
const timestamp = uuidv7.timestamp(id); // 1713489088738
const date = uuidv7.date(id); // 2024-04-19T01:11:28.738Z
const encoded = uuidv7.encode(id); // CANANjseoigQthQMd1VwC
const decoded = uuidv7.decode(encoded); // 018ef3e8-90e2-7be4-b4ea-4be3bf8803b7

You can also use genMany() method to generate multiple UUIDv7s.

Field and Bit Layout

This is the UUIDv7 Field and Bit Layout, took from the draft linked above:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           unix_ts_ms                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          unix_ts_ms           |  ver  |       rand_a          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var|                        rand_b                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                            rand_b                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Description

unix_ts_ms

48 bit big-endian unsigned number of Unix epoch timestamp in milliseconds as per Section 6.1. Occupies bits 0 through 47 (octets 0-5).

ver

The 4 bit version field as defined by Section 4.2, set to 0b0111 (7). Occupies bits 48 through 51 of octet 6.

rand_a

12 bits pseudo-random data to provide uniqueness as per Section 6.8 and/or optional constructs to guarantee additional monotonicity as per Section 6.2. Occupies bits 52 through 63 (octets 6-7).

var

The 2 bit variant field as defined by Section 4.1, set to 0b10. Occupies bits 64 and 65 of octet 8.

rand_b

The final 62 bits of pseudo-random data to provide uniqueness as per Section 6.8 and/or an optional counter to guarantee additional monotonicity as per Section 6.2. Occupies bits 66 through 127 (octets 8-15).

Feedback

If you found a bug in the implementation, please open a new issue.

License

This project is licensed under the MIT License.

1.0.2

2 months ago

1.0.1

2 months ago

1.0.0

2 months ago