/
repl.ts
370 lines (322 loc) · 8.78 KB
/
repl.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import { diffLines } from 'diff';
import { homedir } from 'os';
import { join } from 'path';
import { Recoverable, start } from 'repl';
import { Script } from 'vm';
import { Service, CreateOptions, TSError, env } from './index';
import { readFileSync, statSync } from 'fs';
import { Console } from 'console';
import type * as tty from 'tty';
/**
* Eval filename for REPL/debug.
* @internal
*/
export const EVAL_FILENAME = `[eval].ts`;
export interface ReplService {
readonly state: EvalState;
/**
* Bind this REPL to a ts-node compiler service. A compiler service must be bound before `eval`-ing code or starting the REPL
*/
setService(service: Service): void;
evalCode(code: string): void;
/**
* `eval` implementation compatible with node's REPL API
*/
nodeEval(
code: string,
_context: any,
_filename: string,
callback: (err: Error | null, result?: any) => any
): void;
evalAwarePartialHost: EvalAwarePartialHost;
/** Start a node REPL */
start(code?: string): void;
/** @internal */
readonly stdin: NodeJS.ReadableStream;
/** @internal */
readonly stdout: NodeJS.WritableStream;
/** @internal */
readonly stderr: NodeJS.WritableStream;
/** @internal */
readonly console: Console;
}
export interface CreateReplOptions {
service?: Service;
state?: EvalState;
stdin?: NodeJS.ReadableStream;
stdout?: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream;
}
/**
* Create a ts-node REPL instance.
*
* Usage example:
*
* const repl = tsNode.createRepl()
* const service = tsNode.create({...repl.evalAwarePartialHost})
* repl.setService(service)
* repl.start()
*/
export function createRepl(options: CreateReplOptions = {}) {
let service = options.service;
const state =
options.state ?? new EvalState(join(process.cwd(), EVAL_FILENAME));
const evalAwarePartialHost = createEvalAwarePartialHost(state);
const stdin = options.stdin ?? process.stdin;
const stdout = options.stdout ?? process.stdout;
const stderr = options.stderr ?? process.stderr;
const _console =
stdout === process.stdout && stderr === process.stderr
? console
: new Console(stdout, stderr);
const replService: ReplService = {
state: options.state ?? new EvalState(join(process.cwd(), EVAL_FILENAME)),
setService,
evalCode,
nodeEval,
evalAwarePartialHost,
start,
stdin,
stdout,
stderr,
console: _console,
};
return replService;
function setService(_service: Service) {
service = _service;
}
function evalCode(code: string) {
return _eval(service!, state, code);
}
function nodeEval(
code: string,
_context: any,
_filename: string,
callback: (err: Error | null, result?: any) => any
) {
let err: Error | null = null;
let result: any;
// TODO: Figure out how to handle completion here.
if (code === '.scope') {
callback(err);
return;
}
try {
result = evalCode(code);
} catch (error) {
if (error instanceof TSError) {
// Support recoverable compilations using >= node 6.
if (Recoverable && isRecoverable(error)) {
err = new Recoverable(error);
} else {
_console.error(error);
}
} else {
err = error;
}
}
return callback(err, result);
}
function start(code?: string) {
// TODO assert that service is set; remove all ! postfixes
return startRepl(replService, service!, state, code);
}
}
/**
* Eval state management. Stores virtual `[eval].ts` file
*/
export class EvalState {
/** @internal */
input = '';
/** @internal */
output = '';
/** @internal */
version = 0;
/** @internal */
lines = 0;
__tsNodeEvalStateBrand: unknown;
constructor(public path: string) {}
}
/**
* Filesystem host functions which are aware of the "virtual" [eval].ts file used to compile REPL inputs.
* Must be passed to `create()` to create a ts-node compiler service which can compile REPL inputs.
*/
export type EvalAwarePartialHost = Pick<
CreateOptions,
'readFile' | 'fileExists'
>;
export function createEvalAwarePartialHost(
state: EvalState
): EvalAwarePartialHost {
function readFile(path: string) {
if (path === state.path) return state.input;
try {
return readFileSync(path, 'utf8');
} catch (err) {
/* Ignore. */
}
}
function fileExists(path: string) {
if (path === state.path) return true;
try {
const stats = statSync(path);
return stats.isFile() || stats.isFIFO();
} catch (err) {
return false;
}
}
return { readFile, fileExists };
}
/**
* Evaluate the code snippet.
*/
function _eval(service: Service, state: EvalState, input: string) {
const lines = state.lines;
const isCompletion = !/\n$/.test(input);
const undo = appendEval(state, input);
let output: string;
try {
output = service.compile(state.input, state.path, -lines);
} catch (err) {
undo();
throw err;
}
// Use `diff` to check for new JavaScript to execute.
const changes = diffLines(state.output, output);
if (isCompletion) {
undo();
} else {
state.output = output;
}
return changes.reduce((result, change) => {
return change.added ? exec(change.value, state.path) : result;
}, undefined);
}
/**
* Execute some code.
*/
function exec(code: string, filename: string) {
const script = new Script(code, { filename: filename });
return script.runInThisContext();
}
/**
* Start a CLI REPL.
*/
function startRepl(
replService: ReplService,
service: Service,
state: EvalState,
code?: string
) {
// Eval incoming code before the REPL starts.
if (code) {
try {
replService.evalCode(`${code}\n`);
} catch (err) {
replService.console.error(err);
process.exit(1);
}
}
const repl = start({
prompt: '> ',
input: replService.stdin,
output: replService.stdout,
// Mimicking node's REPL implementation: https://github.com/nodejs/node/blob/168b22ba073ee1cbf8d0bcb4ded7ff3099335d04/lib/internal/repl.js#L28-L30
terminal:
(replService.stdout as tty.WriteStream).isTTY &&
!parseInt(env.NODE_NO_READLINE!, 10),
eval: replService.nodeEval,
useGlobal: true,
});
// Bookmark the point where we should reset the REPL state.
const resetEval = appendEval(state, '');
function reset() {
resetEval();
// Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`.
exec('exports = module.exports', state.path);
}
reset();
repl.on('reset', reset);
repl.defineCommand('type', {
help: 'Check the type of a TypeScript identifier',
action: function (identifier: string) {
if (!identifier) {
repl.displayPrompt();
return;
}
const undo = appendEval(state, identifier);
const { name, comment } = service.getTypeInfo(
state.input,
state.path,
state.input.length
);
undo();
if (name) repl.outputStream.write(`${name}\n`);
if (comment) repl.outputStream.write(`${comment}\n`);
repl.displayPrompt();
},
});
// Set up REPL history when available natively via node.js >= 11.
if (repl.setupHistory) {
const historyPath =
env.TS_NODE_HISTORY || join(homedir(), '.ts_node_repl_history');
repl.setupHistory(historyPath, (err) => {
if (!err) return;
replService.console.error(err);
process.exit(1);
});
}
}
/**
* Append to the eval instance and return an undo function.
*/
function appendEval(state: EvalState, input: string) {
const undoInput = state.input;
const undoVersion = state.version;
const undoOutput = state.output;
const undoLines = state.lines;
// Handle ASI issues with TypeScript re-evaluation.
if (
undoInput.charAt(undoInput.length - 1) === '\n' &&
/^\s*[\/\[(`-]/.test(input) &&
!/;\s*$/.test(undoInput)
) {
state.input = `${state.input.slice(0, -1)};\n`;
}
state.input += input;
state.lines += lineCount(input);
state.version++;
return function () {
state.input = undoInput;
state.output = undoOutput;
state.version = undoVersion;
state.lines = undoLines;
};
}
/**
* Count the number of lines.
*/
function lineCount(value: string) {
let count = 0;
for (const char of value) {
if (char === '\n') {
count++;
}
}
return count;
}
const RECOVERY_CODES: Set<number> = new Set([
1003, // "Identifier expected."
1005, // "')' expected."
1109, // "Expression expected."
1126, // "Unexpected end of text."
1160, // "Unterminated template literal."
1161, // "Unterminated regular expression literal."
2355, // "A function whose declared type is neither 'void' nor 'any' must return a value."
]);
/**
* Check if a function can recover gracefully.
*/
function isRecoverable(error: TSError) {
return error.diagnosticCodes.every((code) => RECOVERY_CODES.has(code));
}