@stencila/jesta
Version:
Stencila plugin for executable documents using JavaScript
70 lines (69 loc) • 2.51 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.session = exports.Session = void 0;
const schema_1 = require("@stencila/schema");
const repl_1 = __importDefault(require("repl"));
const stream_1 = __importDefault(require("stream"));
class Session {
constructor() {
this.outputs = [];
this.errors = [];
this.input = new stream_1.default.PassThrough();
this.repl = repl_1.default.start({
input: this.input,
output: new stream_1.default.PassThrough(),
writer: (result) => this.write(result),
terminal: false,
breakEvalOnSigint: true,
});
this.context = this.repl.context;
}
write(result) {
if (result !== undefined) {
// Because the session is in a different runtime environment
// it seems that `instanceof Error` does not work here
// and that we need to use duck typing instead
// See https://stackoverflow.com/a/45496068
if (typeof result === 'object' &&
result !== null &&
!Array.isArray(result) &&
!schema_1.isEntity(result) &&
typeof (result === null || result === void 0 ? void 0 : result.message) === 'string' &&
typeof (result === null || result === void 0 ? void 0 : result.stack) === 'string')
this.errors.push(result);
else if (typeof result === 'object' &&
result !== null &&
'code' in result &&
result.code === 'ERR_SCRIPT_EXECUTION_INTERRUPTED') {
this.errors.push(new Error('Interrupted'));
}
else {
this.outputs.push(result);
}
}
// For some reason unless we return some string content
// this function gets called twice
return ' ';
}
enter(code) {
this.outputs = [];
this.errors = [];
this.input.write(code + '\n', 'utf8');
return [this.outputs, this.errors];
}
}
exports.Session = Session;
let sessionInstance;
/**
* Get the session for the current document
*/
function session() {
if (sessionInstance === undefined) {
sessionInstance = new Session();
}
return sessionInstance;
}
exports.session = session;