Skip to content

Commit 4bcff46

Browse files
committed
crypto.randomUUID is now polyfilled when it is missing
1 parent ad9c7c8 commit 4bcff46

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/polyfills.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
/* node:coverage disable */
2+
/* eslint-disable @typescript-eslint/unbound-method */
23

34
import { warn } from 'kerium/log';
5+
import type { UUID } from 'node:crypto';
46

5-
// eslint-disable-next-line @typescript-eslint/unbound-method
67
Promise.withResolvers ??=
78
(warn('Using a polyfill of Promise.withResolvers'),
89
function <T>(): PromiseWithResolvers<T> {
@@ -21,4 +22,14 @@ Symbol['dispose'] ??= (warn('Using a polyfill of Symbol.dispose'), Symbol('Symbo
2122
// @ts-expect-error 2540
2223
Symbol['asyncDispose'] ??= (warn('Using a polyfill of Symbol.asyncDispose'), Symbol('Symbol.asyncDispose'));
2324

25+
function randomUUID(): UUID {
26+
const bytes = crypto.getRandomValues(new Uint8Array(16));
27+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
28+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
29+
const hex = [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
30+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
31+
}
32+
33+
globalThis.crypto.randomUUID ??= (warn('Using a polyfill of crypto.randomUUID'), randomUUID);
34+
2435
/* node:coverage enable */

0 commit comments

Comments
 (0)