1 | ;
|
2 | /*-----------------------------------------------------------------------------
|
3 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
4 | |
|
5 | | Distributed under the terms of the BSD 3-Clause License.
|
6 | |
|
7 | | The full license is in the file LICENSE, distributed with this software.
|
8 | |----------------------------------------------------------------------------*/
|
9 | Object.defineProperty(exports, "__esModule", { value: true });
|
10 | /**
|
11 | * The namespace for random number related functionality.
|
12 | */
|
13 | var Random;
|
14 | (function (Random) {
|
15 | /**
|
16 | * A function which generates random bytes.
|
17 | *
|
18 | * @param buffer - The `Uint8Array` to fill with random bytes.
|
19 | *
|
20 | * #### Notes
|
21 | * A cryptographically strong random number generator will be used if
|
22 | * available. Otherwise, `Math.random` will be used as a fallback for
|
23 | * randomness.
|
24 | *
|
25 | * The following RNGs are supported, listed in order of precedence:
|
26 | * - `window.crypto.getRandomValues`
|
27 | * - `window.msCrypto.getRandomValues`
|
28 | * - `require('crypto').randomFillSync
|
29 | * - `require('crypto').randomBytes
|
30 | * - `Math.random`
|
31 | */
|
32 | Random.getRandomValues = (function () {
|
33 | // Look up the crypto module if available.
|
34 | var crypto = ((typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||
|
35 | (typeof require !== 'undefined' && require('crypto')) || null);
|
36 | // Modern browsers and IE 11
|
37 | if (crypto && typeof crypto.getRandomValues === 'function') {
|
38 | return function getRandomValues(buffer) {
|
39 | return crypto.getRandomValues(buffer);
|
40 | };
|
41 | }
|
42 | // Node 7+
|
43 | if (crypto && typeof crypto.randomFillSync === 'function') {
|
44 | return function getRandomValues(buffer) {
|
45 | return crypto.randomFillSync(buffer);
|
46 | };
|
47 | }
|
48 | // Node 0.10+
|
49 | if (crypto && typeof crypto.randomBytes === 'function') {
|
50 | return function getRandomValues(buffer) {
|
51 | var bytes = crypto.randomBytes(buffer.length);
|
52 | for (var i = 0, n = bytes.length; i < n; ++i) {
|
53 | buffer[i] = bytes[i];
|
54 | }
|
55 | };
|
56 | }
|
57 | // Fallback
|
58 | return function getRandomValues(buffer) {
|
59 | var value = 0;
|
60 | for (var i = 0, n = buffer.length; i < n; ++i) {
|
61 | if (i % 4 === 0) {
|
62 | value = Math.random() * 0xFFFFFFFF >>> 0;
|
63 | }
|
64 | buffer[i] = value & 0xFF;
|
65 | value >>>= 8;
|
66 | }
|
67 | };
|
68 | })();
|
69 | })(Random = exports.Random || (exports.Random = {}));
|