rng.js 838 B

123456789101112131415161718
  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. let getRandomValues;
  5. const 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.
  10. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
  11. if (!getRandomValues) {
  12. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  13. }
  14. }
  15. return getRandomValues(rnds8);
  16. }