DefaultStatsFactoryPlugin.js 87 KB

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