From bf24b99c3250e4ab85049fb1bc5615a835ebb3d8 Mon Sep 17 00:00:00 2001 From: Ali Molaei Date: Tue, 6 Aug 2024 01:08:08 +0330 Subject: [PATCH 1/2] fix: remove options default assignment introduced during porting to ts, pull #763 preventing native.randomUUID being used --- src/v4.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/v4.ts b/src/v4.ts index d1447f69..3370e554 100644 --- a/src/v4.ts +++ b/src/v4.ts @@ -6,8 +6,6 @@ import { unsafeStringify } from './stringify.js'; function v4(options?: Version4Options, buf?: undefined, offset?: number): string; function v4(options?: Version4Options, buf?: Uint8Array, offset?: number): Uint8Array; function v4(options?: Version4Options, buf?: Uint8Array, offset?: number): UUIDTypes { - options ??= {}; - if (native.randomUUID && !buf && !options) { return native.randomUUID(); } From f0653733e263bc91c1b592ffd8f04fffd3273def Mon Sep 17 00:00:00 2001 From: Ali Molaei Date: Tue, 6 Aug 2024 22:15:34 +0330 Subject: [PATCH 2/2] test: add unit test to check if native randomUUID should be used or not --- src/test/v4.test.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/test/v4.test.ts b/src/test/v4.test.ts index 36574f39..602aa782 100644 --- a/src/test/v4.test.ts +++ b/src/test/v4.test.ts @@ -1,6 +1,7 @@ import * as assert from 'assert'; -import test, { describe } from 'node:test'; +import test, { describe, mock } from 'node:test'; import v4 from '../v4.js'; +import native from '../native.js'; const randomBytesFixture = Uint8Array.of( 0x10, @@ -48,6 +49,26 @@ describe('v4', () => { assert.ok(id1 !== id2); }); + test('should uses native randomUUID() if no option is passed', () => { + mock.method(native, 'randomUUID'); + + assert.equal((native.randomUUID as any).mock.callCount(), 0); + v4(); + assert.equal((native.randomUUID as any).mock.callCount(), 1); + + mock.restoreAll(); + }); + + test('should not use native randomUUID() if an option is passed', () => { + mock.method(native, 'randomUUID'); + + assert.equal((native.randomUUID as any).mock.callCount(), 0); + v4({}); + assert.equal((native.randomUUID as any).mock.callCount(), 0); + + mock.restoreAll(); + }); + test('explicit options.random produces expected result', () => { const id = v4({ random: randomBytesFixture }); assert.strictEqual(id, '109156be-c4fb-41ea-b1b4-efe1671c5836');