1 | // Copyright (c) Jupyter Development Team.
|
2 | // Distributed under the terms of the Modified BSD License.
|
3 | /*-----------------------------------------------------------------------------
|
4 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
5 | |
|
6 | | Distributed under the terms of the BSD 3-Clause License.
|
7 | |
|
8 | | The full license is in the file LICENSE, distributed with this software.
|
9 | |----------------------------------------------------------------------------*/
|
10 |
|
11 | import { fallbackRandomValues } from './random';
|
12 |
|
13 | // Declare ambient variables for `window` and `require` to avoid a
|
14 | // hard dependency on both. This package must run on node.
|
15 | declare let window: any;
|
16 |
|
17 | /**
|
18 | * The namespace for random number related functionality.
|
19 | */
|
20 | export namespace Random {
|
21 | /**
|
22 | * A function which generates random bytes.
|
23 | *
|
24 | * @param buffer - The `Uint8Array` to fill with random bytes.
|
25 | *
|
26 | * #### Notes
|
27 | * A cryptographically strong random number generator will be used if
|
28 | * available. Otherwise, `Math.random` will be used as a fallback for
|
29 | * randomness.
|
30 | *
|
31 | * The following RNGs are supported, listed in order of precedence:
|
32 | * - `window.crypto.getRandomValues`
|
33 | * - `window.msCrypto.getRandomValues`
|
34 | * - `require('crypto').randomFillSync
|
35 | * - `require('crypto').randomBytes
|
36 | * - `Math.random`
|
37 | */
|
38 | export const getRandomValues = (() => {
|
39 | // Look up the crypto module if available.
|
40 | const crypto: any =
|
41 | (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||
|
42 | null;
|
43 |
|
44 | // Modern browsers and IE 11
|
45 | if (crypto && typeof crypto.getRandomValues === 'function') {
|
46 | return function getRandomValues(buffer: Uint8Array): void {
|
47 | return crypto.getRandomValues(buffer);
|
48 | };
|
49 | }
|
50 |
|
51 | // Fallback
|
52 | return fallbackRandomValues;
|
53 | })();
|
54 | }
|
55 |
|
\ | No newline at end of file |