Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/utils/uuid.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from 'vitest'

import { createUuidv4 } from './uuid'

const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/

describe('createUuidv4', () => {
it('uses crypto.randomUUID when available', () => {
const randomUUID = vi.fn(() => '12345678-1234-4abc-8def-123456789abc')
const getRandomValues = vi.fn()
vi.stubGlobal('crypto', { randomUUID, getRandomValues })

expect(createUuidv4()).toBe('12345678-1234-4abc-8def-123456789abc')
expect(randomUUID).toHaveBeenCalledOnce()
expect(getRandomValues).not.toHaveBeenCalled()
})

it('uses crypto.getRandomValues when randomUUID is unavailable', () => {
const getRandomValues = vi.fn((values: Uint32Array) => {
values.forEach((_, index) => {
values[index] = index * 2654435761
})
return values
})
vi.stubGlobal('crypto', { randomUUID: undefined, getRandomValues })

const uuid = createUuidv4()

expect(getRandomValues).toHaveBeenCalledOnce()
expect(uuid).toMatch(UUID_V4_PATTERN)
})

it('throws when Web Crypto is unavailable', () => {
vi.stubGlobal('crypto', undefined)

expect(() => createUuidv4()).toThrow(
'Web Crypto is required to generate a UUID'
)
})

it('mints unique UUIDv4 values across a sanity sample', () => {
const uuids = Array.from({ length: 1_000 }, () => createUuidv4())

expect(uuids.every((uuid) => UUID_V4_PATTERN.test(uuid))).toBe(true)
expect(new Set(uuids).size).toBe(uuids.length)
})
})
15 changes: 8 additions & 7 deletions src/utils/uuid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ const randomStorage = new Uint32Array(31)
* Original implementation from https://gist.github.com/jed/982883?permalink_comment_id=852670#gistcomment-852670
*
* Prefers the {@link crypto.randomUUID} method if available, falling back to
* {@link crypto.getRandomValues}, then finally the legacy {@link Math.random} method.
* {@link crypto.getRandomValues} for insecure contexts.
*/
export function createUuidv4(): UUID {
if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID()
if (typeof crypto?.getRandomValues === 'function') {
const random = crypto.getRandomValues(randomStorage)
const webCrypto = globalThis.crypto
if (typeof webCrypto?.randomUUID === 'function') {
return webCrypto.randomUUID()
}
if (typeof webCrypto?.getRandomValues === 'function') {
const random = webCrypto.getRandomValues(randomStorage)
let i = 0
return '10000000-1000-4000-8000-100000000000'.replaceAll(/[018]/g, (a) =>
(
Expand All @@ -28,7 +31,5 @@ export function createUuidv4(): UUID {
).toString(16)
)
}
return '10000000-1000-4000-8000-100000000000'.replaceAll(/[018]/g, (a) =>
(Number(a) ^ ((Math.random() * 16) >> (Number(a) * 0.25))).toString(16)
)
throw new Error('Web Crypto is required to generate a UUID')
}
Loading