ProgressPlugin.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Compiler = require("./Compiler");
  7. const MultiCompiler = require("./MultiCompiler");
  8. const NormalModule = require("./NormalModule");
  9. const cli = require("./cli");
  10. const { contextify } = require("./util/identifier");
  11. const memoize = require("./util/memoize");
  12. const getColors = memoize(() =>
  13. cli.createColors({ useColor: cli.isColorSupported() })
  14. );
  15. const BAR_LENGTH = 25;
  16. const BLOCK_CHAR = "━";
  17. const BULLET_ICON = "●";
  18. /** @import { Tap } from "tapable" */
  19. /**
  20. * Defines the hook type used by this module.
  21. * @template T, R, AdditionalOptions
  22. * @typedef {import("tapable").Hook<T, R, AdditionalOptions>} Hook
  23. */
  24. /**
  25. * @import {
  26. * ProgressPluginArgument,
  27. * ProgressPluginOptions
  28. * } from "../declarations/plugins/ProgressPlugin"
  29. */
  30. /** @import Dependency from "./Dependency" */
  31. /** @import { EntryOptions } from "./Entrypoint" */
  32. /** @import Module from "./Module" */
  33. /** @import { Logger } from "./logging/Logger" */
  34. /** @import { Colors } from "./cli" */
  35. /**
  36. * Returns median.
  37. * @param {number} a a
  38. * @param {number} b b
  39. * @param {number} c c
  40. * @returns {number} median
  41. */
  42. const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
  43. /** @typedef {(percentage: number, msg: string, ...args: string[]) => void} HandlerFn */
  44. /**
  45. * @param {Logger} logger logger
  46. * @param {{ value: string | undefined, time: number }[]} lastStateInfo mutable state
  47. * @param {number} percentage percentage
  48. * @param {string} msg msg
  49. * @param {string[]} args args
  50. */
  51. const reportProfile = (logger, lastStateInfo, percentage, msg, args) => {
  52. if (percentage === 0) {
  53. lastStateInfo.length = 0;
  54. }
  55. const fullState = [msg, ...args];
  56. const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, ""));
  57. const now = Date.now();
  58. const len = Math.max(state.length, lastStateInfo.length);
  59. for (let i = len; i >= 0; i--) {
  60. const stateItem = i < state.length ? state[i] : undefined;
  61. const lastStateItem =
  62. i < lastStateInfo.length ? lastStateInfo[i] : undefined;
  63. if (lastStateItem) {
  64. if (stateItem !== lastStateItem.value) {
  65. const diff = now - lastStateItem.time;
  66. if (lastStateItem.value) {
  67. let reportState = lastStateItem.value;
  68. if (i > 0) {
  69. reportState = `${lastStateInfo[i - 1].value} > ${reportState}`;
  70. }
  71. const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
  72. const d = diff;
  73. // This depends on timing so we ignore it for coverage
  74. /* eslint-disable no-lone-blocks */
  75. /* istanbul ignore next */
  76. {
  77. if (d > 10000) {
  78. logger.error(stateMsg);
  79. } else if (d > 1000) {
  80. logger.warn(stateMsg);
  81. } else if (d > 10) {
  82. logger.info(stateMsg);
  83. } else if (d > 5) {
  84. logger.log(stateMsg);
  85. } else {
  86. logger.debug(stateMsg);
  87. }
  88. }
  89. /* eslint-enable no-lone-blocks */
  90. }
  91. if (stateItem === undefined) {
  92. lastStateInfo.length = i;
  93. } else {
  94. lastStateItem.value = stateItem;
  95. lastStateItem.time = now;
  96. lastStateInfo.length = i + 1;
  97. }
  98. }
  99. } else {
  100. lastStateInfo[i] = {
  101. value: stateItem,
  102. time: now
  103. };
  104. }
  105. }
  106. };
  107. /**
  108. * @param {number} ms milliseconds
  109. * @returns {string} human readable duration
  110. */
  111. const formatTime = (ms) => {
  112. if (ms < 1000) return `${Math.round(ms)}ms`;
  113. const seconds = Math.floor(ms / 1000);
  114. if (seconds < 60) return `${seconds}s`;
  115. const minutes = Math.floor(seconds / 60);
  116. if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
  117. const hours = Math.floor(minutes / 60);
  118. return `${hours}h ${minutes % 60}m`;
  119. };
  120. /**
  121. * @param {string} name progress bar name
  122. * @param {string} color progress bar color
  123. * @param {number} width progress bar width in characters
  124. * @returns {(percentage: number) => string} bar renderer
  125. */
  126. const createReportBar = (name, color, width) => {
  127. const c = getColors();
  128. const colorFn = color in c ? c[/** @type {keyof Colors} */ (color)] : c.green;
  129. // The bar only changes when the filled width does, so cache it between steps.
  130. let lastFilled = -1;
  131. let lastBar = "";
  132. return (percentage) => {
  133. const filled = Math.round(percentage * width);
  134. if (filled === lastFilled) return lastBar;
  135. lastFilled = filled;
  136. const filledStr = BLOCK_CHAR.repeat(filled);
  137. const emptyStr = BLOCK_CHAR.repeat(width - filled);
  138. lastBar = `${[BULLET_ICON, name, filledStr].map(colorFn).join(" ")}${c.white(
  139. emptyStr
  140. )}`;
  141. return lastBar;
  142. };
  143. };
  144. /** @typedef {Required<Exclude<NonNullable<ProgressPluginOptions["progressBar"]>, boolean | "auto">>} ProgressBarOptions */
  145. /** @type {ProgressBarOptions} */
  146. const DEFAULT_PROGRESS_BAR = {
  147. name: "Build",
  148. color: "green",
  149. width: BAR_LENGTH
  150. };
  151. /** @typedef {{ progressBar?: ProgressBarOptions | false, estimatedTime?: boolean, phaseTimings?: boolean }} DefaultHandlerOptions */
  152. /**
  153. * Creates a default handler.
  154. * @param {boolean | null | undefined} profile need profile
  155. * @param {Logger} logger logger
  156. * @param {DefaultHandlerOptions=} options display options
  157. * @returns {HandlerFn} default handler
  158. */
  159. const createDefaultHandler = (profile, logger, options = {}) => {
  160. const {
  161. progressBar = false,
  162. estimatedTime = false,
  163. phaseTimings = false
  164. } = options;
  165. const trackTime = estimatedTime || phaseTimings;
  166. /** @type {{ value: string | undefined, time: number }[]} */
  167. const lastStateInfo = [];
  168. let buildStart = 0;
  169. // Exponential moving average of the estimated total build time (0 = unset).
  170. let smoothedTotal = 0;
  171. /** @type {Map<string, number>} accumulated ms per phase (msg) */
  172. const phaseTimes = new Map();
  173. /** @type {string | undefined} */
  174. let currentPhase;
  175. let currentPhaseStart = 0;
  176. let summaryReported = false;
  177. /** @type {((percentage: number) => string) | undefined} */
  178. let reportBar;
  179. /**
  180. * @param {number} now current timestamp
  181. * @returns {void}
  182. */
  183. const reportPhaseSummary = (now) => {
  184. if (!phaseTimings || summaryReported || phaseTimes.size === 0) return;
  185. summaryReported = true;
  186. // Flush the phase still running at completion.
  187. if (currentPhase !== undefined) {
  188. phaseTimes.set(
  189. currentPhase,
  190. (phaseTimes.get(currentPhase) || 0) + (now - currentPhaseStart)
  191. );
  192. }
  193. const total = now - buildStart;
  194. logger.info(`Build completed in ${formatTime(total)}`);
  195. logger.info("Phase breakdown:");
  196. for (const [phase, duration] of phaseTimes) {
  197. if (duration > 0) {
  198. const percent = total > 0 ? Math.round((duration / total) * 100) : 0;
  199. logger.info(` ${phase}: ${formatTime(duration)} (${percent}%)`);
  200. }
  201. }
  202. };
  203. /** @type {HandlerFn} */
  204. const defaultHandler = (percentage, msg, ...args) => {
  205. if (profile) {
  206. reportProfile(logger, lastStateInfo, percentage, msg, args);
  207. }
  208. const now = trackTime ? Date.now() : 0;
  209. if (trackTime && percentage === 0) {
  210. buildStart = now;
  211. smoothedTotal = 0;
  212. summaryReported = false;
  213. phaseTimes.clear();
  214. currentPhase = undefined;
  215. currentPhaseStart = now;
  216. }
  217. // Accumulate time under the previous phase whenever the top-level message changes.
  218. if (phaseTimings && msg && msg !== currentPhase) {
  219. if (currentPhase !== undefined) {
  220. phaseTimes.set(
  221. currentPhase,
  222. (phaseTimes.get(currentPhase) || 0) + (now - currentPhaseStart)
  223. );
  224. }
  225. currentPhase = msg;
  226. currentPhaseStart = now;
  227. }
  228. /** @type {string | undefined} */
  229. let eta;
  230. if (estimatedTime && percentage > 0.05 && percentage < 1) {
  231. const elapsed = now - buildStart;
  232. const rawTotal = elapsed / percentage;
  233. smoothedTotal =
  234. smoothedTotal > 0 ? smoothedTotal * 0.7 + rawTotal * 0.3 : rawTotal;
  235. const remaining = smoothedTotal - elapsed;
  236. if (remaining > 0) eta = `ETA: ${formatTime(remaining)}`;
  237. }
  238. if (progressBar) {
  239. // Build the bar renderer once, then reuse it across every step.
  240. if (reportBar === undefined) {
  241. reportBar = createReportBar(
  242. progressBar.name,
  243. progressBar.color,
  244. progressBar.width
  245. );
  246. }
  247. const c = getColors();
  248. /** @type {string} */
  249. const currentBar = reportBar(percentage);
  250. const suffix = eta ? ` ${eta}` : "";
  251. if (percentage === 1) {
  252. logger.status();
  253. reportPhaseSummary(now);
  254. } else if (msg) {
  255. logger.status(
  256. `${currentBar} (${Math.floor(percentage * 100)}%)${suffix}`,
  257. `\n${[msg, ...args].map(c.gray).join(" ")}`
  258. );
  259. } else {
  260. logger.status(
  261. `${currentBar} (${Math.floor(percentage * 100)}%)${suffix}`
  262. );
  263. }
  264. return;
  265. }
  266. if (eta) {
  267. logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args, eta);
  268. } else {
  269. logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args);
  270. }
  271. if (percentage === 1 || (!msg && args.length === 0)) {
  272. if (percentage === 1) reportPhaseSummary(now);
  273. logger.status();
  274. }
  275. };
  276. return defaultHandler;
  277. };
  278. /**
  279. * Defines the report progress callback.
  280. * @callback ReportProgress
  281. * @param {number} p percentage
  282. * @param {...string} args additional arguments
  283. * @returns {void}
  284. */
  285. /** @type {WeakMap<Compiler, ReportProgress | undefined>} */
  286. const progressReporters = new WeakMap();
  287. const PLUGIN_NAME = "ProgressPlugin";
  288. /** @type {Required<Omit<ProgressPluginOptions, "handler">>} */
  289. const DEFAULT_OPTIONS = {
  290. profile: false,
  291. modulesCount: 5000,
  292. dependenciesCount: 10000,
  293. modules: true,
  294. dependencies: true,
  295. activeModules: false,
  296. entries: true,
  297. percentBy: null,
  298. progressBar: false,
  299. estimatedTime: false,
  300. phaseTimings: false
  301. };
  302. /**
  303. * Whether progress can be rendered in place (interactive TTY). The bar is only
  304. * useful here; in append-only output every update becomes a new line.
  305. * @param {Compiler | MultiCompiler} compiler compiler
  306. * @returns {boolean} true when output is an interactive terminal
  307. */
  308. const isInteractive = (compiler) => {
  309. const c =
  310. compiler instanceof MultiCompiler ? compiler.compilers[0] : compiler;
  311. const infrastructureLogging =
  312. c && c.options && c.options.infrastructureLogging;
  313. if (
  314. infrastructureLogging &&
  315. typeof infrastructureLogging.appendOnly === "boolean"
  316. ) {
  317. return !infrastructureLogging.appendOnly;
  318. }
  319. const stream =
  320. (infrastructureLogging && infrastructureLogging.stream) || process.stderr;
  321. return (
  322. Boolean(/** @type {NodeJS.WriteStream} */ (stream).isTTY) &&
  323. process.env.TERM !== "dumb"
  324. );
  325. };
  326. class ProgressPlugin {
  327. /**
  328. * Returns a progress reporter, if any.
  329. * @param {Compiler} compiler the current compiler
  330. * @returns {ReportProgress | undefined} a progress reporter, if any
  331. */
  332. static getReporter(compiler) {
  333. return progressReporters.get(compiler);
  334. }
  335. /**
  336. * Creates an instance of ProgressPlugin.
  337. * @param {ProgressPluginArgument} options options
  338. */
  339. constructor(options = {}) {
  340. if (typeof options === "function") {
  341. options = {
  342. handler: options
  343. };
  344. }
  345. /** @type {ProgressPluginOptions} */
  346. this.options = options;
  347. const merged = { ...DEFAULT_OPTIONS, ...options };
  348. /** @type {boolean | null} */
  349. this.profile = merged.profile;
  350. /** @type {HandlerFn | undefined} */
  351. this.handler = merged.handler;
  352. /** @type {number} */
  353. this.modulesCount = merged.modulesCount;
  354. /** @type {number} */
  355. this.dependenciesCount = merged.dependenciesCount;
  356. /** @type {boolean} */
  357. this.showEntries = merged.entries;
  358. /** @type {boolean} */
  359. this.showModules = merged.modules;
  360. /** @type {boolean} */
  361. this.showDependencies = merged.dependencies;
  362. /** @type {boolean} */
  363. this.showActiveModules = merged.activeModules;
  364. this.percentBy = merged.percentBy;
  365. const progressBar = merged.progressBar;
  366. /** @type {ProgressBarOptions | false | "auto"} */
  367. this.progressBar =
  368. progressBar === "auto"
  369. ? "auto"
  370. : progressBar
  371. ? {
  372. ...DEFAULT_PROGRESS_BAR,
  373. ...(progressBar === true ? {} : progressBar)
  374. }
  375. : false;
  376. /** @type {boolean} */
  377. this.estimatedTime = merged.estimatedTime;
  378. /** @type {boolean} */
  379. this.phaseTimings = merged.phaseTimings;
  380. }
  381. /**
  382. * Applies the plugin by registering its hooks on the compiler.
  383. * @param {Compiler | MultiCompiler} compiler webpack compiler
  384. * @returns {void}
  385. */
  386. apply(compiler) {
  387. let progressBar = this.progressBar;
  388. // webpack@6 (opt-in today via `experiments.futureDefaults`) turns an unset
  389. // progressBar into the auto bar; an explicit `false` is still respected.
  390. if (progressBar === false && this.options.progressBar === undefined) {
  391. const c =
  392. compiler instanceof MultiCompiler ? compiler.compilers[0] : compiler;
  393. if (c && c.options && c.options.experiments.futureDefaults) {
  394. progressBar = "auto";
  395. }
  396. }
  397. if (progressBar === "auto") {
  398. progressBar = isInteractive(compiler)
  399. ? { ...DEFAULT_PROGRESS_BAR }
  400. : false;
  401. }
  402. const handler =
  403. this.handler ||
  404. createDefaultHandler(
  405. this.profile,
  406. compiler.getInfrastructureLogger("webpack.Progress"),
  407. {
  408. progressBar,
  409. estimatedTime: this.estimatedTime,
  410. phaseTimings: this.phaseTimings
  411. }
  412. );
  413. if (compiler instanceof MultiCompiler) {
  414. this._applyOnMultiCompiler(compiler, handler);
  415. } else if (compiler instanceof Compiler) {
  416. this._applyOnCompiler(compiler, handler);
  417. }
  418. }
  419. /**
  420. * Apply on multi compiler.
  421. * @param {MultiCompiler} compiler webpack multi-compiler
  422. * @param {HandlerFn} handler function that executes for every progress step
  423. * @returns {void}
  424. */
  425. _applyOnMultiCompiler(compiler, handler) {
  426. const states = compiler.compilers.map(
  427. () => /** @type {[number, ...string[]]} */ ([0])
  428. );
  429. for (const [idx, item] of compiler.compilers.entries()) {
  430. new ProgressPlugin((p, msg, ...args) => {
  431. states[idx] = [p, msg, ...args];
  432. let sum = 0;
  433. for (const [p] of states) sum += p;
  434. handler(sum / states.length, `[${idx}] ${msg}`, ...args);
  435. }).apply(item);
  436. }
  437. }
  438. /**
  439. * Processes the provided compiler.
  440. * @param {Compiler} compiler webpack compiler
  441. * @param {HandlerFn} handler function that executes for every progress step
  442. * @returns {void}
  443. */
  444. _applyOnCompiler(compiler, handler) {
  445. compiler.hooks.validate.tap(PLUGIN_NAME, () => {
  446. compiler.validate(
  447. () => require("../schemas/plugins/ProgressPlugin.json"),
  448. this.options,
  449. {
  450. name: "Progress Plugin",
  451. baseDataPath: "options"
  452. },
  453. (options) => require("../schemas/plugins/ProgressPlugin.check")(options)
  454. );
  455. });
  456. const showEntries = this.showEntries;
  457. const showModules = this.showModules;
  458. const showDependencies = this.showDependencies;
  459. const showActiveModules = this.showActiveModules;
  460. let lastActiveModule = "";
  461. let currentLoader = "";
  462. let lastModulesCount = 0;
  463. let lastDependenciesCount = 0;
  464. let lastEntriesCount = 0;
  465. let modulesCount = 0;
  466. let dependenciesCount = 0;
  467. let entriesCount = 1;
  468. let doneModules = 0;
  469. let doneDependencies = 0;
  470. let doneEntries = 0;
  471. /** @type {Set<string>} */
  472. const activeModules = new Set();
  473. let lastUpdate = 0;
  474. const updateThrottled = () => {
  475. if (lastUpdate + 500 < Date.now()) update();
  476. };
  477. const update = () => {
  478. /** @type {string[]} */
  479. const items = [];
  480. const percentByModules =
  481. doneModules /
  482. Math.max(lastModulesCount || this.modulesCount || 1, modulesCount);
  483. const percentByEntries =
  484. doneEntries /
  485. Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount);
  486. const percentByDependencies =
  487. doneDependencies /
  488. Math.max(lastDependenciesCount || 1, dependenciesCount);
  489. /** @type {number} */
  490. let percentageFactor;
  491. switch (this.percentBy) {
  492. case "entries":
  493. percentageFactor = percentByEntries;
  494. break;
  495. case "dependencies":
  496. percentageFactor = percentByDependencies;
  497. break;
  498. case "modules":
  499. percentageFactor = percentByModules;
  500. break;
  501. default:
  502. percentageFactor = median3(
  503. percentByModules,
  504. percentByEntries,
  505. percentByDependencies
  506. );
  507. }
  508. const percentage = 0.1 + percentageFactor * 0.55;
  509. if (currentLoader) {
  510. items.push(
  511. `import loader ${contextify(
  512. compiler.context,
  513. currentLoader,
  514. compiler.root
  515. )}`
  516. );
  517. } else {
  518. /** @type {string[]} */
  519. const statItems = [];
  520. if (showEntries) {
  521. statItems.push(`${doneEntries}/${entriesCount} entries`);
  522. }
  523. if (showDependencies) {
  524. statItems.push(
  525. `${doneDependencies}/${dependenciesCount} dependencies`
  526. );
  527. }
  528. if (showModules) {
  529. statItems.push(`${doneModules}/${modulesCount} modules`);
  530. }
  531. if (showActiveModules) {
  532. statItems.push(`${activeModules.size} active`);
  533. }
  534. if (statItems.length > 0) {
  535. items.push(statItems.join(" "));
  536. }
  537. if (showActiveModules) {
  538. items.push(lastActiveModule);
  539. }
  540. }
  541. handler(percentage, "building", ...items);
  542. lastUpdate = Date.now();
  543. };
  544. const factorizeAdd = () => {
  545. dependenciesCount++;
  546. if (dependenciesCount < 50 || dependenciesCount % 100 === 0) {
  547. updateThrottled();
  548. }
  549. };
  550. const factorizeDone = () => {
  551. doneDependencies++;
  552. if (doneDependencies < 50 || doneDependencies % 100 === 0) {
  553. updateThrottled();
  554. }
  555. };
  556. const moduleAdd = () => {
  557. modulesCount++;
  558. if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled();
  559. };
  560. // only used when showActiveModules is set
  561. /**
  562. * Processes the provided module.
  563. * @param {Module} module the module
  564. */
  565. const moduleBuild = (module) => {
  566. const ident = module.identifier();
  567. if (ident) {
  568. activeModules.add(ident);
  569. lastActiveModule = ident;
  570. update();
  571. }
  572. };
  573. /**
  574. * Processes the provided entry.
  575. * @param {Dependency} entry entry dependency
  576. * @param {EntryOptions} options options object
  577. */
  578. const entryAdd = (entry, options) => {
  579. entriesCount++;
  580. if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled();
  581. };
  582. /**
  583. * Processes the provided module.
  584. * @param {Module} module the module
  585. */
  586. const moduleDone = (module) => {
  587. doneModules++;
  588. if (showActiveModules) {
  589. const ident = module.identifier();
  590. if (ident) {
  591. activeModules.delete(ident);
  592. if (lastActiveModule === ident) {
  593. lastActiveModule = "";
  594. for (const m of activeModules) {
  595. lastActiveModule = m;
  596. }
  597. update();
  598. return;
  599. }
  600. }
  601. }
  602. if (doneModules < 50 || doneModules % 100 === 0) updateThrottled();
  603. };
  604. /**
  605. * Processes the provided entry.
  606. * @param {Dependency} entry entry dependency
  607. * @param {EntryOptions} options options object
  608. */
  609. const entryDone = (entry, options) => {
  610. doneEntries++;
  611. update();
  612. };
  613. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  614. if (compilation.compiler.isChild()) return;
  615. // Carry the previous compilation's counts into the next as an estimate
  616. // (helps watch rebuilds); not persisted, to avoid cache invalidation.
  617. lastModulesCount = modulesCount;
  618. lastEntriesCount = entriesCount;
  619. lastDependenciesCount = dependenciesCount;
  620. modulesCount = dependenciesCount = entriesCount = 0;
  621. doneModules = doneDependencies = doneEntries = 0;
  622. compilation.factorizeQueue.hooks.added.tap(PLUGIN_NAME, factorizeAdd);
  623. compilation.factorizeQueue.hooks.result.tap(PLUGIN_NAME, factorizeDone);
  624. compilation.addModuleQueue.hooks.added.tap(PLUGIN_NAME, moduleAdd);
  625. compilation.processDependenciesQueue.hooks.result.tap(
  626. PLUGIN_NAME,
  627. moduleDone
  628. );
  629. if (showActiveModules) {
  630. compilation.hooks.buildModule.tap(PLUGIN_NAME, moduleBuild);
  631. }
  632. compilation.hooks.addEntry.tap(PLUGIN_NAME, entryAdd);
  633. compilation.hooks.failedEntry.tap(PLUGIN_NAME, entryDone);
  634. compilation.hooks.succeedEntry.tap(PLUGIN_NAME, entryDone);
  635. // @ts-expect-error avoid dynamic require if bundled with webpack
  636. if (typeof __webpack_require__ !== "function") {
  637. /** @type {Set<string>} */
  638. const requiredLoaders = new Set();
  639. NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
  640. PLUGIN_NAME,
  641. (loaders) => {
  642. for (const loader of loaders) {
  643. if (
  644. loader.type !== "module" &&
  645. !requiredLoaders.has(loader.loader)
  646. ) {
  647. requiredLoaders.add(loader.loader);
  648. currentLoader = loader.loader;
  649. update();
  650. require(loader.loader);
  651. }
  652. }
  653. if (currentLoader) {
  654. currentLoader = "";
  655. update();
  656. }
  657. }
  658. );
  659. }
  660. const hooks = {
  661. finishModules: "finish module graph",
  662. seal: "plugins",
  663. optimizeDependencies: "dependencies optimization",
  664. afterOptimizeDependencies: "after dependencies optimization",
  665. beforeChunks: "chunk graph",
  666. afterChunks: "after chunk graph",
  667. optimize: "optimizing",
  668. optimizeModules: "module optimization",
  669. afterOptimizeModules: "after module optimization",
  670. optimizeChunks: "chunk optimization",
  671. afterOptimizeChunks: "after chunk optimization",
  672. optimizeTree: "module and chunk tree optimization",
  673. afterOptimizeTree: "after module and chunk tree optimization",
  674. optimizeChunkModules: "chunk modules optimization",
  675. afterOptimizeChunkModules: "after chunk modules optimization",
  676. reviveModules: "module reviving",
  677. beforeModuleIds: "before module ids",
  678. moduleIds: "module ids",
  679. optimizeModuleIds: "module id optimization",
  680. afterOptimizeModuleIds: "module id optimization",
  681. reviveChunks: "chunk reviving",
  682. beforeChunkIds: "before chunk ids",
  683. chunkIds: "chunk ids",
  684. optimizeChunkIds: "chunk id optimization",
  685. afterOptimizeChunkIds: "after chunk id optimization",
  686. recordModules: "record modules",
  687. recordChunks: "record chunks",
  688. beforeModuleHash: "module hashing",
  689. beforeCodeGeneration: "code generation",
  690. beforeRuntimeRequirements: "runtime requirements",
  691. beforeHash: "hashing",
  692. afterHash: "after hashing",
  693. recordHash: "record hash",
  694. beforeModuleAssets: "module assets processing",
  695. beforeChunkAssets: "chunk assets processing",
  696. processAssets: "asset processing",
  697. afterProcessAssets: "after asset optimization",
  698. record: "recording",
  699. afterSeal: "after seal"
  700. };
  701. const numberOfHooks = Object.keys(hooks).length;
  702. for (const [idx, name] of Object.keys(hooks).entries()) {
  703. const title = hooks[/** @type {keyof typeof hooks} */ (name)];
  704. const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
  705. compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
  706. name: PLUGIN_NAME,
  707. call() {
  708. handler(percentage, "sealing", title);
  709. },
  710. done() {
  711. progressReporters.set(compiler, undefined);
  712. handler(percentage, "sealing", title);
  713. },
  714. result() {
  715. handler(percentage, "sealing", title);
  716. },
  717. error() {
  718. handler(percentage, "sealing", title);
  719. },
  720. tap(tap) {
  721. // p is percentage from 0 to 1
  722. // args is any number of messages in a hierarchical matter
  723. progressReporters.set(compilation.compiler, (p, ...args) => {
  724. handler(percentage, "sealing", title, tap.name, ...args);
  725. });
  726. handler(percentage, "sealing", title, tap.name);
  727. }
  728. });
  729. }
  730. });
  731. compiler.hooks.make.intercept({
  732. name: PLUGIN_NAME,
  733. call() {
  734. handler(0.1, "building");
  735. },
  736. done() {
  737. handler(0.65, "building");
  738. }
  739. });
  740. /**
  741. * Processes the provided hook.
  742. * @template {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} T
  743. * @param {T} hook hook
  744. * @param {number} progress progress from 0 to 1
  745. * @param {string} category category
  746. * @param {string} name name
  747. */
  748. const interceptHook = (hook, progress, category, name) => {
  749. hook.intercept({
  750. name: PLUGIN_NAME,
  751. call() {
  752. handler(progress, category, name);
  753. },
  754. done() {
  755. progressReporters.set(compiler, undefined);
  756. handler(progress, category, name);
  757. },
  758. result() {
  759. handler(progress, category, name);
  760. },
  761. error() {
  762. handler(progress, category, name);
  763. },
  764. /**
  765. * Processes the provided tap.
  766. * @param {Tap} tap tap
  767. */
  768. tap(tap) {
  769. progressReporters.set(compiler, (p, ...args) => {
  770. handler(progress, category, name, tap.name, ...args);
  771. });
  772. handler(progress, category, name, tap.name);
  773. }
  774. });
  775. };
  776. compiler.cache.hooks.endIdle.intercept({
  777. name: PLUGIN_NAME,
  778. call() {
  779. handler(0, "");
  780. }
  781. });
  782. interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle");
  783. compiler.hooks.beforeRun.intercept({
  784. name: PLUGIN_NAME,
  785. call() {
  786. handler(0, "");
  787. }
  788. });
  789. interceptHook(compiler.hooks.beforeRun, 0.01, "setup", "before run");
  790. interceptHook(compiler.hooks.run, 0.02, "setup", "run");
  791. interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run");
  792. interceptHook(
  793. compiler.hooks.normalModuleFactory,
  794. 0.04,
  795. "setup",
  796. "normal module factory"
  797. );
  798. interceptHook(
  799. compiler.hooks.contextModuleFactory,
  800. 0.05,
  801. "setup",
  802. "context module factory"
  803. );
  804. interceptHook(
  805. compiler.hooks.beforeCompile,
  806. 0.06,
  807. "setup",
  808. "before compile"
  809. );
  810. interceptHook(compiler.hooks.compile, 0.07, "setup", "compile");
  811. interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation");
  812. interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation");
  813. interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish");
  814. interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit");
  815. interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit");
  816. interceptHook(compiler.hooks.done, 0.99, "done", "plugins");
  817. compiler.hooks.done.intercept({
  818. name: PLUGIN_NAME,
  819. done() {
  820. handler(0.99, "");
  821. }
  822. });
  823. interceptHook(
  824. compiler.cache.hooks.storeBuildDependencies,
  825. 0.99,
  826. "cache",
  827. "store build dependencies"
  828. );
  829. interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown");
  830. interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle");
  831. interceptHook(
  832. compiler.hooks.watchClose,
  833. 0.99,
  834. "end",
  835. "closing watch compilation"
  836. );
  837. compiler.cache.hooks.beginIdle.intercept({
  838. name: PLUGIN_NAME,
  839. done() {
  840. handler(1, "");
  841. }
  842. });
  843. compiler.cache.hooks.shutdown.intercept({
  844. name: PLUGIN_NAME,
  845. done() {
  846. handler(1, "");
  847. }
  848. });
  849. }
  850. }
  851. ProgressPlugin.defaultOptions = DEFAULT_OPTIONS;
  852. ProgressPlugin.createDefaultHandler = createDefaultHandler;
  853. module.exports = ProgressPlugin;