All files / src/util newId.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 2/2
100% Lines 7/7

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                  6x 6x 1x 1x 1x 16x 1x    
/**
 * A random v4 UUID — for an id the client mints, like the turn id a chat's
 * Stop names before the server has answered.
 *
 * `crypto.randomUUID` exists only in a secure context, and the local stack
 * serves the app over plain HTTP on a hostname that is not localhost; the
 * `getRandomValues` it falls back to is available everywhere.
 */
export function newId(): string {
  const crypto = globalThis.crypto;
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant
  const hex = Array.from(bytes, (b) => b.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)}`;
}