-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjsEval.worker.ts
More file actions
196 lines (181 loc) · 5.5 KB
/
jsEval.worker.ts
File metadata and controls
196 lines (181 loc) · 5.5 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/// <reference lib="webworker" />
import { expose } from "comlink";
import type { ReplOutput } from "../repl";
import type { WorkerCapabilities } from "./runtime";
import inspect from "object-inspect";
function format(...args: unknown[]): string {
// TODO: console.logの第1引数はフォーマット指定文字列を取ることができる
// https://nodejs.org/api/util.html#utilformatformat-args
return args.map((a) => (typeof a === "string" ? a : inspect(a))).join(" ");
}
let currentOutputCallback: ((output: ReplOutput) => void) | null = null;
// Helper function to capture console output
const originalConsole = self.console;
self.console = {
...originalConsole,
log: (...args: unknown[]) => {
if (currentOutputCallback) {
currentOutputCallback({ type: "stdout", message: format(...args) });
}
},
error: (...args: unknown[]) => {
if (currentOutputCallback) {
currentOutputCallback({ type: "stderr", message: format(...args) });
}
},
warn: (...args: unknown[]) => {
if (currentOutputCallback) {
currentOutputCallback({ type: "stderr", message: format(...args) });
}
},
info: (...args: unknown[]) => {
if (currentOutputCallback) {
currentOutputCallback({ type: "stdout", message: format(...args) });
}
},
};
async function init(/*_interruptBuffer?: Uint8Array*/): Promise<{
capabilities: WorkerCapabilities;
}> {
// Initialize the worker and report capabilities
// interruptBuffer is not used for JavaScript (restart-based interruption)
return { capabilities: { interrupt: "restart" } };
}
async function replLikeEval(code: string): Promise<unknown> {
// eval()の中でconst,letを使って変数を作成した場合、
// 次に実行するコマンドはスコープ外扱いでありアクセスできなくなってしまうので、
// varに置き換えている
if (code.trim().startsWith("const ")) {
code = "var " + code.trim().slice(6);
} else if (code.trim().startsWith("let ")) {
code = "var " + code.trim().slice(4);
}
// eval()の中でclassを作成した場合も同様
const classRegExp = /^\s*class\s+(\w+)/;
if (classRegExp.test(code)) {
code = code.replace(classRegExp, "var $1 = class $1");
}
if (code.trim().startsWith("{") && code.trim().endsWith("}")) {
// オブジェクトは ( ) で囲わなければならない
try {
return self.eval(`(${code})`);
} catch (e) {
if (e instanceof SyntaxError) {
// オブジェクトではなくブロックだった場合、再度普通に実行
return self.eval(code);
} else {
throw e;
}
}
} else if (/^\s*await\W/.test(code)) {
// promiseをawaitする場合は、promiseの部分だけをevalし、それを外からawaitする
return await self.eval(code.trim().slice(5));
} else {
return self.eval(code);
}
}
async function runCode(
code: string,
onOutput: (output: ReplOutput) => void
): Promise<{
updatedFiles: Record<string, string>;
}> {
currentOutputCallback = onOutput;
try {
const result = await replLikeEval(code);
onOutput({
type: "return",
message: inspect(result),
});
} catch (e) {
originalConsole.log(e);
// TODO: stack trace?
if (e instanceof Error) {
onOutput({
type: "error",
message: `${e.name}: ${e.message}`,
});
} else {
onOutput({
type: "error",
message: `${String(e)}`,
});
}
} finally {
currentOutputCallback = null;
}
return { updatedFiles: {} as Record<string, string> };
}
function runFile(
name: string,
files: Record<string, string>,
onOutput: (output: ReplOutput) => void
): { updatedFiles: Record<string, string> } {
// pyodide worker などと異なり、複数ファイルを読み込んでimportのようなことをするのには対応していません。
currentOutputCallback = onOutput;
try {
self.eval(files[name]);
} catch (e) {
originalConsole.log(e);
// TODO: stack trace?
if (e instanceof Error) {
onOutput({
type: "error",
message: `${e.name}: ${e.message}`,
});
} else {
onOutput({
type: "error",
message: `${String(e)}`,
});
}
} finally {
currentOutputCallback = null;
}
return { updatedFiles: {} as Record<string, string> };
}
async function checkSyntax(
code: string
): Promise<{ status: "complete" | "incomplete" | "invalid" }> {
try {
// Try to create a Function to check syntax
// new Function(code); // <- not working
self.eval(`() => {${code}}`);
return { status: "complete" };
} catch (e) {
// Check if it's a syntax error or if more input is expected
if (e instanceof SyntaxError) {
// Simple heuristic: check for "Unexpected end of input"
if (
e.message.includes("Unexpected token '}'") ||
e.message.includes("Unexpected end of input")
) {
return { status: "incomplete" };
} else {
return { status: "invalid" };
}
} else {
return { status: "invalid" };
}
}
}
async function restoreState(commands: string[]): Promise<object> {
// Re-execute all previously successful commands to restore state
for (const command of commands) {
try {
replLikeEval(command);
} catch (e) {
// If restoration fails, we still continue with other commands
originalConsole.error("Failed to restore command:", command, e);
}
}
return {};
}
const api = {
init,
runCode,
runFile,
checkSyntax,
restoreState,
};
expose(api);