source: imaps-frontend/node_modules/webpack/lib/optimize/SplitChunksPlugin.js@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

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