UNPKG

core-uuid

Version:

A zero-dependency, secure, and lightweight UUID v4 generator written in TypeScript.

19 lines (18 loc) 736 B
import { getSecureRandomBytes } from "../random/secure-random.js"; /** * Generate a RFC 4122 compliant UUID v4 * @returns UUID v4 string (e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479") */ export function uuidv4() { const bytes = getSecureRandomBytes(16); // Set version (4) and variant (RFC 4122) bits bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; // Convert to hex string const hex = []; for (let i = 0; i < 16; i++) { hex.push(bytes[i].toString(16).padStart(2, "0")); } return `${hex[0]}${hex[1]}${hex[2]}${hex[3]}-${hex[4]}${hex[5]}-${hex[6]}${hex[7]}-${hex[8]}${hex[9]}-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`; } export default uuidv4;