Skip to content

Instantly share code, notes, and snippets.

@mishfit
Forked from amasad/repl.js
Created May 22, 2017 04:57
Show Gist options
  • Save mishfit/5c7c610fc659fc9dc7799371cca519f6 to your computer and use it in GitHub Desktop.
Save mishfit/5c7c610fc659fc9dc7799371cca519f6 to your computer and use it in GitHub Desktop.
a project repl
const babel = require('babel-core');
const vm = require('vm');
const repl = require('repl');
let context = repl.start({ eval: evaluate }).context;
// Autorequire all models so that they're available by name in the repl.
const models = require('../server/models');
for (let name in models) {
context[name] = models[name];
}
const RESULT_SYMBOL = '__eval_res';
function evaluate(cmd, context, filename, callback) {
context = vm.createContext(context);
if (cmd.match(/await/)) {
let assign = null;
if (cmd.match(/\=/)) {
let parts = cmd.split('=');
assign = parts[0];
cmd = parts.slice(1).join('=');
}
cmd = '(async function() { return ' + cmd + '})()';
try {
cmd = compile(cmd);
} catch (e) {
callback(new repl.Recoverable());
return;
}
let res;
try {
res = vm.runInContext(cmd, context);
} catch (e) {
callback(e);
return;
}
res.then(
r => {
context[RESULT_SYMBOL] = r;
if (assign) {
simpleEval(assign + ' = ' + RESULT_SYMBOL, context, filename, callback);
} else {
callback(null, r);
}
},
(e) => callback(e)
);
return;
}
simpleEval(cmd, context, filename, callback);
}
function simpleEval(cmd, context, filename, callback) {
try {
cmd = compile(cmd);
} catch (e) {
callback(new repl.Recoverable());
return;
}
try {
callback(null, vm.runInContext(cmd, context));
} catch (e) {
callback(e);
return;
}
}
function compile(cmd) {
return babel.transform(cmd, {
sourceType: 'script',
blacklist: ['strict'],
}).code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment