Skip to content

Commit 76b5889

Browse files
committed
perf: faster and lazy entropy loading in bundles
1 parent c3e9b5d commit 76b5889

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

bundler/modules/globals.cjs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -317,17 +317,33 @@ This activity created errors and would have caused tests to fail, but instead tr
317317
}
318318

319319
if (!globalThis.crypto?.getRandomValues && globalThis.EXODUS_TEST_CRYPTO_ENTROPY) {
320-
const entropy = Buffer.from(globalThis.EXODUS_TEST_CRYPTO_ENTROPY, 'base64')
320+
let entropy
321+
let entropyBase64 = globalThis.EXODUS_TEST_CRYPTO_ENTROPY
322+
const loadEntropy = () => {
323+
if (Uint8Array.fromBase64) {
324+
entropy = Uint8Array.fromBase64(entropyBase64)
325+
} else if (globalThis.atob) {
326+
const raw = atob(entropyBase64)
327+
const length = raw.length
328+
entropy = new Uint8Array(length)
329+
for (let i = 0; i < length; i++) entropy[i] = raw.charCodeAt(i) // eslint-disable-line unicorn/prefer-code-point
330+
} else {
331+
entropy = Buffer.from(entropyBase64, 'base64')
332+
}
333+
334+
entropyBase64 = ''
335+
}
336+
321337
let pos = 0
322338
if (!globalThis.crypto) globalThis.crypto = {}
323339
const TypedArray = Object.getPrototypeOf(Uint8Array)
324340
globalThis.crypto.getRandomValues = (typedArray) => {
325341
if (!(typedArray instanceof TypedArray)) throw new Error('Argument should be a TypedArray')
326-
const view = Buffer.from(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength)
342+
const view = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength)
343+
if (!entropy) loadEntropy()
327344
if (pos + view.length <= entropy.length) {
345+
view.set(entropy.subarray(pos, pos + view.length))
328346
pos += view.length
329-
const copied = entropy.copy(view, 0, pos - view.length)
330-
if (copied !== view.length) throw new Error('Unexpected')
331347
return typedArray
332348
}
333349

0 commit comments

Comments
 (0)