/
node.impl.ts
206 lines (184 loc) · 5.1 KB
/
node.impl.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
import {
ExecutorContext,
joinPathFragments,
logger,
parseTargetString,
runExecutor,
} from '@nrwl/devkit';
import { readCachedProjectGraph } from '@nrwl/workspace/src/core/project-graph';
import { calculateProjectDependencies } from '@nrwl/workspace/src/utilities/buildable-libs-utils';
import { ChildProcess, fork } from 'child_process';
import * as treeKill from 'tree-kill';
import { promisify } from 'util';
import { InspectType, NodeExecutorOptions } from './schema';
let subProcess: ChildProcess = null;
export interface ExecutorEvent {
outfile: string;
success: boolean;
}
export async function* nodeExecutor(
options: NodeExecutorOptions,
context: ExecutorContext
) {
process.on('SIGTERM', async () => {
await killCurrentProcess();
process.exit(128 + 15);
});
process.on('SIGINT', async () => {
await killCurrentProcess();
process.exit(128 + 2);
});
process.on('SIGHUP', async () => {
await killCurrentProcess();
process.exit(128 + 1);
});
if (options.waitUntilTargets && options.waitUntilTargets.length > 0) {
const results = await runWaitUntilTargets(options, context);
for (const [i, result] of results.entries()) {
if (!result.success) {
throw new Error(
`Wait until target failed: ${options.waitUntilTargets[i]}.`
);
}
}
}
const mappings = calculateResolveMappings(context, options);
for await (const event of startBuild(options, context)) {
if (!event.success) {
logger.error('There was an error with the build. See above.');
logger.info(`${event.outfile} was not restarted.`);
}
await handleBuildEvent(event, options, mappings);
yield event;
}
}
function calculateResolveMappings(
context: ExecutorContext,
options: NodeExecutorOptions
) {
const projectGraph = readCachedProjectGraph();
const parsed = parseTargetString(options.buildTarget);
const { dependencies } = calculateProjectDependencies(
projectGraph,
context.root,
parsed.project,
parsed.target,
parsed.configuration
);
return dependencies.reduce((m, c) => {
if (!c.outputs[0] && c.node.type === 'npm') {
c.outputs[0] = `node_modules/${c.node.data.packageName}`;
}
m[c.name] = joinPathFragments(context.root, c.outputs[0]);
return m;
}, {});
}
async function runProcess(
event: ExecutorEvent,
options: NodeExecutorOptions,
mappings: { [project: string]: string }
) {
subProcess = fork(
joinPathFragments(__dirname, 'node-with-require-overrides'),
options.args,
{
execArgv: getExecArgv(options),
stdio: 'inherit',
env: {
...process.env,
NX_FILE_TO_RUN: event.outfile,
NX_MAPPINGS: JSON.stringify(mappings),
},
}
);
if (!options.watch) {
return new Promise<void>((resolve, reject) => {
subProcess.on('exit', (code) => {
if (code === 0) {
resolve(undefined);
} else {
reject();
}
});
});
}
}
function getExecArgv(options: NodeExecutorOptions) {
const args = [
'-r',
require.resolve('source-map-support/register'),
...options.runtimeArgs,
];
if (options.inspect === true) {
options.inspect = InspectType.Inspect;
}
if (options.inspect) {
args.push(`--${options.inspect}=${options.host}:${options.port}`);
}
return args;
}
async function handleBuildEvent(
event: ExecutorEvent,
options: NodeExecutorOptions,
mappings: { [project: string]: string }
) {
// Don't kill previous run unless new build is successful.
if (options.watch && event.success) {
await killCurrentProcess();
}
if (event.success) {
await runProcess(event, options, mappings);
}
}
const promisifiedTreeKill: (pid: number, signal: string) => Promise<void> =
promisify(treeKill);
async function killCurrentProcess() {
if (!subProcess) return;
try {
await promisifiedTreeKill(subProcess.pid, 'SIGTERM');
} catch (err) {
if (Array.isArray(err) && err[0] && err[2]) {
const errorMessage = err[2];
logger.error(errorMessage);
} else if (err.message) {
logger.error(err.message);
}
} finally {
subProcess = null;
}
}
async function* startBuild(
options: NodeExecutorOptions,
context: ExecutorContext
) {
const buildTarget = parseTargetString(options.buildTarget);
yield* await runExecutor<ExecutorEvent>(
buildTarget,
{
...options.buildTargetOptions,
watch: options.watch,
},
context
);
}
function runWaitUntilTargets(
options: NodeExecutorOptions,
context: ExecutorContext
): Promise<{ success: boolean }[]> {
return Promise.all(
options.waitUntilTargets.map(async (waitUntilTarget) => {
const target = parseTargetString(waitUntilTarget);
const output = await runExecutor(target, {}, context);
return new Promise<{ success: boolean }>(async (resolve) => {
let event = await output.next();
// Resolve after first event
resolve(event.value as { success: boolean });
// Continue iterating
while (!event.done) {
event = await output.next();
}
});
})
);
}
export default nodeExecutor;