import * as crypto from 'crypto'; function v4_uuid() { let rand_bytes = crypto.randomBytes(16); let rand_bytes_int = Uint8Array.from(rand_bytes); // replace 7th byte with 4 (0100) // & 0b00001111 replaces the first 4 bits with 0s // | 0b01000000 replaces the first 4 bits with 0100 rand_bytes_int[6] = (rand_bytes_int[6] & 0b00001111) | 0b01000000; // set 2 significant bits of 9th byte to 2 (10) // & 0b00111111 replaces the first 2 bits with 0s // | 0b10000000 replaces the first 2 bits with 10 rand_bytes_int[8] = (rand_bytes_int[8] & 0b00111111) | 0b10000000; let output = ''; const hyphen_points = [2, 4, 6, 8]; for (let i = 0; i < rand_bytes_int.length; i++) { output += rand_bytes_int[i].toString(16).padStart(2, '0'); if (hyphen_points.includes(i)) { output += '-'; } } return output; }