UNPKG

1.49 kBPlain TextView Raw
1import { UnavailabilityError } from '@unimodules/core';
2import { toByteArray } from 'base64-js';
3
4import ExpoRandom from './ExpoRandom';
5
6function assertByteCount(value: any, methodName: string): 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: ${methodName}(${value}) expected a valid number from range 0...1024`
15 );
16 }
17}
18
19export function getRandomBytes(byteCount: number): Uint8Array {
20 assertByteCount(byteCount, 'getRandomBytes');
21 const validByteCount = Math.floor(byteCount);
22 if (ExpoRandom.getRandomBytes) {
23 return ExpoRandom.getRandomBytes(validByteCount);
24 } else if (ExpoRandom.getRandomBase64String) {
25 const base64 = ExpoRandom.getRandomBase64String(validByteCount);
26 return toByteArray(base64);
27 } else {
28 throw new UnavailabilityError('expo-random', 'getRandomBytes');
29 }
30}
31
32export async function getRandomBytesAsync(byteCount: number): Promise<Uint8Array> {
33 assertByteCount(byteCount, 'getRandomBytesAsync');
34 const validByteCount = Math.floor(byteCount);
35 if (ExpoRandom.getRandomBytesAsync) {
36 return await ExpoRandom.getRandomBytesAsync(validByteCount);
37 } else if (ExpoRandom.getRandomBase64StringAsync) {
38 const base64 = await ExpoRandom.getRandomBase64StringAsync(validByteCount);
39 return toByteArray(base64);
40 } else {
41 throw new UnavailabilityError('expo-random', 'getRandomBytesAsync');
42 }
43}