DefaultStatsFactoryPlugin.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const ModuleDependency = require("../dependencies/ModuleDependency");
  8. const formatLocation = require("../formatLocation");
  9. const { LogType } = require("../logging/Logger");
  10. const AggressiveSplittingPlugin = require("../optimize/AggressiveSplittingPlugin");
  11. const SizeLimitsPlugin = require("../performance/SizeLimitsPlugin");
  12. const { countIterable } = require("../util/IterableHelpers");
  13. const {
  14. compareLocations,
  15. compareChunksById,
  16. compareNumbers,
  17. compareIds,
  18. concatComparators,
  19. compareSelect,
  20. compareModulesByIdentifier
  21. } = require("../util/comparators");
  22. const { makePathsRelative, parseResource } = require("../util/identifier");
  23. /** @typedef {import("webpack-sources").Source} Source */
  24. /** @typedef {import("../Chunk")} Chunk */
  25. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  26. /** @typedef {import("../ChunkGroup").OriginRecord} OriginRecord */
  27. /** @typedef {import("../Compilation")} Compilation */
  28. /** @typedef {import("../Compilation").Asset} Asset */
  29. /** @typedef {import("../Compilation").AssetInfo} AssetInfo */
  30. /** @typedef {import("../Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
  31. /** @typedef {import("../Compiler")} Compiler */
  32. /** @typedef {import("../Dependency")} Dependency */
  33. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  34. /** @typedef {import("../Module")} Module */
  35. /** @typedef {import("../ModuleGraphConnection")} ModuleGraphConnection */
  36. /** @typedef {import("../ModuleProfile")} ModuleProfile */
  37. /** @typedef {import("../RequestShortener")} RequestShortener */
  38. /** @typedef {import("../WebpackError")} WebpackError */
  39. /** @template T @typedef {import("../util/comparators").Comparator<T>} Comparator<T> */
  40. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  41. /** @typedef {import("../util/smartGrouping").GroupConfig<any, object>} GroupConfig */
  42. /** @typedef {import("./StatsFactory")} StatsFactory */
  43. /** @typedef {import("./StatsFactory").StatsFactoryContext} StatsFactoryContext */
  44. /** @typedef {KnownStatsCompilation & Record<string, any>} StatsCompilation */
  45. /**
  46. * @typedef {Object} KnownStatsCompilation
  47. * @property {any=} env
  48. * @property {string=} name
  49. * @property {string=} hash
  50. * @property {string=} version
  51. * @property {number=} time
  52. * @property {number=} builtAt
  53. * @property {boolean=} needAdditionalPass
  54. * @property {string=} publicPath
  55. * @property {string=} outputPath
  56. * @property {Record<string, string[]>=} assetsByChunkName
  57. * @property {StatsAsset[]=} assets
  58. * @property {number=} filteredAssets
  59. * @property {StatsChunk[]=} chunks
  60. * @property {StatsModule[]=} modules
  61. * @property {number=} filteredModules
  62. * @property {Record<string, StatsChunkGroup>=} entrypoints
  63. * @property {Record<string, StatsChunkGroup>=} namedChunkGroups
  64. * @property {StatsError[]=} errors
  65. * @property {number=} errorsCount
  66. * @property {StatsError[]=} warnings
  67. * @property {number=} warningsCount
  68. * @property {StatsCompilation[]=} children
  69. * @property {Record<string, StatsLogging>=} logging
  70. */
  71. /** @typedef {KnownStatsLogging & Record<string, any>} StatsLogging */
  72. /**
  73. * @typedef {Object} KnownStatsLogging
  74. * @property {StatsLoggingEntry[]} entries
  75. * @property {number} filteredEntries
  76. * @property {boolean} debug
  77. */
  78. /** @typedef {KnownStatsLoggingEntry & Record<string, any>} StatsLoggingEntry */
  79. /**
  80. * @typedef {Object} KnownStatsLoggingEntry
  81. * @property {string} type
  82. * @property {string} message
  83. * @property {string[]=} trace
  84. * @property {StatsLoggingEntry[]=} children
  85. * @property {any[]=} args
  86. * @property {number=} time
  87. */
  88. /** @typedef {KnownStatsAsset & Record<string, any>} StatsAsset */
  89. /**
  90. * @typedef {Object} KnownStatsAsset
  91. * @property {string} type
  92. * @property {string} name
  93. * @property {AssetInfo} info
  94. * @property {number} size
  95. * @property {boolean} emitted
  96. * @property {boolean} comparedForEmit
  97. * @property {boolean} cached
  98. * @property {StatsAsset[]=} related
  99. * @property {(string|number)[]=} chunkNames
  100. * @property {(string|number)[]=} chunkIdHints
  101. * @property {(string|number)[]=} chunks
  102. * @property {(string|number)[]=} auxiliaryChunkNames
  103. * @property {(string|number)[]=} auxiliaryChunks
  104. * @property {(string|number)[]=} auxiliaryChunkIdHints
  105. * @property {number=} filteredRelated
  106. * @property {boolean=} isOverSizeLimit
  107. */
  108. /** @typedef {KnownStatsChunkGroup & Record<string, any>} StatsChunkGroup */
  109. /**
  110. * @typedef {Object} KnownStatsChunkGroup
  111. * @property {string=} name
  112. * @property {(string|number)[]=} chunks
  113. * @property {({ name: string, size?: number })[]=} assets
  114. * @property {number=} filteredAssets
  115. * @property {number=} assetsSize
  116. * @property {({ name: string, size?: number })[]=} auxiliaryAssets
  117. * @property {number=} filteredAuxiliaryAssets
  118. * @property {number=} auxiliaryAssetsSize
  119. * @property {{ [x: string]: StatsChunkGroup[] }=} children
  120. * @property {{ [x: string]: string[] }=} childAssets
  121. * @property {boolean=} isOverSizeLimit
  122. */
  123. /** @typedef {KnownStatsModule & Record<string, any>} StatsModule */
  124. /**
  125. * @typedef {Object} KnownStatsModule
  126. * @property {string=} type
  127. * @property {string=} moduleType
  128. * @property {string=} layer
  129. * @property {string=} identifier
  130. * @property {string=} name
  131. * @property {string=} nameForCondition
  132. * @property {number=} index
  133. * @property {number=} preOrderIndex
  134. * @property {number=} index2
  135. * @property {number=} postOrderIndex
  136. * @property {number=} size
  137. * @property {{[x: string]: number}=} sizes
  138. * @property {boolean=} cacheable
  139. * @property {boolean=} built
  140. * @property {boolean=} codeGenerated
  141. * @property {boolean=} buildTimeExecuted
  142. * @property {boolean=} cached
  143. * @property {boolean=} optional
  144. * @property {boolean=} orphan
  145. * @property {string|number=} id
  146. * @property {string|number=} issuerId
  147. * @property {(string|number)[]=} chunks
  148. * @property {(string|number)[]=} assets
  149. * @property {boolean=} dependent
  150. * @property {string=} issuer
  151. * @property {string=} issuerName
  152. * @property {StatsModuleIssuer[]=} issuerPath
  153. * @property {boolean=} failed
  154. * @property {number=} errors
  155. * @property {number=} warnings
  156. * @property {StatsProfile=} profile
  157. * @property {StatsModuleReason[]=} reasons
  158. * @property {(boolean | string[])=} usedExports
  159. * @property {string[]=} providedExports
  160. * @property {string[]=} optimizationBailout
  161. * @property {number=} depth
  162. * @property {StatsModule[]=} modules
  163. * @property {number=} filteredModules
  164. * @property {ReturnType<Source["source"]>=} source
  165. */
  166. /** @typedef {KnownStatsProfile & Record<string, any>} StatsProfile */
  167. /**
  168. * @typedef {Object} KnownStatsProfile
  169. * @property {number} total
  170. * @property {number} resolving
  171. * @property {number} restoring
  172. * @property {number} building
  173. * @property {number} integration
  174. * @property {number} storing
  175. * @property {number} additionalResolving
  176. * @property {number} additionalIntegration
  177. * @property {number} factory
  178. * @property {number} dependencies
  179. */
  180. /** @typedef {KnownStatsModuleIssuer & Record<string, any>} StatsModuleIssuer */
  181. /**
  182. * @typedef {Object} KnownStatsModuleIssuer
  183. * @property {string=} identifier
  184. * @property {string=} name
  185. * @property {(string|number)=} id
  186. * @property {StatsProfile=} profile
  187. */
  188. /** @typedef {KnownStatsModuleReason & Record<string, any>} StatsModuleReason */
  189. /**
  190. * @typedef {Object} KnownStatsModuleReason
  191. * @property {string=} moduleIdentifier
  192. * @property {string=} module
  193. * @property {string=} moduleName
  194. * @property {string=} resolvedModuleIdentifier
  195. * @property {string=} resolvedModule
  196. * @property {string=} type
  197. * @property {boolean} active
  198. * @property {string=} explanation
  199. * @property {string=} userRequest
  200. * @property {string=} loc
  201. * @property {(string|number)=} moduleId
  202. * @property {(string|number)=} resolvedModuleId
  203. */
  204. /** @typedef {KnownStatsChunk & Record<string, any>} StatsChunk */
  205. /**
  206. * @typedef {Object} KnownStatsChunk
  207. * @property {boolean} rendered
  208. * @property {boolean} initial
  209. * @property {boolean} entry
  210. * @property {boolean} recorded
  211. * @property {string=} reason
  212. * @property {number} size
  213. * @property {Record<string, number>=} sizes
  214. * @property {string[]=} names
  215. * @property {string[]=} idHints
  216. * @property {string[]=} runtime
  217. * @property {string[]=} files
  218. * @property {string[]=} auxiliaryFiles
  219. * @property {string} hash
  220. * @property {Record<string, (string|number)[]>=} childrenByOrder
  221. * @property {(string|number)=} id
  222. * @property {(string|number)[]=} siblings
  223. * @property {(string|number)[]=} parents
  224. * @property {(string|number)[]=} children
  225. * @property {StatsModule[]=} modules
  226. * @property {number=} filteredModules
  227. * @property {StatsChunkOrigin[]=} origins
  228. */
  229. /** @typedef {KnownStatsChunkOrigin & Record<string, any>} StatsChunkOrigin */
  230. /**
  231. * @typedef {Object} KnownStatsChunkOrigin
  232. * @property {string=} module
  233. * @property {string=} moduleIdentifier
  234. * @property {string=} moduleName
  235. * @property {string=} loc
  236. * @property {string=} request
  237. * @property {(string|number)=} moduleId
  238. */
  239. /** @typedef {KnownStatsModuleTraceItem & Record<string, any>} StatsModuleTraceItem */
  240. /**
  241. * @typedef {Object} KnownStatsModuleTraceItem
  242. * @property {string=} originIdentifier
  243. * @property {string=} originName
  244. * @property {string=} moduleIdentifier
  245. * @property {string=} moduleName
  246. * @property {StatsModuleTraceDependency[]=} dependencies
  247. * @property {(string|number)=} originId
  248. * @property {(string|number)=} moduleId
  249. */
  250. /** @typedef {KnownStatsModuleTraceDependency & Record<string, any>} StatsModuleTraceDependency */
  251. /**
  252. * @typedef {Object} KnownStatsModuleTraceDependency
  253. * @property {string=} loc
  254. */
  255. /** @typedef {KnownStatsError & Record<string, any>} StatsError */
  256. /**
  257. * @typedef {Object} KnownStatsError
  258. * @property {string} message
  259. * @property {string=} chunkName
  260. * @property {boolean=} chunkEntry
  261. * @property {boolean=} chunkInitial
  262. * @property {string=} file
  263. * @property {string=} moduleIdentifier
  264. * @property {string=} moduleName
  265. * @property {string=} loc
  266. * @property {string|number=} chunkId
  267. * @property {string|number=} moduleId
  268. * @property {StatsModuleTraceItem[]=} moduleTrace
  269. * @property {any=} details
  270. * @property {string=} stack
  271. */
  272. /** @typedef {Asset & { type: string, related: PreprocessedAsset[] }} PreprocessedAsset */
  273. /**
  274. * @template T
  275. * @template O
  276. * @typedef {Record<string, (object: O, data: T, context: StatsFactoryContext, options: NormalizedStatsOptions, factory: StatsFactory) => void>} ExtractorsByOption
  277. */
  278. /**
  279. * @typedef {Object} SimpleExtractors
  280. * @property {ExtractorsByOption<Compilation, StatsCompilation>} compilation
  281. * @property {ExtractorsByOption<PreprocessedAsset, StatsAsset>} asset
  282. * @property {ExtractorsByOption<PreprocessedAsset, StatsAsset>} asset$visible
  283. * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }, StatsChunkGroup>} chunkGroup
  284. * @property {ExtractorsByOption<Module, StatsModule>} module
  285. * @property {ExtractorsByOption<Module, StatsModule>} module$visible
  286. * @property {ExtractorsByOption<Module, StatsModuleIssuer>} moduleIssuer
  287. * @property {ExtractorsByOption<ModuleProfile, StatsProfile>} profile
  288. * @property {ExtractorsByOption<ModuleGraphConnection, StatsModuleReason>} moduleReason
  289. * @property {ExtractorsByOption<Chunk, StatsChunk>} chunk
  290. * @property {ExtractorsByOption<OriginRecord, StatsChunkOrigin>} chunkOrigin
  291. * @property {ExtractorsByOption<WebpackError, StatsError>} error
  292. * @property {ExtractorsByOption<WebpackError, StatsError>} warning
  293. * @property {ExtractorsByOption<{ origin: Module, module: Module }, StatsModuleTraceItem>} moduleTraceItem
  294. * @property {ExtractorsByOption<Dependency, StatsModuleTraceDependency>} moduleTraceDependency
  295. */
  296. /**
  297. * @template T
  298. * @template I
  299. * @param {Iterable<T>} items items to select from
  300. * @param {function(T): Iterable<I>} selector selector function to select values from item
  301. * @returns {I[]} array of values
  302. */
  303. const uniqueArray = (items, selector) => {
  304. /** @type {Set<I>} */
  305. const set = new Set();
  306. for (const item of items) {
  307. for (const i of selector(item)) {
  308. set.add(i);
  309. }
  310. }
  311. return Array.from(set);
  312. };
  313. /**
  314. * @template T
  315. * @template I
  316. * @param {Iterable<T>} items items to select from
  317. * @param {function(T): Iterable<I>} selector selector function to select values from item
  318. * @param {Comparator<I>} comparator comparator function
  319. * @returns {I[]} array of values
  320. */
  321. const uniqueOrderedArray = (items, selector, comparator) => {
  322. return uniqueArray(items, selector).sort(comparator);
  323. };
  324. /** @template T @template R @typedef {{ [P in keyof T]: R }} MappedValues<T, R> */
  325. /**
  326. * @template T
  327. * @template R
  328. * @param {T} obj object to be mapped
  329. * @param {function(T[keyof T], keyof T): R} fn mapping function
  330. * @returns {MappedValues<T, R>} mapped object
  331. */
  332. const mapObject = (obj, fn) => {
  333. const newObj = Object.create(null);
  334. for (const key of Object.keys(obj)) {
  335. newObj[key] = fn(obj[key], /** @type {keyof T} */ (key));
  336. }
  337. return newObj;
  338. };
  339. /**
  340. * @param {Compilation} compilation the compilation
  341. * @param {function(Compilation, string): any[]} getItems get items
  342. * @returns {number} total number
  343. */
  344. const countWithChildren = (compilation, getItems) => {
  345. let count = getItems(compilation, "").length;
  346. for (const child of compilation.children) {
  347. count += countWithChildren(child, (c, type) =>
  348. getItems(c, `.children[].compilation${type}`)
  349. );
  350. }
  351. return count;
  352. };
  353. /** @type {ExtractorsByOption<WebpackError | string, StatsError>} */
  354. const EXTRACT_ERROR = {
  355. _: (object, error, context, { requestShortener }) => {
  356. // TODO webpack 6 disallow strings in the errors/warnings list
  357. if (typeof error === "string") {
  358. object.message = error;
  359. } else {
  360. if (error.chunk) {
  361. object.chunkName = error.chunk.name;
  362. object.chunkEntry = error.chunk.hasRuntime();
  363. object.chunkInitial = error.chunk.canBeInitial();
  364. }
  365. if (error.file) {
  366. object.file = error.file;
  367. }
  368. if (error.module) {
  369. object.moduleIdentifier = error.module.identifier();
  370. object.moduleName = error.module.readableIdentifier(requestShortener);
  371. }
  372. if (error.loc) {
  373. object.loc = formatLocation(error.loc);
  374. }
  375. object.message = error.message;
  376. }
  377. },
  378. ids: (object, error, { compilation: { chunkGraph } }) => {
  379. if (typeof error !== "string") {
  380. if (error.chunk) {
  381. object.chunkId = error.chunk.id;
  382. }
  383. if (error.module) {
  384. object.moduleId = chunkGraph.getModuleId(error.module);
  385. }
  386. }
  387. },
  388. moduleTrace: (object, error, context, options, factory) => {
  389. if (typeof error !== "string" && error.module) {
  390. const {
  391. type,
  392. compilation: { moduleGraph }
  393. } = context;
  394. /** @type {Set<Module>} */
  395. const visitedModules = new Set();
  396. const moduleTrace = [];
  397. let current = error.module;
  398. while (current) {
  399. if (visitedModules.has(current)) break; // circular (technically impossible, but how knows)
  400. visitedModules.add(current);
  401. const origin = moduleGraph.getIssuer(current);
  402. if (!origin) break;
  403. moduleTrace.push({ origin, module: current });
  404. current = origin;
  405. }
  406. object.moduleTrace = factory.create(
  407. `${type}.moduleTrace`,
  408. moduleTrace,
  409. context
  410. );
  411. }
  412. },
  413. errorDetails: (
  414. object,
  415. error,
  416. { type, compilation, cachedGetErrors, cachedGetWarnings },
  417. { errorDetails }
  418. ) => {
  419. if (
  420. typeof error !== "string" &&
  421. (errorDetails === true ||
  422. (type.endsWith(".error") && cachedGetErrors(compilation).length < 3))
  423. ) {
  424. object.details = error.details;
  425. }
  426. },
  427. errorStack: (object, error) => {
  428. if (typeof error !== "string") {
  429. object.stack = error.stack;
  430. }
  431. }
  432. };
  433. /** @type {SimpleExtractors} */
  434. const SIMPLE_EXTRACTORS = {
  435. compilation: {
  436. _: (object, compilation, context, options) => {
  437. if (!context.makePathsRelative) {
  438. context.makePathsRelative = makePathsRelative.bindContextCache(
  439. compilation.compiler.context,
  440. compilation.compiler.root
  441. );
  442. }
  443. if (!context.cachedGetErrors) {
  444. const map = new WeakMap();
  445. context.cachedGetErrors = compilation => {
  446. return (
  447. map.get(compilation) ||
  448. (errors => (map.set(compilation, errors), errors))(
  449. compilation.getErrors()
  450. )
  451. );
  452. };
  453. }
  454. if (!context.cachedGetWarnings) {
  455. const map = new WeakMap();
  456. context.cachedGetWarnings = compilation => {
  457. return (
  458. map.get(compilation) ||
  459. (warnings => (map.set(compilation, warnings), warnings))(
  460. compilation.getWarnings()
  461. )
  462. );
  463. };
  464. }
  465. if (compilation.name) {
  466. object.name = compilation.name;
  467. }
  468. if (compilation.needAdditionalPass) {
  469. object.needAdditionalPass = true;
  470. }
  471. const { logging, loggingDebug, loggingTrace } = options;
  472. if (logging || (loggingDebug && loggingDebug.length > 0)) {
  473. const util = require("util");
  474. object.logging = {};
  475. let acceptedTypes;
  476. let collapsedGroups = false;
  477. switch (logging) {
  478. default:
  479. acceptedTypes = new Set();
  480. break;
  481. case "error":
  482. acceptedTypes = new Set([LogType.error]);
  483. break;
  484. case "warn":
  485. acceptedTypes = new Set([LogType.error, LogType.warn]);
  486. break;
  487. case "info":
  488. acceptedTypes = new Set([
  489. LogType.error,
  490. LogType.warn,
  491. LogType.info
  492. ]);
  493. break;
  494. case "log":
  495. acceptedTypes = new Set([
  496. LogType.error,
  497. LogType.warn,
  498. LogType.info,
  499. LogType.log,
  500. LogType.group,
  501. LogType.groupEnd,
  502. LogType.groupCollapsed,
  503. LogType.clear
  504. ]);
  505. break;
  506. case "verbose":
  507. acceptedTypes = new Set([
  508. LogType.error,
  509. LogType.warn,
  510. LogType.info,
  511. LogType.log,
  512. LogType.group,
  513. LogType.groupEnd,
  514. LogType.groupCollapsed,
  515. LogType.profile,
  516. LogType.profileEnd,
  517. LogType.time,
  518. LogType.status,
  519. LogType.clear
  520. ]);
  521. collapsedGroups = true;
  522. break;
  523. }
  524. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  525. options.context,
  526. compilation.compiler.root
  527. );
  528. let depthInCollapsedGroup = 0;
  529. for (const [origin, logEntries] of compilation.logging) {
  530. const debugMode = loggingDebug.some(fn => fn(origin));
  531. if (logging === false && !debugMode) continue;
  532. /** @type {KnownStatsLoggingEntry[]} */
  533. const groupStack = [];
  534. /** @type {KnownStatsLoggingEntry[]} */
  535. const rootList = [];
  536. let currentList = rootList;
  537. let processedLogEntries = 0;
  538. for (const entry of logEntries) {
  539. let type = entry.type;
  540. if (!debugMode && !acceptedTypes.has(type)) continue;
  541. // Expand groups in verbose and debug modes
  542. if (
  543. type === LogType.groupCollapsed &&
  544. (debugMode || collapsedGroups)
  545. )
  546. type = LogType.group;
  547. if (depthInCollapsedGroup === 0) {
  548. processedLogEntries++;
  549. }
  550. if (type === LogType.groupEnd) {
  551. groupStack.pop();
  552. if (groupStack.length > 0) {
  553. currentList = groupStack[groupStack.length - 1].children;
  554. } else {
  555. currentList = rootList;
  556. }
  557. if (depthInCollapsedGroup > 0) depthInCollapsedGroup--;
  558. continue;
  559. }
  560. let message = undefined;
  561. if (entry.type === LogType.time) {
  562. message = `${entry.args[0]}: ${
  563. entry.args[1] * 1000 + entry.args[2] / 1000000
  564. } ms`;
  565. } else if (entry.args && entry.args.length > 0) {
  566. message = util.format(entry.args[0], ...entry.args.slice(1));
  567. }
  568. /** @type {KnownStatsLoggingEntry} */
  569. const newEntry = {
  570. ...entry,
  571. type,
  572. message,
  573. trace: loggingTrace ? entry.trace : undefined,
  574. children:
  575. type === LogType.group || type === LogType.groupCollapsed
  576. ? []
  577. : undefined
  578. };
  579. currentList.push(newEntry);
  580. if (newEntry.children) {
  581. groupStack.push(newEntry);
  582. currentList = newEntry.children;
  583. if (depthInCollapsedGroup > 0) {
  584. depthInCollapsedGroup++;
  585. } else if (type === LogType.groupCollapsed) {
  586. depthInCollapsedGroup = 1;
  587. }
  588. }
  589. }
  590. let name = cachedMakePathsRelative(origin).replace(/\|/g, " ");
  591. if (name in object.logging) {
  592. let i = 1;
  593. while (`${name}#${i}` in object.logging) {
  594. i++;
  595. }
  596. name = `${name}#${i}`;
  597. }
  598. object.logging[name] = {
  599. entries: rootList,
  600. filteredEntries: logEntries.length - processedLogEntries,
  601. debug: debugMode
  602. };
  603. }
  604. }
  605. },
  606. hash: (object, compilation) => {
  607. object.hash = compilation.hash;
  608. },
  609. version: object => {
  610. object.version = require("../../package.json").version;
  611. },
  612. env: (object, compilation, context, { _env }) => {
  613. object.env = _env;
  614. },
  615. timings: (object, compilation) => {
  616. object.time = compilation.endTime - compilation.startTime;
  617. },
  618. builtAt: (object, compilation) => {
  619. object.builtAt = compilation.endTime;
  620. },
  621. publicPath: (object, compilation) => {
  622. object.publicPath = compilation.getPath(
  623. compilation.outputOptions.publicPath
  624. );
  625. },
  626. outputPath: (object, compilation) => {
  627. object.outputPath = compilation.outputOptions.path;
  628. },
  629. assets: (object, compilation, context, options, factory) => {
  630. const { type } = context;
  631. /** @type {Map<string, Chunk[]>} */
  632. const compilationFileToChunks = new Map();
  633. /** @type {Map<string, Chunk[]>} */
  634. const compilationAuxiliaryFileToChunks = new Map();
  635. for (const chunk of compilation.chunks) {
  636. for (const file of chunk.files) {
  637. let array = compilationFileToChunks.get(file);
  638. if (array === undefined) {
  639. array = [];
  640. compilationFileToChunks.set(file, array);
  641. }
  642. array.push(chunk);
  643. }
  644. for (const file of chunk.auxiliaryFiles) {
  645. let array = compilationAuxiliaryFileToChunks.get(file);
  646. if (array === undefined) {
  647. array = [];
  648. compilationAuxiliaryFileToChunks.set(file, array);
  649. }
  650. array.push(chunk);
  651. }
  652. }
  653. /** @type {Map<string, PreprocessedAsset>} */
  654. const assetMap = new Map();
  655. /** @type {Set<PreprocessedAsset>} */
  656. const assets = new Set();
  657. for (const asset of compilation.getAssets()) {
  658. /** @type {PreprocessedAsset} */
  659. const item = {
  660. ...asset,
  661. type: "asset",
  662. related: undefined
  663. };
  664. assets.add(item);
  665. assetMap.set(asset.name, item);
  666. }
  667. for (const item of assetMap.values()) {
  668. const related = item.info.related;
  669. if (!related) continue;
  670. for (const type of Object.keys(related)) {
  671. const relatedEntry = related[type];
  672. const deps = Array.isArray(relatedEntry)
  673. ? relatedEntry
  674. : [relatedEntry];
  675. for (const dep of deps) {
  676. const depItem = assetMap.get(dep);
  677. if (!depItem) continue;
  678. assets.delete(depItem);
  679. depItem.type = type;
  680. item.related = item.related || [];
  681. item.related.push(depItem);
  682. }
  683. }
  684. }
  685. object.assetsByChunkName = {};
  686. for (const [file, chunks] of compilationFileToChunks) {
  687. for (const chunk of chunks) {
  688. const name = chunk.name;
  689. if (!name) continue;
  690. if (
  691. !Object.prototype.hasOwnProperty.call(
  692. object.assetsByChunkName,
  693. name
  694. )
  695. ) {
  696. object.assetsByChunkName[name] = [];
  697. }
  698. object.assetsByChunkName[name].push(file);
  699. }
  700. }
  701. const groupedAssets = factory.create(
  702. `${type}.assets`,
  703. Array.from(assets),
  704. {
  705. ...context,
  706. compilationFileToChunks,
  707. compilationAuxiliaryFileToChunks
  708. }
  709. );
  710. const limited = spaceLimited(groupedAssets, options.assetsSpace);
  711. object.assets = limited.children;
  712. object.filteredAssets = limited.filteredChildren;
  713. },
  714. chunks: (object, compilation, context, options, factory) => {
  715. const { type } = context;
  716. object.chunks = factory.create(
  717. `${type}.chunks`,
  718. Array.from(compilation.chunks),
  719. context
  720. );
  721. },
  722. modules: (object, compilation, context, options, factory) => {
  723. const { type } = context;
  724. const array = Array.from(compilation.modules);
  725. const groupedModules = factory.create(`${type}.modules`, array, context);
  726. const limited = spaceLimited(groupedModules, options.modulesSpace);
  727. object.modules = limited.children;
  728. object.filteredModules = limited.filteredChildren;
  729. },
  730. entrypoints: (
  731. object,
  732. compilation,
  733. context,
  734. { entrypoints, chunkGroups, chunkGroupAuxiliary, chunkGroupChildren },
  735. factory
  736. ) => {
  737. const { type } = context;
  738. const array = Array.from(compilation.entrypoints, ([key, value]) => ({
  739. name: key,
  740. chunkGroup: value
  741. }));
  742. if (entrypoints === "auto" && !chunkGroups) {
  743. if (array.length > 5) return;
  744. if (
  745. !chunkGroupChildren &&
  746. array.every(({ chunkGroup }) => {
  747. if (chunkGroup.chunks.length !== 1) return false;
  748. const chunk = chunkGroup.chunks[0];
  749. return (
  750. chunk.files.size === 1 &&
  751. (!chunkGroupAuxiliary || chunk.auxiliaryFiles.size === 0)
  752. );
  753. })
  754. ) {
  755. return;
  756. }
  757. }
  758. object.entrypoints = factory.create(
  759. `${type}.entrypoints`,
  760. array,
  761. context
  762. );
  763. },
  764. chunkGroups: (object, compilation, context, options, factory) => {
  765. const { type } = context;
  766. const array = Array.from(
  767. compilation.namedChunkGroups,
  768. ([key, value]) => ({
  769. name: key,
  770. chunkGroup: value
  771. })
  772. );
  773. object.namedChunkGroups = factory.create(
  774. `${type}.namedChunkGroups`,
  775. array,
  776. context
  777. );
  778. },
  779. errors: (object, compilation, context, options, factory) => {
  780. const { type, cachedGetErrors } = context;
  781. const rawErrors = cachedGetErrors(compilation);
  782. const factorizedErrors = factory.create(
  783. `${type}.errors`,
  784. cachedGetErrors(compilation),
  785. context
  786. );
  787. let filtered = 0;
  788. if (options.errorDetails === "auto" && rawErrors.length >= 3) {
  789. filtered = rawErrors
  790. .map(e => typeof e !== "string" && e.details)
  791. .filter(Boolean).length;
  792. }
  793. if (
  794. options.errorDetails === true ||
  795. !Number.isFinite(options.errorsSpace)
  796. ) {
  797. object.errors = factorizedErrors;
  798. if (filtered) object.filteredErrorDetailsCount = filtered;
  799. return;
  800. }
  801. const [errors, filteredBySpace] = errorsSpaceLimit(
  802. factorizedErrors,
  803. options.errorsSpace
  804. );
  805. object.filteredErrorDetailsCount = filtered + filteredBySpace;
  806. object.errors = errors;
  807. },
  808. errorsCount: (object, compilation, { cachedGetErrors }) => {
  809. object.errorsCount = countWithChildren(compilation, c =>
  810. cachedGetErrors(c)
  811. );
  812. },
  813. warnings: (object, compilation, context, options, factory) => {
  814. const { type, cachedGetWarnings } = context;
  815. const rawWarnings = factory.create(
  816. `${type}.warnings`,
  817. cachedGetWarnings(compilation),
  818. context
  819. );
  820. let filtered = 0;
  821. if (options.errorDetails === "auto") {
  822. filtered = cachedGetWarnings(compilation)
  823. .map(e => typeof e !== "string" && e.details)
  824. .filter(Boolean).length;
  825. }
  826. if (
  827. options.errorDetails === true ||
  828. !Number.isFinite(options.warningsSpace)
  829. ) {
  830. object.warnings = rawWarnings;
  831. if (filtered) object.filteredWarningDetailsCount = filtered;
  832. return;
  833. }
  834. const [warnings, filteredBySpace] = errorsSpaceLimit(
  835. rawWarnings,
  836. options.warningsSpace
  837. );
  838. object.filteredWarningDetailsCount = filtered + filteredBySpace;
  839. object.warnings = warnings;
  840. },
  841. warningsCount: (
  842. object,
  843. compilation,
  844. context,
  845. { warningsFilter },
  846. factory
  847. ) => {
  848. const { type, cachedGetWarnings } = context;
  849. object.warningsCount = countWithChildren(compilation, (c, childType) => {
  850. if (!warningsFilter && warningsFilter.length === 0)
  851. return cachedGetWarnings(c);
  852. return factory
  853. .create(`${type}${childType}.warnings`, cachedGetWarnings(c), context)
  854. .filter(warning => {
  855. const warningString = Object.keys(warning)
  856. .map(key => `${warning[key]}`)
  857. .join("\n");
  858. return !warningsFilter.some(filter =>
  859. filter(warning, warningString)
  860. );
  861. });
  862. });
  863. },
  864. children: (object, compilation, context, options, factory) => {
  865. const { type } = context;
  866. object.children = factory.create(
  867. `${type}.children`,
  868. compilation.children,
  869. context
  870. );
  871. }
  872. },
  873. asset: {
  874. _: (object, asset, context, options, factory) => {
  875. const { compilation } = context;
  876. object.type = asset.type;
  877. object.name = asset.name;
  878. object.size = asset.source.size();
  879. object.emitted = compilation.emittedAssets.has(asset.name);
  880. object.comparedForEmit = compilation.comparedForEmitAssets.has(
  881. asset.name
  882. );
  883. const cached = !object.emitted && !object.comparedForEmit;
  884. object.cached = cached;
  885. object.info = asset.info;
  886. if (!cached || options.cachedAssets) {
  887. Object.assign(
  888. object,
  889. factory.create(`${context.type}$visible`, asset, context)
  890. );
  891. }
  892. }
  893. },
  894. asset$visible: {
  895. _: (
  896. object,
  897. asset,
  898. { compilation, compilationFileToChunks, compilationAuxiliaryFileToChunks }
  899. ) => {
  900. const chunks = compilationFileToChunks.get(asset.name) || [];
  901. const auxiliaryChunks =
  902. compilationAuxiliaryFileToChunks.get(asset.name) || [];
  903. object.chunkNames = uniqueOrderedArray(
  904. chunks,
  905. c => (c.name ? [c.name] : []),
  906. compareIds
  907. );
  908. object.chunkIdHints = uniqueOrderedArray(
  909. chunks,
  910. c => Array.from(c.idNameHints),
  911. compareIds
  912. );
  913. object.auxiliaryChunkNames = uniqueOrderedArray(
  914. auxiliaryChunks,
  915. c => (c.name ? [c.name] : []),
  916. compareIds
  917. );
  918. object.auxiliaryChunkIdHints = uniqueOrderedArray(
  919. auxiliaryChunks,
  920. c => Array.from(c.idNameHints),
  921. compareIds
  922. );
  923. object.filteredRelated = asset.related ? asset.related.length : undefined;
  924. },
  925. relatedAssets: (object, asset, context, options, factory) => {
  926. const { type } = context;
  927. object.related = factory.create(
  928. `${type.slice(0, -8)}.related`,
  929. asset.related,
  930. context
  931. );
  932. object.filteredRelated = asset.related
  933. ? asset.related.length - object.related.length
  934. : undefined;
  935. },
  936. ids: (
  937. object,
  938. asset,
  939. { compilationFileToChunks, compilationAuxiliaryFileToChunks }
  940. ) => {
  941. const chunks = compilationFileToChunks.get(asset.name) || [];
  942. const auxiliaryChunks =
  943. compilationAuxiliaryFileToChunks.get(asset.name) || [];
  944. object.chunks = uniqueOrderedArray(chunks, c => c.ids, compareIds);
  945. object.auxiliaryChunks = uniqueOrderedArray(
  946. auxiliaryChunks,
  947. c => c.ids,
  948. compareIds
  949. );
  950. },
  951. performance: (object, asset) => {
  952. object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(asset.source);
  953. }
  954. },
  955. chunkGroup: {
  956. _: (
  957. object,
  958. { name, chunkGroup },
  959. { compilation, compilation: { moduleGraph, chunkGraph } },
  960. { ids, chunkGroupAuxiliary, chunkGroupChildren, chunkGroupMaxAssets }
  961. ) => {
  962. const children =
  963. chunkGroupChildren &&
  964. chunkGroup.getChildrenByOrders(moduleGraph, chunkGraph);
  965. /**
  966. * @param {string} name Name
  967. * @returns {{ name: string, size: number }} Asset object
  968. */
  969. const toAsset = name => {
  970. const asset = compilation.getAsset(name);
  971. return {
  972. name,
  973. size: asset ? asset.info.size : -1
  974. };
  975. };
  976. /** @type {(total: number, asset: { size: number }) => number} */
  977. const sizeReducer = (total, { size }) => total + size;
  978. const assets = uniqueArray(chunkGroup.chunks, c => c.files).map(toAsset);
  979. const auxiliaryAssets = uniqueOrderedArray(
  980. chunkGroup.chunks,
  981. c => c.auxiliaryFiles,
  982. compareIds
  983. ).map(toAsset);
  984. const assetsSize = assets.reduce(sizeReducer, 0);
  985. const auxiliaryAssetsSize = auxiliaryAssets.reduce(sizeReducer, 0);
  986. /** @type {KnownStatsChunkGroup} */
  987. const statsChunkGroup = {
  988. name,
  989. chunks: ids ? chunkGroup.chunks.map(c => c.id) : undefined,
  990. assets: assets.length <= chunkGroupMaxAssets ? assets : undefined,
  991. filteredAssets:
  992. assets.length <= chunkGroupMaxAssets ? 0 : assets.length,
  993. assetsSize,
  994. auxiliaryAssets:
  995. chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets
  996. ? auxiliaryAssets
  997. : undefined,
  998. filteredAuxiliaryAssets:
  999. chunkGroupAuxiliary && auxiliaryAssets.length <= chunkGroupMaxAssets
  1000. ? 0
  1001. : auxiliaryAssets.length,
  1002. auxiliaryAssetsSize,
  1003. children: children
  1004. ? mapObject(children, groups =>
  1005. groups.map(group => {
  1006. const assets = uniqueArray(group.chunks, c => c.files).map(
  1007. toAsset
  1008. );
  1009. const auxiliaryAssets = uniqueOrderedArray(
  1010. group.chunks,
  1011. c => c.auxiliaryFiles,
  1012. compareIds
  1013. ).map(toAsset);
  1014. /** @type {KnownStatsChunkGroup} */
  1015. const childStatsChunkGroup = {
  1016. name: group.name,
  1017. chunks: ids ? group.chunks.map(c => c.id) : undefined,
  1018. assets:
  1019. assets.length <= chunkGroupMaxAssets ? assets : undefined,
  1020. filteredAssets:
  1021. assets.length <= chunkGroupMaxAssets ? 0 : assets.length,
  1022. auxiliaryAssets:
  1023. chunkGroupAuxiliary &&
  1024. auxiliaryAssets.length <= chunkGroupMaxAssets
  1025. ? auxiliaryAssets
  1026. : undefined,
  1027. filteredAuxiliaryAssets:
  1028. chunkGroupAuxiliary &&
  1029. auxiliaryAssets.length <= chunkGroupMaxAssets
  1030. ? 0
  1031. : auxiliaryAssets.length
  1032. };
  1033. return childStatsChunkGroup;
  1034. })
  1035. )
  1036. : undefined,
  1037. childAssets: children
  1038. ? mapObject(children, groups => {
  1039. /** @type {Set<string>} */
  1040. const set = new Set();
  1041. for (const group of groups) {
  1042. for (const chunk of group.chunks) {
  1043. for (const asset of chunk.files) {
  1044. set.add(asset);
  1045. }
  1046. }
  1047. }
  1048. return Array.from(set);
  1049. })
  1050. : undefined
  1051. };
  1052. Object.assign(object, statsChunkGroup);
  1053. },
  1054. performance: (object, { chunkGroup }) => {
  1055. object.isOverSizeLimit = SizeLimitsPlugin.isOverSizeLimit(chunkGroup);
  1056. }
  1057. },
  1058. module: {
  1059. _: (object, module, context, options, factory) => {
  1060. const { compilation, type } = context;
  1061. const built = compilation.builtModules.has(module);
  1062. const codeGenerated = compilation.codeGeneratedModules.has(module);
  1063. const buildTimeExecuted =
  1064. compilation.buildTimeExecutedModules.has(module);
  1065. /** @type {{[x: string]: number}} */
  1066. const sizes = {};
  1067. for (const sourceType of module.getSourceTypes()) {
  1068. sizes[sourceType] = module.size(sourceType);
  1069. }
  1070. /** @type {KnownStatsModule} */
  1071. const statsModule = {
  1072. type: "module",
  1073. moduleType: module.type,
  1074. layer: module.layer,
  1075. size: module.size(),
  1076. sizes,
  1077. built,
  1078. codeGenerated,
  1079. buildTimeExecuted,
  1080. cached: !built && !codeGenerated
  1081. };
  1082. Object.assign(object, statsModule);
  1083. if (built || codeGenerated || options.cachedModules) {
  1084. Object.assign(
  1085. object,
  1086. factory.create(`${type}$visible`, module, context)
  1087. );
  1088. }
  1089. }
  1090. },
  1091. module$visible: {
  1092. _: (object, module, context, { requestShortener }, factory) => {
  1093. const { compilation, type, rootModules } = context;
  1094. const { moduleGraph } = compilation;
  1095. /** @type {Module[]} */
  1096. const path = [];
  1097. const issuer = moduleGraph.getIssuer(module);
  1098. let current = issuer;
  1099. while (current) {
  1100. path.push(current);
  1101. current = moduleGraph.getIssuer(current);
  1102. }
  1103. path.reverse();
  1104. const profile = moduleGraph.getProfile(module);
  1105. const errors = module.getErrors();
  1106. const errorsCount = errors !== undefined ? countIterable(errors) : 0;
  1107. const warnings = module.getWarnings();
  1108. const warningsCount =
  1109. warnings !== undefined ? countIterable(warnings) : 0;
  1110. /** @type {{[x: string]: number}} */
  1111. const sizes = {};
  1112. for (const sourceType of module.getSourceTypes()) {
  1113. sizes[sourceType] = module.size(sourceType);
  1114. }
  1115. /** @type {KnownStatsModule} */
  1116. const statsModule = {
  1117. identifier: module.identifier(),
  1118. name: module.readableIdentifier(requestShortener),
  1119. nameForCondition: module.nameForCondition(),
  1120. index: moduleGraph.getPreOrderIndex(module),
  1121. preOrderIndex: moduleGraph.getPreOrderIndex(module),
  1122. index2: moduleGraph.getPostOrderIndex(module),
  1123. postOrderIndex: moduleGraph.getPostOrderIndex(module),
  1124. cacheable: module.buildInfo.cacheable,
  1125. optional: module.isOptional(moduleGraph),
  1126. orphan:
  1127. !type.endsWith("module.modules[].module$visible") &&
  1128. compilation.chunkGraph.getNumberOfModuleChunks(module) === 0,
  1129. dependent: rootModules ? !rootModules.has(module) : undefined,
  1130. issuer: issuer && issuer.identifier(),
  1131. issuerName: issuer && issuer.readableIdentifier(requestShortener),
  1132. issuerPath:
  1133. issuer &&
  1134. factory.create(`${type.slice(0, -8)}.issuerPath`, path, context),
  1135. failed: errorsCount > 0,
  1136. errors: errorsCount,
  1137. warnings: warningsCount
  1138. };
  1139. Object.assign(object, statsModule);
  1140. if (profile) {
  1141. object.profile = factory.create(
  1142. `${type.slice(0, -8)}.profile`,
  1143. profile,
  1144. context
  1145. );
  1146. }
  1147. },
  1148. ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => {
  1149. object.id = chunkGraph.getModuleId(module);
  1150. const issuer = moduleGraph.getIssuer(module);
  1151. object.issuerId = issuer && chunkGraph.getModuleId(issuer);
  1152. object.chunks = Array.from(
  1153. chunkGraph.getOrderedModuleChunksIterable(module, compareChunksById),
  1154. chunk => chunk.id
  1155. );
  1156. },
  1157. moduleAssets: (object, module) => {
  1158. object.assets = module.buildInfo.assets
  1159. ? Object.keys(module.buildInfo.assets)
  1160. : [];
  1161. },
  1162. reasons: (object, module, context, options, factory) => {
  1163. const {
  1164. type,
  1165. compilation: { moduleGraph }
  1166. } = context;
  1167. const groupsReasons = factory.create(
  1168. `${type.slice(0, -8)}.reasons`,
  1169. Array.from(moduleGraph.getIncomingConnections(module)),
  1170. context
  1171. );
  1172. const limited = spaceLimited(groupsReasons, options.reasonsSpace);
  1173. object.reasons = limited.children;
  1174. object.filteredReasons = limited.filteredChildren;
  1175. },
  1176. usedExports: (
  1177. object,
  1178. module,
  1179. { runtime, compilation: { moduleGraph } }
  1180. ) => {
  1181. const usedExports = moduleGraph.getUsedExports(module, runtime);
  1182. if (usedExports === null) {
  1183. object.usedExports = null;
  1184. } else if (typeof usedExports === "boolean") {
  1185. object.usedExports = usedExports;
  1186. } else {
  1187. object.usedExports = Array.from(usedExports);
  1188. }
  1189. },
  1190. providedExports: (object, module, { compilation: { moduleGraph } }) => {
  1191. const providedExports = moduleGraph.getProvidedExports(module);
  1192. object.providedExports = Array.isArray(providedExports)
  1193. ? providedExports
  1194. : null;
  1195. },
  1196. optimizationBailout: (
  1197. object,
  1198. module,
  1199. { compilation: { moduleGraph } },
  1200. { requestShortener }
  1201. ) => {
  1202. object.optimizationBailout = moduleGraph
  1203. .getOptimizationBailout(module)
  1204. .map(item => {
  1205. if (typeof item === "function") return item(requestShortener);
  1206. return item;
  1207. });
  1208. },
  1209. depth: (object, module, { compilation: { moduleGraph } }) => {
  1210. object.depth = moduleGraph.getDepth(module);
  1211. },
  1212. nestedModules: (object, module, context, options, factory) => {
  1213. const { type } = context;
  1214. const innerModules = /** @type {Module & { modules?: Module[] }} */ (
  1215. module
  1216. ).modules;
  1217. if (Array.isArray(innerModules)) {
  1218. const groupedModules = factory.create(
  1219. `${type.slice(0, -8)}.modules`,
  1220. innerModules,
  1221. context
  1222. );
  1223. const limited = spaceLimited(
  1224. groupedModules,
  1225. options.nestedModulesSpace
  1226. );
  1227. object.modules = limited.children;
  1228. object.filteredModules = limited.filteredChildren;
  1229. }
  1230. },
  1231. source: (object, module) => {
  1232. const originalSource = module.originalSource();
  1233. if (originalSource) {
  1234. object.source = originalSource.source();
  1235. }
  1236. }
  1237. },
  1238. profile: {
  1239. _: (object, profile) => {
  1240. /** @type {KnownStatsProfile} */
  1241. const statsProfile = {
  1242. total:
  1243. profile.factory +
  1244. profile.restoring +
  1245. profile.integration +
  1246. profile.building +
  1247. profile.storing,
  1248. resolving: profile.factory,
  1249. restoring: profile.restoring,
  1250. building: profile.building,
  1251. integration: profile.integration,
  1252. storing: profile.storing,
  1253. additionalResolving: profile.additionalFactories,
  1254. additionalIntegration: profile.additionalIntegration,
  1255. // TODO remove this in webpack 6
  1256. factory: profile.factory,
  1257. // TODO remove this in webpack 6
  1258. dependencies: profile.additionalFactories
  1259. };
  1260. Object.assign(object, statsProfile);
  1261. }
  1262. },
  1263. moduleIssuer: {
  1264. _: (object, module, context, { requestShortener }, factory) => {
  1265. const { compilation, type } = context;
  1266. const { moduleGraph } = compilation;
  1267. const profile = moduleGraph.getProfile(module);
  1268. /** @type {KnownStatsModuleIssuer} */
  1269. const statsModuleIssuer = {
  1270. identifier: module.identifier(),
  1271. name: module.readableIdentifier(requestShortener)
  1272. };
  1273. Object.assign(object, statsModuleIssuer);
  1274. if (profile) {
  1275. object.profile = factory.create(`${type}.profile`, profile, context);
  1276. }
  1277. },
  1278. ids: (object, module, { compilation: { chunkGraph } }) => {
  1279. object.id = chunkGraph.getModuleId(module);
  1280. }
  1281. },
  1282. moduleReason: {
  1283. _: (object, reason, { runtime }, { requestShortener }) => {
  1284. const dep = reason.dependency;
  1285. const moduleDep =
  1286. dep && dep instanceof ModuleDependency ? dep : undefined;
  1287. /** @type {KnownStatsModuleReason} */
  1288. const statsModuleReason = {
  1289. moduleIdentifier: reason.originModule
  1290. ? reason.originModule.identifier()
  1291. : null,
  1292. module: reason.originModule
  1293. ? reason.originModule.readableIdentifier(requestShortener)
  1294. : null,
  1295. moduleName: reason.originModule
  1296. ? reason.originModule.readableIdentifier(requestShortener)
  1297. : null,
  1298. resolvedModuleIdentifier: reason.resolvedOriginModule
  1299. ? reason.resolvedOriginModule.identifier()
  1300. : null,
  1301. resolvedModule: reason.resolvedOriginModule
  1302. ? reason.resolvedOriginModule.readableIdentifier(requestShortener)
  1303. : null,
  1304. type: reason.dependency ? reason.dependency.type : null,
  1305. active: reason.isActive(runtime),
  1306. explanation: reason.explanation,
  1307. userRequest: (moduleDep && moduleDep.userRequest) || null
  1308. };
  1309. Object.assign(object, statsModuleReason);
  1310. if (reason.dependency) {
  1311. const locInfo = formatLocation(reason.dependency.loc);
  1312. if (locInfo) {
  1313. object.loc = locInfo;
  1314. }
  1315. }
  1316. },
  1317. ids: (object, reason, { compilation: { chunkGraph } }) => {
  1318. object.moduleId = reason.originModule
  1319. ? chunkGraph.getModuleId(reason.originModule)
  1320. : null;
  1321. object.resolvedModuleId = reason.resolvedOriginModule
  1322. ? chunkGraph.getModuleId(reason.resolvedOriginModule)
  1323. : null;
  1324. }
  1325. },
  1326. chunk: {
  1327. _: (object, chunk, { makePathsRelative, compilation: { chunkGraph } }) => {
  1328. const childIdByOrder = chunk.getChildIdsByOrders(chunkGraph);
  1329. /** @type {KnownStatsChunk} */
  1330. const statsChunk = {
  1331. rendered: chunk.rendered,
  1332. initial: chunk.canBeInitial(),
  1333. entry: chunk.hasRuntime(),
  1334. recorded: AggressiveSplittingPlugin.wasChunkRecorded(chunk),
  1335. reason: chunk.chunkReason,
  1336. size: chunkGraph.getChunkModulesSize(chunk),
  1337. sizes: chunkGraph.getChunkModulesSizes(chunk),
  1338. names: chunk.name ? [chunk.name] : [],
  1339. idHints: Array.from(chunk.idNameHints),
  1340. runtime:
  1341. chunk.runtime === undefined
  1342. ? undefined
  1343. : typeof chunk.runtime === "string"
  1344. ? [makePathsRelative(chunk.runtime)]
  1345. : Array.from(chunk.runtime.sort(), makePathsRelative),
  1346. files: Array.from(chunk.files),
  1347. auxiliaryFiles: Array.from(chunk.auxiliaryFiles).sort(compareIds),
  1348. hash: chunk.renderedHash,
  1349. childrenByOrder: childIdByOrder
  1350. };
  1351. Object.assign(object, statsChunk);
  1352. },
  1353. ids: (object, chunk) => {
  1354. object.id = chunk.id;
  1355. },
  1356. chunkRelations: (object, chunk, { compilation: { chunkGraph } }) => {
  1357. /** @type {Set<string|number>} */
  1358. const parents = new Set();
  1359. /** @type {Set<string|number>} */
  1360. const children = new Set();
  1361. /** @type {Set<string|number>} */
  1362. const siblings = new Set();
  1363. for (const chunkGroup of chunk.groupsIterable) {
  1364. for (const parentGroup of chunkGroup.parentsIterable) {
  1365. for (const chunk of parentGroup.chunks) {
  1366. parents.add(chunk.id);
  1367. }
  1368. }
  1369. for (const childGroup of chunkGroup.childrenIterable) {
  1370. for (const chunk of childGroup.chunks) {
  1371. children.add(chunk.id);
  1372. }
  1373. }
  1374. for (const sibling of chunkGroup.chunks) {
  1375. if (sibling !== chunk) siblings.add(sibling.id);
  1376. }
  1377. }
  1378. object.siblings = Array.from(siblings).sort(compareIds);
  1379. object.parents = Array.from(parents).sort(compareIds);
  1380. object.children = Array.from(children).sort(compareIds);
  1381. },
  1382. chunkModules: (object, chunk, context, options, factory) => {
  1383. const {
  1384. type,
  1385. compilation: { chunkGraph }
  1386. } = context;
  1387. const array = chunkGraph.getChunkModules(chunk);
  1388. const groupedModules = factory.create(`${type}.modules`, array, {
  1389. ...context,
  1390. runtime: chunk.runtime,
  1391. rootModules: new Set(chunkGraph.getChunkRootModules(chunk))
  1392. });
  1393. const limited = spaceLimited(groupedModules, options.chunkModulesSpace);
  1394. object.modules = limited.children;
  1395. object.filteredModules = limited.filteredChildren;
  1396. },
  1397. chunkOrigins: (object, chunk, context, options, factory) => {
  1398. const {
  1399. type,
  1400. compilation: { chunkGraph }
  1401. } = context;
  1402. /** @type {Set<string>} */
  1403. const originsKeySet = new Set();
  1404. const origins = [];
  1405. for (const g of chunk.groupsIterable) {
  1406. origins.push(...g.origins);
  1407. }
  1408. const array = origins.filter(origin => {
  1409. const key = [
  1410. origin.module ? chunkGraph.getModuleId(origin.module) : undefined,
  1411. formatLocation(origin.loc),
  1412. origin.request
  1413. ].join();
  1414. if (originsKeySet.has(key)) return false;
  1415. originsKeySet.add(key);
  1416. return true;
  1417. });
  1418. object.origins = factory.create(`${type}.origins`, array, context);
  1419. }
  1420. },
  1421. chunkOrigin: {
  1422. _: (object, origin, context, { requestShortener }) => {
  1423. /** @type {KnownStatsChunkOrigin} */
  1424. const statsChunkOrigin = {
  1425. module: origin.module ? origin.module.identifier() : "",
  1426. moduleIdentifier: origin.module ? origin.module.identifier() : "",
  1427. moduleName: origin.module
  1428. ? origin.module.readableIdentifier(requestShortener)
  1429. : "",
  1430. loc: formatLocation(origin.loc),
  1431. request: origin.request
  1432. };
  1433. Object.assign(object, statsChunkOrigin);
  1434. },
  1435. ids: (object, origin, { compilation: { chunkGraph } }) => {
  1436. object.moduleId = origin.module
  1437. ? chunkGraph.getModuleId(origin.module)
  1438. : undefined;
  1439. }
  1440. },
  1441. error: EXTRACT_ERROR,
  1442. warning: EXTRACT_ERROR,
  1443. moduleTraceItem: {
  1444. _: (object, { origin, module }, context, { requestShortener }, factory) => {
  1445. const {
  1446. type,
  1447. compilation: { moduleGraph }
  1448. } = context;
  1449. object.originIdentifier = origin.identifier();
  1450. object.originName = origin.readableIdentifier(requestShortener);
  1451. object.moduleIdentifier = module.identifier();
  1452. object.moduleName = module.readableIdentifier(requestShortener);
  1453. const dependencies = Array.from(
  1454. moduleGraph.getIncomingConnections(module)
  1455. )
  1456. .filter(c => c.resolvedOriginModule === origin && c.dependency)
  1457. .map(c => c.dependency);
  1458. object.dependencies = factory.create(
  1459. `${type}.dependencies`,
  1460. Array.from(new Set(dependencies)),
  1461. context
  1462. );
  1463. },
  1464. ids: (object, { origin, module }, { compilation: { chunkGraph } }) => {
  1465. object.originId = chunkGraph.getModuleId(origin);
  1466. object.moduleId = chunkGraph.getModuleId(module);
  1467. }
  1468. },
  1469. moduleTraceDependency: {
  1470. _: (object, dependency) => {
  1471. object.loc = formatLocation(dependency.loc);
  1472. }
  1473. }
  1474. };
  1475. /** @type {Record<string, Record<string, (thing: any, context: StatsFactoryContext, options: NormalizedStatsOptions) => boolean | undefined>>} */
  1476. const FILTER = {
  1477. "module.reasons": {
  1478. "!orphanModules": (reason, { compilation: { chunkGraph } }) => {
  1479. if (
  1480. reason.originModule &&
  1481. chunkGraph.getNumberOfModuleChunks(reason.originModule) === 0
  1482. ) {
  1483. return false;
  1484. }
  1485. }
  1486. }
  1487. };
  1488. /** @type {Record<string, Record<string, (thing: Object, context: StatsFactoryContext, options: NormalizedStatsOptions) => boolean | undefined>>} */
  1489. const FILTER_RESULTS = {
  1490. "compilation.warnings": {
  1491. warningsFilter: util.deprecate(
  1492. (warning, context, { warningsFilter }) => {
  1493. const warningString = Object.keys(warning)
  1494. .map(key => `${warning[key]}`)
  1495. .join("\n");
  1496. return !warningsFilter.some(filter => filter(warning, warningString));
  1497. },
  1498. "config.stats.warningsFilter is deprecated in favor of config.ignoreWarnings",
  1499. "DEP_WEBPACK_STATS_WARNINGS_FILTER"
  1500. )
  1501. }
  1502. };
  1503. /** @type {Record<string, (comparators: Function[], context: StatsFactoryContext) => void>} */
  1504. const MODULES_SORTER = {
  1505. _: (comparators, { compilation: { moduleGraph } }) => {
  1506. comparators.push(
  1507. compareSelect(
  1508. /**
  1509. * @param {Module} m module
  1510. * @returns {number} depth
  1511. */
  1512. m => moduleGraph.getDepth(m),
  1513. compareNumbers
  1514. ),
  1515. compareSelect(
  1516. /**
  1517. * @param {Module} m module
  1518. * @returns {number} index
  1519. */
  1520. m => moduleGraph.getPreOrderIndex(m),
  1521. compareNumbers
  1522. ),
  1523. compareSelect(
  1524. /**
  1525. * @param {Module} m module
  1526. * @returns {string} identifier
  1527. */
  1528. m => m.identifier(),
  1529. compareIds
  1530. )
  1531. );
  1532. }
  1533. };
  1534. /** @type {Record<string, Record<string, (comparators: Function[], context: StatsFactoryContext) => void>>} */
  1535. const SORTERS = {
  1536. "compilation.chunks": {
  1537. _: comparators => {
  1538. comparators.push(compareSelect(c => c.id, compareIds));
  1539. }
  1540. },
  1541. "compilation.modules": MODULES_SORTER,
  1542. "chunk.rootModules": MODULES_SORTER,
  1543. "chunk.modules": MODULES_SORTER,
  1544. "module.modules": MODULES_SORTER,
  1545. "module.reasons": {
  1546. _: (comparators, { compilation: { chunkGraph } }) => {
  1547. comparators.push(
  1548. compareSelect(x => x.originModule, compareModulesByIdentifier)
  1549. );
  1550. comparators.push(
  1551. compareSelect(x => x.resolvedOriginModule, compareModulesByIdentifier)
  1552. );
  1553. comparators.push(
  1554. compareSelect(
  1555. x => x.dependency,
  1556. concatComparators(
  1557. compareSelect(
  1558. /**
  1559. * @param {Dependency} x dependency
  1560. * @returns {DependencyLocation} location
  1561. */
  1562. x => x.loc,
  1563. compareLocations
  1564. ),
  1565. compareSelect(x => x.type, compareIds)
  1566. )
  1567. )
  1568. );
  1569. }
  1570. },
  1571. "chunk.origins": {
  1572. _: (comparators, { compilation: { chunkGraph } }) => {
  1573. comparators.push(
  1574. compareSelect(
  1575. origin =>
  1576. origin.module ? chunkGraph.getModuleId(origin.module) : undefined,
  1577. compareIds
  1578. ),
  1579. compareSelect(origin => formatLocation(origin.loc), compareIds),
  1580. compareSelect(origin => origin.request, compareIds)
  1581. );
  1582. }
  1583. }
  1584. };
  1585. const getItemSize = item => {
  1586. // Each item takes 1 line
  1587. // + the size of the children
  1588. // + 1 extra line when it has children and filteredChildren
  1589. return !item.children
  1590. ? 1
  1591. : item.filteredChildren
  1592. ? 2 + getTotalSize(item.children)
  1593. : 1 + getTotalSize(item.children);
  1594. };
  1595. const getTotalSize = children => {
  1596. let size = 0;
  1597. for (const child of children) {
  1598. size += getItemSize(child);
  1599. }
  1600. return size;
  1601. };
  1602. const getTotalItems = children => {
  1603. let count = 0;
  1604. for (const child of children) {
  1605. if (!child.children && !child.filteredChildren) {
  1606. count++;
  1607. } else {
  1608. if (child.children) count += getTotalItems(child.children);
  1609. if (child.filteredChildren) count += child.filteredChildren;
  1610. }
  1611. }
  1612. return count;
  1613. };
  1614. const collapse = children => {
  1615. // After collapse each child must take exactly one line
  1616. const newChildren = [];
  1617. for (const child of children) {
  1618. if (child.children) {
  1619. let filteredChildren = child.filteredChildren || 0;
  1620. filteredChildren += getTotalItems(child.children);
  1621. newChildren.push({
  1622. ...child,
  1623. children: undefined,
  1624. filteredChildren
  1625. });
  1626. } else {
  1627. newChildren.push(child);
  1628. }
  1629. }
  1630. return newChildren;
  1631. };
  1632. const spaceLimited = (
  1633. itemsAndGroups,
  1634. max,
  1635. filteredChildrenLineReserved = false
  1636. ) => {
  1637. if (max < 1) {
  1638. return {
  1639. children: undefined,
  1640. filteredChildren: getTotalItems(itemsAndGroups)
  1641. };
  1642. }
  1643. /** @type {any[] | undefined} */
  1644. let children = undefined;
  1645. /** @type {number | undefined} */
  1646. let filteredChildren = undefined;
  1647. // This are the groups, which take 1+ lines each
  1648. const groups = [];
  1649. // The sizes of the groups are stored in groupSizes
  1650. const groupSizes = [];
  1651. // This are the items, which take 1 line each
  1652. const items = [];
  1653. // The total of group sizes
  1654. let groupsSize = 0;
  1655. for (const itemOrGroup of itemsAndGroups) {
  1656. // is item
  1657. if (!itemOrGroup.children && !itemOrGroup.filteredChildren) {
  1658. items.push(itemOrGroup);
  1659. } else {
  1660. groups.push(itemOrGroup);
  1661. const size = getItemSize(itemOrGroup);
  1662. groupSizes.push(size);
  1663. groupsSize += size;
  1664. }
  1665. }
  1666. if (groupsSize + items.length <= max) {
  1667. // The total size in the current state fits into the max
  1668. // keep all
  1669. children = groups.length > 0 ? groups.concat(items) : items;
  1670. } else if (groups.length === 0) {
  1671. // slice items to max
  1672. // inner space marks that lines for filteredChildren already reserved
  1673. const limit = max - (filteredChildrenLineReserved ? 0 : 1);
  1674. filteredChildren = items.length - limit;
  1675. items.length = limit;
  1676. children = items;
  1677. } else {
  1678. // limit is the size when all groups are collapsed
  1679. const limit =
  1680. groups.length +
  1681. (filteredChildrenLineReserved || items.length === 0 ? 0 : 1);
  1682. if (limit < max) {
  1683. // calculate how much we are over the size limit
  1684. // this allows to approach the limit faster
  1685. let oversize;
  1686. // If each group would take 1 line the total would be below the maximum
  1687. // collapse some groups, keep items
  1688. while (
  1689. (oversize =
  1690. groupsSize +
  1691. items.length +
  1692. (filteredChildren && !filteredChildrenLineReserved ? 1 : 0) -
  1693. max) > 0
  1694. ) {
  1695. // Find the maximum group and process only this one
  1696. const maxGroupSize = Math.max(...groupSizes);
  1697. if (maxGroupSize < items.length) {
  1698. filteredChildren = items.length;
  1699. items.length = 0;
  1700. continue;
  1701. }
  1702. for (let i = 0; i < groups.length; i++) {
  1703. if (groupSizes[i] === maxGroupSize) {
  1704. const group = groups[i];
  1705. // run this algorithm recursively and limit the size of the children to
  1706. // current size - oversize / number of groups
  1707. // So it should always end up being smaller
  1708. const headerSize = group.filteredChildren ? 2 : 1;
  1709. const limited = spaceLimited(
  1710. group.children,
  1711. maxGroupSize -
  1712. // we should use ceil to always feet in max
  1713. Math.ceil(oversize / groups.length) -
  1714. // we substitute size of group head
  1715. headerSize,
  1716. headerSize === 2
  1717. );
  1718. groups[i] = {
  1719. ...group,
  1720. children: limited.children,
  1721. filteredChildren: limited.filteredChildren
  1722. ? (group.filteredChildren || 0) + limited.filteredChildren
  1723. : group.filteredChildren
  1724. };
  1725. const newSize = getItemSize(groups[i]);
  1726. groupsSize -= maxGroupSize - newSize;
  1727. groupSizes[i] = newSize;
  1728. break;
  1729. }
  1730. }
  1731. }
  1732. children = groups.concat(items);
  1733. } else if (limit === max) {
  1734. // If we have only enough space to show one line per group and one line for the filtered items
  1735. // collapse all groups and items
  1736. children = collapse(groups);
  1737. filteredChildren = items.length;
  1738. } else {
  1739. // If we have no space
  1740. // collapse complete group
  1741. filteredChildren = getTotalItems(itemsAndGroups);
  1742. }
  1743. }
  1744. return {
  1745. children,
  1746. filteredChildren
  1747. };
  1748. };
  1749. const errorsSpaceLimit = (errors, max) => {
  1750. let filtered = 0;
  1751. // Can not fit into limit
  1752. // print only messages
  1753. if (errors.length + 1 >= max)
  1754. return [
  1755. errors.map(error => {
  1756. if (typeof error === "string" || !error.details) return error;
  1757. filtered++;
  1758. return { ...error, details: "" };
  1759. }),
  1760. filtered
  1761. ];
  1762. let fullLength = errors.length;
  1763. let result = errors;
  1764. let i = 0;
  1765. for (; i < errors.length; i++) {
  1766. const error = errors[i];
  1767. if (typeof error !== "string" && error.details) {
  1768. const splitted = error.details.split("\n");
  1769. const len = splitted.length;
  1770. fullLength += len;
  1771. if (fullLength > max) {
  1772. result = i > 0 ? errors.slice(0, i) : [];
  1773. const overLimit = fullLength - max + 1;
  1774. const error = errors[i++];
  1775. result.push({
  1776. ...error,
  1777. details: error.details.split("\n").slice(0, -overLimit).join("\n"),
  1778. filteredDetails: overLimit
  1779. });
  1780. filtered = errors.length - i;
  1781. for (; i < errors.length; i++) {
  1782. const error = errors[i];
  1783. if (typeof error === "string" || !error.details) result.push(error);
  1784. result.push({ ...error, details: "" });
  1785. }
  1786. break;
  1787. } else if (fullLength === max) {
  1788. result = errors.slice(0, ++i);
  1789. filtered = errors.length - i;
  1790. for (; i < errors.length; i++) {
  1791. const error = errors[i];
  1792. if (typeof error === "string" || !error.details) result.push(error);
  1793. result.push({ ...error, details: "" });
  1794. }
  1795. break;
  1796. }
  1797. }
  1798. }
  1799. return [result, filtered];
  1800. };
  1801. const assetGroup = (children, assets) => {
  1802. let size = 0;
  1803. for (const asset of children) {
  1804. size += asset.size;
  1805. }
  1806. return {
  1807. size
  1808. };
  1809. };
  1810. const moduleGroup = (children, modules) => {
  1811. let size = 0;
  1812. const sizes = {};
  1813. for (const module of children) {
  1814. size += module.size;
  1815. for (const key of Object.keys(module.sizes)) {
  1816. sizes[key] = (sizes[key] || 0) + module.sizes[key];
  1817. }
  1818. }
  1819. return {
  1820. size,
  1821. sizes
  1822. };
  1823. };
  1824. const reasonGroup = (children, reasons) => {
  1825. let active = false;
  1826. for (const reason of children) {
  1827. active = active || reason.active;
  1828. }
  1829. return {
  1830. active
  1831. };
  1832. };
  1833. const GROUP_EXTENSION_REGEXP = /(\.[^.]+?)(?:\?|(?: \+ \d+ modules?)?$)/;
  1834. const GROUP_PATH_REGEXP = /(.+)[/\\][^/\\]+?(?:\?|(?: \+ \d+ modules?)?$)/;
  1835. /** @type {Record<string, (groupConfigs: GroupConfig[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} */
  1836. const ASSETS_GROUPERS = {
  1837. _: (groupConfigs, context, options) => {
  1838. const groupByFlag = (name, exclude) => {
  1839. groupConfigs.push({
  1840. getKeys: asset => {
  1841. return asset[name] ? ["1"] : undefined;
  1842. },
  1843. getOptions: () => {
  1844. return {
  1845. groupChildren: !exclude,
  1846. force: exclude
  1847. };
  1848. },
  1849. createGroup: (key, children, assets) => {
  1850. return exclude
  1851. ? {
  1852. type: "assets by status",
  1853. [name]: !!key,
  1854. filteredChildren: assets.length,
  1855. ...assetGroup(children, assets)
  1856. }
  1857. : {
  1858. type: "assets by status",
  1859. [name]: !!key,
  1860. children,
  1861. ...assetGroup(children, assets)
  1862. };
  1863. }
  1864. });
  1865. };
  1866. const {
  1867. groupAssetsByEmitStatus,
  1868. groupAssetsByPath,
  1869. groupAssetsByExtension
  1870. } = options;
  1871. if (groupAssetsByEmitStatus) {
  1872. groupByFlag("emitted");
  1873. groupByFlag("comparedForEmit");
  1874. groupByFlag("isOverSizeLimit");
  1875. }
  1876. if (groupAssetsByEmitStatus || !options.cachedAssets) {
  1877. groupByFlag("cached", !options.cachedAssets);
  1878. }
  1879. if (groupAssetsByPath || groupAssetsByExtension) {
  1880. groupConfigs.push({
  1881. getKeys: asset => {
  1882. const extensionMatch =
  1883. groupAssetsByExtension && GROUP_EXTENSION_REGEXP.exec(asset.name);
  1884. const extension = extensionMatch ? extensionMatch[1] : "";
  1885. const pathMatch =
  1886. groupAssetsByPath && GROUP_PATH_REGEXP.exec(asset.name);
  1887. const path = pathMatch ? pathMatch[1].split(/[/\\]/) : [];
  1888. const keys = [];
  1889. if (groupAssetsByPath) {
  1890. keys.push(".");
  1891. if (extension)
  1892. keys.push(
  1893. path.length
  1894. ? `${path.join("/")}/*${extension}`
  1895. : `*${extension}`
  1896. );
  1897. while (path.length > 0) {
  1898. keys.push(path.join("/") + "/");
  1899. path.pop();
  1900. }
  1901. } else {
  1902. if (extension) keys.push(`*${extension}`);
  1903. }
  1904. return keys;
  1905. },
  1906. createGroup: (key, children, assets) => {
  1907. return {
  1908. type: groupAssetsByPath ? "assets by path" : "assets by extension",
  1909. name: key,
  1910. children,
  1911. ...assetGroup(children, assets)
  1912. };
  1913. }
  1914. });
  1915. }
  1916. },
  1917. groupAssetsByInfo: (groupConfigs, context, options) => {
  1918. const groupByAssetInfoFlag = name => {
  1919. groupConfigs.push({
  1920. getKeys: asset => {
  1921. return asset.info && asset.info[name] ? ["1"] : undefined;
  1922. },
  1923. createGroup: (key, children, assets) => {
  1924. return {
  1925. type: "assets by info",
  1926. info: {
  1927. [name]: !!key
  1928. },
  1929. children,
  1930. ...assetGroup(children, assets)
  1931. };
  1932. }
  1933. });
  1934. };
  1935. groupByAssetInfoFlag("immutable");
  1936. groupByAssetInfoFlag("development");
  1937. groupByAssetInfoFlag("hotModuleReplacement");
  1938. },
  1939. groupAssetsByChunk: (groupConfigs, context, options) => {
  1940. const groupByNames = name => {
  1941. groupConfigs.push({
  1942. getKeys: asset => {
  1943. return asset[name];
  1944. },
  1945. createGroup: (key, children, assets) => {
  1946. return {
  1947. type: "assets by chunk",
  1948. [name]: [key],
  1949. children,
  1950. ...assetGroup(children, assets)
  1951. };
  1952. }
  1953. });
  1954. };
  1955. groupByNames("chunkNames");
  1956. groupByNames("auxiliaryChunkNames");
  1957. groupByNames("chunkIdHints");
  1958. groupByNames("auxiliaryChunkIdHints");
  1959. },
  1960. excludeAssets: (groupConfigs, context, { excludeAssets }) => {
  1961. groupConfigs.push({
  1962. getKeys: asset => {
  1963. const ident = asset.name;
  1964. const excluded = excludeAssets.some(fn => fn(ident, asset));
  1965. if (excluded) return ["excluded"];
  1966. },
  1967. getOptions: () => ({
  1968. groupChildren: false,
  1969. force: true
  1970. }),
  1971. createGroup: (key, children, assets) => ({
  1972. type: "hidden assets",
  1973. filteredChildren: assets.length,
  1974. ...assetGroup(children, assets)
  1975. })
  1976. });
  1977. }
  1978. };
  1979. /** @type {function("module" | "chunk" | "root-of-chunk" | "nested"): Record<string, (groupConfigs: GroupConfig[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>} */
  1980. const MODULES_GROUPERS = type => ({
  1981. _: (groupConfigs, context, options) => {
  1982. const groupByFlag = (name, type, exclude) => {
  1983. groupConfigs.push({
  1984. getKeys: module => {
  1985. return module[name] ? ["1"] : undefined;
  1986. },
  1987. getOptions: () => {
  1988. return {
  1989. groupChildren: !exclude,
  1990. force: exclude
  1991. };
  1992. },
  1993. createGroup: (key, children, modules) => {
  1994. return {
  1995. type,
  1996. [name]: !!key,
  1997. ...(exclude ? { filteredChildren: modules.length } : { children }),
  1998. ...moduleGroup(children, modules)
  1999. };
  2000. }
  2001. });
  2002. };
  2003. const {
  2004. groupModulesByCacheStatus,
  2005. groupModulesByLayer,
  2006. groupModulesByAttributes,
  2007. groupModulesByType,
  2008. groupModulesByPath,
  2009. groupModulesByExtension
  2010. } = options;
  2011. if (groupModulesByAttributes) {
  2012. groupByFlag("errors", "modules with errors");
  2013. groupByFlag("warnings", "modules with warnings");
  2014. groupByFlag("assets", "modules with assets");
  2015. groupByFlag("optional", "optional modules");
  2016. }
  2017. if (groupModulesByCacheStatus) {
  2018. groupByFlag("cacheable", "cacheable modules");
  2019. groupByFlag("built", "built modules");
  2020. groupByFlag("codeGenerated", "code generated modules");
  2021. }
  2022. if (groupModulesByCacheStatus || !options.cachedModules) {
  2023. groupByFlag("cached", "cached modules", !options.cachedModules);
  2024. }
  2025. if (groupModulesByAttributes || !options.orphanModules) {
  2026. groupByFlag("orphan", "orphan modules", !options.orphanModules);
  2027. }
  2028. if (groupModulesByAttributes || !options.dependentModules) {
  2029. groupByFlag("dependent", "dependent modules", !options.dependentModules);
  2030. }
  2031. if (groupModulesByType || !options.runtimeModules) {
  2032. groupConfigs.push({
  2033. getKeys: module => {
  2034. if (!module.moduleType) return;
  2035. if (groupModulesByType) {
  2036. return [module.moduleType.split("/", 1)[0]];
  2037. } else if (module.moduleType === "runtime") {
  2038. return ["runtime"];
  2039. }
  2040. },
  2041. getOptions: key => {
  2042. const exclude = key === "runtime" && !options.runtimeModules;
  2043. return {
  2044. groupChildren: !exclude,
  2045. force: exclude
  2046. };
  2047. },
  2048. createGroup: (key, children, modules) => {
  2049. const exclude = key === "runtime" && !options.runtimeModules;
  2050. return {
  2051. type: `${key} modules`,
  2052. moduleType: key,
  2053. ...(exclude ? { filteredChildren: modules.length } : { children }),
  2054. ...moduleGroup(children, modules)
  2055. };
  2056. }
  2057. });
  2058. }
  2059. if (groupModulesByLayer) {
  2060. groupConfigs.push({
  2061. getKeys: module => {
  2062. return [module.layer];
  2063. },
  2064. createGroup: (key, children, modules) => {
  2065. return {
  2066. type: "modules by layer",
  2067. layer: key,
  2068. children,
  2069. ...moduleGroup(children, modules)
  2070. };
  2071. }
  2072. });
  2073. }
  2074. if (groupModulesByPath || groupModulesByExtension) {
  2075. groupConfigs.push({
  2076. getKeys: module => {
  2077. if (!module.name) return;
  2078. const resource = parseResource(module.name.split("!").pop()).path;
  2079. const dataUrl = /^data:[^,;]+/.exec(resource);
  2080. if (dataUrl) return [dataUrl[0]];
  2081. const extensionMatch =
  2082. groupModulesByExtension && GROUP_EXTENSION_REGEXP.exec(resource);
  2083. const extension = extensionMatch ? extensionMatch[1] : "";
  2084. const pathMatch =
  2085. groupModulesByPath && GROUP_PATH_REGEXP.exec(resource);
  2086. const path = pathMatch ? pathMatch[1].split(/[/\\]/) : [];
  2087. const keys = [];
  2088. if (groupModulesByPath) {
  2089. if (extension)
  2090. keys.push(
  2091. path.length
  2092. ? `${path.join("/")}/*${extension}`
  2093. : `*${extension}`
  2094. );
  2095. while (path.length > 0) {
  2096. keys.push(path.join("/") + "/");
  2097. path.pop();
  2098. }
  2099. } else {
  2100. if (extension) keys.push(`*${extension}`);
  2101. }
  2102. return keys;
  2103. },
  2104. createGroup: (key, children, modules) => {
  2105. const isDataUrl = key.startsWith("data:");
  2106. return {
  2107. type: isDataUrl
  2108. ? "modules by mime type"
  2109. : groupModulesByPath
  2110. ? "modules by path"
  2111. : "modules by extension",
  2112. name: isDataUrl ? key.slice(/* 'data:'.length */ 5) : key,
  2113. children,
  2114. ...moduleGroup(children, modules)
  2115. };
  2116. }
  2117. });
  2118. }
  2119. },
  2120. excludeModules: (groupConfigs, context, { excludeModules }) => {
  2121. groupConfigs.push({
  2122. getKeys: module => {
  2123. const name = module.name;
  2124. if (name) {
  2125. const excluded = excludeModules.some(fn => fn(name, module, type));
  2126. if (excluded) return ["1"];
  2127. }
  2128. },
  2129. getOptions: () => ({
  2130. groupChildren: false,
  2131. force: true
  2132. }),
  2133. createGroup: (key, children, modules) => ({
  2134. type: "hidden modules",
  2135. filteredChildren: children.length,
  2136. ...moduleGroup(children, modules)
  2137. })
  2138. });
  2139. }
  2140. });
  2141. /** @type {Record<string, Record<string, (groupConfigs: GroupConfig[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */
  2142. const RESULT_GROUPERS = {
  2143. "compilation.assets": ASSETS_GROUPERS,
  2144. "asset.related": ASSETS_GROUPERS,
  2145. "compilation.modules": MODULES_GROUPERS("module"),
  2146. "chunk.modules": MODULES_GROUPERS("chunk"),
  2147. "chunk.rootModules": MODULES_GROUPERS("root-of-chunk"),
  2148. "module.modules": MODULES_GROUPERS("nested"),
  2149. "module.reasons": {
  2150. groupReasonsByOrigin: groupConfigs => {
  2151. groupConfigs.push({
  2152. getKeys: reason => {
  2153. return [reason.module];
  2154. },
  2155. createGroup: (key, children, reasons) => {
  2156. return {
  2157. type: "from origin",
  2158. module: key,
  2159. children,
  2160. ...reasonGroup(children, reasons)
  2161. };
  2162. }
  2163. });
  2164. }
  2165. }
  2166. };
  2167. // remove a prefixed "!" that can be specified to reverse sort order
  2168. const normalizeFieldKey = field => {
  2169. if (field[0] === "!") {
  2170. return field.slice(1);
  2171. }
  2172. return field;
  2173. };
  2174. // if a field is prefixed by a "!" reverse sort order
  2175. const sortOrderRegular = field => {
  2176. if (field[0] === "!") {
  2177. return false;
  2178. }
  2179. return true;
  2180. };
  2181. /**
  2182. * @param {string} field field name
  2183. * @returns {function(Object, Object): number} comparators
  2184. */
  2185. const sortByField = field => {
  2186. if (!field) {
  2187. /**
  2188. * @param {any} a first
  2189. * @param {any} b second
  2190. * @returns {-1|0|1} zero
  2191. */
  2192. const noSort = (a, b) => 0;
  2193. return noSort;
  2194. }
  2195. const fieldKey = normalizeFieldKey(field);
  2196. let sortFn = compareSelect(m => m[fieldKey], compareIds);
  2197. // if a field is prefixed with a "!" the sort is reversed!
  2198. const sortIsRegular = sortOrderRegular(field);
  2199. if (!sortIsRegular) {
  2200. const oldSortFn = sortFn;
  2201. sortFn = (a, b) => oldSortFn(b, a);
  2202. }
  2203. return sortFn;
  2204. };
  2205. const ASSET_SORTERS = {
  2206. /** @type {(comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void} */
  2207. assetsSort: (comparators, context, { assetsSort }) => {
  2208. comparators.push(sortByField(assetsSort));
  2209. },
  2210. _: comparators => {
  2211. comparators.push(compareSelect(a => a.name, compareIds));
  2212. }
  2213. };
  2214. /** @type {Record<string, Record<string, (comparators: Function[], context: StatsFactoryContext, options: NormalizedStatsOptions) => void>>} */
  2215. const RESULT_SORTERS = {
  2216. "compilation.chunks": {
  2217. chunksSort: (comparators, context, { chunksSort }) => {
  2218. comparators.push(sortByField(chunksSort));
  2219. }
  2220. },
  2221. "compilation.modules": {
  2222. modulesSort: (comparators, context, { modulesSort }) => {
  2223. comparators.push(sortByField(modulesSort));
  2224. }
  2225. },
  2226. "chunk.modules": {
  2227. chunkModulesSort: (comparators, context, { chunkModulesSort }) => {
  2228. comparators.push(sortByField(chunkModulesSort));
  2229. }
  2230. },
  2231. "module.modules": {
  2232. nestedModulesSort: (comparators, context, { nestedModulesSort }) => {
  2233. comparators.push(sortByField(nestedModulesSort));
  2234. }
  2235. },
  2236. "compilation.assets": ASSET_SORTERS,
  2237. "asset.related": ASSET_SORTERS
  2238. };
  2239. /**
  2240. * @param {Record<string, Record<string, Function>>} config the config see above
  2241. * @param {NormalizedStatsOptions} options stats options
  2242. * @param {function(string, Function): void} fn handler function called for every active line in config
  2243. * @returns {void}
  2244. */
  2245. const iterateConfig = (config, options, fn) => {
  2246. for (const hookFor of Object.keys(config)) {
  2247. const subConfig = config[hookFor];
  2248. for (const option of Object.keys(subConfig)) {
  2249. if (option !== "_") {
  2250. if (option.startsWith("!")) {
  2251. if (options[option.slice(1)]) continue;
  2252. } else {
  2253. const value = options[option];
  2254. if (
  2255. value === false ||
  2256. value === undefined ||
  2257. (Array.isArray(value) && value.length === 0)
  2258. )
  2259. continue;
  2260. }
  2261. }
  2262. fn(hookFor, subConfig[option]);
  2263. }
  2264. }
  2265. };
  2266. /** @type {Record<string, string>} */
  2267. const ITEM_NAMES = {
  2268. "compilation.children[]": "compilation",
  2269. "compilation.modules[]": "module",
  2270. "compilation.entrypoints[]": "chunkGroup",
  2271. "compilation.namedChunkGroups[]": "chunkGroup",
  2272. "compilation.errors[]": "error",
  2273. "compilation.warnings[]": "warning",
  2274. "chunk.modules[]": "module",
  2275. "chunk.rootModules[]": "module",
  2276. "chunk.origins[]": "chunkOrigin",
  2277. "compilation.chunks[]": "chunk",
  2278. "compilation.assets[]": "asset",
  2279. "asset.related[]": "asset",
  2280. "module.issuerPath[]": "moduleIssuer",
  2281. "module.reasons[]": "moduleReason",
  2282. "module.modules[]": "module",
  2283. "module.children[]": "module",
  2284. "moduleTrace[]": "moduleTraceItem",
  2285. "moduleTraceItem.dependencies[]": "moduleTraceDependency"
  2286. };
  2287. /**
  2288. * @param {Object[]} items items to be merged
  2289. * @returns {Object} an object
  2290. */
  2291. const mergeToObject = items => {
  2292. const obj = Object.create(null);
  2293. for (const item of items) {
  2294. obj[item.name] = item;
  2295. }
  2296. return obj;
  2297. };
  2298. /** @type {Record<string, (items: Object[]) => any>} */
  2299. const MERGER = {
  2300. "compilation.entrypoints": mergeToObject,
  2301. "compilation.namedChunkGroups": mergeToObject
  2302. };
  2303. class DefaultStatsFactoryPlugin {
  2304. /**
  2305. * Apply the plugin
  2306. * @param {Compiler} compiler the compiler instance
  2307. * @returns {void}
  2308. */
  2309. apply(compiler) {
  2310. compiler.hooks.compilation.tap("DefaultStatsFactoryPlugin", compilation => {
  2311. compilation.hooks.statsFactory.tap(
  2312. "DefaultStatsFactoryPlugin",
  2313. (stats, options, context) => {
  2314. iterateConfig(SIMPLE_EXTRACTORS, options, (hookFor, fn) => {
  2315. stats.hooks.extract
  2316. .for(hookFor)
  2317. .tap("DefaultStatsFactoryPlugin", (obj, data, ctx) =>
  2318. fn(obj, data, ctx, options, stats)
  2319. );
  2320. });
  2321. iterateConfig(FILTER, options, (hookFor, fn) => {
  2322. stats.hooks.filter
  2323. .for(hookFor)
  2324. .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) =>
  2325. fn(item, ctx, options, idx, i)
  2326. );
  2327. });
  2328. iterateConfig(FILTER_RESULTS, options, (hookFor, fn) => {
  2329. stats.hooks.filterResults
  2330. .for(hookFor)
  2331. .tap("DefaultStatsFactoryPlugin", (item, ctx, idx, i) =>
  2332. fn(item, ctx, options, idx, i)
  2333. );
  2334. });
  2335. iterateConfig(SORTERS, options, (hookFor, fn) => {
  2336. stats.hooks.sort
  2337. .for(hookFor)
  2338. .tap("DefaultStatsFactoryPlugin", (comparators, ctx) =>
  2339. fn(comparators, ctx, options)
  2340. );
  2341. });
  2342. iterateConfig(RESULT_SORTERS, options, (hookFor, fn) => {
  2343. stats.hooks.sortResults
  2344. .for(hookFor)
  2345. .tap("DefaultStatsFactoryPlugin", (comparators, ctx) =>
  2346. fn(comparators, ctx, options)
  2347. );
  2348. });
  2349. iterateConfig(RESULT_GROUPERS, options, (hookFor, fn) => {
  2350. stats.hooks.groupResults
  2351. .for(hookFor)
  2352. .tap("DefaultStatsFactoryPlugin", (groupConfigs, ctx) =>
  2353. fn(groupConfigs, ctx, options)
  2354. );
  2355. });
  2356. for (const key of Object.keys(ITEM_NAMES)) {
  2357. const itemName = ITEM_NAMES[key];
  2358. stats.hooks.getItemName
  2359. .for(key)
  2360. .tap("DefaultStatsFactoryPlugin", () => itemName);
  2361. }
  2362. for (const key of Object.keys(MERGER)) {
  2363. const merger = MERGER[key];
  2364. stats.hooks.merge.for(key).tap("DefaultStatsFactoryPlugin", merger);
  2365. }
  2366. if (options.children) {
  2367. if (Array.isArray(options.children)) {
  2368. stats.hooks.getItemFactory
  2369. .for("compilation.children[].compilation")
  2370. .tap("DefaultStatsFactoryPlugin", (comp, { _index: idx }) => {
  2371. if (idx < options.children.length) {
  2372. return compilation.createStatsFactory(
  2373. compilation.createStatsOptions(
  2374. options.children[idx],
  2375. context
  2376. )
  2377. );
  2378. }
  2379. });
  2380. } else if (options.children !== true) {
  2381. const childFactory = compilation.createStatsFactory(
  2382. compilation.createStatsOptions(options.children, context)
  2383. );
  2384. stats.hooks.getItemFactory
  2385. .for("compilation.children[].compilation")
  2386. .tap("DefaultStatsFactoryPlugin", () => {
  2387. return childFactory;
  2388. });
  2389. }
  2390. }
  2391. }
  2392. );
  2393. });
  2394. }
  2395. }
  2396. module.exports = DefaultStatsFactoryPlugin;