Created
May 16, 2020 19:14
-
-
Save devsnek/acf4354450f8f66aee0ed0811d043bf4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const { EventEmitter } = require('events'); | |
const { spawn } = require('child_process'); | |
const WebSocket = require('ws'); | |
class Session extends EventEmitter { | |
constructor(url) { | |
super(); | |
this.ws = new WebSocket(url); | |
this.ws.on('message', (d) => { | |
this.onMessage(d); | |
}); | |
this.ws.on('open', () => { | |
this.emit('open'); | |
}); | |
this.messageCounter = 0; | |
this.messages = new Map(); | |
} | |
onMessage(d) { | |
const { id, result } = JSON.parse(d); | |
const { resolve } = this.messages.get(id); | |
this.messages.delete(id); | |
resolve(result); | |
} | |
post(method, params) { | |
return new Promise((resolve, reject) => { | |
const id = this.messageCounter; | |
this.messageCounter += 1; | |
const message = { | |
method, | |
params, | |
id, | |
}; | |
this.messages.set(id, { resolve, reject }); | |
this.ws.send(JSON.stringify(message)); | |
}); | |
} | |
} | |
const child = spawn(process.execPath, ['--inspect', './stub.js'], { | |
cwd: process.cwd(), | |
windowsHide: true, | |
}); | |
child.stdout.on('data', (data) => { | |
process.stdout.write(data); | |
}); | |
const re = /^Debugger listening on ([^ \n]+)/; | |
child.stderr.on('data', (data) => { | |
const s = data.toString(); | |
const r = re.exec(s); | |
if (r !== null) { | |
const [, url] = r; | |
start(url); | |
} | |
}); | |
function start(wsUrl) { | |
const session = new Session(wsUrl); | |
session.on('open', () => { | |
// TIMEOUTS: | |
// >9ms -> NEVER RESPONDS | |
// 9ms -> RESPONDS ~50% OF TIME | |
// <9ms -> ALWAYS RESPONDS | |
setTimeout(() => { | |
session.post('Runtime.evaluate', { | |
expression: '1 + 1', | |
replMode: true, | |
}).then(console.log); | |
}, 100); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// keep inspect target alive | |
setTimeout(() => {}, 2147483647); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment