-
-
Notifications
You must be signed in to change notification settings - Fork 154
/
index.ts
220 lines (191 loc) · 5.01 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
import type { ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { constants as osConstants } from 'node:os';
import path from 'node:path';
import { command } from 'cleye';
import { watch } from 'chokidar';
import { lightMagenta, lightGreen, yellow } from 'kolorist';
import { run } from '../run.js';
import {
removeArgvFlags,
ignoreAfterArgument,
} from '../remove-argv-flags.js';
import { createIpcServer } from '../utils/ipc/server.js';
import {
clearScreen,
debounce,
log,
} from './utils.js';
const flags = {
noCache: {
type: Boolean,
description: 'Disable caching',
default: false,
},
tsconfig: {
type: String,
description: 'Custom tsconfig.json path',
},
clearScreen: {
type: Boolean,
description: 'Clearing the screen on rerun',
default: true,
},
ignore: {
type: [String],
description: 'Paths & globs to exclude from being watched',
},
} as const;
export const watchCommand = command({
name: 'watch',
parameters: ['<script path>'],
flags,
help: {
description: 'Run the script and watch for changes',
},
/**
* ignoreAfterArgument needs to parse the first argument
* because cleye will error on missing arguments
*
* Remove once cleye supports error callbacks on missing arguments
*/
ignoreArgv: ignoreAfterArgument(false),
}, async (argv) => {
const rawArgvs = removeArgvFlags(flags, process.argv.slice(3));
const options = {
noCache: argv.flags.noCache,
tsconfigPath: argv.flags.tsconfig,
clearScreen: argv.flags.clearScreen,
ignore: argv.flags.ignore,
ipc: true,
};
let runProcess: ChildProcess | undefined;
let exiting = false;
const server = await createIpcServer();
server.on('data', (data) => {
// Collect run-time dependencies to watch
if (
data
&& typeof data === 'object'
&& 'type' in data
&& data.type === 'dependency'
&& 'path' in data
&& typeof data.path === 'string'
) {
const dependencyPath = (
data.path.startsWith('file:')
? fileURLToPath(data.path)
: data.path
);
if (path.isAbsolute(dependencyPath)) {
watcher.add(dependencyPath);
}
}
});
const spawnProcess = () => {
if (exiting) {
return;
}
return run(rawArgvs, options);
};
let waitingChildExit = false;
const killProcess = async (
childProcess: ChildProcess,
signal: NodeJS.Signals = 'SIGTERM',
forceKillOnTimeout = 5000,
) => {
let exited = false;
const waitForExit = new Promise<number | null>((resolve) => {
childProcess.on('exit', (exitCode) => {
exited = true;
waitingChildExit = false;
resolve(exitCode);
});
});
waitingChildExit = true;
childProcess.kill(signal);
setTimeout(() => {
if (!exited) {
log(yellow(`Process didn't exit in ${Math.floor(forceKillOnTimeout / 1000)}s. Force killing...`));
childProcess.kill('SIGKILL');
}
}, forceKillOnTimeout);
return await waitForExit;
};
const reRun = debounce(async (event?: string, filePath?: string) => {
const reason = event ? `${event ? lightMagenta(event) : ''}${filePath ? ` in ${lightGreen(`./${filePath}`)}` : ''}` : '';
if (waitingChildExit) {
log(reason, yellow('Process hasn\'t exited. Killing process...'));
runProcess!.kill('SIGKILL');
return;
}
// If not first run
if (runProcess) {
// If process still running
if (runProcess.exitCode === null) {
log(reason, yellow('Restarting...'));
await killProcess(runProcess);
} else {
log(reason, yellow('Rerunning...'));
}
if (options.clearScreen) {
process.stdout.write(clearScreen);
}
}
runProcess = spawnProcess();
}, 100);
reRun();
const relaySignal = (signal: NodeJS.Signals) => {
// Disable further spawns
exiting = true;
// Child is still running, kill it
if (runProcess?.exitCode === null) {
if (waitingChildExit) {
log(yellow('Previous process hasn\'t exited yet. Force killing...'));
}
killProcess(
runProcess,
// Second Ctrl+C force kills
waitingChildExit ? 'SIGKILL' : signal,
).then(
(exitCode) => {
// eslint-disable-next-line n/no-process-exit
process.exit(exitCode ?? 0);
},
() => {},
);
} else {
// eslint-disable-next-line n/no-process-exit
process.exit(osConstants.signals[signal]);
}
};
process.on('SIGINT', relaySignal);
process.on('SIGTERM', relaySignal);
/**
* Ideally, we can get a list of files loaded from the run above
* and only watch those files, but it's not possible to detect
* the full dependency-tree at run-time because they can be hidden
* in a if-condition/async-delay.
*
* As an alternative, we watch cwd and all run-time dependencies
*/
const watcher = watch(
argv._,
{
cwd: process.cwd(),
ignoreInitial: true,
ignored: [
// Hidden directories like .git
'**/.*/**',
// Hidden files (e.g. logs or temp files)
'**/.*',
// 3rd party packages
'**/{node_modules,bower_components,vendor}/**',
...options.ignore,
],
ignorePermissionErrors: true,
},
).on('all', reRun);
// On "Return" key
process.stdin.on('data', () => reRun('Return key'));
});