All files / src randomBytesGenerator.ts

100% Statements 12/12
100% Branches 3/3
100% Functions 1/1
100% Lines 12/12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 278x     8x       8x 2x 1x         1x 1x 1x 1x 1x     1x       8x  
import {
  isNode,
} from './isNode';
import {
  randomBytes,
} from 'crypto';
 
export const randomBytesGenerator = (size: number) => {
  if (isNode()) {
    return new Uint8Array(randomBytes(size));
  } else {
    /* We are in-browser. Using the node crypto library here would increase
     * bundle size enormously. */
    // @ts-ignore
    const crypto = (window.crypto /* istanbul ignore next */ || window.msCrypto);
    const quota = 65536;
    const arr = new Uint8Array(size);
    for (let ii = 0; ii < size; ii += quota) {
      crypto.getRandomValues(arr.subarray(ii, ii + Math.min(size - ii, quota)));
    }
 
    return arr;
  }
};
 
export default randomBytesGenerator;