import * as path from 'path' ; import { promisify } from 'util' ; import * as getBrowserLauncherCb from '@httptoolkit/browser-launcher' ; import { LaunchOptions , Launch , BrowserInstance , Browser , update as updateBrowserCacheCb } from '@httptoolkit/browser-launcher' ; import { reportError } from './error-tracking' ; import { delay } from './util/promise' ; import { isErrorLike } from './util/error' ; import { readFile , deleteFile } from './util/fs' ; const getBrowserLauncher = promisify ( getBrowserLauncherCb ) ; const updateBrowserCache = promisify ( updateBrowserCacheCb ) ; const browserConfigPath = ( configPath ) => path . join ( configPath , 'browsers.json' ) ; export { BrowserInstance , Browser } ; export async function checkBrowserConfig ( configPath ) { const browserConfig = browserConfigPath ( configPath ) ; try { const rawConfig = await readFile ( browserConfig , 'utf8' ) ; JSON . parse ( rawConfig ) ; } catch ( error ) { if ( isErrorLike ( error ) && error . code === 'ENOENT' ) return ; console . warn ( `Failed to read browser config cache from ${ browserConfig }, clearing.` , error ) ; return deleteFile ( browserConfig ) . catch ( ( err ) => { if ( isErrorLike ( err ) && err . code === 'ENOENT' ) return ; console . error ( 'Failed to clear broken config file:' , err ) ; reportError ( err ) ; } ) ; } } let launcher ; function getLauncher ( configPath ) { if ( ! launcher ) { const browserConfig = browserConfigPath ( configPath ) ; launcher = getBrowserLauncher ( browserConfig ) ; launcher . then ( async ( ) => { await delay ( 2000 ) ; try { await updateBrowserCache ( browserConfig ) ; console . log ( 'Browser cache updated' ) ; launcher = getBrowserLauncher ( browserConfig ) ; } catch ( e ) { reportError ( e ) ; } } ) ; launcher . catch ( ( e ) => { reportError ( e ) ; launcher = undefined ; } ) ; } return launcher ; } export const getAvailableBrowsers = async ( configPath ) => { return ( await getLauncher ( configPath ) ) . browsers ; } ; export { LaunchOptions } ; export const launchBrowser = async ( url , options , configPath ) => { const launcher = await getLauncher ( configPath ) ; const browserInstance = await promisify ( launcher ) ( url , options ) ; browserInstance . process . on ( 'error' , ( e ) => { if ( browserInstance . process . listenerCount ( 'error' ) === 1 ) { console . log ( 'Browser launch error' ) ; reportError ( e ) ; } } ) ; return browserInstance ; } ;