MultiCompiler.js 18 KB

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