All files / apps / api/src / lib id.ts

100% Statements 9/9
100% Branches 1/1
100% Functions 2/2
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22      1877x 1877x   1877x 1877x 1877x 1877x   30032x   1877x                
// UUIDv7 (RFC 9562): the first 48 bits are the Unix time in ms, so ids sort by creation time (design 3.1).
// Ids made in the same millisecond are in random order; order that matters uses seq or events.id.
export function newId(now: number = Date.now()): string {
  const bytes = crypto.getRandomValues(new Uint8Array(16))
  const view = new DataView(bytes.buffer)
 
  view.setUint16(0, Math.floor(now / 2 ** 32))
  view.setUint32(2, now % 2 ** 32)
  view.setUint8(6, (view.getUint8(6) & 0x0f) | 0x70) // version 7
  view.setUint8(8, (view.getUint8(8) & 0x3f) | 0x80) // variant 10
 
  const hex = Array.from(bytes, (byte) => byte.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),
  ].join('-')
}