/
index.ts
323 lines (279 loc) · 8.19 KB
/
index.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
import { fork, ChildProcess } from 'child_process'
import chokidar from 'chokidar'
import fs from 'fs'
import readline from 'readline'
const kill = require('tree-kill')
import * as ipc from './ipc'
import { resolveMain } from './resolveMain'
import { Options } from './bin'
import { makeCompiler, CompileParams } from './compiler'
import { makeCfg } from './cfg'
import { makeNotify } from './notify'
import { makeLog } from './log'
const version = require('../package.json').version
const tsNodeVersion = require('ts-node').VERSION
const tsVersion = require('typescript').version
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']
export const runDev = (
script: string,
scriptArgs: string[],
nodeArgs: string[],
opts: Options
) => {
if (typeof script !== 'string' || script.length === 0) {
throw new TypeError('`script` must be a string')
}
if (!Array.isArray(scriptArgs)) {
throw new TypeError('`scriptArgs` must be an array')
}
if (!Array.isArray(nodeArgs)) {
throw new TypeError('`nodeArgs` must be an array')
}
// The child_process
let child:
| (ChildProcess & {
stopping?: boolean
respawn?: boolean
})
| undefined
const wrapper = resolveMain(__dirname + '/wrap.js')
const main = resolveMain(script)
const cfg = makeCfg(main, opts)
const log = makeLog(cfg)
const notify = makeNotify(cfg, log)
// Run ./dedupe.js as preload script
if (cfg.dedupe) process.env.NODE_DEV_PRELOAD = __dirname + '/dedupe'
function initWatcher() {
const watcher = chokidar.watch([], {
usePolling: opts.poll,
interval: parseInt(opts.interval) || undefined,
})
watcher.on('change', restart)
watcher.on('fallback', function (limit) {
log.warn(
'node-dev ran out of file handles after watching %s files.',
limit
)
log.warn('Falling back to polling which uses more CPU.')
log.info('Run ulimit -n 10000 to increase the file descriptor limit.')
if (cfg.deps) log.info('... or add `--no-deps` to use less file handles.')
})
return watcher
}
let watcher = initWatcher()
let starting = false
// Read for "rs" from command line
if (opts.rs !== false) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
})
rl.on('line', (line: string) => {
if (line.trim() === 'rs') {
restart('', true)
}
})
}
log.info(
'ts-node-dev ver. ' +
version +
' (using ts-node ver. ' +
tsNodeVersion +
', typescript ver. ' +
tsVersion +
')'
)
/**
* Run the wrapped script.
*/
let compileReqWatcher: chokidar.FSWatcher
function start() {
if (cfg.clear) process.stdout.write('\u001bc')
for (const watched of (opts.watch || '').split(',')) {
if (watched) watcher.add(watched)
}
let cmd = nodeArgs.concat(wrapper, script, scriptArgs)
const childHookPath = compiler.getChildHookPath()
cmd = (opts.priorNodeArgs || []).concat(['-r', childHookPath]).concat(cmd)
log.debug('Starting child process %s', cmd.join(' '))
child = fork(cmd[0], cmd.slice(1), {
cwd: process.cwd(),
env: process.env,
detached: true,
})
starting = false
if (compileReqWatcher) {
compileReqWatcher.close()
}
compileReqWatcher = chokidar.watch([], {
usePolling: opts.poll,
interval: parseInt(opts.interval) || undefined,
})
let currentCompilePath: string
fs.writeFileSync(compiler.getCompileReqFilePath(), '')
compileReqWatcher.add(compiler.getCompileReqFilePath())
compileReqWatcher.on('change', function (file) {
fs.readFile(file, 'utf-8', function (err, data) {
if (err) {
log.error('Error reading compile request file', err)
return
}
const split = data.split('\n')
const compile = split[0]
const compiledPath = split[1]
if (currentCompilePath == compiledPath) return
currentCompilePath = compiledPath
if (compiledPath) {
compiler.compile({
compile: compile,
compiledPath: compiledPath,
})
}
})
})
child.on('message', function (message: CompileParams) {
if (
!message.compiledPath ||
currentCompilePath === message.compiledPath
) {
return
}
currentCompilePath = message.compiledPath
compiler.compile(message)
})
child.on('close', (code: number, signal: string) => {
log.debug('Child closed with code %s', code)
if (signal) {
log.debug(`Exiting process with signal ${signal}`)
process.kill(process.pid, signal)
} else {
log.debug(`Exiting process with code ${code}`)
process.exit(code)
}
})
if (cfg.respawn) {
child.respawn = true
}
if (compiler.tsConfigPath) {
watcher.add(compiler.tsConfigPath)
}
// Listen for `required` messages and watch the required file.
ipc.on(child, 'required', function (m: ipc.IPCMessage) {
const required = m.required!
const isIgnored =
cfg.ignore.some(isPrefixOf(required)) ||
cfg.ignore.some(isRegExpMatch(required))
if (!isIgnored && (cfg.deps === -1 || getLevel(required) <= cfg.deps)) {
log.debug(required, 'added to watcher')
watcher.add(required)
}
})
// Upon errors, display a notification and tell the child to exit.
ipc.on(child, 'error', function (m: ipc.IPCMessage) {
log.debug('Child error')
notify(m.error!, m.message!, 'error')
stop(m.willTerminate)
})
compiler.writeReadyFile()
}
const killChild = (signal: NodeJS.Signals) => {
if (!child) return
log.debug(`Sending ${signal} to child pid`, child.pid)
if (opts['tree-kill']) {
log.debug('Using tree-kill')
kill(child.pid)
} else {
child.kill(signal)
}
}
function stop(willTerminate?: boolean) {
if (!child || child.stopping) {
return
}
child.stopping = true
child.respawn = true
if (child.connected === undefined || child.connected === true) {
log.debug('Disconnecting from child')
child.disconnect()
if (!willTerminate) {
}
killChild('SIGTERM')
}
}
function restart(file: string, isManualRestart?: boolean) {
if (file === compiler.tsConfigPath) {
notify('Reinitializing TS compilation', '')
compiler.init()
}
compiler.clearErrorCompile()
if (isManualRestart === true) {
notify('Restarting', 'manual restart from user')
} else {
notify('Restarting', file + ' has been modified')
}
compiler.compileChanged(file)
if (starting) {
log.debug('Already starting')
return
}
log.debug('Removing all watchers from files')
//watcher.removeAll()ya
watcher.close()
watcher = initWatcher()
starting = true
if (child) {
log.debug('Child is still running, restart upon exit')
child.on('exit', start)
stop()
} else {
log.debug('Child is already stopped, probably due to a previous error')
start()
}
}
signals.forEach((signal: NodeJS.Signals) =>
process.on(signal, () => {
log.debug(`Process got ${signal}, killing child`)
killChild(signal)
})
)
process.on('exit', () => {
if(child) {
child.kill()
}
})
const compiler = makeCompiler(opts, {
restart,
log: log,
})
compiler.init()
start()
}
/**
* Returns the nesting-level of the given module.
* Will return 0 for modules from the main package or linked modules,
* a positive integer otherwise.
*/
function getLevel(mod: string) {
const p = getPrefix(mod)
return p.split('node_modules').length - 1
}
/**
* Returns the path up to the last occurence of `node_modules` or an
* empty string if the path does not contain a node_modules dir.
*/
function getPrefix(mod: string) {
const n = 'node_modules'
const i = mod.lastIndexOf(n)
return ~i ? mod.slice(0, i + n.length) : ''
}
function isPrefixOf(value: string) {
return function (prefix: string) {
return value.indexOf(prefix) === 0
}
}
function isRegExpMatch(value: string) {
return function (regExp: string) {
return new RegExp(regExp).test(value)
}
}