import { Converter } from './Converter' ; import { DecodedData } from './DecodedData' ; export class Decoder { public static fromBase64 ( data ) { see https const nonBase64Alphabet = new RegExp ( '[^-A-Za-z0-9+/=]|=[^=]|={3,}$' , 'igm' ) ; const encoded = Converter . toString ( data ) . replace ( nonBase64Alphabet , '' ) ; const asBytes = Decoder . toByteArray ( encoded ) ; const asString = Converter . arrayBufferViewToStringUTF8 ( asBytes ) ; return new DecodedData ( asBytes , asString ) ; } private static toByteArray ( encoded ) { if ( encoded . length % 4 !== 0 ) { throw new Error ( 'Invalid string. Length must be a multiple of 4.' ) ; } if ( typeof window === 'object' ) { const decoded = window . atob ( encoded ) ; const rawLength = decoded . length ; const arrayBufferView = new Uint8Array ( new ArrayBuffer ( rawLength ) ) ; for ( let i = 0 , len = arrayBufferView . length ; i < len ; i ++ ) { arrayBufferView [ i ] = decoded . charCodeAt ( i ) ; } return arrayBufferView ; } const buffer = Buffer . from ( encoded , 'base64' ) ; return Converter . numberArrayToArrayBufferView ( buffer ) ; } }