From 8976029ac3b184e770d8731ffc3f893d093ded01 Mon Sep 17 00:00:00 2001 From: Luis Capuyon Date: Mon, 25 Sep 2023 04:22:52 +0800 Subject: [PATCH] Update getRandomValues polyfill Add logic to check if global exists. Move existing condition blocks into this block. Note that these global checks are for non-browser environments. For browser environments, add similar polyfill via the window global variable. Reference: - https://github.com/brix/crypto-js/issues/256#issuecomment-1095605673 --- packages/core/src/polyfills/crypto.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/core/src/polyfills/crypto.js b/packages/core/src/polyfills/crypto.js index 798b89f..976875c 100644 --- a/packages/core/src/polyfills/crypto.js +++ b/packages/core/src/polyfills/crypto.js @@ -1,11 +1,19 @@ import crypto from 'crypto'; // should have webcrypto.getRandomValues defined -if (typeof global.crypto !== 'object') { - global.crypto = crypto; +let context; + +if (typeof global !== 'undefined') { + context = global; +} else if (typeof window !== 'undefined') { + context = window; +} + +if (typeof context.crypto !== 'object') { + context.crypto = crypto; } -if (typeof global.crypto.getRandomValues !== 'function') { - global.crypto.getRandomValues = getRandomValues; +if (typeof context.crypto.getRandomValues !== 'function') { + context.crypto.getRandomValues = getRandomValues; } function getRandomValues(array) {