rng.js 1.0 KB

12345678910111213141516171819
  1. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  2. // require the crypto API and do not support built-in fallback to lower quality random number
  3. // generators (like Math.random()).
  4. var getRandomValues;
  5. var rnds8 = new Uint8Array(16);
  6. export default function rng() {
  7. // lazy load so that environments that need to polyfill have a chance to do so
  8. if (!getRandomValues) {
  9. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  10. // find the complete implementation of crypto (msCrypto) on IE11.
  11. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  12. if (!getRandomValues) {
  13. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  14. }
  15. }
  16. return getRandomValues(rnds8);
  17. }