1 | import { UnavailabilityError } from '@unimodules/core';
|
2 | import { toByteArray } from 'base64-js';
|
3 |
|
4 | import ExpoRandom from './ExpoRandom';
|
5 |
|
6 | function assertByteCount(value: any): void {
|
7 | if (
|
8 | typeof value !== 'number' ||
|
9 | isNaN(value) ||
|
10 | Math.floor(value) < 0 ||
|
11 | Math.floor(value) > 1024
|
12 | ) {
|
13 | throw new TypeError(
|
14 | `expo-random: getRandomBytesAsync(${value}) expected a valid number from range 0...1024`
|
15 | );
|
16 | }
|
17 | }
|
18 |
|
19 | export async function getRandomBytesAsync(byteCount: number): Promise<Uint8Array> {
|
20 | assertByteCount(byteCount);
|
21 | const validByteCount = Math.floor(byteCount);
|
22 | if (ExpoRandom.getRandomBytesAsync) {
|
23 | return await ExpoRandom.getRandomBytesAsync(validByteCount);
|
24 | } else if (ExpoRandom.getRandomBase64StringAsync) {
|
25 | const base64 = await ExpoRandom.getRandomBase64StringAsync(validByteCount);
|
26 | return toByteArray(base64);
|
27 | } else {
|
28 | throw new UnavailabilityError('expo-random', 'getRandomBytesAsync');
|
29 | }
|
30 | }
|