export type HttpRequestOptions = { body ? : Array < any > | Object | string ; url : string ; method : 'POST' | 'GET' ; skipContentTypeHeader ? : boolean ; } ; let _fetch = typeof window === `undefined` ? ( ) => Promise . reject ( ) : window . fetch ; let _isNode = false ; export function setFetch ( fetch , isNode ? ) { _fetch = fetch ; _isNode = ! ! isNode ; } function contentType ( body ) { if ( typeof body === `string` ) { if ( body === `` ) { return `text/plain` ; } return `application/octet-stream` ; } return `application/json` ; } function wrapBody ( body ) { if ( typeof body === `string` ) { return body ; } return JSON . stringify ( body ) ; } function parseResult ( text ) { try { return JSON . parse ( text ) ; } catch ( e ) { return text ; } } export async function request ( options ) { const fetchOptions = { method : options . method , body : wrapBody ( options . body ) , credentials : `same-origin` , headers : { } , } ; if ( options . skipContentTypeHeader == null || options . skipContentTypeHeader === false ) { fetchOptions . headers = { ... fetchOptions . headers , 'Content-Type' : contentType ( options . body == null ? `` : options . body ) , } ; } if ( _isNode ) { fetchOptions . headers = { ... fetchOptions . headers , Origin : `https://node.trezor.io` , } ; } const res = await _fetch ( options . url , fetchOptions ) ; const resText = await res . text ( ) ; if ( res . ok ) { return parseResult ( resText ) ; } const resJson = parseResult ( resText ) ; if ( typeof resJson === `object` && resJson != null && resJson . error != null ) { throw new Error ( resJson . error ) ; } else { throw new Error ( resText ) ; } }