import fetch from "node-fetch" ; import * as fs from "./fileSystem" ; import Debug from "debug" ; const debug = Debug ( "live-plugin-manager.HttpUtils" ) ; export interface Headers { [ name ] : string ; } export function headersBearerAuth ( token ) { return { Authorization : "Bearer " + token } ; } export function headersTokenAuth ( token ) { return { Authorization : "token " + token } ; } export function headersBasicAuth ( username , password ) { return { Authorization : "Basic " + Buffer . from ( username + ":" + password ) . toString ( "base64" ) } ; } export async function httpJsonGet < T > ( sourceUrl , headers ? ) { if ( debug . enabled ) { debug ( `Json GET ${ sourceUrl } ...` ) ; debug ( "HEADERS" , headers ) ; } const res = await fetch ( sourceUrl , { headers : { ... headers } } ) ; if ( debug . enabled ) { debug ( "Response HEADERS" , res . headers ) ; } if ( ! res . ok ) { throw new Error ( `Response error ${ res . status } ${ res . statusText }` ) ; } return res . json ( ) ; } export async function httpDownload ( sourceUrl , destinationFile , headers ? ) { if ( debug . enabled ) { debug ( `Download GET ${ sourceUrl } ...` ) ; debug ( "HEADERS" , headers ) ; } const res = await fetch ( sourceUrl , { headers : { ... headers } } ) ; if ( debug . enabled ) { debug ( "Response HEADERS" , res . headers ) ; } if ( ! res . ok ) { throw new Error ( `Response error ${ res . status } ${ res . statusText }` ) ; } return new Promise < void > ( ( resolve , reject ) => { const fileStream = fs . createWriteStream ( destinationFile ) ; res . body . pipe ( fileStream ) ; res . body . on ( "error" , ( err ) => { fileStream . close ( ) ; if ( fs . fileExists ( destinationFile ) ) { fs . remove ( destinationFile ) ; } reject ( err ) ; } ) ; fileStream . on ( "finish" , function ( ) { fileStream . close ( ) ; resolve ( ) ; } ) ; } ) ; }