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