import * as child from "child_process" ; import { fork } from "child_process" ; import WebSocket = require ( "ws" ) ; export function run ( host = "localhost" , port = "8081" , role = "debugger" , debuggerName = "OfficeAddinDebugger" ) { const debuggerWorkerRelativePath = "\\debuggerWorker.js" ; const debuggerWorkerFullPath = `${ __dirname }${ debuggerWorkerRelativePath }` ; const websocketRetryTimeout = 500 ; function connectToDebuggerProxy ( ) { var ws = new WebSocket ( `ws://${ host }:${ port }/debugger-proxy?role=${ role }&name=${ debuggerName }` ) ; var worker ; function createJSRuntime ( ) { worker = fork ( `${ debuggerWorkerFullPath }` , [ ] , { stdio : [ "pipe" , "pipe" , "pipe" , "ipc" ] , execArgv : [ "--inspect" ] , } ) ; worker . on ( "message" , ( message ) => { ws . send ( JSON . stringify ( message ) ) ; } ) ; } function shutdownJSRuntime ( ) { if ( worker ) { worker . kill ( ) ; worker . unref ( ) ; } } ws . onopen = ( ) => { console . log ( "Web socket opened..." ) ; } ; ws . onmessage = ( message ) => { if ( ! message . data ) { return ; } var object = JSON . parse ( message . data . toString ( ) ) ; if ( object . $event === "client-disconnected" ) { shutdownJSRuntime ( ) ; return ; } if ( ! object . method ) { return ; } if ( object . method === "prepareJSRuntime" ) { shutdownJSRuntime ( ) ; createJSRuntime ( ) ; ws . send ( JSON . stringify ( { replyID : object . id } ) ) ; } else if ( object . method === "$disconnected" ) { shutdownJSRuntime ( ) ; } else { worker . send ( object ) ; } } ; ws . onclose = ( e ) => { shutdownJSRuntime ( ) ; if ( e . reason ) { console . log ( `Web socket closed because the following reason: ${ e . reason }` ) ; } setTimeout ( connectToDebuggerProxy , websocketRetryTimeout ) ; } ; ws . onerror = ( event ) => { console . log ( `${ event . error }` ) ; } ; } connectToDebuggerProxy ( ) ; }