38 lines
994 B
TypeScript
38 lines
994 B
TypeScript
import { randomBytes } from 'node:crypto';
|
|
|
|
/**
|
|
* Generate UUID v7 (time-ordered, sortable).
|
|
* Simplified implementation: timestamp (48 bit) + random (74 bit).
|
|
*/
|
|
export function uuid7(): string {
|
|
const timestamp = Date.now();
|
|
const random = randomBytes(10);
|
|
|
|
const high = (timestamp / 0x100000000) >>> 0;
|
|
const low = timestamp >>> 0;
|
|
|
|
const b = new Uint8Array(16);
|
|
b[0] = (high >> 24) & 0xff;
|
|
b[1] = (high >> 16) & 0xff;
|
|
b[2] = (high >> 8) & 0xff;
|
|
b[3] = high & 0xff;
|
|
b[4] = (low >> 24) & 0xff;
|
|
b[5] = (low >> 16) & 0xff;
|
|
b[6] = ((low >> 8) & 0x3f) | 0x70;
|
|
b[7] = low & 0xff;
|
|
b[8] = 0x80 | (random[0] & 0x3f);
|
|
b[9] = random[1];
|
|
b[10] = random[2];
|
|
b[11] = random[3];
|
|
b[12] = random[4];
|
|
b[13] = random[5];
|
|
b[14] = random[6];
|
|
b[15] = random[7];
|
|
|
|
const hex = Array.from(b)
|
|
.map((x) => x.toString(16).padStart(2, '0'))
|
|
.join('');
|
|
|
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
}
|