const restify = require ( 'restify' ) ; const open_url = require ( 'open' ) ; const querystring = require ( 'querystring' ) ; const fs = require ( 'fs' ) ; /**
 * Read a file to a string.
 */ function read_string ( filename ) { return new Promise ( ( resolve , reject ) => { fs . readFile ( filename , function ( err , data ) { if ( err ) { reject ( err ) ; } else { resolve ( data . toString ( ) ) ; } } ) ; } ) ; } /**
 * Start the server and return its URL.
 */ function serve ( log ) { let server = restify . createServer ( ) ; let qp = restify . queryParser ( { mapParams : false } ) ; server . get ( '/log' , qp , ( req , res , next ) => { let out = log ( JSON . parse ( req . query [ 'msg' ] ) ) ; res . send ( out ) ; return next ( ) ; } ) ; server . get ( '/' , restify . serveStatic ( { directory : '../harness' , file : 'index.html' , maxAge : 0 } ) ) ; server . get ( '/client.js' , restify . serveStatic ( { directory : './build' , file : 'client.js' , maxAge : 0 } ) ) ; server . get ( /\/.*/ , restify . serveStatic ( { directory : '../dingus' , default : 'index.html' , maxAge : 0 } ) ) ; server . on ( 'uncaughtException' , ( req , res , route , err ) => { if ( err . stack ) { console . error ( err . stack ) ; } else { console . error ( err ) ; } } ) ; server . on ( 'after' , ( req , res , route , err ) => { plog ( res . statusCode + " " + req . method + " " + req . url ) ; } ) ; let port = 4700 ; let url = "http://localhost:" + port ; return new Promise ( ( resolve , reject ) => { server . listen ( port , ( ) => { resolve ( url ) ; } ) ; } ) ; } let MESSAGE_COUNT = 4 ; /**
 * Called when a performance experiment has finished with data about the
 * experiment.
 */ function experiment_finished ( data ) { process . stdout . write ( JSON . stringify ( data ) ) ; setTimeout ( ( ) => { process . exit ( ) ; } , 500 ) ; } /**
 * Write a message to stderr.
 */ function plog ( s ) { if ( typeof ( s ) === "string" ) { process . stderr . write ( s ) ; } else { process . stderr . write ( JSON . stringify ( s ) ) ; } process . stderr . write ( "\n" ) ; } function main ( ) { let fn = process . argv [ 2 ] ; let code ; plog ( "executing " + fn ) ; read_string ( fn ) . then ( ( code ) => { let messages = [ ] ; let handle_log = ( msg ) => { plog ( msg ) ; messages . push ( msg ) ; if ( messages . length >= MESSAGE_COUNT ) { experiment_finished ( { fn , messages } ) ; return "done" ; } else { return "ok" ; } } ; serve ( handle_log ) . then ( ( url ) => { plog ( url ) ; let query = querystring . stringify ( { code } ) ; open_url ( url + '/#' + query ) ; } ) ; } ) ; } main ( ) ;