Skip to content
This repository was archived by the owner on Feb 1, 2022. It is now read-only.

Commit 3f46c2c

Browse files
author
Jan Krems
committed
feat: Working repl eval
1 parent cfa197b commit 3f46c2c

3 files changed

Lines changed: 49 additions & 4 deletions

File tree

lib/internal/inspect-repl.js

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,43 @@
11
'use strict';
22
const Repl = require('repl');
3+
const vm = require('vm');
4+
5+
function toCallback(promise, callback) {
6+
function forward(...args) {
7+
process.nextTick(() => callback(...args));
8+
}
9+
promise.then(forward.bind(null, null), forward);
10+
}
311

412
function startRepl(inspector) {
513
let repl; // forward declaration
14+
let lastCommand;
15+
16+
function prepareControlCode(input) {
17+
if (input === '\n') return lastCommand;
18+
// exec process.title => exec("process.title");
19+
const match = input.match(/^\s*exec\s+([^\n]*)/);
20+
if (match) {
21+
lastCommand = `exec(${JSON.stringify(match[1])})`;
22+
} else {
23+
lastCommand = input;
24+
}
25+
return lastCommand;
26+
}
27+
28+
function controlEval(input, context, filename, callback) {
29+
try {
30+
const code = prepareControlCode(input);
31+
const result = vm.runInContext(code, context, filename);
632

7-
function controlEval(code, ctx, file, cb) {
8-
cb(new Error('Not implemented'));
33+
if (result && typeof result.then === 'function') {
34+
toCallback(result, callback);
35+
return;
36+
}
37+
callback(null, result);
38+
} catch (e) {
39+
callback(e);
40+
}
941
}
1042

1143
const replOptions = {

test/cli/launch.test.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,16 @@ const startCLI = require('./start-cli');
66
tap.test('examples/empty.js', (t) => {
77
const cli = startCLI(['examples/empty.js']);
88
return cli.waitForPrompt()
9-
.then(() => cli.quit())
10-
.then((code) => {
9+
.then(() => {
1110
t.match(cli.output, 'debug>', 'prints a prompt');
1211
t.match(cli.output, '< Debugger listening on port 9229', 'forwards child output');
12+
})
13+
.then(() => cli.command('["hello", "world"].join(" ")'))
14+
.then(() => {
15+
t.match(cli.output, 'hello world', 'prints the result');
16+
})
17+
.then(() => cli.quit())
18+
.then((code) => {
1319
t.equal(code, 0, 'exits with success');
1420
});
1521
});

test/cli/start-cli.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,13 @@ function startCLI(args) {
7878
return getOutput();
7979
},
8080

81+
command(input) {
82+
this.flushOutput();
83+
child.stdin.write(input);
84+
child.stdin.write('\n');
85+
return this.waitForPrompt();
86+
},
87+
8188
quit() {
8289
return new Promise((resolve) => {
8390
child.stdin.end();

0 commit comments

Comments
 (0)