uuid.spec.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * The minted UUID's contract: RFC 9562 v4 shape (version and variant bits
  3. * pinned), uniqueness across calls, and no dependence on the secure-context
  4. * `crypto.randomUUID` — the reason this package exists.
  5. */
  6. import { describe, expect, it, vi } from 'vitest'
  7. import { bytesToBase64, randomUUID } from '../src/index.ts'
  8. const V4_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
  9. describe('randomUUID', () => {
  10. it('emits RFC 9562 v4 ids', () => {
  11. for (let round = 0; round < 64; round += 1) expect(randomUUID()).toMatch(V4_SHAPE)
  12. })
  13. it('emits distinct ids across calls', () => {
  14. expect(new Set(Array.from({ length: 64 }, () => randomUUID())).size).toBe(64)
  15. })
  16. it('mints without the platform randomUUID, the insecure-origin shape', () => {
  17. const bare = { getRandomValues: globalThis.crypto.getRandomValues.bind(globalThis.crypto) }
  18. vi.stubGlobal('crypto', bare)
  19. try {
  20. expect(randomUUID()).toMatch(V4_SHAPE)
  21. } finally {
  22. vi.unstubAllGlobals()
  23. }
  24. })
  25. })
  26. describe('bytesToBase64', () => {
  27. it('encodes empty, binary, and multi-chunk byte arrays', () => {
  28. expect(bytesToBase64(new Uint8Array())).toBe('')
  29. expect(bytesToBase64(new Uint8Array([0, 127, 128, 255]))).toBe('AH+A/w==')
  30. expect(bytesToBase64(new Uint8Array(0x8001).fill(65))).toBe('QUFB'.repeat(10923))
  31. })
  32. })