UNPKG

15.7 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const asyncLib = require("neo-async");
9const { SyncHook, MultiHook } = require("tapable");
10
11const ConcurrentCompilationError = require("./ConcurrentCompilationError");
12const MultiStats = require("./MultiStats");
13const MultiWatching = require("./MultiWatching");
14const ArrayQueue = require("./util/ArrayQueue");
15
16/** @template T @typedef {import("tapable").AsyncSeriesHook<T>} AsyncSeriesHook<T> */
17/** @template T @template R @typedef {import("tapable").SyncBailHook<T, R>} SyncBailHook<T, R> */
18/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
19/** @typedef {import("./Compiler")} Compiler */
20/** @typedef {import("./Stats")} Stats */
21/** @typedef {import("./Watching")} Watching */
22/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
23/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
24/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
25/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
26
27/**
28 * @template T
29 * @callback Callback
30 * @param {Error=} err
31 * @param {T=} result
32 */
33
34/**
35 * @callback RunWithDependenciesHandler
36 * @param {Compiler} compiler
37 * @param {Callback<MultiStats>} callback
38 */
39
40/**
41 * @typedef {Object} MultiCompilerOptions
42 * @property {number=} parallelism how many Compilers are allows to run at the same time in parallel
43 */
44
45module.exports = class MultiCompiler {
46 /**
47 * @param {Compiler[] | Record<string, Compiler>} compilers child compilers
48 * @param {MultiCompilerOptions} options options
49 */
50 constructor(compilers, options) {
51 if (!Array.isArray(compilers)) {
52 compilers = Object.keys(compilers).map(name => {
53 compilers[name].name = name;
54 return compilers[name];
55 });
56 }
57
58 this.hooks = Object.freeze({
59 /** @type {SyncHook<[MultiStats]>} */
60 done: new SyncHook(["stats"]),
61 /** @type {MultiHook<SyncHook<[string | null, number]>>} */
62 invalid: new MultiHook(compilers.map(c => c.hooks.invalid)),
63 /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
64 run: new MultiHook(compilers.map(c => c.hooks.run)),
65 /** @type {SyncHook<[]>} */
66 watchClose: new SyncHook([]),
67 /** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
68 watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)),
69 /** @type {MultiHook<SyncBailHook<[string, string, any[]], true>>} */
70 infrastructureLog: new MultiHook(
71 compilers.map(c => c.hooks.infrastructureLog)
72 )
73 });
74 this.compilers = compilers;
75 /** @type {MultiCompilerOptions} */
76 this._options = {
77 parallelism: options.parallelism || Infinity
78 };
79 /** @type {WeakMap<Compiler, string[]>} */
80 this.dependencies = new WeakMap();
81 this.running = false;
82
83 /** @type {Stats[]} */
84 const compilerStats = this.compilers.map(() => null);
85 let doneCompilers = 0;
86 for (let index = 0; index < this.compilers.length; index++) {
87 const compiler = this.compilers[index];
88 const compilerIndex = index;
89 let compilerDone = false;
90 // eslint-disable-next-line no-loop-func
91 compiler.hooks.done.tap("MultiCompiler", stats => {
92 if (!compilerDone) {
93 compilerDone = true;
94 doneCompilers++;
95 }
96 compilerStats[compilerIndex] = stats;
97 if (doneCompilers === this.compilers.length) {
98 this.hooks.done.call(new MultiStats(compilerStats));
99 }
100 });
101 // eslint-disable-next-line no-loop-func
102 compiler.hooks.invalid.tap("MultiCompiler", () => {
103 if (compilerDone) {
104 compilerDone = false;
105 doneCompilers--;
106 }
107 });
108 }
109 }
110
111 get options() {
112 return Object.assign(
113 this.compilers.map(c => c.options),
114 this._options
115 );
116 }
117
118 get outputPath() {
119 let commonPath = this.compilers[0].outputPath;
120 for (const compiler of this.compilers) {
121 while (
122 compiler.outputPath.indexOf(commonPath) !== 0 &&
123 /[/\\]/.test(commonPath)
124 ) {
125 commonPath = commonPath.replace(/[/\\][^/\\]*$/, "");
126 }
127 }
128
129 if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/";
130 return commonPath;
131 }
132
133 get inputFileSystem() {
134 throw new Error("Cannot read inputFileSystem of a MultiCompiler");
135 }
136
137 get outputFileSystem() {
138 throw new Error("Cannot read outputFileSystem of a MultiCompiler");
139 }
140
141 get watchFileSystem() {
142 throw new Error("Cannot read watchFileSystem of a MultiCompiler");
143 }
144
145 get intermediateFileSystem() {
146 throw new Error("Cannot read outputFileSystem of a MultiCompiler");
147 }
148
149 /**
150 * @param {InputFileSystem} value the new input file system
151 */
152 set inputFileSystem(value) {
153 for (const compiler of this.compilers) {
154 compiler.inputFileSystem = value;
155 }
156 }
157
158 /**
159 * @param {OutputFileSystem} value the new output file system
160 */
161 set outputFileSystem(value) {
162 for (const compiler of this.compilers) {
163 compiler.outputFileSystem = value;
164 }
165 }
166
167 /**
168 * @param {WatchFileSystem} value the new watch file system
169 */
170 set watchFileSystem(value) {
171 for (const compiler of this.compilers) {
172 compiler.watchFileSystem = value;
173 }
174 }
175
176 /**
177 * @param {IntermediateFileSystem} value the new intermediate file system
178 */
179 set intermediateFileSystem(value) {
180 for (const compiler of this.compilers) {
181 compiler.intermediateFileSystem = value;
182 }
183 }
184
185 getInfrastructureLogger(name) {
186 return this.compilers[0].getInfrastructureLogger(name);
187 }
188
189 /**
190 * @param {Compiler} compiler the child compiler
191 * @param {string[]} dependencies its dependencies
192 * @returns {void}
193 */
194 setDependencies(compiler, dependencies) {
195 this.dependencies.set(compiler, dependencies);
196 }
197
198 /**
199 * @param {Callback<MultiStats>} callback signals when the validation is complete
200 * @returns {boolean} true if the dependencies are valid
201 */
202 validateDependencies(callback) {
203 /** @type {Set<{source: Compiler, target: Compiler}>} */
204 const edges = new Set();
205 /** @type {string[]} */
206 const missing = [];
207 const targetFound = compiler => {
208 for (const edge of edges) {
209 if (edge.target === compiler) {
210 return true;
211 }
212 }
213 return false;
214 };
215 const sortEdges = (e1, e2) => {
216 return (
217 e1.source.name.localeCompare(e2.source.name) ||
218 e1.target.name.localeCompare(e2.target.name)
219 );
220 };
221 for (const source of this.compilers) {
222 const dependencies = this.dependencies.get(source);
223 if (dependencies) {
224 for (const dep of dependencies) {
225 const target = this.compilers.find(c => c.name === dep);
226 if (!target) {
227 missing.push(dep);
228 } else {
229 edges.add({
230 source,
231 target
232 });
233 }
234 }
235 }
236 }
237 /** @type {string[]} */
238 const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`);
239 const stack = this.compilers.filter(c => !targetFound(c));
240 while (stack.length > 0) {
241 const current = stack.pop();
242 for (const edge of edges) {
243 if (edge.source === current) {
244 edges.delete(edge);
245 const target = edge.target;
246 if (!targetFound(target)) {
247 stack.push(target);
248 }
249 }
250 }
251 }
252 if (edges.size > 0) {
253 /** @type {string[]} */
254 const lines = Array.from(edges)
255 .sort(sortEdges)
256 .map(edge => `${edge.source.name} -> ${edge.target.name}`);
257 lines.unshift("Circular dependency found in compiler dependencies.");
258 errors.unshift(lines.join("\n"));
259 }
260 if (errors.length > 0) {
261 const message = errors.join("\n");
262 callback(new Error(message));
263 return false;
264 }
265 return true;
266 }
267
268 // TODO webpack 6 remove
269 /**
270 * @deprecated This method should have been private
271 * @param {Compiler[]} compilers the child compilers
272 * @param {RunWithDependenciesHandler} fn a handler to run for each compiler
273 * @param {Callback<MultiStats>} callback the compiler's handler
274 * @returns {void}
275 */
276 runWithDependencies(compilers, fn, callback) {
277 const fulfilledNames = new Set();
278 let remainingCompilers = compilers;
279 const isDependencyFulfilled = d => fulfilledNames.has(d);
280 const getReadyCompilers = () => {
281 let readyCompilers = [];
282 let list = remainingCompilers;
283 remainingCompilers = [];
284 for (const c of list) {
285 const dependencies = this.dependencies.get(c);
286 const ready =
287 !dependencies || dependencies.every(isDependencyFulfilled);
288 if (ready) {
289 readyCompilers.push(c);
290 } else {
291 remainingCompilers.push(c);
292 }
293 }
294 return readyCompilers;
295 };
296 const runCompilers = callback => {
297 if (remainingCompilers.length === 0) return callback();
298 asyncLib.map(
299 getReadyCompilers(),
300 (compiler, callback) => {
301 fn(compiler, err => {
302 if (err) return callback(err);
303 fulfilledNames.add(compiler.name);
304 runCompilers(callback);
305 });
306 },
307 callback
308 );
309 };
310 runCompilers(callback);
311 }
312
313 /**
314 * @template SetupResult
315 * @param {function(Compiler, number, Callback<Stats>, function(): boolean, function(): void, function(): void): SetupResult} setup setup a single compiler
316 * @param {function(Compiler, Callback<Stats>): void} run run/continue a single compiler
317 * @param {Callback<MultiStats>} callback callback when all compilers are done, result includes Stats of all changed compilers
318 * @returns {SetupResult[]} result of setup
319 */
320 _runGraph(setup, run, callback) {
321 /** @typedef {{ compiler: Compiler, result: Stats, state: "pending" | "blocked" | "queued" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */
322
323 // State transitions for nodes:
324 // -> blocked (initial)
325 // blocked -> queued [add to queue] (when all parents done)
326 // queued -> running [running++] (when processing the queue)
327 // running -> done [running--] (when compilation is done)
328 // done -> pending (when invalidated from file change)
329 // pending -> blocked (when invalidated from aggregated changes)
330 // done -> blocked (when invalidated, from parent invalidation)
331 // running -> running-outdated (when invalidated, either from change or parent invalidation)
332 // running-outdated -> blocked [running--] (when compilation is done)
333
334 /** @type {Node[]} */
335 const nodes = this.compilers.map(compiler => ({
336 compiler,
337 result: undefined,
338 state: "blocked",
339 children: [],
340 parents: []
341 }));
342 /** @type {Map<string, Node>} */
343 const compilerToNode = new Map();
344 for (const node of nodes) compilerToNode.set(node.compiler.name, node);
345 for (const node of nodes) {
346 const dependencies = this.dependencies.get(node.compiler);
347 if (!dependencies) continue;
348 for (const dep of dependencies) {
349 const parent = compilerToNode.get(dep);
350 node.parents.push(parent);
351 parent.children.push(node);
352 }
353 }
354 const queue = new ArrayQueue();
355 for (const node of nodes) {
356 if (node.parents.length === 0) {
357 node.state = "queued";
358 queue.enqueue(node);
359 }
360 }
361 let errored = false;
362 let running = 0;
363 const parallelism = this._options.parallelism;
364 /**
365 * @param {Node} node node
366 * @param {Error=} err error
367 * @param {Stats=} stats result
368 * @returns {void}
369 */
370 const nodeDone = (node, err, stats) => {
371 if (errored) return;
372 if (err) {
373 errored = true;
374 return asyncLib.each(
375 nodes,
376 (node, callback) => {
377 if (node.compiler.watching) {
378 node.compiler.watching.close(callback);
379 } else {
380 callback();
381 }
382 },
383 () => callback(err)
384 );
385 }
386 node.result = stats;
387 running--;
388 if (node.state === "running") {
389 node.state = "done";
390 for (const child of node.children) {
391 checkUnblocked(child);
392 }
393 } else if (node.state === "running-outdated") {
394 node.state = "blocked";
395 checkUnblocked(node);
396 }
397 process.nextTick(processQueue);
398 };
399 /**
400 * @param {Node} node node
401 * @returns {void}
402 */
403 const nodeInvalidFromParent = node => {
404 if (node.state === "done") {
405 node.state = "blocked";
406 } else if (node.state === "running") {
407 node.state = "running-outdated";
408 }
409 for (const child of node.children) {
410 nodeInvalidFromParent(child);
411 }
412 };
413 /**
414 * @param {Node} node node
415 * @returns {void}
416 */
417 const nodeInvalid = node => {
418 if (node.state === "done") {
419 node.state = "pending";
420 } else if (node.state === "running") {
421 node.state = "running-outdated";
422 }
423 for (const child of node.children) {
424 nodeInvalidFromParent(child);
425 }
426 };
427 /**
428 * @param {Node} node node
429 * @returns {void}
430 */
431 const nodeChange = node => {
432 nodeInvalid(node);
433 if (node.state === "pending") {
434 node.state = "blocked";
435 }
436 checkUnblocked(node);
437 processQueue();
438 };
439 /**
440 * @param {Node} node node
441 * @returns {void}
442 */
443 const checkUnblocked = node => {
444 if (
445 node.state === "blocked" &&
446 node.parents.every(p => p.state === "done")
447 ) {
448 node.state = "queued";
449 queue.enqueue(node);
450 }
451 };
452
453 const setupResults = [];
454 nodes.forEach((node, i) => {
455 setupResults.push(
456 setup(
457 node.compiler,
458 i,
459 nodeDone.bind(null, node),
460 () => node.state !== "done" && node.state !== "running",
461 () => nodeChange(node),
462 () => nodeInvalid(node)
463 )
464 );
465 });
466 const processQueue = () => {
467 while (running < parallelism && queue.length > 0 && !errored) {
468 const node = queue.dequeue();
469 if (node.state !== "queued") continue;
470 running++;
471 node.state = "running";
472 run(node.compiler, nodeDone.bind(null, node));
473 }
474 if (
475 !errored &&
476 running === 0 &&
477 nodes.every(node => node.state === "done")
478 ) {
479 const stats = [];
480 for (const node of nodes) {
481 const result = node.result;
482 if (result) {
483 node.result = undefined;
484 stats.push(result);
485 }
486 }
487 if (stats.length > 0) {
488 callback(null, new MultiStats(stats));
489 }
490 }
491 };
492 processQueue();
493 return setupResults;
494 }
495
496 /**
497 * @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options
498 * @param {Callback<MultiStats>} handler signals when the call finishes
499 * @returns {MultiWatching} a compiler watcher
500 */
501 watch(watchOptions, handler) {
502 if (this.running) {
503 return handler(new ConcurrentCompilationError());
504 }
505 this.running = true;
506
507 if (this.validateDependencies(handler)) {
508 const watchings = this._runGraph(
509 (compiler, idx, callback, isBlocked, setChanged, setInvalid) => {
510 const watching = compiler.watch(
511 Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions,
512 callback
513 );
514 if (watching) {
515 watching._onInvalid = setInvalid;
516 watching._onChange = setChanged;
517 watching._isBlocked = isBlocked;
518 }
519 return watching;
520 },
521 (compiler, initial, callback) => {
522 if (!compiler.watching.running) compiler.watching.invalidate();
523 },
524 handler
525 );
526 return new MultiWatching(watchings, this);
527 }
528
529 return new MultiWatching([], this);
530 }
531
532 /**
533 * @param {Callback<MultiStats>} callback signals when the call finishes
534 * @returns {void}
535 */
536 run(callback) {
537 if (this.running) {
538 return callback(new ConcurrentCompilationError());
539 }
540 this.running = true;
541
542 if (this.validateDependencies(callback)) {
543 this._runGraph(
544 () => {},
545 (compiler, callback) => compiler.run(callback),
546 (err, stats) => {
547 this.running = false;
548
549 if (callback !== undefined) {
550 return callback(err, stats);
551 }
552 }
553 );
554 }
555 }
556
557 purgeInputFileSystem() {
558 for (const compiler of this.compilers) {
559 if (compiler.inputFileSystem && compiler.inputFileSystem.purge) {
560 compiler.inputFileSystem.purge();
561 }
562 }
563 }
564
565 /**
566 * @param {Callback<void>} callback signals when the compiler closes
567 * @returns {void}
568 */
569 close(callback) {
570 asyncLib.each(
571 this.compilers,
572 (compiler, callback) => {
573 compiler.close(callback);
574 },
575 callback
576 );
577 }
578};