The wire format (bytes and string) is fully compatible with Go's xid, but a few
behaviors differ:
Machine identifier: Go derives it from the platform machine id or hostname, so all
processes on one machine share the same value. This port fills it with random bytes
per state instead: JavaScript runtimes often host many isolates, worker threads or
bundled copies of this module within one machine and even one process, and a per-state
random value keeps ids from those instances from colliding. The trade-off is that ids
cannot be grouped by machine.
Process id: taken from process.pid when available (without Go's container
cpuset mixing), otherwise 2 random bytes.
JSON null: like Go, a zero (nil) Xid serializes to JSON null (toJSON() returns
null), and Xid.fromValue(null) returns a zero Xid.
Requirements
A runtime with the Web Crypto API (crypto.getRandomValues): Node.js >= 20, Deno, Bun,
Cloudflare Workers, and all modern browsers.
Usage
npm i xid-ts --save
Examples
Create and Parse Xid
import { Xid } from 'xid-ts'const defaultXid = Xid.default()assert.equal(defaultXid.isZero(), true)const now = Math.floor(Date.now() / 1000)const newXid = new Xid()assert.equal(newXid.isZero(), false)assert.isTrue(newXid.timestamp() >= now)const xid = Xid.parse('9m4e2mr0ui3e8a215n4g')assert.equal(xid.isZero
new Xid() works in Workers as is. The default state is created lazily on the first call
(Workers forbid crypto.getRandomValues during module initialization), and its random
machine identifier keeps ids from different isolates from colliding.