DefaultStatsFactoryPlugin.js 80 KB

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