forked from jupyterlite/javascript-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime_evaluator.ts
More file actions
340 lines (297 loc) · 8.67 KB
/
Copy pathruntime_evaluator.ts
File metadata and controls
340 lines (297 loc) · 8.67 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import type { KernelMessage } from '@jupyterlab/services';
import { JavaScriptExecutor } from './executor';
import { normalizeError } from './errors';
import type { RuntimeOutputHandler } from './runtime_protocol';
/**
* Shared execution logic for iframe and worker runtime backends.
*/
export class JavaScriptRuntimeEvaluator {
/**
* Instantiate a runtime evaluator.
*/
constructor(options: JavaScriptRuntimeEvaluator.IOptions) {
this._globalScope = options.globalScope;
this._onOutput = options.onOutput;
this._executor =
options.executor ?? new JavaScriptExecutor(options.globalScope);
this._setupDisplay();
this._setupConsoleOverrides();
}
/**
* Dispose the evaluator and restore patched globals where possible.
*/
dispose(): void {
this._restoreConsoleOverrides();
this._restoreDisplay();
}
/**
* The runtime global scope.
*/
get globalScope(): Record<string, any> {
return this._globalScope;
}
/**
* The executor used by the evaluator.
*/
get executor(): JavaScriptExecutor {
return this._executor;
}
/**
* Execute user code in the configured runtime global scope.
*/
async execute(
code: string,
executionCount: number
): Promise<KernelMessage.IExecuteReplyMsg['content']> {
// Parse-time errors are syntax errors, so show only `Name: message`.
let asyncFunction: () => Promise<any>;
let withReturn: boolean;
try {
const parsed = this._executor.makeAsyncFromCode(code);
asyncFunction = parsed.asyncFunction;
withReturn = parsed.withReturn;
} catch (error) {
const normalized = normalizeError(error);
return this._emitError(executionCount, normalized, false);
}
// Runtime errors may include useful eval frames from user code.
try {
const resultPromise = this._evalFunc(asyncFunction);
if (withReturn) {
const result = await resultPromise;
if (result !== undefined) {
const data = this._executor.getMimeBundle(result);
this._onOutput({
type: 'execute_result',
bundle: {
execution_count: executionCount,
data,
metadata: {}
}
});
}
} else {
await resultPromise;
}
return {
status: 'ok',
execution_count: executionCount,
user_expressions: {}
};
} catch (error) {
const normalized = normalizeError(error);
return this._emitError(executionCount, normalized, true);
}
}
/**
* Complete code at the given cursor position.
*/
complete(
code: string,
cursorPos: number
): KernelMessage.ICompleteReplyMsg['content'] {
const result = this._executor.completeRequest(code, cursorPos);
return {
matches: result.matches,
cursor_start: result.cursorStart,
cursor_end: result.cursorEnd || cursorPos,
metadata: {},
status: 'ok'
};
}
/**
* Inspect symbol information at the given cursor position.
*/
inspect(
code: string,
cursorPos: number,
detailLevel: KernelMessage.IInspectRequestMsg['content']['detail_level']
): KernelMessage.IInspectReplyMsg['content'] {
return this._executor.inspect(code, cursorPos, detailLevel);
}
/**
* Check whether the provided code is complete.
*/
isComplete(code: string): KernelMessage.IIsCompleteReplyMsg['content'] {
return this._executor.isComplete(code);
}
/**
* Evaluate an async function within the configured global scope.
*/
private _evalFunc(asyncFunc: () => Promise<any>): Promise<any> {
return asyncFunc.call(this._globalScope);
}
/**
* Build and emit an execute error reply.
*/
private _emitError(
executionCount: number,
error: Error,
includeStack: boolean
): KernelMessage.IExecuteReplyMsg['content'] {
const traceback = includeStack
? this._executor.cleanStackTrace(error)
: `${error.name}: ${error.message}`;
const content: KernelMessage.IReplyErrorContent = {
status: 'error',
ename: error.name || 'Error',
evalue: error.message || '',
traceback: [traceback]
};
this._onOutput({
type: 'execute_error',
bundle: content
});
return {
...content,
execution_count: executionCount
};
}
/**
* Patch console methods in runtime scope to emit Jupyter stream messages.
*/
private _setupConsoleOverrides(): void {
const scopeConsole = this._globalScope.console as Console | undefined;
if (!scopeConsole) {
return;
}
this._originalConsole = {
log: scopeConsole.log,
info: scopeConsole.info,
error: scopeConsole.error,
warn: scopeConsole.warn,
debug: scopeConsole.debug,
dir: scopeConsole.dir,
trace: scopeConsole.trace,
table: scopeConsole.table
};
const toText = (args: any[]) => {
const text = args
.map(arg => {
if (typeof arg === 'string') {
return arg;
}
try {
if (typeof arg === 'object' && arg !== null) {
const bundle = this._executor.getMimeBundle(arg);
const plain = bundle['text/plain'];
if (typeof plain === 'string') {
return plain;
}
}
return String(arg);
} catch {
return '[Unprintable value]';
}
})
.join(' ');
return `${text}\n`;
};
scopeConsole.log = (...args: any[]) => {
this._onOutput({
type: 'stream',
bundle: { name: 'stdout', text: toText(args) }
});
};
scopeConsole.info = scopeConsole.log;
scopeConsole.error = (...args: any[]) => {
this._onOutput({
type: 'stream',
bundle: { name: 'stderr', text: toText(args) }
});
};
scopeConsole.warn = scopeConsole.error;
scopeConsole.debug = scopeConsole.log;
scopeConsole.dir = scopeConsole.log;
scopeConsole.trace = scopeConsole.log;
scopeConsole.table = scopeConsole.log;
if ('onerror' in this._globalScope) {
this._originalOnError = this._globalScope.onerror;
this._globalScope.onerror = (message: any) => {
scopeConsole.error(message);
return false;
};
}
}
/**
* Restore original console methods if they were patched.
*/
private _restoreConsoleOverrides(): void {
if (!this._originalConsole) {
return;
}
const scopeConsole = this._globalScope.console as Console | undefined;
if (scopeConsole) {
scopeConsole.log = this._originalConsole.log;
scopeConsole.info = this._originalConsole.info;
scopeConsole.error = this._originalConsole.error;
scopeConsole.warn = this._originalConsole.warn;
scopeConsole.debug = this._originalConsole.debug;
scopeConsole.dir = this._originalConsole.dir;
scopeConsole.trace = this._originalConsole.trace;
scopeConsole.table = this._originalConsole.table;
}
if ('onerror' in this._globalScope) {
this._globalScope.onerror = this._originalOnError;
}
this._originalConsole = null;
this._originalOnError = undefined;
}
/**
* Install display() helper in runtime scope.
*/
private _setupDisplay(): void {
this._previousDisplay = this._globalScope.display;
this._globalScope.display = (obj: any, metadata?: Record<string, any>) => {
const data = this._executor.getMimeBundle(obj);
this._onOutput({
type: 'display_data',
bundle: {
data,
metadata: metadata ?? {},
transient: {}
}
});
};
}
/**
* Restore previous display binding.
*/
private _restoreDisplay(): void {
if (this._previousDisplay === undefined) {
delete this._globalScope.display;
return;
}
this._globalScope.display = this._previousDisplay;
}
private _globalScope: Record<string, any>;
private _onOutput: RuntimeOutputHandler;
private _executor: JavaScriptExecutor;
private _previousDisplay: any;
private _originalOnError: any;
private _originalConsole: {
log: Console['log'];
info: Console['info'];
error: Console['error'];
warn: Console['warn'];
debug: Console['debug'];
dir: Console['dir'];
trace: Console['trace'];
table: Console['table'];
} | null = null;
}
/**
* A namespace for JavaScriptRuntimeEvaluator statics.
*/
export namespace JavaScriptRuntimeEvaluator {
/**
* The instantiation options for a runtime evaluator.
*/
export interface IOptions {
globalScope: Record<string, any>;
onOutput: RuntimeOutputHandler;
executor?: JavaScriptExecutor;
}
}