import { _encodeUTF8 , _encodeBase64URLFromByteArray } from "@skygear/core" ; function byteToHex ( byte ) { return ( "0" + byte . toString ( 16 ) ) . substr ( - 2 ) ; } function uint8ArrayFrom ( arr ) { const output = new Uint8Array ( arr . length ) ; for ( let i = 0 ; i < arr . length ; ++ i ) { output [ i ] = arr [ i ] ; } return output ; } function windowCryptoSubtleDigest ( algorithm , data ) { const promiseOrEvent = window . crypto . subtle . digest ( algorithm , data . buffer ) ; if ( promiseOrEvent . then ) { return promiseOrEvent . then ( ( output ) => { return new Uint8Array ( output ) ; } ) ; } return new Promise ( ( resolve , reject ) => { ( promiseOrEvent as any ) . oncomplete = function ( output ) { resolve ( new Uint8Array ( output ) ) ; } ; ( promiseOrEvent as any ) . onerror = function ( err ) { reject ( err ) ; } ; } ) ; } function sha256 ( s ) { const bytes = uint8ArrayFrom ( _encodeUTF8 ( s ) ) ; return windowCryptoSubtleDigest ( "SHA-256" , bytes ) ; } export async function computeCodeChallenge ( codeVerifier ) { const hash = await sha256 ( codeVerifier ) ; const base64 = _encodeBase64URLFromByteArray ( hash ) ; return base64 ; } export function generateCodeVerifier ( ) { const arr = new Uint8Array ( 32 ) ; window . crypto . getRandomValues ( arr ) ; let output = "" ; for ( let i = 0 ; i < arr . length ; ++ i ) { output += byteToHex ( arr [ i ] ) ; } return output ; }