import { describe, expect, it } from "vitest"; import vm from "node:vm"; import { randomUUIDPolyfillScript } from "@/lib/client/random-uuid-polyfill"; type RandomUUIDContext = { crypto?: { randomUUID?: () => string; getRandomValues?: (bytes: Uint8Array) => Uint8Array; }; }; describe("client randomUUID polyfill", () => { it("defines crypto.randomUUID when crypto is missing", () => { const context: RandomUUIDContext = {}; vm.runInNewContext(randomUUIDPolyfillScript, context); expect(context.crypto?.randomUUID?.()).toMatch( /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ ); }); it("defines crypto.randomUUID when only getRandomValues is available", () => { const context: RandomUUIDContext = { crypto: { getRandomValues(bytes: Uint8Array) { for (let index = 0; index < bytes.length; index += 1) bytes[index] = index; return bytes; } } }; vm.runInNewContext(randomUUIDPolyfillScript, context); expect(context.crypto?.randomUUID?.()).toMatch( /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ ); }); });