SplitChunksPlugin.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Chunk = require("../Chunk");
  7. const { STAGE_ADVANCED } = require("../OptimizationStages");
  8. const WebpackError = require("../errors/WebpackError");
  9. const { requestToId } = require("../ids/IdHelpers");
  10. const { isSubset } = require("../util/SetHelpers");
  11. const SortableSet = require("../util/SortableSet");
  12. const {
  13. compareIterables,
  14. compareModulesByIdentifier
  15. } = require("../util/comparators");
  16. const createHash = require("../util/createHash");
  17. const deterministicGrouping = require("../util/deterministicGrouping");
  18. const { makePathsRelative } = require("../util/identifier");
  19. const memoize = require("../util/memoize");
  20. const MinMaxSizeWarning = require("./MinMaxSizeWarning");
  21. /**
  22. * @import {
  23. * OptimizationSplitChunksCacheGroup,
  24. * OptimizationSplitChunksOptions,
  25. * OptimizationSplitChunksSizes
  26. * } from "../../declarations/WebpackOptions"
  27. */
  28. /**
  29. * @import {
  30. * OutputNormalizedWithDefaults as OutputOptions
  31. * } from "../config/defaults"
  32. */
  33. /** @import { ChunkName, ChunkFilenameTemplate } from "../Chunk" */
  34. /** @import ChunkGraph from "../ChunkGraph" */
  35. /** @import ChunkGroup from "../ChunkGroup" */
  36. /** @import Compilation from "../Compilation" */
  37. /** @import Compiler from "../Compiler" */
  38. /** @import Module, { SourceType } from "../Module" */
  39. /** @import ModuleGraph from "../ModuleGraph" */
  40. /** @typedef {import("../util/deterministicGrouping").GroupedItems<Module>} DeterministicGroupingGroupedItemsForModule */
  41. /** @typedef {import("../util/deterministicGrouping").Options<Module>} DeterministicGroupingOptionsForModule */
  42. /** @import { Sizes } from "../util/deterministicGrouping" */
  43. /**
  44. * Defines the chunk filter fn callback.
  45. * @callback ChunkFilterFn
  46. * @param {Chunk} chunk
  47. * @returns {boolean | undefined}
  48. */
  49. /** @typedef {number} Priority */
  50. /** @typedef {number} Size */
  51. /** @typedef {number} CountOfChunk */
  52. /** @typedef {number} CountOfRequest */
  53. /**
  54. * Defines the combine size function callback.
  55. * @callback CombineSizeFunction
  56. * @param {Size} a
  57. * @param {Size} b
  58. * @returns {Size}
  59. */
  60. /** @typedef {SourceType[]} SourceTypes */
  61. /** @typedef {SourceType[]} DefaultSizeTypes */
  62. /** @typedef {Record<SourceType, Size>} SplitChunksSizes */
  63. /**
  64. * Defines the cache group source type used by this module.
  65. * @typedef {object} CacheGroupSource
  66. * @property {string} key
  67. * @property {Priority=} priority
  68. * @property {GetNameFn=} getName
  69. * @property {ChunkFilterFn=} chunksFilter
  70. * @property {boolean=} enforce
  71. * @property {SplitChunksSizes} minSize
  72. * @property {SplitChunksSizes} minSizeReduction
  73. * @property {SplitChunksSizes} minRemainingSize
  74. * @property {SplitChunksSizes} enforceSizeThreshold
  75. * @property {SplitChunksSizes} maxAsyncSize
  76. * @property {SplitChunksSizes} maxInitialSize
  77. * @property {CountOfChunk=} minChunks
  78. * @property {CountOfRequest=} maxAsyncRequests
  79. * @property {CountOfRequest=} maxInitialRequests
  80. * @property {ChunkFilenameTemplate=} filename
  81. * @property {string=} idHint
  82. * @property {string=} automaticNameDelimiter
  83. * @property {boolean=} reuseExistingChunk
  84. * @property {boolean=} usedExports
  85. */
  86. /**
  87. * Defines the cache group type used by this module.
  88. * @typedef {object} CacheGroup
  89. * @property {string} key
  90. * @property {Priority} priority
  91. * @property {GetNameFn=} getName
  92. * @property {ChunkFilterFn} chunksFilter
  93. * @property {SplitChunksSizes} minSize
  94. * @property {SplitChunksSizes} minSizeReduction
  95. * @property {SplitChunksSizes} minRemainingSize
  96. * @property {SplitChunksSizes} enforceSizeThreshold
  97. * @property {SplitChunksSizes} maxAsyncSize
  98. * @property {SplitChunksSizes} maxInitialSize
  99. * @property {CountOfChunk} minChunks
  100. * @property {CountOfRequest} maxAsyncRequests
  101. * @property {CountOfRequest} maxInitialRequests
  102. * @property {ChunkFilenameTemplate=} filename
  103. * @property {string} idHint
  104. * @property {string} automaticNameDelimiter
  105. * @property {boolean} reuseExistingChunk
  106. * @property {boolean} usedExports
  107. * @property {boolean} _validateSize
  108. * @property {boolean} _validateRemainingSize
  109. * @property {SplitChunksSizes} _minSizeForMaxSize
  110. * @property {boolean} _conditionalEnforce
  111. */
  112. /**
  113. * Defines the fallback cache group type used by this module.
  114. * @typedef {object} FallbackCacheGroup
  115. * @property {ChunkFilterFn} chunksFilter
  116. * @property {SplitChunksSizes} minSize
  117. * @property {SplitChunksSizes} maxAsyncSize
  118. * @property {SplitChunksSizes} maxInitialSize
  119. * @property {string} automaticNameDelimiter
  120. */
  121. /**
  122. * Defines the cache groups context type used by this module.
  123. * @typedef {object} CacheGroupsContext
  124. * @property {ModuleGraph} moduleGraph
  125. * @property {ChunkGraph} chunkGraph
  126. */
  127. /** @typedef {(module: Module) => OptimizationSplitChunksCacheGroup | OptimizationSplitChunksCacheGroup[] | void} RawGetCacheGroups */
  128. /**
  129. * Defines the get cache groups callback.
  130. * @callback GetCacheGroups
  131. * @param {Module} module
  132. * @param {CacheGroupsContext} context
  133. * @returns {CacheGroupSource[] | null}
  134. */
  135. /**
  136. * Defines the get name fn callback.
  137. * @callback GetNameFn
  138. * @param {Module} module
  139. * @param {Chunk[]} chunks
  140. * @param {string} key
  141. * @returns {string | undefined}
  142. */
  143. /**
  144. * Defines the split chunks options type used by this module.
  145. * @typedef {object} SplitChunksOptions
  146. * @property {ChunkFilterFn} chunksFilter
  147. * @property {DefaultSizeTypes} defaultSizeTypes
  148. * @property {SplitChunksSizes} minSize
  149. * @property {SplitChunksSizes} minSizeReduction
  150. * @property {SplitChunksSizes} minRemainingSize
  151. * @property {SplitChunksSizes} enforceSizeThreshold
  152. * @property {SplitChunksSizes} maxInitialSize
  153. * @property {SplitChunksSizes} maxAsyncSize
  154. * @property {CountOfChunk} minChunks
  155. * @property {CountOfRequest} maxAsyncRequests
  156. * @property {CountOfRequest} maxInitialRequests
  157. * @property {boolean} hidePathInfo
  158. * @property {ChunkFilenameTemplate=} filename
  159. * @property {string} automaticNameDelimiter
  160. * @property {GetCacheGroups} getCacheGroups
  161. * @property {GetNameFn} getName
  162. * @property {boolean} usedExports
  163. * @property {FallbackCacheGroup} fallbackCacheGroup
  164. */
  165. /** @typedef {Set<Chunk>} ChunkSet */
  166. /**
  167. * Defines the chunks info item type used by this module.
  168. * @typedef {object} ChunksInfoItem
  169. * @property {SortableSet<Module>} modules
  170. * @property {CacheGroup} cacheGroup
  171. * @property {number} cacheGroupIndex
  172. * @property {string=} name
  173. * @property {SplitChunksSizes} sizes
  174. * @property {ChunkSet} chunks
  175. * @property {Set<bigint | Chunk>} chunksKeys
  176. */
  177. /** @type {GetNameFn} */
  178. const defaultGetName = () => undefined;
  179. const deterministicGroupingForModules =
  180. /** @type {(options: DeterministicGroupingOptionsForModule) => DeterministicGroupingGroupedItemsForModule[]} */
  181. (deterministicGrouping);
  182. /** @type {WeakMap<Module, string>} */
  183. const getKeyCache = new WeakMap();
  184. /**
  185. * Returns hashed filename.
  186. * @param {string} name a filename to hash
  187. * @param {OutputOptions} outputOptions hash function used
  188. * @returns {string} hashed filename
  189. */
  190. const hashFilename = (name, outputOptions) => {
  191. const digest =
  192. /** @type {string} */
  193. (
  194. createHash(outputOptions.hashFunction)
  195. .update(name)
  196. .digest(outputOptions.hashDigest)
  197. );
  198. return digest.slice(0, 8);
  199. };
  200. /**
  201. * A split `maxInitialRequests`/`maxAsyncRequests` refused, recorded for
  202. * `performance.splitChunksCapped`.
  203. * @typedef {object} CappedSplit
  204. * @property {string} cacheGroup the cache group whose split was refused
  205. * @property {Chunk} chunk the chunk it would have been taken out of
  206. * @property {"maxAsyncRequests" | "maxInitialRequests"} limit the option that refused it
  207. * @property {number} maxRequests the value that option had
  208. * @property {number} modules how many modules the split would have moved
  209. */
  210. /** @type {WeakMap<Compilation, CappedSplit[]>} */
  211. const CAPPED_SPLITS = new WeakMap();
  212. /**
  213. * Reads back the splits a request cap refused during this compilation.
  214. * @param {Compilation} compilation the compilation
  215. * @returns {CappedSplit[] | undefined} the refused splits, or `undefined` when nothing recorded them
  216. */
  217. const getCappedSplits = (compilation) => CAPPED_SPLITS.get(compilation);
  218. /**
  219. * Returns the number of requests.
  220. * @param {Chunk} chunk the chunk
  221. * @returns {CountOfRequest} the number of requests
  222. */
  223. const getRequests = (chunk) => {
  224. let requests = 0;
  225. for (const chunkGroup of chunk.groupsIterable) {
  226. requests = Math.max(requests, chunkGroup.chunks.length);
  227. }
  228. return requests;
  229. };
  230. /**
  231. * Returns result.
  232. * @template {object} T
  233. * @param {T} obj obj an object
  234. * @param {(obj: T[keyof T], key: keyof T) => T[keyof T]} fn fn
  235. * @returns {T} result
  236. */
  237. const mapObject = (obj, fn) => {
  238. /** @type {T} */
  239. const newObj = Object.create(null);
  240. for (const key of Object.keys(obj)) {
  241. newObj[/** @type {keyof T} */ (key)] = fn(
  242. obj[/** @type {keyof T} */ (key)],
  243. /** @type {keyof T} */
  244. (key)
  245. );
  246. }
  247. return newObj;
  248. };
  249. /**
  250. * Checks whether this object is overlap.
  251. * @template T
  252. * @param {Set<T>} a set
  253. * @param {Set<T>} b other set
  254. * @returns {boolean} true if at least one item of a is in b
  255. */
  256. const isOverlap = (a, b) => {
  257. for (const item of a) {
  258. if (b.has(item)) return true;
  259. }
  260. return false;
  261. };
  262. const compareModuleIterables = compareIterables(compareModulesByIdentifier);
  263. /**
  264. * Compares the provided values and returns their ordering.
  265. * @param {ChunksInfoItem} a item
  266. * @param {ChunksInfoItem} b item
  267. * @returns {number} compare result
  268. */
  269. const compareEntries = (a, b) => {
  270. // 1. by priority
  271. const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority;
  272. if (diffPriority) return diffPriority;
  273. // 2. by number of chunks
  274. const diffCount = a.chunks.size - b.chunks.size;
  275. if (diffCount) return diffCount;
  276. // 3. by size reduction
  277. const aSizeReduce = totalSize(a.sizes) * (a.chunks.size - 1);
  278. const bSizeReduce = totalSize(b.sizes) * (b.chunks.size - 1);
  279. const diffSizeReduce = aSizeReduce - bSizeReduce;
  280. if (diffSizeReduce) return diffSizeReduce;
  281. // 4. by cache group index
  282. const indexDiff = b.cacheGroupIndex - a.cacheGroupIndex;
  283. if (indexDiff) return indexDiff;
  284. // 5. by number of modules (to be able to compare by identifier)
  285. const modulesA = a.modules;
  286. const modulesB = b.modules;
  287. const diff = modulesA.size - modulesB.size;
  288. if (diff) return diff;
  289. // 6. by module identifiers
  290. modulesA.sort();
  291. modulesB.sort();
  292. return compareModuleIterables(modulesA, modulesB);
  293. };
  294. /**
  295. * Initial chunk filter.
  296. * @param {Chunk} chunk the chunk
  297. * @returns {boolean} true, if the chunk is an entry chunk
  298. */
  299. const INITIAL_CHUNK_FILTER = (chunk) => chunk.canBeInitial();
  300. /**
  301. * Async chunk filter.
  302. * @param {Chunk} chunk the chunk
  303. * @returns {boolean} true, if the chunk is an async chunk
  304. */
  305. const ASYNC_CHUNK_FILTER = (chunk) => !chunk.canBeInitial();
  306. /**
  307. * Returns always true.
  308. * @param {Chunk} _chunk the chunk
  309. * @returns {boolean} always true
  310. */
  311. const ALL_CHUNK_FILTER = (_chunk) => true;
  312. /** Placeholder until a chunk set group is filled and its signatures are written. */
  313. const EMPTY_SIGNATURES = new Uint32Array(0);
  314. /**
  315. * Returns normalized representation.
  316. * @param {OptimizationSplitChunksSizes | undefined} value the sizes
  317. * @param {DefaultSizeTypes} defaultSizeTypes the default size types
  318. * @returns {SplitChunksSizes} normalized representation
  319. */
  320. const normalizeSizes = (value, defaultSizeTypes) => {
  321. if (typeof value === "number") {
  322. /** @type {SplitChunksSizes} */
  323. const o = {};
  324. for (const sizeType of defaultSizeTypes) o[sizeType] = value;
  325. return o;
  326. } else if (typeof value === "object" && value !== null) {
  327. return { ...value };
  328. }
  329. return {};
  330. };
  331. /**
  332. * Merges the provided values into a single result.
  333. * @param {...(SplitChunksSizes | undefined)} sizes the sizes
  334. * @returns {SplitChunksSizes} the merged sizes
  335. */
  336. const mergeSizes = (...sizes) => {
  337. /** @type {SplitChunksSizes} */
  338. let merged = {};
  339. for (let i = sizes.length - 1; i >= 0; i--) {
  340. merged = Object.assign(merged, sizes[i]);
  341. }
  342. return merged;
  343. };
  344. /**
  345. * Checks whether this object contains the size.
  346. * @param {SplitChunksSizes} sizes the sizes
  347. * @returns {boolean} true, if there are sizes > 0
  348. */
  349. const hasNonZeroSizes = (sizes) => {
  350. for (const key of /** @type {SourceType[]} */ (Object.keys(sizes))) {
  351. if (sizes[key] > 0) return true;
  352. }
  353. return false;
  354. };
  355. /**
  356. * Returns the combine sizes.
  357. * @param {SplitChunksSizes} a first sizes
  358. * @param {SplitChunksSizes} b second sizes
  359. * @param {CombineSizeFunction} combine a function to combine sizes
  360. * @returns {SplitChunksSizes} the combine sizes
  361. */
  362. const combineSizes = (a, b, combine) => {
  363. const aKeys = /** @type {Set<SourceType>} */ (new Set(Object.keys(a)));
  364. const bKeys = /** @type {Set<SourceType>} */ (new Set(Object.keys(b)));
  365. /** @type {SplitChunksSizes} */
  366. const result = {};
  367. for (const key of aKeys) {
  368. result[key] = bKeys.has(key) ? combine(a[key], b[key]) : a[key];
  369. }
  370. for (const key of bKeys) {
  371. if (!aKeys.has(key)) {
  372. result[key] = b[key];
  373. }
  374. }
  375. return result;
  376. };
  377. /**
  378. * Checks true if there are sizes and all existing sizes are at least minSize.
  379. * @param {SplitChunksSizes} sizes the sizes
  380. * @param {SplitChunksSizes} minSize the min sizes
  381. * @returns {boolean} true if there are sizes and all existing sizes are at least `minSize`
  382. */
  383. const checkMinSize = (sizes, minSize) => {
  384. for (const key of /** @type {SourceType[]} */ (Object.keys(minSize))) {
  385. const size = sizes[key];
  386. if (size === undefined || size === 0) continue;
  387. if (size < minSize[key]) return false;
  388. }
  389. return true;
  390. };
  391. /**
  392. * Checks min size reduction.
  393. * @param {SplitChunksSizes} sizes the sizes
  394. * @param {SplitChunksSizes} minSizeReduction the min sizes
  395. * @param {CountOfChunk} chunkCount number of chunks
  396. * @returns {boolean} true if there are sizes and all existing sizes are at least `minSizeReduction`
  397. */
  398. const checkMinSizeReduction = (sizes, minSizeReduction, chunkCount) => {
  399. for (const key of /** @type {SourceType[]} */ (
  400. Object.keys(minSizeReduction)
  401. )) {
  402. const size = sizes[key];
  403. if (size === undefined || size === 0) continue;
  404. if (size * chunkCount < minSizeReduction[key]) return false;
  405. }
  406. return true;
  407. };
  408. /**
  409. * Gets violating min sizes.
  410. * @param {SplitChunksSizes} sizes the sizes
  411. * @param {SplitChunksSizes} minSize the min sizes
  412. * @returns {undefined | SourceTypes} list of size types that are below min size
  413. */
  414. const getViolatingMinSizes = (sizes, minSize) => {
  415. /** @type {SourceTypes | undefined} */
  416. let list;
  417. for (const key of /** @type {SourceType[]} */ (Object.keys(minSize))) {
  418. const size = sizes[key];
  419. if (size === undefined || size === 0) continue;
  420. if (size < minSize[key]) {
  421. if (list === undefined) list = [key];
  422. else list.push(key);
  423. }
  424. }
  425. return list;
  426. };
  427. /**
  428. * Returns the total size.
  429. * @param {SplitChunksSizes} sizes the sizes
  430. * @returns {Size} the total size
  431. */
  432. const totalSize = (sizes) => {
  433. let size = 0;
  434. for (const key of /** @type {SourceType[]} */ (Object.keys(sizes))) {
  435. size += sizes[key];
  436. }
  437. return size;
  438. };
  439. /**
  440. * Returns a function to get the name of the chunk.
  441. * @param {OptimizationSplitChunksCacheGroup["name"]} name the chunk name
  442. * @returns {GetNameFn | undefined} a function to get the name of the chunk
  443. */
  444. const normalizeName = (name) => {
  445. if (typeof name === "string") {
  446. return () => name;
  447. }
  448. if (typeof name === "function") {
  449. return /** @type {GetNameFn} */ (name);
  450. }
  451. };
  452. /**
  453. * Normalizes chunks filter.
  454. * @param {OptimizationSplitChunksCacheGroup["chunks"]} chunks the chunk filter option
  455. * @returns {ChunkFilterFn | undefined} the chunk filter function
  456. */
  457. const normalizeChunksFilter = (chunks) => {
  458. if (chunks === "initial") {
  459. return INITIAL_CHUNK_FILTER;
  460. }
  461. if (chunks === "async") {
  462. return ASYNC_CHUNK_FILTER;
  463. }
  464. if (chunks === "all") {
  465. return ALL_CHUNK_FILTER;
  466. }
  467. if (chunks instanceof RegExp) {
  468. return (chunk) => (chunk.name ? chunks.test(chunk.name) : false);
  469. }
  470. if (typeof chunks === "function") {
  471. return chunks;
  472. }
  473. };
  474. /**
  475. * Normalizes cache groups.
  476. * @param {undefined | GetCacheGroups | Record<string, false | string | RegExp | RawGetCacheGroups | OptimizationSplitChunksCacheGroup>} cacheGroups the cache group options
  477. * @param {DefaultSizeTypes} defaultSizeTypes the default size types
  478. * @returns {GetCacheGroups} a function to get the cache groups
  479. */
  480. const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => {
  481. if (typeof cacheGroups === "function") {
  482. return cacheGroups;
  483. }
  484. if (typeof cacheGroups === "object" && cacheGroups !== null) {
  485. /** @type {((module: Module, context: CacheGroupsContext, results: CacheGroupSource[]) => void)[]} */
  486. const handlers = [];
  487. for (const key of Object.keys(cacheGroups)) {
  488. const option = cacheGroups[key];
  489. if (option === false) {
  490. continue;
  491. }
  492. if (typeof option === "string" || option instanceof RegExp) {
  493. const source = createCacheGroupSource({}, key, defaultSizeTypes);
  494. handlers.push((module, context, results) => {
  495. if (checkTest(option, module, context)) {
  496. results.push(source);
  497. }
  498. });
  499. } else if (typeof option === "function") {
  500. /** @type {WeakMap<OptimizationSplitChunksCacheGroup, CacheGroupSource>} */
  501. const cache = new WeakMap();
  502. handlers.push((module, context, results) => {
  503. const result = option(module);
  504. if (result) {
  505. const groups = Array.isArray(result) ? result : [result];
  506. for (const group of groups) {
  507. const cachedSource = cache.get(group);
  508. if (cachedSource !== undefined) {
  509. results.push(cachedSource);
  510. } else {
  511. const source = createCacheGroupSource(
  512. group,
  513. key,
  514. defaultSizeTypes
  515. );
  516. cache.set(group, source);
  517. results.push(source);
  518. }
  519. }
  520. }
  521. });
  522. } else {
  523. const source = createCacheGroupSource(option, key, defaultSizeTypes);
  524. handlers.push((module, context, results) => {
  525. if (
  526. checkTest(option.test, module, context) &&
  527. checkModuleType(option.type, module) &&
  528. checkModuleLayer(option.layer, module)
  529. ) {
  530. results.push(source);
  531. }
  532. });
  533. }
  534. }
  535. /**
  536. * Returns the matching cache groups.
  537. * @param {Module} module the current module
  538. * @param {CacheGroupsContext} context the current context
  539. * @returns {CacheGroupSource[]} the matching cache groups
  540. */
  541. const fn = (module, context) => {
  542. /** @type {CacheGroupSource[]} */
  543. const results = [];
  544. for (const fn of handlers) {
  545. fn(module, context, results);
  546. }
  547. return results;
  548. };
  549. return fn;
  550. }
  551. return () => null;
  552. };
  553. /** @typedef {(module: Module, context: CacheGroupsContext) => boolean} CheckTestFn */
  554. /**
  555. * Checks true, if the module should be selected.
  556. * @param {OptimizationSplitChunksCacheGroup["test"]} test test option
  557. * @param {Module} module the module
  558. * @param {CacheGroupsContext} context context object
  559. * @returns {boolean} true, if the module should be selected
  560. */
  561. const checkTest = (test, module, context) => {
  562. if (test === undefined) return true;
  563. if (typeof test === "function") {
  564. return test(module, context);
  565. }
  566. if (typeof test === "boolean") return test;
  567. if (typeof test === "string") {
  568. const name = module.nameForCondition();
  569. return name ? name.startsWith(test) : false;
  570. }
  571. if (test instanceof RegExp) {
  572. const name = module.nameForCondition();
  573. return name ? test.test(name) : false;
  574. }
  575. return false;
  576. };
  577. /** @typedef {(type: string) => boolean} CheckModuleTypeFn */
  578. /**
  579. * Checks module type.
  580. * @param {OptimizationSplitChunksCacheGroup["type"]} test type option
  581. * @param {Module} module the module
  582. * @returns {boolean} true, if the module should be selected
  583. */
  584. const checkModuleType = (test, module) => {
  585. if (test === undefined) return true;
  586. if (typeof test === "function") {
  587. return test(module.type);
  588. }
  589. if (typeof test === "string") {
  590. const type = module.type;
  591. return test === type;
  592. }
  593. if (test instanceof RegExp) {
  594. const type = module.type;
  595. return test.test(type);
  596. }
  597. return false;
  598. };
  599. /** @typedef {(layer: string | null) => boolean} CheckModuleLayerFn */
  600. /**
  601. * Checks module layer.
  602. * @param {OptimizationSplitChunksCacheGroup["layer"]} test type option
  603. * @param {Module} module the module
  604. * @returns {boolean} true, if the module should be selected
  605. */
  606. const checkModuleLayer = (test, module) => {
  607. if (test === undefined) return true;
  608. if (typeof test === "function") {
  609. return test(module.layer);
  610. }
  611. if (typeof test === "string") {
  612. const layer = module.layer;
  613. return test === "" ? !layer : layer ? layer.startsWith(test) : false;
  614. }
  615. if (test instanceof RegExp) {
  616. const layer = module.layer;
  617. return layer ? test.test(layer) : false;
  618. }
  619. return false;
  620. };
  621. /**
  622. * Creates a cache group source.
  623. * @param {OptimizationSplitChunksCacheGroup} options the group options
  624. * @param {string} key key of cache group
  625. * @param {DefaultSizeTypes} defaultSizeTypes the default size types
  626. * @returns {CacheGroupSource} the normalized cached group
  627. */
  628. const createCacheGroupSource = (options, key, defaultSizeTypes) => {
  629. const minSize = normalizeSizes(options.minSize, defaultSizeTypes);
  630. const minSizeReduction = normalizeSizes(
  631. options.minSizeReduction,
  632. defaultSizeTypes
  633. );
  634. const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes);
  635. return {
  636. key,
  637. priority: options.priority,
  638. getName: normalizeName(options.name),
  639. chunksFilter: normalizeChunksFilter(options.chunks),
  640. enforce: options.enforce,
  641. minSize,
  642. minSizeReduction,
  643. minRemainingSize: mergeSizes(
  644. normalizeSizes(options.minRemainingSize, defaultSizeTypes),
  645. minSize
  646. ),
  647. enforceSizeThreshold: normalizeSizes(
  648. options.enforceSizeThreshold,
  649. defaultSizeTypes
  650. ),
  651. maxAsyncSize: mergeSizes(
  652. normalizeSizes(options.maxAsyncSize, defaultSizeTypes),
  653. maxSize
  654. ),
  655. maxInitialSize: mergeSizes(
  656. normalizeSizes(options.maxInitialSize, defaultSizeTypes),
  657. maxSize
  658. ),
  659. minChunks: options.minChunks,
  660. maxAsyncRequests: options.maxAsyncRequests,
  661. maxInitialRequests: options.maxInitialRequests,
  662. filename: options.filename,
  663. idHint: options.idHint,
  664. automaticNameDelimiter: options.automaticNameDelimiter,
  665. reuseExistingChunk: options.reuseExistingChunk,
  666. usedExports: options.usedExports
  667. };
  668. };
  669. const PLUGIN_NAME = "SplitChunksPlugin";
  670. class SplitChunksPlugin {
  671. /**
  672. * Creates an instance of SplitChunksPlugin.
  673. * @param {OptimizationSplitChunksOptions=} options plugin options
  674. */
  675. constructor(options = {}) {
  676. const defaultSizeTypes = options.defaultSizeTypes || [
  677. "javascript",
  678. "unknown"
  679. ];
  680. const fallbackCacheGroup = options.fallbackCacheGroup || {};
  681. const minSize = normalizeSizes(options.minSize, defaultSizeTypes);
  682. const minSizeReduction = normalizeSizes(
  683. options.minSizeReduction,
  684. defaultSizeTypes
  685. );
  686. const maxSize = normalizeSizes(options.maxSize, defaultSizeTypes);
  687. /** @type {SplitChunksOptions} */
  688. this.options = {
  689. chunksFilter:
  690. /** @type {ChunkFilterFn} */
  691. (normalizeChunksFilter(options.chunks || "all")),
  692. defaultSizeTypes,
  693. minSize,
  694. minSizeReduction,
  695. minRemainingSize: mergeSizes(
  696. normalizeSizes(options.minRemainingSize, defaultSizeTypes),
  697. minSize
  698. ),
  699. enforceSizeThreshold: normalizeSizes(
  700. options.enforceSizeThreshold,
  701. defaultSizeTypes
  702. ),
  703. maxAsyncSize: mergeSizes(
  704. normalizeSizes(options.maxAsyncSize, defaultSizeTypes),
  705. maxSize
  706. ),
  707. maxInitialSize: mergeSizes(
  708. normalizeSizes(options.maxInitialSize, defaultSizeTypes),
  709. maxSize
  710. ),
  711. minChunks: options.minChunks || 1,
  712. maxAsyncRequests: options.maxAsyncRequests || 1,
  713. maxInitialRequests: options.maxInitialRequests || 1,
  714. hidePathInfo: options.hidePathInfo || false,
  715. filename: options.filename || undefined,
  716. getCacheGroups: normalizeCacheGroups(
  717. options.cacheGroups,
  718. defaultSizeTypes
  719. ),
  720. getName: options.name
  721. ? /** @type {GetNameFn} */ (normalizeName(options.name))
  722. : defaultGetName,
  723. automaticNameDelimiter: options.automaticNameDelimiter || "-",
  724. usedExports: options.usedExports || false,
  725. fallbackCacheGroup: {
  726. chunksFilter:
  727. /** @type {ChunkFilterFn} */
  728. (
  729. normalizeChunksFilter(
  730. fallbackCacheGroup.chunks || options.chunks || "all"
  731. )
  732. ),
  733. minSize: mergeSizes(
  734. normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes),
  735. minSize
  736. ),
  737. maxAsyncSize: mergeSizes(
  738. normalizeSizes(fallbackCacheGroup.maxAsyncSize, defaultSizeTypes),
  739. normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes),
  740. normalizeSizes(options.maxAsyncSize, defaultSizeTypes),
  741. normalizeSizes(options.maxSize, defaultSizeTypes)
  742. ),
  743. maxInitialSize: mergeSizes(
  744. normalizeSizes(fallbackCacheGroup.maxInitialSize, defaultSizeTypes),
  745. normalizeSizes(fallbackCacheGroup.maxSize, defaultSizeTypes),
  746. normalizeSizes(options.maxInitialSize, defaultSizeTypes),
  747. normalizeSizes(options.maxSize, defaultSizeTypes)
  748. ),
  749. automaticNameDelimiter:
  750. fallbackCacheGroup.automaticNameDelimiter ||
  751. options.automaticNameDelimiter ||
  752. "~"
  753. }
  754. };
  755. /** @type {WeakMap<CacheGroupSource, CacheGroup>} */
  756. this._cacheGroupCache = new WeakMap();
  757. }
  758. /**
  759. * Returns the cache group (cached).
  760. * @param {CacheGroupSource} cacheGroupSource source
  761. * @returns {CacheGroup} the cache group (cached)
  762. */
  763. _getCacheGroup(cacheGroupSource) {
  764. const cacheEntry = this._cacheGroupCache.get(cacheGroupSource);
  765. if (cacheEntry !== undefined) return cacheEntry;
  766. const minSize = mergeSizes(
  767. cacheGroupSource.minSize,
  768. cacheGroupSource.enforce ? undefined : this.options.minSize
  769. );
  770. const minSizeReduction = mergeSizes(
  771. cacheGroupSource.minSizeReduction,
  772. cacheGroupSource.enforce ? undefined : this.options.minSizeReduction
  773. );
  774. const minRemainingSize = mergeSizes(
  775. cacheGroupSource.minRemainingSize,
  776. cacheGroupSource.enforce ? undefined : this.options.minRemainingSize
  777. );
  778. const enforceSizeThreshold = mergeSizes(
  779. cacheGroupSource.enforceSizeThreshold,
  780. cacheGroupSource.enforce ? undefined : this.options.enforceSizeThreshold
  781. );
  782. /** @type {CacheGroup} */
  783. const cacheGroup = {
  784. key: cacheGroupSource.key,
  785. priority: cacheGroupSource.priority || 0,
  786. chunksFilter: cacheGroupSource.chunksFilter || this.options.chunksFilter,
  787. minSize,
  788. minSizeReduction,
  789. minRemainingSize,
  790. enforceSizeThreshold,
  791. maxAsyncSize: mergeSizes(
  792. cacheGroupSource.maxAsyncSize,
  793. cacheGroupSource.enforce ? undefined : this.options.maxAsyncSize
  794. ),
  795. maxInitialSize: mergeSizes(
  796. cacheGroupSource.maxInitialSize,
  797. cacheGroupSource.enforce ? undefined : this.options.maxInitialSize
  798. ),
  799. minChunks:
  800. cacheGroupSource.minChunks !== undefined
  801. ? cacheGroupSource.minChunks
  802. : cacheGroupSource.enforce
  803. ? 1
  804. : this.options.minChunks,
  805. maxAsyncRequests:
  806. cacheGroupSource.maxAsyncRequests !== undefined
  807. ? cacheGroupSource.maxAsyncRequests
  808. : cacheGroupSource.enforce
  809. ? Infinity
  810. : this.options.maxAsyncRequests,
  811. maxInitialRequests:
  812. cacheGroupSource.maxInitialRequests !== undefined
  813. ? cacheGroupSource.maxInitialRequests
  814. : cacheGroupSource.enforce
  815. ? Infinity
  816. : this.options.maxInitialRequests,
  817. getName:
  818. cacheGroupSource.getName !== undefined
  819. ? cacheGroupSource.getName
  820. : this.options.getName,
  821. usedExports:
  822. cacheGroupSource.usedExports !== undefined
  823. ? cacheGroupSource.usedExports
  824. : this.options.usedExports,
  825. filename:
  826. cacheGroupSource.filename !== undefined
  827. ? cacheGroupSource.filename
  828. : this.options.filename,
  829. automaticNameDelimiter:
  830. cacheGroupSource.automaticNameDelimiter !== undefined
  831. ? cacheGroupSource.automaticNameDelimiter
  832. : this.options.automaticNameDelimiter,
  833. idHint:
  834. cacheGroupSource.idHint !== undefined
  835. ? cacheGroupSource.idHint
  836. : cacheGroupSource.key,
  837. reuseExistingChunk: cacheGroupSource.reuseExistingChunk || false,
  838. _validateSize: hasNonZeroSizes(minSize),
  839. _validateRemainingSize: hasNonZeroSizes(minRemainingSize),
  840. _minSizeForMaxSize: mergeSizes(
  841. cacheGroupSource.minSize,
  842. this.options.minSize
  843. ),
  844. _conditionalEnforce: hasNonZeroSizes(enforceSizeThreshold)
  845. };
  846. this._cacheGroupCache.set(cacheGroupSource, cacheGroup);
  847. return cacheGroup;
  848. }
  849. /**
  850. * Applies the plugin by registering its hooks on the compiler.
  851. * @param {Compiler} compiler the compiler instance
  852. * @returns {void}
  853. */
  854. apply(compiler) {
  855. const cachedMakePathsRelative = makePathsRelative.bindContextCache(
  856. compiler.context,
  857. compiler.root
  858. );
  859. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  860. const logger = compilation.getLogger(`webpack.${PLUGIN_NAME}`);
  861. let alreadyOptimized = false;
  862. compilation.hooks.unseal.tap(PLUGIN_NAME, () => {
  863. alreadyOptimized = false;
  864. });
  865. compilation.hooks.optimizeChunks.tap(
  866. {
  867. name: PLUGIN_NAME,
  868. stage: STAGE_ADVANCED
  869. },
  870. (chunks) => {
  871. if (alreadyOptimized) return;
  872. alreadyOptimized = true;
  873. const { performance } = compilation.options;
  874. // Mirrors both of `SplitChunksCappedPlugin`'s gates: a build that
  875. // would not report records nothing and allocates nothing.
  876. /** @type {CappedSplit[] | undefined} */
  877. let cappedSplits;
  878. if (
  879. performance !== false &&
  880. performance.splitChunksCapped === true &&
  881. Boolean(performance.hints)
  882. ) {
  883. cappedSplits = [];
  884. CAPPED_SPLITS.set(compilation, cappedSplits);
  885. }
  886. logger.time("prepare");
  887. const chunkGraph = compilation.chunkGraph;
  888. const moduleGraph = compilation.moduleGraph;
  889. // Give each selected chunk an index (to create strings from chunks)
  890. /** @type {Map<Chunk, bigint>} */
  891. const chunkIndexMap = new Map();
  892. // Dense per-chunk index, folded into the 64 bit membership
  893. // signatures that reject non-subsets in getCombinations
  894. /** @type {Map<Chunk, number>} */
  895. const chunkSignatureBitMap = new Map();
  896. const ZERO = BigInt("0");
  897. const ONE = BigInt("1");
  898. const START = ONE << BigInt("31");
  899. let index = START;
  900. let denseIndex = 0;
  901. for (const chunk of chunks) {
  902. chunkIndexMap.set(
  903. chunk,
  904. index | BigInt((Math.random() * 0x7fffffff) | 0)
  905. );
  906. chunkSignatureBitMap.set(chunk, denseIndex++ & 63);
  907. index <<= ONE;
  908. }
  909. /**
  910. * Returns key of the chunks.
  911. * @param {Iterable<Chunk, undefined, undefined>} chunks list of chunks
  912. * @returns {bigint | Chunk} key of the chunks
  913. */
  914. const getKey = (chunks) => {
  915. const iterator = chunks[Symbol.iterator]();
  916. let result = iterator.next();
  917. if (result.done) return ZERO;
  918. const first = result.value;
  919. result = iterator.next();
  920. if (result.done) return first;
  921. let key =
  922. /** @type {bigint} */ (chunkIndexMap.get(first)) |
  923. /** @type {bigint} */ (chunkIndexMap.get(result.value));
  924. while (!(result = iterator.next()).done) {
  925. const raw = chunkIndexMap.get(result.value);
  926. key ^= /** @type {bigint} */ (raw);
  927. }
  928. return key;
  929. };
  930. /**
  931. * Returns stringified key.
  932. * @param {bigint | Chunk} key key of the chunks
  933. * @returns {string} stringified key
  934. */
  935. const keyToString = (key) => {
  936. if (typeof key === "bigint") return key.toString(16);
  937. return /** @type {bigint} */ (chunkIndexMap.get(key)).toString(16);
  938. };
  939. const getChunkSetsInGraph = memoize(() => {
  940. /** @type {Map<bigint, ChunkSet>} */
  941. const chunkSetsInGraph = new Map();
  942. /** @type {ChunkSet} */
  943. const singleChunkSets = new Set();
  944. for (const module of compilation.modules) {
  945. const chunks = chunkGraph.getModuleChunksIterable(module);
  946. const chunksKey = getKey(chunks);
  947. if (typeof chunksKey === "bigint") {
  948. if (!chunkSetsInGraph.has(chunksKey)) {
  949. chunkSetsInGraph.set(chunksKey, new Set(chunks));
  950. }
  951. } else {
  952. singleChunkSets.add(chunksKey);
  953. }
  954. }
  955. return { chunkSetsInGraph, singleChunkSets };
  956. });
  957. /**
  958. * Group chunks by exports.
  959. * @param {Module} module the module
  960. * @returns {Iterable<Chunk[]>} groups of chunks with equal exports
  961. */
  962. const groupChunksByExports = (module) => {
  963. const exportsInfo = moduleGraph.getExportsInfo(module);
  964. /** @type {Map<string, Chunk[]>} */
  965. const groupedByUsedExports = new Map();
  966. for (const chunk of chunkGraph.getModuleChunksIterable(module)) {
  967. const key = exportsInfo.getUsageKey(chunk.runtime);
  968. const list = groupedByUsedExports.get(key);
  969. if (list !== undefined) {
  970. list.push(chunk);
  971. } else {
  972. groupedByUsedExports.set(key, [chunk]);
  973. }
  974. }
  975. return groupedByUsedExports.values();
  976. };
  977. /** @type {Map<Module, Iterable<Chunk[]>>} */
  978. const groupedByExportsMap = new Map();
  979. /** @typedef {Map<bigint | Chunk, ChunkSet>} ChunkSetsInGraph */
  980. const getExportsChunkSetsInGraph = memoize(() => {
  981. /** @type {ChunkSetsInGraph} */
  982. const chunkSetsInGraph = new Map();
  983. /** @type {ChunkSet} */
  984. const singleChunkSets = new Set();
  985. for (const module of compilation.modules) {
  986. const groupedChunks = [...groupChunksByExports(module)];
  987. groupedByExportsMap.set(module, groupedChunks);
  988. for (const chunks of groupedChunks) {
  989. if (chunks.length === 1) {
  990. singleChunkSets.add(chunks[0]);
  991. } else {
  992. const chunksKey = getKey(chunks);
  993. if (!chunkSetsInGraph.has(chunksKey)) {
  994. chunkSetsInGraph.set(chunksKey, new Set(chunks));
  995. }
  996. }
  997. }
  998. }
  999. return { chunkSetsInGraph, singleChunkSets };
  1000. });
  1001. /**
  1002. * Chunk sets of equal size, with a 64 bit membership signature
  1003. * per set stored as two words at `2 * i` in `signatures`.
  1004. * @typedef {object} ChunkSetGroup
  1005. * @property {ChunkSet[]} sets the chunk sets
  1006. * @property {Uint32Array} signatures two signature words per set
  1007. */
  1008. /** @typedef {Map<CountOfChunk, ChunkSetGroup>} ChunkSetsByCount */
  1009. // holds the signature of the set currently being combined; transient
  1010. const signatureScratch = new Uint32Array(2);
  1011. /**
  1012. * Folds a chunk set into a 64 bit membership signature.
  1013. * @param {ChunkSet} chunksSet set of chunks
  1014. * @param {Uint32Array} out target array
  1015. * @param {number} offset index of the first of the two words
  1016. * @returns {void}
  1017. */
  1018. const writeSignature = (chunksSet, out, offset) => {
  1019. out[offset] = 0;
  1020. out[offset + 1] = 0;
  1021. for (const chunk of chunksSet) {
  1022. const bit = /** @type {number} */ (
  1023. chunkSignatureBitMap.get(chunk)
  1024. );
  1025. out[offset + (bit >> 5)] |= 1 << (bit & 31);
  1026. }
  1027. };
  1028. // group these set of chunks by count
  1029. // to allow to check less sets via isSubset
  1030. // (only smaller sets can be subset)
  1031. /**
  1032. * Group chunk sets by count.
  1033. * @param {IterableIterator<ChunkSet>} chunkSets set of sets of chunks
  1034. * @returns {ChunkSetsByCount} map of sets of chunks by count
  1035. */
  1036. const groupChunkSetsByCount = (chunkSets) => {
  1037. /** @type {ChunkSetsByCount} */
  1038. const chunkSetsByCount = new Map();
  1039. for (const chunksSet of chunkSets) {
  1040. const count = chunksSet.size;
  1041. let group = chunkSetsByCount.get(count);
  1042. if (group === undefined) {
  1043. group = { sets: [], signatures: EMPTY_SIGNATURES };
  1044. chunkSetsByCount.set(count, group);
  1045. }
  1046. group.sets.push(chunksSet);
  1047. }
  1048. for (const group of chunkSetsByCount.values()) {
  1049. const { sets } = group;
  1050. const signatures = new Uint32Array(sets.length * 2);
  1051. for (let i = 0; i < sets.length; i++) {
  1052. writeSignature(sets[i], signatures, i * 2);
  1053. }
  1054. group.signatures = signatures;
  1055. }
  1056. return chunkSetsByCount;
  1057. };
  1058. const getChunkSetsByCount = memoize(() =>
  1059. groupChunkSetsByCount(
  1060. getChunkSetsInGraph().chunkSetsInGraph.values()
  1061. )
  1062. );
  1063. const getExportsChunkSetsByCount = memoize(() =>
  1064. groupChunkSetsByCount(
  1065. getExportsChunkSetsInGraph().chunkSetsInGraph.values()
  1066. )
  1067. );
  1068. /** @typedef {(ChunkSet | Chunk)[]} Combinations */
  1069. // Create a list of possible combinations
  1070. /**
  1071. * Creates a get combinations.
  1072. * @param {ChunkSetsInGraph} chunkSets chunk sets
  1073. * @param {ChunkSet} singleChunkSets single chunks sets
  1074. * @param {ChunkSetsByCount} chunkSetsByCount chunk sets by count
  1075. * @returns {(key: bigint | Chunk) => Combinations} combinations
  1076. */
  1077. const createGetCombinations = (
  1078. chunkSets,
  1079. singleChunkSets,
  1080. chunkSetsByCount
  1081. ) => {
  1082. /** @type {Map<bigint | Chunk, Combinations>} */
  1083. const combinationsCache = new Map();
  1084. return (key) => {
  1085. const cacheEntry = combinationsCache.get(key);
  1086. if (cacheEntry !== undefined) return cacheEntry;
  1087. if (key instanceof Chunk) {
  1088. const result = [key];
  1089. combinationsCache.set(key, result);
  1090. return result;
  1091. }
  1092. const chunksSet =
  1093. /** @type {ChunkSet} */
  1094. (chunkSets.get(key));
  1095. /** @type {Combinations} */
  1096. const array = [chunksSet];
  1097. writeSignature(chunksSet, signatureScratch, 0);
  1098. const selfLow = signatureScratch[0];
  1099. const selfHigh = signatureScratch[1];
  1100. for (const [count, group] of chunkSetsByCount) {
  1101. // "equal" is not needed because they would have been merge in the first step
  1102. if (count < chunksSet.size) {
  1103. const { sets, signatures } = group;
  1104. for (let i = 0; i < sets.length; i++) {
  1105. // a subset cannot hold a signature bit the superset lacks,
  1106. // so this rejects nearly every candidate without touching the Set
  1107. const offset = i * 2;
  1108. if (
  1109. (signatures[offset] & ~selfLow) !== 0 ||
  1110. (signatures[offset + 1] & ~selfHigh) !== 0
  1111. ) {
  1112. continue;
  1113. }
  1114. const set = sets[i];
  1115. if (isSubset(chunksSet, set)) {
  1116. array.push(set);
  1117. }
  1118. }
  1119. }
  1120. }
  1121. for (const chunk of singleChunkSets) {
  1122. if (chunksSet.has(chunk)) {
  1123. array.push(chunk);
  1124. }
  1125. }
  1126. combinationsCache.set(key, array);
  1127. return array;
  1128. };
  1129. };
  1130. const getCombinationsFactory = memoize(() => {
  1131. const { chunkSetsInGraph, singleChunkSets } = getChunkSetsInGraph();
  1132. return createGetCombinations(
  1133. chunkSetsInGraph,
  1134. singleChunkSets,
  1135. getChunkSetsByCount()
  1136. );
  1137. });
  1138. /**
  1139. * Returns combinations by key.
  1140. * @param {bigint | Chunk} key key
  1141. * @returns {Combinations} combinations by key
  1142. */
  1143. const getCombinations = (key) => getCombinationsFactory()(key);
  1144. const getExportsCombinationsFactory = memoize(() => {
  1145. const { chunkSetsInGraph, singleChunkSets } =
  1146. getExportsChunkSetsInGraph();
  1147. return createGetCombinations(
  1148. chunkSetsInGraph,
  1149. singleChunkSets,
  1150. getExportsChunkSetsByCount()
  1151. );
  1152. });
  1153. /**
  1154. * Gets exports combinations.
  1155. * @param {bigint | Chunk} key key
  1156. * @returns {Combinations} exports combinations by key
  1157. */
  1158. const getExportsCombinations = (key) =>
  1159. getExportsCombinationsFactory()(key);
  1160. /**
  1161. * Defines the selected chunks result type used by this module.
  1162. * @typedef {object} SelectedChunksResult
  1163. * @property {Chunk[]} chunks the list of chunks
  1164. * @property {bigint | Chunk} key a key of the list
  1165. */
  1166. /** @typedef {WeakMap<ChunkFilterFn, SelectedChunksResult>} ChunkMap */
  1167. /** @type {WeakMap<ChunkSet | Chunk, ChunkMap>} */
  1168. const selectedChunksCacheByChunksSet = new WeakMap();
  1169. /**
  1170. * get list and key by applying the filter function to the list
  1171. * It is cached for performance reasons
  1172. * @param {ChunkSet | Chunk} chunks list of chunks
  1173. * @param {ChunkFilterFn} chunkFilter filter function for chunks
  1174. * @returns {SelectedChunksResult} list and key
  1175. */
  1176. const getSelectedChunks = (chunks, chunkFilter) => {
  1177. let entry = selectedChunksCacheByChunksSet.get(chunks);
  1178. if (entry === undefined) {
  1179. /** @type {ChunkMap} */
  1180. entry = new WeakMap();
  1181. selectedChunksCacheByChunksSet.set(chunks, entry);
  1182. }
  1183. let entry2 =
  1184. /** @type {SelectedChunksResult} */
  1185. (entry.get(chunkFilter));
  1186. if (entry2 === undefined) {
  1187. /** @type {Chunk[]} */
  1188. const selectedChunks = [];
  1189. if (chunks instanceof Chunk) {
  1190. if (chunkFilter(chunks)) selectedChunks.push(chunks);
  1191. } else {
  1192. for (const chunk of chunks) {
  1193. if (chunkFilter(chunk)) selectedChunks.push(chunk);
  1194. }
  1195. }
  1196. entry2 = {
  1197. chunks: selectedChunks,
  1198. key: getKey(selectedChunks)
  1199. };
  1200. entry.set(chunkFilter, entry2);
  1201. }
  1202. return entry2;
  1203. };
  1204. /** @type {Map<string, boolean>} */
  1205. const alreadyValidatedParents = new Map();
  1206. /** @type {Set<string>} */
  1207. const alreadyReportedErrors = new Set();
  1208. // Map a list of chunks to a list of modules
  1209. // For the key the chunk "index" is used, the value is a SortableSet of modules
  1210. /** @type {Map<string, ChunksInfoItem>} */
  1211. const chunksInfoMap = new Map();
  1212. // The unnamed key is derived only from cache group and chunk set, so it
  1213. // repeats for every module sharing that pair — build the string once
  1214. /** @type {Map<CacheGroup, Map<bigint | Chunk, string>>} */
  1215. const unnamedKeyCache = new Map();
  1216. /**
  1217. * Returns the chunksInfoMap key for a cache group and chunk set.
  1218. * @param {CacheGroup} cacheGroup the current cache group
  1219. * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks
  1220. * @returns {string} key into chunksInfoMap
  1221. */
  1222. const getUnnamedKey = (cacheGroup, selectedChunksKey) => {
  1223. let byChunksKey = unnamedKeyCache.get(cacheGroup);
  1224. if (byChunksKey === undefined) {
  1225. byChunksKey = new Map();
  1226. unnamedKeyCache.set(cacheGroup, byChunksKey);
  1227. }
  1228. let key = byChunksKey.get(selectedChunksKey);
  1229. if (key === undefined) {
  1230. key = `${cacheGroup.key} chunks:${keyToString(selectedChunksKey)}`;
  1231. byChunksKey.set(selectedChunksKey, key);
  1232. }
  1233. return key;
  1234. };
  1235. /**
  1236. * Adds module to chunks info map.
  1237. * @param {CacheGroup} cacheGroup the current cache group
  1238. * @param {number} cacheGroupIndex the index of the cache group of ordering
  1239. * @param {Chunk[]} selectedChunks chunks selected for this module
  1240. * @param {bigint | Chunk} selectedChunksKey a key of selectedChunks
  1241. * @param {Module} module the current module
  1242. * @returns {void}
  1243. */
  1244. const addModuleToChunksInfoMap = (
  1245. cacheGroup,
  1246. cacheGroupIndex,
  1247. selectedChunks,
  1248. selectedChunksKey,
  1249. module
  1250. ) => {
  1251. // Break if minimum number of chunks is not reached
  1252. if (selectedChunks.length < cacheGroup.minChunks) return;
  1253. // Determine name for split chunk
  1254. const name =
  1255. /** @type {GetNameFn} */
  1256. (cacheGroup.getName)(module, selectedChunks, cacheGroup.key);
  1257. // Check if the name is ok
  1258. const existingChunk = name && compilation.namedChunks.get(name);
  1259. if (existingChunk) {
  1260. const parentValidationKey = `${name}|${
  1261. typeof selectedChunksKey === "bigint"
  1262. ? selectedChunksKey
  1263. : selectedChunksKey.debugId
  1264. }`;
  1265. const valid = alreadyValidatedParents.get(parentValidationKey);
  1266. if (valid === false) return;
  1267. if (valid === undefined) {
  1268. // Module can only be moved into the existing chunk if the existing chunk
  1269. // is a parent of all selected chunks
  1270. let isInAllParents = true;
  1271. /** @type {Set<ChunkGroup>} */
  1272. const queue = new Set();
  1273. for (const chunk of selectedChunks) {
  1274. for (const group of chunk.groupsIterable) {
  1275. queue.add(group);
  1276. }
  1277. }
  1278. for (const group of queue) {
  1279. if (existingChunk.isInGroup(group)) continue;
  1280. let hasParent = false;
  1281. for (const parent of group.parentsIterable) {
  1282. hasParent = true;
  1283. queue.add(parent);
  1284. }
  1285. if (!hasParent) {
  1286. isInAllParents = false;
  1287. }
  1288. }
  1289. const valid = isInAllParents;
  1290. alreadyValidatedParents.set(parentValidationKey, valid);
  1291. if (!valid) {
  1292. if (!alreadyReportedErrors.has(name)) {
  1293. alreadyReportedErrors.add(name);
  1294. compilation.errors.push(
  1295. new WebpackError(
  1296. `${PLUGIN_NAME}\n` +
  1297. `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` +
  1298. `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` +
  1299. "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" +
  1300. 'HINT: You can omit "name" to automatically create a name.\n' +
  1301. "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " +
  1302. "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" +
  1303. "Remove this entrypoint and add modules to cache group's 'test' instead. " +
  1304. "If you need modules to be evaluated on startup, add them to the existing entrypoints (make them arrays). " +
  1305. "See migration guide of more info."
  1306. )
  1307. );
  1308. }
  1309. return;
  1310. }
  1311. }
  1312. }
  1313. // Create key for maps
  1314. // When it has a name we use the name as key
  1315. // Otherwise we create the key from chunks and cache group key
  1316. // This automatically merges equal names
  1317. const key = name
  1318. ? `${cacheGroup.key} name:${name}`
  1319. : getUnnamedKey(cacheGroup, selectedChunksKey);
  1320. // Add module to maps
  1321. let info = chunksInfoMap.get(key);
  1322. if (info === undefined) {
  1323. chunksInfoMap.set(
  1324. key,
  1325. (info = {
  1326. modules: new SortableSet(
  1327. undefined,
  1328. compareModulesByIdentifier
  1329. ),
  1330. cacheGroup,
  1331. cacheGroupIndex,
  1332. name,
  1333. sizes: {},
  1334. chunks: new Set(),
  1335. chunksKeys: new Set()
  1336. })
  1337. );
  1338. }
  1339. const oldSize = info.modules.size;
  1340. info.modules.add(module);
  1341. if (info.modules.size !== oldSize) {
  1342. for (const type of module.getSourceTypes()) {
  1343. info.sizes[type] = (info.sizes[type] || 0) + module.size(type);
  1344. }
  1345. }
  1346. const oldChunksKeysSize = info.chunksKeys.size;
  1347. info.chunksKeys.add(selectedChunksKey);
  1348. if (oldChunksKeysSize !== info.chunksKeys.size) {
  1349. for (const chunk of selectedChunks) {
  1350. info.chunks.add(chunk);
  1351. }
  1352. }
  1353. };
  1354. const context = {
  1355. moduleGraph,
  1356. chunkGraph
  1357. };
  1358. /**
  1359. * Returns combinations of the chunks the module is in.
  1360. * @param {Module} module the module
  1361. * @returns {Combinations} chunk combinations
  1362. */
  1363. const computeCombinations = (module) =>
  1364. getCombinations(getKey(chunkGraph.getModuleChunksIterable(module)));
  1365. /**
  1366. * Returns combinations of the module's chunks grouped by used exports.
  1367. * @param {Module} module the module
  1368. * @returns {Set<ChunkSet | Chunk>} chunk combinations
  1369. */
  1370. const computeCombinationsByUsedExports = (module) => {
  1371. // fill the groupedByExportsMap
  1372. getExportsChunkSetsInGraph();
  1373. /** @type {Set<ChunkSet | Chunk>} */
  1374. const set = new Set();
  1375. const groupedByUsedExports =
  1376. /** @type {Iterable<Chunk[]>} */
  1377. (groupedByExportsMap.get(module));
  1378. for (const chunks of groupedByUsedExports) {
  1379. for (const comb of getExportsCombinations(getKey(chunks))) {
  1380. set.add(comb);
  1381. }
  1382. }
  1383. return set;
  1384. };
  1385. logger.timeEnd("prepare");
  1386. logger.time("modules");
  1387. // Walk through all modules
  1388. for (const module of compilation.modules) {
  1389. // Get cache group
  1390. const cacheGroups = this.options.getCacheGroups(module, context);
  1391. if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) {
  1392. continue;
  1393. }
  1394. // Computed at most once per module, on first use by a cache group
  1395. /** @type {Combinations | undefined} */
  1396. let combsCache;
  1397. /** @type {Set<ChunkSet | Chunk> | undefined} */
  1398. let combsByUsedExportsCache;
  1399. let cacheGroupIndex = 0;
  1400. for (const cacheGroupSource of cacheGroups) {
  1401. const cacheGroup = this._getCacheGroup(cacheGroupSource);
  1402. let combs;
  1403. if (cacheGroup.usedExports) {
  1404. if (combsByUsedExportsCache === undefined) {
  1405. combsByUsedExportsCache =
  1406. computeCombinationsByUsedExports(module);
  1407. }
  1408. combs = combsByUsedExportsCache;
  1409. } else {
  1410. if (combsCache === undefined) {
  1411. combsCache = computeCombinations(module);
  1412. }
  1413. combs = combsCache;
  1414. }
  1415. // For all combination of chunk selection
  1416. for (const chunkCombination of combs) {
  1417. // Break if minimum number of chunks is not reached
  1418. const count =
  1419. chunkCombination instanceof Chunk ? 1 : chunkCombination.size;
  1420. if (count < cacheGroup.minChunks) continue;
  1421. // Select chunks by configuration
  1422. const { chunks: selectedChunks, key: selectedChunksKey } =
  1423. getSelectedChunks(
  1424. chunkCombination,
  1425. /** @type {ChunkFilterFn} */
  1426. (cacheGroup.chunksFilter)
  1427. );
  1428. addModuleToChunksInfoMap(
  1429. cacheGroup,
  1430. cacheGroupIndex,
  1431. selectedChunks,
  1432. selectedChunksKey,
  1433. module
  1434. );
  1435. }
  1436. cacheGroupIndex++;
  1437. }
  1438. }
  1439. logger.timeEnd("modules");
  1440. logger.time("queue");
  1441. /**
  1442. * Removes modules with source type.
  1443. * @param {ChunksInfoItem} info entry
  1444. * @param {SourceTypes} sourceTypes source types to be removed
  1445. */
  1446. const removeModulesWithSourceType = (info, sourceTypes) => {
  1447. for (const module of info.modules) {
  1448. const types = module.getSourceTypes();
  1449. if (sourceTypes.some((type) => types.has(type))) {
  1450. info.modules.delete(module);
  1451. for (const type of types) {
  1452. info.sizes[type] -= module.size(type);
  1453. }
  1454. }
  1455. }
  1456. };
  1457. /**
  1458. * Removes min size violating modules.
  1459. * @param {ChunksInfoItem} info entry
  1460. * @returns {boolean} true, if entry become empty
  1461. */
  1462. const removeMinSizeViolatingModules = (info) => {
  1463. if (!info.cacheGroup._validateSize) return false;
  1464. const violatingSizes = getViolatingMinSizes(
  1465. info.sizes,
  1466. info.cacheGroup.minSize
  1467. );
  1468. if (violatingSizes === undefined) return false;
  1469. removeModulesWithSourceType(info, violatingSizes);
  1470. return info.modules.size === 0;
  1471. };
  1472. // Filter items were size < minSize
  1473. for (const [key, info] of chunksInfoMap) {
  1474. if (removeMinSizeViolatingModules(info)) {
  1475. chunksInfoMap.delete(key);
  1476. } else if (
  1477. !checkMinSizeReduction(
  1478. info.sizes,
  1479. info.cacheGroup.minSizeReduction,
  1480. info.chunks.size
  1481. )
  1482. ) {
  1483. chunksInfoMap.delete(key);
  1484. }
  1485. }
  1486. /**
  1487. * Defines the max size queue item type used by this module.
  1488. * @typedef {object} MaxSizeQueueItem
  1489. * @property {SplitChunksSizes} minSize
  1490. * @property {SplitChunksSizes} maxAsyncSize
  1491. * @property {SplitChunksSizes} maxInitialSize
  1492. * @property {string} automaticNameDelimiter
  1493. * @property {string[]} keys
  1494. */
  1495. /** @type {Map<Chunk, MaxSizeQueueItem>} */
  1496. const maxSizeQueueMap = new Map();
  1497. while (chunksInfoMap.size > 0) {
  1498. // Find best matching entry
  1499. /** @type {undefined | string} */
  1500. let bestEntryKey;
  1501. /** @type {undefined | ChunksInfoItem} */
  1502. let bestEntry;
  1503. for (const pair of chunksInfoMap) {
  1504. const key = pair[0];
  1505. const info = pair[1];
  1506. if (
  1507. bestEntry === undefined ||
  1508. compareEntries(bestEntry, info) < 0
  1509. ) {
  1510. bestEntry = info;
  1511. bestEntryKey = key;
  1512. }
  1513. }
  1514. const item = /** @type {ChunksInfoItem} */ (bestEntry);
  1515. chunksInfoMap.delete(/** @type {string} */ (bestEntryKey));
  1516. /** @type {ChunkName | undefined} */
  1517. let chunkName = item.name;
  1518. // Variable for the new chunk (lazy created)
  1519. /** @type {Chunk | undefined} */
  1520. let newChunk;
  1521. // When no chunk name, check if we can reuse a chunk instead of creating a new one
  1522. let isExistingChunk = false;
  1523. let isReusedWithAllModules = false;
  1524. if (chunkName) {
  1525. const chunkByName = compilation.namedChunks.get(chunkName);
  1526. if (chunkByName !== undefined) {
  1527. newChunk = chunkByName;
  1528. const oldSize = item.chunks.size;
  1529. item.chunks.delete(newChunk);
  1530. isExistingChunk = item.chunks.size !== oldSize;
  1531. }
  1532. } else if (item.cacheGroup.reuseExistingChunk) {
  1533. outer: for (const chunk of item.chunks) {
  1534. if (
  1535. chunkGraph.getNumberOfChunkModules(chunk) !==
  1536. item.modules.size
  1537. ) {
  1538. continue;
  1539. }
  1540. if (
  1541. item.chunks.size > 1 &&
  1542. chunkGraph.getNumberOfEntryModules(chunk) > 0
  1543. ) {
  1544. continue;
  1545. }
  1546. for (const module of item.modules) {
  1547. if (!chunkGraph.isModuleInChunk(module, chunk)) {
  1548. continue outer;
  1549. }
  1550. }
  1551. if (!newChunk || !newChunk.name) {
  1552. newChunk = chunk;
  1553. } else if (
  1554. chunk.name &&
  1555. chunk.name.length < newChunk.name.length
  1556. ) {
  1557. newChunk = chunk;
  1558. } else if (
  1559. chunk.name &&
  1560. chunk.name.length === newChunk.name.length &&
  1561. chunk.name < newChunk.name
  1562. ) {
  1563. newChunk = chunk;
  1564. }
  1565. }
  1566. if (newChunk) {
  1567. item.chunks.delete(newChunk);
  1568. chunkName = undefined;
  1569. isExistingChunk = true;
  1570. isReusedWithAllModules = true;
  1571. }
  1572. }
  1573. const enforced =
  1574. item.cacheGroup._conditionalEnforce &&
  1575. checkMinSize(item.sizes, item.cacheGroup.enforceSizeThreshold);
  1576. /** @type {Set<Chunk>} */
  1577. const usedChunks = new Set(item.chunks);
  1578. // Check if maxRequests condition can be fulfilled
  1579. if (
  1580. !enforced &&
  1581. (Number.isFinite(item.cacheGroup.maxInitialRequests) ||
  1582. Number.isFinite(item.cacheGroup.maxAsyncRequests))
  1583. ) {
  1584. for (const chunk of usedChunks) {
  1585. // respect max requests: a chunk that is both initial and
  1586. // async answers to the stricter of the two caps
  1587. const isOnlyInitial = chunk.isOnlyInitial();
  1588. const byAsyncRequests =
  1589. !isOnlyInitial &&
  1590. (!chunk.canBeInitial() ||
  1591. item.cacheGroup.maxAsyncRequests <
  1592. item.cacheGroup.maxInitialRequests);
  1593. const maxRequests = byAsyncRequests
  1594. ? item.cacheGroup.maxAsyncRequests
  1595. : item.cacheGroup.maxInitialRequests;
  1596. if (
  1597. Number.isFinite(maxRequests) &&
  1598. getRequests(chunk) >= maxRequests
  1599. ) {
  1600. if (cappedSplits !== undefined) {
  1601. cappedSplits.push({
  1602. cacheGroup: item.cacheGroup.key,
  1603. chunk,
  1604. // which cap it was cannot be read back off the value:
  1605. // the two are equal by default in production
  1606. limit: byAsyncRequests
  1607. ? "maxAsyncRequests"
  1608. : "maxInitialRequests",
  1609. maxRequests:
  1610. /** @type {number} */
  1611. (maxRequests),
  1612. modules: item.modules.size
  1613. });
  1614. }
  1615. usedChunks.delete(chunk);
  1616. }
  1617. }
  1618. }
  1619. outer: for (const chunk of usedChunks) {
  1620. for (const module of item.modules) {
  1621. if (chunkGraph.isModuleInChunk(module, chunk)) continue outer;
  1622. }
  1623. usedChunks.delete(chunk);
  1624. }
  1625. // Were some (invalid) chunks removed from usedChunks?
  1626. // => readd all modules to the queue, as things could have been changed
  1627. if (usedChunks.size < item.chunks.size) {
  1628. if (isExistingChunk) {
  1629. usedChunks.add(/** @type {Chunk} */ (newChunk));
  1630. }
  1631. if (usedChunks.size >= item.cacheGroup.minChunks) {
  1632. const chunksArr = [...usedChunks];
  1633. // invariant across the module loop below
  1634. const usedChunksKey = getKey(usedChunks);
  1635. for (const module of item.modules) {
  1636. addModuleToChunksInfoMap(
  1637. item.cacheGroup,
  1638. item.cacheGroupIndex,
  1639. chunksArr,
  1640. usedChunksKey,
  1641. module
  1642. );
  1643. }
  1644. }
  1645. continue;
  1646. }
  1647. // Validate minRemainingSize constraint when a single chunk is left over
  1648. if (
  1649. !enforced &&
  1650. item.cacheGroup._validateRemainingSize &&
  1651. usedChunks.size === 1
  1652. ) {
  1653. const [chunk] = usedChunks;
  1654. /** @type {SplitChunksSizes} */
  1655. const chunkSizes = Object.create(null);
  1656. for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
  1657. if (!item.modules.has(module)) {
  1658. for (const type of module.getSourceTypes()) {
  1659. chunkSizes[type] =
  1660. (chunkSizes[type] || 0) + module.size(type);
  1661. }
  1662. }
  1663. }
  1664. const violatingSizes = getViolatingMinSizes(
  1665. chunkSizes,
  1666. item.cacheGroup.minRemainingSize
  1667. );
  1668. if (violatingSizes !== undefined) {
  1669. const oldModulesSize = item.modules.size;
  1670. removeModulesWithSourceType(item, violatingSizes);
  1671. if (
  1672. item.modules.size > 0 &&
  1673. item.modules.size !== oldModulesSize
  1674. ) {
  1675. // queue this item again to be processed again
  1676. // without violating modules
  1677. chunksInfoMap.set(/** @type {string} */ (bestEntryKey), item);
  1678. }
  1679. continue;
  1680. }
  1681. }
  1682. // Create the new chunk if not reusing one
  1683. if (newChunk === undefined) {
  1684. newChunk = compilation.addChunk(chunkName);
  1685. }
  1686. // Walk through all chunks
  1687. for (const chunk of usedChunks) {
  1688. // Add graph connections for splitted chunk
  1689. chunk.split(newChunk);
  1690. }
  1691. // Add a note to the chunk
  1692. newChunk.chunkReason =
  1693. (newChunk.chunkReason ? `${newChunk.chunkReason}, ` : "") +
  1694. (isReusedWithAllModules
  1695. ? "reused as split chunk"
  1696. : "split chunk");
  1697. if (item.cacheGroup.key) {
  1698. newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`;
  1699. }
  1700. if (chunkName) {
  1701. newChunk.chunkReason += ` (name: ${chunkName})`;
  1702. }
  1703. if (item.cacheGroup.filename) {
  1704. newChunk.filenameTemplate = item.cacheGroup.filename;
  1705. }
  1706. if (item.cacheGroup.idHint) {
  1707. newChunk.idNameHints.add(item.cacheGroup.idHint);
  1708. }
  1709. if (!isReusedWithAllModules) {
  1710. // Add all modules to the new chunk
  1711. for (const module of item.modules) {
  1712. if (!module.chunkCondition(newChunk, compilation)) continue;
  1713. // Add module to new chunk
  1714. chunkGraph.connectChunkAndModule(newChunk, module);
  1715. // Remove module from used chunks
  1716. for (const chunk of usedChunks) {
  1717. chunkGraph.disconnectChunkAndModule(chunk, module);
  1718. }
  1719. }
  1720. } else {
  1721. // Remove all modules from used chunks
  1722. for (const module of item.modules) {
  1723. for (const chunk of usedChunks) {
  1724. chunkGraph.disconnectChunkAndModule(chunk, module);
  1725. }
  1726. }
  1727. }
  1728. if (
  1729. Object.keys(item.cacheGroup.maxAsyncSize).length > 0 ||
  1730. Object.keys(item.cacheGroup.maxInitialSize).length > 0
  1731. ) {
  1732. const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk);
  1733. maxSizeQueueMap.set(newChunk, {
  1734. minSize: oldMaxSizeSettings
  1735. ? combineSizes(
  1736. oldMaxSizeSettings.minSize,
  1737. item.cacheGroup._minSizeForMaxSize,
  1738. Math.max
  1739. )
  1740. : item.cacheGroup.minSize,
  1741. maxAsyncSize: oldMaxSizeSettings
  1742. ? combineSizes(
  1743. oldMaxSizeSettings.maxAsyncSize,
  1744. item.cacheGroup.maxAsyncSize,
  1745. Math.min
  1746. )
  1747. : item.cacheGroup.maxAsyncSize,
  1748. maxInitialSize: oldMaxSizeSettings
  1749. ? combineSizes(
  1750. oldMaxSizeSettings.maxInitialSize,
  1751. item.cacheGroup.maxInitialSize,
  1752. Math.min
  1753. )
  1754. : item.cacheGroup.maxInitialSize,
  1755. automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter,
  1756. keys: oldMaxSizeSettings
  1757. ? [...oldMaxSizeSettings.keys, item.cacheGroup.key]
  1758. : [item.cacheGroup.key]
  1759. });
  1760. }
  1761. // remove all modules from other entries and update size
  1762. for (const [key, info] of chunksInfoMap) {
  1763. if (isOverlap(info.chunks, usedChunks)) {
  1764. // update modules and total size
  1765. // may remove it from the map when < minSize
  1766. let updated = false;
  1767. for (const module of item.modules) {
  1768. if (info.modules.has(module)) {
  1769. // remove module
  1770. info.modules.delete(module);
  1771. // update size
  1772. for (const key of module.getSourceTypes()) {
  1773. info.sizes[key] -= module.size(key);
  1774. }
  1775. updated = true;
  1776. }
  1777. }
  1778. if (updated) {
  1779. if (info.modules.size === 0) {
  1780. chunksInfoMap.delete(key);
  1781. continue;
  1782. }
  1783. if (
  1784. removeMinSizeViolatingModules(info) ||
  1785. !checkMinSizeReduction(
  1786. info.sizes,
  1787. info.cacheGroup.minSizeReduction,
  1788. info.chunks.size
  1789. )
  1790. ) {
  1791. chunksInfoMap.delete(key);
  1792. continue;
  1793. }
  1794. }
  1795. }
  1796. }
  1797. }
  1798. logger.timeEnd("queue");
  1799. logger.time("maxSize");
  1800. /** @type {Set<string>} */
  1801. const incorrectMinMaxSizeSet = new Set();
  1802. const { outputOptions } = compilation;
  1803. // Make sure that maxSize is fulfilled
  1804. const { fallbackCacheGroup } = this.options;
  1805. for (const chunk of compilation.chunks) {
  1806. const chunkConfig = maxSizeQueueMap.get(chunk);
  1807. const {
  1808. minSize,
  1809. maxAsyncSize,
  1810. maxInitialSize,
  1811. automaticNameDelimiter
  1812. } = chunkConfig || fallbackCacheGroup;
  1813. if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk)) {
  1814. continue;
  1815. }
  1816. /** @type {SplitChunksSizes} */
  1817. let maxSize;
  1818. if (chunk.isOnlyInitial()) {
  1819. maxSize = maxInitialSize;
  1820. } else if (chunk.canBeInitial()) {
  1821. maxSize = combineSizes(maxAsyncSize, maxInitialSize, Math.min);
  1822. } else {
  1823. maxSize = maxAsyncSize;
  1824. }
  1825. if (Object.keys(maxSize).length === 0) {
  1826. continue;
  1827. }
  1828. for (const key of /** @type {SourceType[]} */ (
  1829. Object.keys(maxSize)
  1830. )) {
  1831. const maxSizeValue = maxSize[key];
  1832. const minSizeValue = minSize[key];
  1833. if (
  1834. typeof minSizeValue === "number" &&
  1835. minSizeValue > maxSizeValue
  1836. ) {
  1837. const keys = chunkConfig && chunkConfig.keys;
  1838. const warningKey = `${
  1839. keys && keys.join()
  1840. } ${minSizeValue} ${maxSizeValue}`;
  1841. if (!incorrectMinMaxSizeSet.has(warningKey)) {
  1842. incorrectMinMaxSizeSet.add(warningKey);
  1843. compilation.warnings.push(
  1844. new MinMaxSizeWarning(keys, minSizeValue, maxSizeValue)
  1845. );
  1846. }
  1847. }
  1848. }
  1849. const results = deterministicGroupingForModules({
  1850. minSize,
  1851. maxSize: mapObject(maxSize, (value, key) => {
  1852. const minSizeValue = minSize[key];
  1853. return typeof minSizeValue === "number"
  1854. ? Math.max(value, minSizeValue)
  1855. : value;
  1856. }),
  1857. items: chunkGraph.getChunkModulesIterable(chunk),
  1858. getKey(module) {
  1859. const cache = getKeyCache.get(module);
  1860. if (cache !== undefined) return cache;
  1861. const ident = cachedMakePathsRelative(module.identifier());
  1862. const nameForCondition =
  1863. module.nameForCondition && module.nameForCondition();
  1864. const name = nameForCondition
  1865. ? cachedMakePathsRelative(nameForCondition)
  1866. : ident.replace(/^.*!|\?[^?!]*$/g, "");
  1867. const fullKey =
  1868. name +
  1869. automaticNameDelimiter +
  1870. hashFilename(ident, outputOptions);
  1871. const key = requestToId(fullKey);
  1872. getKeyCache.set(module, key);
  1873. return key;
  1874. },
  1875. getSize(module) {
  1876. /** @type {Sizes} */
  1877. const size = Object.create(null);
  1878. for (const key of module.getSourceTypes()) {
  1879. size[key] = module.size(key);
  1880. }
  1881. return size;
  1882. }
  1883. });
  1884. if (results.length <= 1) {
  1885. continue;
  1886. }
  1887. for (let i = 0; i < results.length; i++) {
  1888. const group = results[i];
  1889. const key = this.options.hidePathInfo
  1890. ? hashFilename(group.key, outputOptions)
  1891. : group.key;
  1892. let name = chunk.name
  1893. ? chunk.name + automaticNameDelimiter + key
  1894. : null;
  1895. if (name && name.length > 100) {
  1896. name =
  1897. name.slice(0, 100) +
  1898. automaticNameDelimiter +
  1899. hashFilename(name, outputOptions);
  1900. }
  1901. if (i !== results.length - 1) {
  1902. const newPart = compilation.addChunk(name);
  1903. chunk.split(newPart);
  1904. newPart.chunkReason = chunk.chunkReason;
  1905. if (chunk.filenameTemplate) {
  1906. newPart.filenameTemplate = chunk.filenameTemplate;
  1907. }
  1908. // Add all modules to the new chunk
  1909. for (const module of group.items) {
  1910. if (!module.chunkCondition(newPart, compilation)) {
  1911. continue;
  1912. }
  1913. // Add module to new chunk
  1914. chunkGraph.connectChunkAndModule(newPart, module);
  1915. // Remove module from used chunks
  1916. chunkGraph.disconnectChunkAndModule(chunk, module);
  1917. }
  1918. } else {
  1919. // change the chunk to be a part
  1920. chunk.name = name;
  1921. }
  1922. }
  1923. }
  1924. logger.timeEnd("maxSize");
  1925. }
  1926. );
  1927. });
  1928. }
  1929. }
  1930. SplitChunksPlugin.getCappedSplits = getCappedSplits;
  1931. module.exports = SplitChunksPlugin;