MultiCompiler.js 18 KB

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