Stats.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RequestShortener = require("./RequestShortener");
  7. const SizeFormatHelpers = require("./SizeFormatHelpers");
  8. const formatLocation = require("./formatLocation");
  9. const identifierUtils = require("./util/identifier");
  10. const optionsOrFallback = function() {
  11. let optionValues = [];
  12. optionValues.push.apply(optionValues, arguments);
  13. return optionValues.find(optionValue => typeof optionValue !== "undefined");
  14. };
  15. class Stats {
  16. constructor(compilation) {
  17. this.compilation = compilation;
  18. this.hash = compilation.hash;
  19. }
  20. static filterWarnings(warnings, warningsFilter) {
  21. // we dont have anything to filter so all warnings can be shown
  22. if(!warningsFilter) {
  23. return warnings;
  24. }
  25. // create a chain of filters
  26. // if they return "true" a warning should be surpressed
  27. const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => {
  28. if(typeof filter === "string") {
  29. return warning => warning.indexOf(filter) > -1;
  30. }
  31. if(filter instanceof RegExp) {
  32. return warning => filter.test(warning);
  33. }
  34. if(typeof filter === "function") {
  35. return filter;
  36. }
  37. throw new Error(`Can only filter warnings with Strings or RegExps. (Given: ${filter})`);
  38. });
  39. return warnings.filter(warning => {
  40. return !normalizedWarningsFilters.some(check => check(warning));
  41. });
  42. }
  43. hasWarnings() {
  44. return this.compilation.warnings.length > 0;
  45. }
  46. hasErrors() {
  47. return this.compilation.errors.length > 0;
  48. }
  49. // remove a prefixed "!" that can be specified to reverse sort order
  50. normalizeFieldKey(field) {
  51. if(field[0] === "!") {
  52. return field.substr(1);
  53. }
  54. return field;
  55. }
  56. // if a field is prefixed by a "!" reverse sort order
  57. sortOrderRegular(field) {
  58. if(field[0] === "!") {
  59. return false;
  60. }
  61. return true;
  62. }
  63. toJson(options, forToString) {
  64. if(typeof options === "boolean" || typeof options === "string") {
  65. options = Stats.presetToOptions(options);
  66. } else if(!options) {
  67. options = {};
  68. }
  69. const optionOrLocalFallback = (v, def) =>
  70. typeof v !== "undefined" ? v :
  71. typeof options.all !== "undefined" ? options.all : def;
  72. const testAgainstGivenOption = (item) => {
  73. if(typeof item === "string") {
  74. const regExp = new RegExp(`[\\\\/]${item.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")}([\\\\/]|$|!|\\?)`); // eslint-disable-line no-useless-escape
  75. return ident => regExp.test(ident);
  76. }
  77. if(item && typeof item === "object" && typeof item.test === "function")
  78. return ident => item.test(ident);
  79. if(typeof item === "function")
  80. return item;
  81. };
  82. const compilation = this.compilation;
  83. const context = optionsOrFallback(options.context, process.cwd());
  84. const requestShortener = new RequestShortener(context);
  85. const showPerformance = optionOrLocalFallback(options.performance, true);
  86. const showHash = optionOrLocalFallback(options.hash, true);
  87. const showVersion = optionOrLocalFallback(options.version, true);
  88. const showTimings = optionOrLocalFallback(options.timings, true);
  89. const showAssets = optionOrLocalFallback(options.assets, true);
  90. const showEntrypoints = optionOrLocalFallback(options.entrypoints, !forToString);
  91. const showChunks = optionOrLocalFallback(options.chunks, !forToString);
  92. const showChunkModules = optionOrLocalFallback(options.chunkModules, true);
  93. const showChunkOrigins = optionOrLocalFallback(options.chunkOrigins, !forToString);
  94. const showModules = optionOrLocalFallback(options.modules, true);
  95. const showDepth = optionOrLocalFallback(options.depth, !forToString);
  96. const showCachedModules = optionOrLocalFallback(options.cached, true);
  97. const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true);
  98. const showReasons = optionOrLocalFallback(options.reasons, !forToString);
  99. const showUsedExports = optionOrLocalFallback(options.usedExports, !forToString);
  100. const showProvidedExports = optionOrLocalFallback(options.providedExports, !forToString);
  101. const showOptimizationBailout = optionOrLocalFallback(options.optimizationBailout, !forToString);
  102. const showChildren = optionOrLocalFallback(options.children, true);
  103. const showSource = optionOrLocalFallback(options.source, !forToString);
  104. const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true);
  105. const showErrors = optionOrLocalFallback(options.errors, true);
  106. const showErrorDetails = optionOrLocalFallback(options.errorDetails, !forToString);
  107. const showWarnings = optionOrLocalFallback(options.warnings, true);
  108. const warningsFilter = optionsOrFallback(options.warningsFilter, null);
  109. const showPublicPath = optionOrLocalFallback(options.publicPath, !forToString);
  110. const excludeModules = [].concat(optionsOrFallback(options.excludeModules, options.exclude, [])).map(testAgainstGivenOption);
  111. const excludeAssets = [].concat(optionsOrFallback(options.excludeAssets, [])).map(testAgainstGivenOption);
  112. const maxModules = optionsOrFallback(options.maxModules, forToString ? 15 : Infinity);
  113. const sortModules = optionsOrFallback(options.modulesSort, "id");
  114. const sortChunks = optionsOrFallback(options.chunksSort, "id");
  115. const sortAssets = optionsOrFallback(options.assetsSort, "");
  116. if(!showCachedModules) {
  117. excludeModules.push((ident, module) => !module.built);
  118. }
  119. const createModuleFilter = () => {
  120. let i = 0;
  121. return module => {
  122. if(excludeModules.length > 0) {
  123. const ident = requestShortener.shorten(module.resource);
  124. const excluded = excludeModules.some(fn => fn(ident, module));
  125. if(excluded)
  126. return false;
  127. }
  128. return i++ < maxModules;
  129. };
  130. };
  131. const createAssetFilter = () => {
  132. return asset => {
  133. if(excludeAssets.length > 0) {
  134. const ident = asset.name;
  135. const excluded = excludeAssets.some(fn => fn(ident, asset));
  136. if(excluded)
  137. return false;
  138. }
  139. return showCachedAssets || asset.emitted;
  140. };
  141. };
  142. const sortByFieldAndOrder = (fieldKey, a, b) => {
  143. if(a[fieldKey] === null && b[fieldKey] === null) return 0;
  144. if(a[fieldKey] === null) return 1;
  145. if(b[fieldKey] === null) return -1;
  146. if(a[fieldKey] === b[fieldKey]) return 0;
  147. return a[fieldKey] < b[fieldKey] ? -1 : 1;
  148. };
  149. const sortByField = (field) => (a, b) => {
  150. if(!field) {
  151. return 0;
  152. }
  153. const fieldKey = this.normalizeFieldKey(field);
  154. // if a field is prefixed with a "!" the sort is reversed!
  155. const sortIsRegular = this.sortOrderRegular(field);
  156. return sortByFieldAndOrder(fieldKey, sortIsRegular ? a : b, sortIsRegular ? b : a);
  157. };
  158. const formatError = (e) => {
  159. let text = "";
  160. if(typeof e === "string")
  161. e = {
  162. message: e
  163. };
  164. if(e.chunk) {
  165. text += `chunk ${e.chunk.name || e.chunk.id}${e.chunk.hasRuntime() ? " [entry]" : e.chunk.isInitial() ? " [initial]" : ""}\n`;
  166. }
  167. if(e.file) {
  168. text += `${e.file}\n`;
  169. }
  170. if(e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function") {
  171. text += `${e.module.readableIdentifier(requestShortener)}\n`;
  172. }
  173. text += e.message;
  174. if(showErrorDetails && e.details) text += `\n${e.details}`;
  175. if(showErrorDetails && e.missing) text += e.missing.map(item => `\n[${item}]`).join("");
  176. if(showModuleTrace && e.dependencies && e.origin) {
  177. text += `\n @ ${e.origin.readableIdentifier(requestShortener)}`;
  178. e.dependencies.forEach(dep => {
  179. if(!dep.loc) return;
  180. if(typeof dep.loc === "string") return;
  181. const locInfo = formatLocation(dep.loc);
  182. if(!locInfo) return;
  183. text += ` ${locInfo}`;
  184. });
  185. let current = e.origin;
  186. while(current.issuer) {
  187. current = current.issuer;
  188. text += `\n @ ${current.readableIdentifier(requestShortener)}`;
  189. }
  190. }
  191. return text;
  192. };
  193. const obj = {
  194. errors: compilation.errors.map(formatError),
  195. warnings: Stats.filterWarnings(compilation.warnings.map(formatError), warningsFilter)
  196. };
  197. //We just hint other renderers since actually omitting
  198. //errors/warnings from the JSON would be kind of weird.
  199. Object.defineProperty(obj, "_showWarnings", {
  200. value: showWarnings,
  201. enumerable: false
  202. });
  203. Object.defineProperty(obj, "_showErrors", {
  204. value: showErrors,
  205. enumerable: false
  206. });
  207. if(showVersion) {
  208. obj.version = require("../package.json").version;
  209. }
  210. if(showHash) obj.hash = this.hash;
  211. if(showTimings && this.startTime && this.endTime) {
  212. obj.time = this.endTime - this.startTime;
  213. }
  214. if(compilation.needAdditionalPass) {
  215. obj.needAdditionalPass = true;
  216. }
  217. if(showPublicPath) {
  218. obj.publicPath = this.compilation.mainTemplate.getPublicPath({
  219. hash: this.compilation.hash
  220. });
  221. }
  222. if(showAssets) {
  223. const assetsByFile = {};
  224. const compilationAssets = Object.keys(compilation.assets);
  225. obj.assetsByChunkName = {};
  226. obj.assets = compilationAssets.map(asset => {
  227. const obj = {
  228. name: asset,
  229. size: compilation.assets[asset].size(),
  230. chunks: [],
  231. chunkNames: [],
  232. emitted: compilation.assets[asset].emitted
  233. };
  234. if(showPerformance) {
  235. obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit;
  236. }
  237. assetsByFile[asset] = obj;
  238. return obj;
  239. }).filter(createAssetFilter());
  240. obj.filteredAssets = compilationAssets.length - obj.assets.length;
  241. compilation.chunks.forEach(chunk => {
  242. chunk.files.forEach(asset => {
  243. if(assetsByFile[asset]) {
  244. chunk.ids.forEach(id => {
  245. assetsByFile[asset].chunks.push(id);
  246. });
  247. if(chunk.name) {
  248. assetsByFile[asset].chunkNames.push(chunk.name);
  249. if(obj.assetsByChunkName[chunk.name])
  250. obj.assetsByChunkName[chunk.name] = [].concat(obj.assetsByChunkName[chunk.name]).concat([asset]);
  251. else
  252. obj.assetsByChunkName[chunk.name] = asset;
  253. }
  254. }
  255. });
  256. });
  257. obj.assets.sort(sortByField(sortAssets));
  258. }
  259. if(showEntrypoints) {
  260. obj.entrypoints = {};
  261. Object.keys(compilation.entrypoints).forEach(name => {
  262. const ep = compilation.entrypoints[name];
  263. obj.entrypoints[name] = {
  264. chunks: ep.chunks.map(c => c.id),
  265. assets: ep.chunks.reduce((array, c) => array.concat(c.files || []), [])
  266. };
  267. if(showPerformance) {
  268. obj.entrypoints[name].isOverSizeLimit = ep.isOverSizeLimit;
  269. }
  270. });
  271. }
  272. function fnModule(module) {
  273. const obj = {
  274. id: module.id,
  275. identifier: module.identifier(),
  276. name: module.readableIdentifier(requestShortener),
  277. index: module.index,
  278. index2: module.index2,
  279. size: module.size(),
  280. cacheable: !!module.cacheable,
  281. built: !!module.built,
  282. optional: !!module.optional,
  283. prefetched: !!module.prefetched,
  284. chunks: module.mapChunks(chunk => chunk.id),
  285. assets: Object.keys(module.assets || {}),
  286. issuer: module.issuer && module.issuer.identifier(),
  287. issuerId: module.issuer && module.issuer.id,
  288. issuerName: module.issuer && module.issuer.readableIdentifier(requestShortener),
  289. profile: module.profile,
  290. failed: !!module.error,
  291. errors: module.errors && module.dependenciesErrors && (module.errors.length + module.dependenciesErrors.length),
  292. warnings: module.errors && module.dependenciesErrors && (module.warnings.length + module.dependenciesWarnings.length)
  293. };
  294. if(showReasons) {
  295. obj.reasons = module.reasons.filter(reason => reason.dependency && reason.module).map(reason => {
  296. const obj = {
  297. moduleId: reason.module.id,
  298. moduleIdentifier: reason.module.identifier(),
  299. module: reason.module.readableIdentifier(requestShortener),
  300. moduleName: reason.module.readableIdentifier(requestShortener),
  301. type: reason.dependency.type,
  302. userRequest: reason.dependency.userRequest
  303. };
  304. const locInfo = formatLocation(reason.dependency.loc);
  305. if(locInfo) obj.loc = locInfo;
  306. return obj;
  307. }).sort((a, b) => a.moduleId - b.moduleId);
  308. }
  309. if(showUsedExports) {
  310. obj.usedExports = module.used ? module.usedExports : false;
  311. }
  312. if(showProvidedExports) {
  313. obj.providedExports = Array.isArray(module.providedExports) ? module.providedExports : null;
  314. }
  315. if(showOptimizationBailout) {
  316. obj.optimizationBailout = module.optimizationBailout.map(item => {
  317. if(typeof item === "function") return item(requestShortener);
  318. return item;
  319. });
  320. }
  321. if(showDepth) {
  322. obj.depth = module.depth;
  323. }
  324. if(showSource && module._source) {
  325. obj.source = module._source.source();
  326. }
  327. return obj;
  328. }
  329. if(showChunks) {
  330. obj.chunks = compilation.chunks.map(chunk => {
  331. const obj = {
  332. id: chunk.id,
  333. rendered: chunk.rendered,
  334. initial: chunk.isInitial(),
  335. entry: chunk.hasRuntime(),
  336. recorded: chunk.recorded,
  337. extraAsync: !!chunk.extraAsync,
  338. size: chunk.mapModules(m => m.size()).reduce((size, moduleSize) => size + moduleSize, 0),
  339. names: chunk.name ? [chunk.name] : [],
  340. files: chunk.files.slice(),
  341. hash: chunk.renderedHash,
  342. parents: chunk.parents.map(c => c.id)
  343. };
  344. if(showChunkModules) {
  345. obj.modules = chunk
  346. .getModules()
  347. .sort(sortByField("depth"))
  348. .filter(createModuleFilter())
  349. .map(fnModule);
  350. obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length;
  351. obj.modules.sort(sortByField(sortModules));
  352. }
  353. if(showChunkOrigins) {
  354. obj.origins = chunk.origins.map(origin => ({
  355. moduleId: origin.module ? origin.module.id : undefined,
  356. module: origin.module ? origin.module.identifier() : "",
  357. moduleIdentifier: origin.module ? origin.module.identifier() : "",
  358. moduleName: origin.module ? origin.module.readableIdentifier(requestShortener) : "",
  359. loc: formatLocation(origin.loc),
  360. name: origin.name,
  361. reasons: origin.reasons || []
  362. }));
  363. }
  364. return obj;
  365. });
  366. obj.chunks.sort(sortByField(sortChunks));
  367. }
  368. if(showModules) {
  369. obj.modules = compilation.modules
  370. .slice()
  371. .sort(sortByField("depth"))
  372. .filter(createModuleFilter())
  373. .map(fnModule);
  374. obj.filteredModules = compilation.modules.length - obj.modules.length;
  375. obj.modules.sort(sortByField(sortModules));
  376. }
  377. if(showChildren) {
  378. obj.children = compilation.children.map((child, idx) => {
  379. const childOptions = Stats.getChildOptions(options, idx);
  380. const obj = new Stats(child).toJson(childOptions, forToString);
  381. delete obj.hash;
  382. delete obj.version;
  383. if(child.name)
  384. obj.name = identifierUtils.makePathsRelative(context, child.name, compilation.cache);
  385. return obj;
  386. });
  387. }
  388. return obj;
  389. }
  390. toString(options) {
  391. if(typeof options === "boolean" || typeof options === "string") {
  392. options = Stats.presetToOptions(options);
  393. } else if(!options) {
  394. options = {};
  395. }
  396. const useColors = optionsOrFallback(options.colors, false);
  397. const obj = this.toJson(options, true);
  398. return Stats.jsonToString(obj, useColors);
  399. }
  400. static jsonToString(obj, useColors) {
  401. const buf = [];
  402. const defaultColors = {
  403. bold: "\u001b[1m",
  404. yellow: "\u001b[1m\u001b[33m",
  405. red: "\u001b[1m\u001b[31m",
  406. green: "\u001b[1m\u001b[32m",
  407. cyan: "\u001b[1m\u001b[36m",
  408. magenta: "\u001b[1m\u001b[35m"
  409. };
  410. const colors = Object.keys(defaultColors).reduce((obj, color) => {
  411. obj[color] = str => {
  412. if(useColors) {
  413. buf.push(
  414. (useColors === true || useColors[color] === undefined) ?
  415. defaultColors[color] : useColors[color]
  416. );
  417. }
  418. buf.push(str);
  419. if(useColors) {
  420. buf.push("\u001b[39m\u001b[22m");
  421. }
  422. };
  423. return obj;
  424. }, {
  425. normal: (str) => buf.push(str)
  426. });
  427. const coloredTime = (time) => {
  428. let times = [800, 400, 200, 100];
  429. if(obj.time) {
  430. times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16];
  431. }
  432. if(time < times[3])
  433. colors.normal(`${time}ms`);
  434. else if(time < times[2])
  435. colors.bold(`${time}ms`);
  436. else if(time < times[1])
  437. colors.green(`${time}ms`);
  438. else if(time < times[0])
  439. colors.yellow(`${time}ms`);
  440. else
  441. colors.red(`${time}ms`);
  442. };
  443. const newline = () => buf.push("\n");
  444. const getText = (arr, row, col) => {
  445. return arr[row][col].value;
  446. };
  447. const table = (array, align, splitter) => {
  448. const rows = array.length;
  449. const cols = array[0].length;
  450. const colSizes = new Array(cols);
  451. for(let col = 0; col < cols; col++)
  452. colSizes[col] = 0;
  453. for(let row = 0; row < rows; row++) {
  454. for(let col = 0; col < cols; col++) {
  455. const value = `${getText(array, row, col)}`;
  456. if(value.length > colSizes[col]) {
  457. colSizes[col] = value.length;
  458. }
  459. }
  460. }
  461. for(let row = 0; row < rows; row++) {
  462. for(let col = 0; col < cols; col++) {
  463. const format = array[row][col].color;
  464. const value = `${getText(array, row, col)}`;
  465. let l = value.length;
  466. if(align[col] === "l")
  467. format(value);
  468. for(; l < colSizes[col] && col !== cols - 1; l++)
  469. colors.normal(" ");
  470. if(align[col] === "r")
  471. format(value);
  472. if(col + 1 < cols && colSizes[col] !== 0)
  473. colors.normal(splitter || " ");
  474. }
  475. newline();
  476. }
  477. };
  478. const getAssetColor = (asset, defaultColor) => {
  479. if(asset.isOverSizeLimit) {
  480. return colors.yellow;
  481. }
  482. return defaultColor;
  483. };
  484. if(obj.hash) {
  485. colors.normal("Hash: ");
  486. colors.bold(obj.hash);
  487. newline();
  488. }
  489. if(obj.version) {
  490. colors.normal("Version: webpack ");
  491. colors.bold(obj.version);
  492. newline();
  493. }
  494. if(typeof obj.time === "number") {
  495. colors.normal("Time: ");
  496. colors.bold(obj.time);
  497. colors.normal("ms");
  498. newline();
  499. }
  500. if(obj.publicPath) {
  501. colors.normal("PublicPath: ");
  502. colors.bold(obj.publicPath);
  503. newline();
  504. }
  505. if(obj.assets && obj.assets.length > 0) {
  506. const t = [
  507. [{
  508. value: "Asset",
  509. color: colors.bold
  510. }, {
  511. value: "Size",
  512. color: colors.bold
  513. }, {
  514. value: "Chunks",
  515. color: colors.bold
  516. }, {
  517. value: "",
  518. color: colors.bold
  519. }, {
  520. value: "",
  521. color: colors.bold
  522. }, {
  523. value: "Chunk Names",
  524. color: colors.bold
  525. }]
  526. ];
  527. obj.assets.forEach(asset => {
  528. t.push([{
  529. value: asset.name,
  530. color: getAssetColor(asset, colors.green)
  531. }, {
  532. value: SizeFormatHelpers.formatSize(asset.size),
  533. color: getAssetColor(asset, colors.normal)
  534. }, {
  535. value: asset.chunks.join(", "),
  536. color: colors.bold
  537. }, {
  538. value: asset.emitted ? "[emitted]" : "",
  539. color: colors.green
  540. }, {
  541. value: asset.isOverSizeLimit ? "[big]" : "",
  542. color: getAssetColor(asset, colors.normal)
  543. }, {
  544. value: asset.chunkNames.join(", "),
  545. color: colors.normal
  546. }]);
  547. });
  548. table(t, "rrrlll");
  549. }
  550. if(obj.filteredAssets > 0) {
  551. colors.normal(" ");
  552. if(obj.assets.length > 0)
  553. colors.normal("+ ");
  554. colors.normal(obj.filteredAssets);
  555. if(obj.assets.length > 0)
  556. colors.normal(" hidden");
  557. colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset");
  558. newline();
  559. }
  560. if(obj.entrypoints) {
  561. Object.keys(obj.entrypoints).forEach(name => {
  562. const ep = obj.entrypoints[name];
  563. colors.normal("Entrypoint ");
  564. colors.bold(name);
  565. if(ep.isOverSizeLimit) {
  566. colors.normal(" ");
  567. colors.yellow("[big]");
  568. }
  569. colors.normal(" =");
  570. ep.assets.forEach(asset => {
  571. colors.normal(" ");
  572. colors.green(asset);
  573. });
  574. newline();
  575. });
  576. }
  577. const modulesByIdentifier = {};
  578. if(obj.modules) {
  579. obj.modules.forEach(module => {
  580. modulesByIdentifier[`$${module.identifier}`] = module;
  581. });
  582. } else if(obj.chunks) {
  583. obj.chunks.forEach(chunk => {
  584. if(chunk.modules) {
  585. chunk.modules.forEach(module => {
  586. modulesByIdentifier[`$${module.identifier}`] = module;
  587. });
  588. }
  589. });
  590. }
  591. const processModuleAttributes = (module) => {
  592. colors.normal(" ");
  593. colors.normal(SizeFormatHelpers.formatSize(module.size));
  594. if(module.chunks) {
  595. module.chunks.forEach(chunk => {
  596. colors.normal(" {");
  597. colors.yellow(chunk);
  598. colors.normal("}");
  599. });
  600. }
  601. if(typeof module.depth === "number") {
  602. colors.normal(` [depth ${module.depth}]`);
  603. }
  604. if(!module.cacheable) {
  605. colors.red(" [not cacheable]");
  606. }
  607. if(module.optional) {
  608. colors.yellow(" [optional]");
  609. }
  610. if(module.built) {
  611. colors.green(" [built]");
  612. }
  613. if(module.prefetched) {
  614. colors.magenta(" [prefetched]");
  615. }
  616. if(module.failed)
  617. colors.red(" [failed]");
  618. if(module.warnings)
  619. colors.yellow(` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]`);
  620. if(module.errors)
  621. colors.red(` [${module.errors} error${module.errors === 1 ? "" : "s"}]`);
  622. };
  623. const processModuleContent = (module, prefix) => {
  624. if(Array.isArray(module.providedExports)) {
  625. colors.normal(prefix);
  626. if(module.providedExports.length === 0)
  627. colors.cyan("[no exports]");
  628. else
  629. colors.cyan(`[exports: ${module.providedExports.join(", ")}]`);
  630. newline();
  631. }
  632. if(module.usedExports !== undefined) {
  633. if(module.usedExports !== true) {
  634. colors.normal(prefix);
  635. if(module.usedExports === false || module.usedExports.length === 0)
  636. colors.cyan("[no exports used]");
  637. else
  638. colors.cyan(`[only some exports used: ${module.usedExports.join(", ")}]`);
  639. newline();
  640. }
  641. }
  642. if(Array.isArray(module.optimizationBailout)) {
  643. module.optimizationBailout.forEach(item => {
  644. colors.normal(prefix);
  645. colors.yellow(item);
  646. newline();
  647. });
  648. }
  649. if(module.reasons) {
  650. module.reasons.forEach(reason => {
  651. colors.normal(prefix);
  652. colors.normal(reason.type);
  653. colors.normal(" ");
  654. colors.cyan(reason.userRequest);
  655. colors.normal(" [");
  656. colors.normal(reason.moduleId);
  657. colors.normal("] ");
  658. colors.magenta(reason.module);
  659. if(reason.loc) {
  660. colors.normal(" ");
  661. colors.normal(reason.loc);
  662. }
  663. newline();
  664. });
  665. }
  666. if(module.profile) {
  667. colors.normal(prefix);
  668. let sum = 0;
  669. const path = [];
  670. let current = module;
  671. while(current.issuer) {
  672. path.push(current = current.issuer);
  673. }
  674. path.reverse().forEach(module => {
  675. colors.normal("[");
  676. colors.normal(module.id);
  677. colors.normal("] ");
  678. if(module.profile) {
  679. const time = (module.profile.factory || 0) + (module.profile.building || 0);
  680. coloredTime(time);
  681. sum += time;
  682. colors.normal(" ");
  683. }
  684. colors.normal("->");
  685. });
  686. Object.keys(module.profile).forEach(key => {
  687. colors.normal(` ${key}:`);
  688. const time = module.profile[key];
  689. coloredTime(time);
  690. sum += time;
  691. });
  692. colors.normal(" = ");
  693. coloredTime(sum);
  694. newline();
  695. }
  696. };
  697. const processModulesList = (obj, prefix) => {
  698. if(obj.modules) {
  699. obj.modules.forEach(module => {
  700. colors.normal(prefix);
  701. if(module.id < 1000) colors.normal(" ");
  702. if(module.id < 100) colors.normal(" ");
  703. if(module.id < 10) colors.normal(" ");
  704. colors.normal("[");
  705. colors.normal(module.id);
  706. colors.normal("] ");
  707. colors.bold(module.name || module.identifier);
  708. processModuleAttributes(module);
  709. newline();
  710. processModuleContent(module, prefix + " ");
  711. });
  712. if(obj.filteredModules > 0) {
  713. colors.normal(prefix);
  714. colors.normal(" ");
  715. if(obj.modules.length > 0)
  716. colors.normal(" + ");
  717. colors.normal(obj.filteredModules);
  718. if(obj.modules.length > 0)
  719. colors.normal(" hidden");
  720. colors.normal(obj.filteredModules !== 1 ? " modules" : " module");
  721. newline();
  722. }
  723. }
  724. };
  725. if(obj.chunks) {
  726. obj.chunks.forEach(chunk => {
  727. colors.normal("chunk ");
  728. if(chunk.id < 1000) colors.normal(" ");
  729. if(chunk.id < 100) colors.normal(" ");
  730. if(chunk.id < 10) colors.normal(" ");
  731. colors.normal("{");
  732. colors.yellow(chunk.id);
  733. colors.normal("} ");
  734. colors.green(chunk.files.join(", "));
  735. if(chunk.names && chunk.names.length > 0) {
  736. colors.normal(" (");
  737. colors.normal(chunk.names.join(", "));
  738. colors.normal(")");
  739. }
  740. colors.normal(" ");
  741. colors.normal(SizeFormatHelpers.formatSize(chunk.size));
  742. chunk.parents.forEach(id => {
  743. colors.normal(" {");
  744. colors.yellow(id);
  745. colors.normal("}");
  746. });
  747. if(chunk.entry) {
  748. colors.yellow(" [entry]");
  749. } else if(chunk.initial) {
  750. colors.yellow(" [initial]");
  751. }
  752. if(chunk.rendered) {
  753. colors.green(" [rendered]");
  754. }
  755. if(chunk.recorded) {
  756. colors.green(" [recorded]");
  757. }
  758. newline();
  759. if(chunk.origins) {
  760. chunk.origins.forEach(origin => {
  761. colors.normal(" > ");
  762. if(origin.reasons && origin.reasons.length) {
  763. colors.yellow(origin.reasons.join(" "));
  764. colors.normal(" ");
  765. }
  766. if(origin.name) {
  767. colors.normal(origin.name);
  768. colors.normal(" ");
  769. }
  770. if(origin.module) {
  771. colors.normal("[");
  772. colors.normal(origin.moduleId);
  773. colors.normal("] ");
  774. const module = modulesByIdentifier[`$${origin.module}`];
  775. if(module) {
  776. colors.bold(module.name);
  777. colors.normal(" ");
  778. }
  779. if(origin.loc) {
  780. colors.normal(origin.loc);
  781. }
  782. }
  783. newline();
  784. });
  785. }
  786. processModulesList(chunk, " ");
  787. });
  788. }
  789. processModulesList(obj, "");
  790. if(obj._showWarnings && obj.warnings) {
  791. obj.warnings.forEach(warning => {
  792. newline();
  793. colors.yellow(`WARNING in ${warning}`);
  794. newline();
  795. });
  796. }
  797. if(obj._showErrors && obj.errors) {
  798. obj.errors.forEach(error => {
  799. newline();
  800. colors.red(`ERROR in ${error}`);
  801. newline();
  802. });
  803. }
  804. if(obj.children) {
  805. obj.children.forEach(child => {
  806. const childString = Stats.jsonToString(child, useColors);
  807. if(childString) {
  808. if(child.name) {
  809. colors.normal("Child ");
  810. colors.bold(child.name);
  811. colors.normal(":");
  812. } else {
  813. colors.normal("Child");
  814. }
  815. newline();
  816. buf.push(" ");
  817. buf.push(childString.replace(/\n/g, "\n "));
  818. newline();
  819. }
  820. });
  821. }
  822. if(obj.needAdditionalPass) {
  823. colors.yellow("Compilation needs an additional pass and will compile again.");
  824. }
  825. while(buf[buf.length - 1] === "\n") buf.pop();
  826. return buf.join("");
  827. }
  828. static presetToOptions(name) {
  829. // Accepted values: none, errors-only, minimal, normal, detailed, verbose
  830. // Any other falsy value will behave as 'none', truthy values as 'normal'
  831. const pn = (typeof name === "string") && name.toLowerCase() || name || "none";
  832. switch(pn) {
  833. case "none":
  834. return {
  835. all: false
  836. };
  837. case "verbose":
  838. return {
  839. entrypoints: true,
  840. modules: false,
  841. chunks: true,
  842. chunkModules: true,
  843. chunkOrigins: true,
  844. depth: true,
  845. reasons: true,
  846. usedExports: true,
  847. providedExports: true,
  848. optimizationBailout: true,
  849. errorDetails: true,
  850. publicPath: true,
  851. exclude: () => false,
  852. maxModules: Infinity,
  853. };
  854. case "detailed":
  855. return {
  856. entrypoints: true,
  857. chunks: true,
  858. chunkModules: false,
  859. chunkOrigins: true,
  860. depth: true,
  861. usedExports: true,
  862. providedExports: true,
  863. optimizationBailout: true,
  864. errorDetails: true,
  865. publicPath: true,
  866. exclude: () => false,
  867. maxModules: Infinity,
  868. };
  869. case "minimal":
  870. return {
  871. all: false,
  872. modules: true,
  873. maxModules: 0,
  874. errors: true,
  875. warnings: true,
  876. };
  877. case "errors-only":
  878. return {
  879. all: false,
  880. errors: true,
  881. moduleTrace: true,
  882. };
  883. default:
  884. return {};
  885. }
  886. }
  887. static getChildOptions(options, idx) {
  888. let innerOptions;
  889. if(Array.isArray(options.children)) {
  890. if(idx < options.children.length)
  891. innerOptions = options.children[idx];
  892. } else if(typeof options.children === "object" && options.children) {
  893. innerOptions = options.children;
  894. }
  895. if(typeof innerOptions === "boolean" || typeof innerOptions === "string")
  896. innerOptions = Stats.presetToOptions(innerOptions);
  897. if(!innerOptions)
  898. return options;
  899. const childOptions = Object.assign({}, options);
  900. delete childOptions.children; // do not inherit children
  901. return Object.assign(childOptions, innerOptions);
  902. }
  903. }
  904. module.exports = Stats;