Merge pull request #370 from aminya/performance-polyfill

fix: polyfill performance for crypto randomuuid
This commit is contained in:
Amin Ya 2025-03-10 19:38:20 -07:00 committed by GitHub
commit 413acc39d5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 39 additions and 7 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -193,7 +193,8 @@
"util.types",
"web-streams-polyfill",
"timers-browserify",
"fs-extra"
"fs-extra",
"randomuuid-polyfill"
],
"engines": {
"node": ">=12.x",

View File

@ -3,4 +3,4 @@ export * from "crypto"
import * as crypto from "crypto"
export default crypto
export { randomUUID } from "randomuuid-polyfill"
export { randomUUID } from "./randomuuid.mjs"

View File

@ -0,0 +1,31 @@
// from https://www.npmjs.com/package/randomuuid-polyfill
import { performance } from "perf_hooks"
// Adapted from https://stackoverflow.com/a/8809472/2993077
if (!global.crypto?.randomUUID) {
if (!global.crypto) {
global.crypto = {}
}
global.crypto.randomUUID = () => {
let date = new Date().getTime()
let performanceNow = performance.now() * 1000
// cspell:disable-next-line
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, char => {
let random = Math.random() * 16
if (date > 0) {
random = (date + random) % 16 | 0
date = Math.floor(date / 16)
} else {
random = (performanceNow + random) % 16 | 0
performanceNow = Math.floor(performanceNow / 16)
}
return (char === "x" ? random : (random & 0x3 | 0x8)).toString(16)
})
}
}
const randomUUID = global.crypto.randomUUID.bind(global.crypto)
export { randomUUID }