2323const crypto = require ( 'crypto' ) ;
2424const { EventEmitter } = require ( 'events' ) ;
2525const http = require ( 'http' ) ;
26+ const URL = require ( 'url' ) ;
2627const util = require ( 'util' ) ;
2728
2829const debuglog = util . debuglog ( 'inspect' ) ;
@@ -228,7 +229,53 @@ class Client extends EventEmitter {
228229 } ) ;
229230 }
230231
232+ _fetchJSON ( urlPath ) {
233+ return new Promise ( ( resolve , reject ) => {
234+ const httpReq = http . get ( {
235+ host : this . _host ,
236+ port : this . _port ,
237+ path : urlPath ,
238+ } ) ;
239+
240+ const chunks = [ ] ;
241+
242+ function onResponse ( httpRes ) {
243+ function parseChunks ( ) {
244+ const resBody = Buffer . concat ( chunks ) . toString ( ) ;
245+ if ( httpRes . statusCode !== 200 ) {
246+ reject ( new Error ( `Unexpected ${ httpRes . statusCode } : ${ resBody } ` ) ) ;
247+ return ;
248+ }
249+ try {
250+ resolve ( JSON . parse ( resBody ) ) ;
251+ } catch ( parseError ) {
252+ reject ( new Error ( `Response did not contain valid JSON: ${ resBody } ` ) ) ;
253+ return ;
254+ }
255+ }
256+
257+ httpRes . on ( 'error' , reject ) ;
258+ httpRes . on ( 'data' , chunk => chunks . push ( chunk ) ) ;
259+ httpRes . on ( 'end' , parseChunks ) ;
260+ }
261+
262+ httpReq . on ( 'error' , reject ) ;
263+ httpReq . on ( 'response' , onResponse ) ;
264+ } ) ;
265+ }
266+
231267 connect ( ) {
268+ return this . _discoverWebsocketPath ( )
269+ . then ( urlPath => this . _connectWebsocket ( urlPath ) ) ;
270+ }
271+
272+ _discoverWebsocketPath ( ) {
273+ return this . _fetchJSON ( '/json' )
274+ . then ( ( [ { webSocketDebuggerUrl } ] ) =>
275+ URL . parse ( webSocketDebuggerUrl ) . path ) ;
276+ }
277+
278+ _connectWebsocket ( urlPath ) {
232279 this . reset ( ) ;
233280
234281 const key1 = crypto . randomBytes ( 16 ) . toString ( 'base64' ) ;
@@ -237,18 +284,20 @@ class Client extends EventEmitter {
237284 const httpReq = this . _http = http . request ( {
238285 host : this . _host ,
239286 port : this . _port ,
240- path : '/node' ,
287+ path : urlPath ,
241288 headers : {
242289 Connection : 'Upgrade' ,
243290 Upgrade : 'websocket' ,
244291 'Sec-WebSocket-Key' : key1 ,
292+ 'Sec-WebSocket-Version' : '13' ,
245293 } ,
246294 } ) ;
247295 httpReq . on ( 'error' , e => {
248296 this . emit ( 'error' , e ) ;
249297 } ) ;
250298 httpReq . on ( 'response' , httpRes => {
251299 if ( httpRes . statusCode >= 400 ) {
300+ process . stderr . write ( `Unexpected HTTP response: ${ httpRes . statusCode } \n` ) ;
252301 httpRes . pipe ( process . stderr ) ;
253302 } else {
254303 httpRes . pipe ( process . stderr ) ;
0 commit comments