package
xid is a globally unique id generator thought for the web. A Typescript port of https://github.com/rs/xid.
npm install xid-tsGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Estimated unpacked size across 1 packages.
43.2 kB
Includes dependencies.
xid-tsGlobally unique sortable id generator. A Typescript port of https://github.com/rs/xid.
The binary representation is compatible with the Mongo DB 12-byte ObjectId. The value consists of:
The string representation is 20 bytes, using a base32 hex variant with characters [0-9a-v]
to retain the sortable property of the id.
See the original xid project for more details.
The wire format (bytes and string) is fully compatible with Go's xid, but a few
behaviors differ:
process.pid when available (without Go's container
cpuset mixing), otherwise 2 random bytes.null (toJSON() returns
null), and Xid.fromValue(null) returns a zero Xid.A runtime with the Web Crypto API (crypto.getRandomValues): Node.js >= 20, Deno, Bun,
Cloudflare Workers, and all modern browsers.
npm i xid-ts --saveimport { 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
https://github.com/yiwen-ai/xid-ts/blob/main/src/index.test.ts
import { decode, encode } from 'cborg'
import { Xid } from 'xid-ts'
const xid = Xid.fromValue('9m4e2mr0ui3e8a215n4g')
const obj = {
id: xid,
name: 'yiwen'
}
const json = JSON.stringify(obj)
assert.equal(json, '{"id":"9m4e2mr0ui3e8a215n4g","name":"yiwen"}')
const obj1 = JSON.parse(json)
assert.isTrue(xid.equals(Xid.fromValue(obj1.id)))
const data = encode(obj)
assert.equal
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.
import { Xid } from 'xid-ts'
export default {
async fetch(request, env, ctx): Promise<Response> {
return Response.json({ id: new Xid() })
// {"id":"d4amdocsodcmnao0bddg"}
},
} satisfies ExportedHandler<Env>An Xid passed through RPC (Durable Objects, service bindings) arrives as a plain
Uint8Array; wrap it with new Xid(bytes) or Xid.fromValue(bytes).
Copyright © 2023-present Yiwen AI.
yiwen-ai/xid-ts is licensed under the MIT License. See LICENSE for the full license text.