Skip to content

Instantly share code, notes, and snippets.

@devsnek
Created May 16, 2020 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devsnek/acf4354450f8f66aee0ed0811d043bf4 to your computer and use it in GitHub Desktop.
Save devsnek/acf4354450f8f66aee0ed0811d043bf4 to your computer and use it in GitHub Desktop.
'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);
});
}
'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