-
Notifications
You must be signed in to change notification settings - Fork 10
/
nodejs.ts
117 lines (99 loc) · 3.06 KB
/
nodejs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import repl from 'repl';
import vm from 'vm';
import util from 'util';
import { spawn } from 'child_process';
import { Response } from 'express';
import { transformSync } from "@babel/core";
import { RunNodeCodeOptions } from "../types";
import { generateBashCode } from '../utils';
//A simple repl server to evaluate code from the browser
const replServer = repl.start({
prompt: '',
eval: replEvalCode,
ignoreUndefined: true,
terminal: true,
useColors: true,
useGlobal: false
});
replServer.context.__dirname = process.cwd();
replServer.context.require = require;
replServer.context.spawn = spawn;
replServer.context.util = util;
async function replEvalCode(code: string) {
/**@ts-ignore */
return runNodeCode({ code });
}
const runNodeCode = ({ code, res, language }: RunNodeCodeOptions) => {
switch (language) {
case "sh":
const bashCode = generateBashCode(code);
runJsCodeInContext({ code: bashCode, res });
break;
case "javascript":
try {
let transformedJsCode = transformSync(code, {
presets: [
[
"@babel/preset-env",
{
"targets": {
"esmodules": true
}
}
]
],
})?.code || code;
transformedJsCode = `${transformedJsCode}\nconsole.log('')`
runJsCodeInContext({ code: transformedJsCode, res })
} catch (err) {
let errMsg = formatErrorOutput(err)
res.write(`${errMsg}<br />`);
res.end();
}
break;
case "process":
handleProcessCmds(code, res);
break;
default:
throw new Error(`Language ${language} is not supported`);
}
}
const runJsCodeInContext = async ({ code, res }: any) => {
try {
//Ensures all console.log statements in code are written to the response
replServer.context.console = {
log: (...args: any[]) => {
res.write(`${args[0]}<br />`);
}
};
replServer.context.res = res;
await vm.runInNewContext(code, replServer.context, {
displayErrors: true,
})
} catch (err: any) {
console.log(err)
let errMsg = formatErrorOutput(err)
res.write(`${errMsg}<br />`);
res.end();
}
}
const formatErrorOutput = (err: any) => {
return JSON.stringify({ output: err.message, name: err.name, __$hasError: true })
}
const handleProcessCmds = async (code: string, res: Response) => {
switch (code) {
case "stop":
stopKernel(res);
break;
default:
break;
}
}
const stopKernel = async (res: Response) => {
console.log("Stopping running kernel...")
replServer.context.process.exit();
res.write("STOPPED");
}
export {
runNodeCode,
}