|
1 |
| -// Unique ID creation requires a high quality random # generator. In the |
2 |
| -// browser this is a little complicated due to unknown quality of Math.random() |
3 |
| -// and inconsistent support for the `crypto` API. We do the best we can via |
4 |
| -// feature-detection |
| 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()). |
5 | 4 |
|
6 |
| -// getRandomValues needs to be invoked in a context where "this" is a Crypto |
7 |
| -// implementation. Also, find the complete implementation of crypto on IE11. |
| 5 | +// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, |
| 6 | +// find the complete implementation of crypto (msCrypto) on IE11. |
8 | 7 | var getRandomValues =
|
9 | 8 | (typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
|
10 | 9 | (typeof msCrypto != 'undefined' &&
|
11 | 10 | typeof window.msCrypto.getRandomValues == 'function' &&
|
12 | 11 | msCrypto.getRandomValues.bind(msCrypto));
|
13 | 12 |
|
14 |
| -let rng; |
15 |
| - |
16 |
| -if (getRandomValues) { |
17 |
| - // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto |
18 |
| - var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef |
19 |
| - |
20 |
| - rng = function whatwgRNG() { |
21 |
| - getRandomValues(rnds8); |
22 |
| - return rnds8; |
23 |
| - }; |
24 |
| -} else { |
25 |
| - // Math.random()-based (RNG) |
26 |
| - // |
27 |
| - // If all else fails, use Math.random(). It's fast, but is of unspecified |
28 |
| - // quality. |
29 |
| - var rnds = new Array(16); |
30 |
| - |
31 |
| - rng = function mathRNG() { |
32 |
| - for (var i = 0, r; i < 16; i++) { |
33 |
| - if ((i & 0x03) === 0) r = Math.random() * 0x100000000; |
34 |
| - rnds[i] = (r >>> ((i & 0x03) << 3)) & 0xff; |
35 |
| - } |
36 |
| - |
37 |
| - return rnds; |
38 |
| - }; |
| 13 | +var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef |
| 14 | +export default function rng() { |
| 15 | + if (!getRandomValues) { |
| 16 | + throw new Error( |
| 17 | + 'uuid: This browser does not seem to support crypto.getRandomValues(). If you need to support this browser, please provide a custom random number generator through options.rng.', |
| 18 | + ); |
| 19 | + } |
| 20 | + return getRandomValues(rnds8); |
39 | 21 | }
|
40 |
| - |
41 |
| -export default rng; |
0 commit comments