/
repl.ts
292 lines (245 loc) · 7.22 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
import { diffLines } from 'diff'
import { homedir } from 'os'
import { join } from 'path'
import { Recoverable, start } from 'repl'
import { Script } from 'vm'
import { Register, CreateOptions, TSError } from './index'
import { readFileSync, statSync } from 'fs'
/**
* Eval filename for REPL/debug.
* @internal
*/
export const EVAL_FILENAME = `[eval].ts`
export interface ReplService {
readonly state: EvalState
setService (service: Register): void
evalCode (code: string): void
/**
* eval implementation compatible with node's REPL API
*/
nodeReplEval (code: string, _context: any, _filename: string, callback: (err: Error | null, result?: any) => any): void
evalStateAwareHostFunctions: EvalStateAwareHostFunctions
/** Start a node REPL */
start (code?: string): void
}
export interface CreateReplServiceOptions {
service?: Register
state?: EvalState
}
export function createReplService (options: CreateReplServiceOptions = {}) {
let service = options.service
const state = options.state ?? new EvalState(join(process.cwd(), EVAL_FILENAME))
const evalStateAwareHostFunctions = createEvalStateAwareHostFunctions(state)
const replService: ReplService = {
state: options.state ?? new EvalState(join(process.cwd(), EVAL_FILENAME)),
setService,
evalCode,
nodeReplEval,
evalStateAwareHostFunctions,
start
}
return replService
function setService (_service: Register) {
service = _service
}
function evalCode (code: string) {
return _eval(service!, state, code)
}
/**
* Eval code from the REPL.
*/
function nodeReplEval (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.
*/
export class EvalState {
input = ''
output = ''
version = 0
lines = 0
constructor (public path: string) { }
}
export type EvalStateAwareHostFunctions = Pick<CreateOptions, 'readFile' | 'fileExists'>
export function createEvalStateAwareHostFunctions (state: EvalState): EvalStateAwareHostFunctions {
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: Register, 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: Register, state: EvalState, code?: string) {
// Eval incoming code before the REPL starts.
if (code) {
try {
replService.evalCode(`${code}\n`)
} catch (err) {
console.error(err)
process.exit(1)
}
}
const repl = start({
prompt: '> ',
input: process.stdin,
output: process.stdout,
// Mimicking node's REPL implementation: https://github.com/nodejs/node/blob/168b22ba073ee1cbf8d0bcb4ded7ff3099335d04/lib/internal/repl.js#L28-L30
terminal: process.stdout.isTTY && !parseInt(process.env.NODE_NO_READLINE!, 10),
eval: replService.nodeReplEval,
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 = process.env.TS_NODE_HISTORY || join(homedir(), '.ts_node_repl_history')
repl.setupHistory(historyPath, err => {
if (!err) return
console.error(err)
process.exit(1)
})
}
}
/**
* Append to the eval instance and return an undo function.
*/
export 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))
}