1'use strict'; 2 3const common = require('../common'); 4 5if (!common.hasCrypto) 6 common.skip('missing crypto'); 7 8const assert = require('assert'); 9const { 10 randomUUID, 11} = require('crypto'); 12 13const last = new Set([ 14 '00000000-0000-0000-0000-000000000000', 15]); 16 17function testMatch(uuid) { 18 assert.match( 19 uuid, 20 /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); 21} 22 23// Generate a number of UUID's to make sure we're 24// not just generating the same value over and over 25// and to make sure the batching changes the random 26// bytes. 27for (let n = 0; n < 130; n++) { 28 const uuid = randomUUID(); 29 assert(!last.has(uuid)); 30 last.add(uuid); 31 assert.strictEqual(typeof uuid, 'string'); 32 assert.strictEqual(uuid.length, 36); 33 testMatch(uuid); 34 35 // Check that version 4 identifier was populated. 36 assert.strictEqual( 37 Buffer.from(uuid.substr(14, 2), 'hex')[0] & 0x40, 0x40); 38 39 // Check that clock_seq_hi_and_reserved was populated with reserved bits. 40 assert.strictEqual( 41 Buffer.from(uuid.substr(19, 2), 'hex')[0] & 0b1100_0000, 0b1000_0000); 42} 43 44// Test non-buffered UUID's 45{ 46 testMatch(randomUUID({ disableEntropyCache: true })); 47 testMatch(randomUUID({ disableEntropyCache: true })); 48 testMatch(randomUUID({ disableEntropyCache: true })); 49 testMatch(randomUUID({ disableEntropyCache: true })); 50 51 assert.throws(() => randomUUID(1), { 52 code: 'ERR_INVALID_ARG_TYPE' 53 }); 54 55 assert.throws(() => randomUUID({ disableEntropyCache: '' }), { 56 code: 'ERR_INVALID_ARG_TYPE' 57 }); 58} 59