buildChunkGraph.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const AsyncDependencyToInitialChunkError = require("./AsyncDependencyToInitialChunkError");
  7. const { connectChunkGroupParentAndChild } = require("./GraphHelpers");
  8. const ModuleGraphConnection = require("./ModuleGraphConnection");
  9. const { getEntryRuntime, mergeRuntime } = require("./util/runtime");
  10. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  11. /** @typedef {import("./Chunk")} Chunk */
  12. /** @typedef {import("./ChunkGroup")} ChunkGroup */
  13. /** @typedef {import("./Compilation")} Compilation */
  14. /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
  15. /** @typedef {import("./Dependency")} Dependency */
  16. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  17. /** @typedef {import("./Entrypoint")} Entrypoint */
  18. /** @typedef {import("./Module")} Module */
  19. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  20. /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
  21. /** @typedef {import("./logging/Logger").Logger} Logger */
  22. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  23. /**
  24. * @typedef {object} QueueItem
  25. * @property {number} action
  26. * @property {DependenciesBlock} block
  27. * @property {Module} module
  28. * @property {Chunk} chunk
  29. * @property {ChunkGroup} chunkGroup
  30. * @property {ChunkGroupInfo} chunkGroupInfo
  31. */
  32. /**
  33. * @typedef {object} ChunkGroupInfo
  34. * @property {ChunkGroup} chunkGroup the chunk group
  35. * @property {RuntimeSpec} runtime the runtimes
  36. * @property {bigint | undefined} minAvailableModules current minimal set of modules available at this point
  37. * @property {bigint[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules
  38. * @property {Set<Module>=} skippedItems modules that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking)
  39. * @property {Set<[Module, ModuleGraphConnection[]]>=} skippedModuleConnections referenced modules that where skipped because they were not active in this runtime
  40. * @property {bigint | undefined} resultingAvailableModules set of modules available including modules from this chunk group
  41. * @property {Set<ChunkGroupInfo> | undefined} children set of children chunk groups, that will be revisited when availableModules shrink
  42. * @property {Set<ChunkGroupInfo> | undefined} availableSources set of chunk groups that are the source for minAvailableModules
  43. * @property {Set<ChunkGroupInfo> | undefined} availableChildren set of chunk groups which depend on the this chunk group as availableSource
  44. * @property {number} preOrderIndex next pre order index
  45. * @property {number} postOrderIndex next post order index
  46. * @property {boolean} chunkLoading has a chunk loading mechanism
  47. * @property {boolean} asyncChunks create async chunks
  48. */
  49. /**
  50. * @typedef {object} BlockChunkGroupConnection
  51. * @property {ChunkGroupInfo} originChunkGroupInfo origin chunk group
  52. * @property {ChunkGroup} chunkGroup referenced chunk group
  53. */
  54. /** @typedef {(Module | ConnectionState | ModuleGraphConnection)[]} BlockModulesInTuples */
  55. /** @typedef {(Module | ConnectionState | ModuleGraphConnection[])[]} BlockModulesInFlattenTuples */
  56. /** @typedef {Map<DependenciesBlock, BlockModulesInFlattenTuples>} BlockModulesMap */
  57. /** @typedef {Map<Chunk, bigint>} MaskByChunk */
  58. /** @typedef {Set<DependenciesBlock>} BlocksWithNestedBlocks */
  59. /** @typedef {Map<AsyncDependenciesBlock, BlockChunkGroupConnection[]>} BlockConnections */
  60. /** @typedef {Map<ChunkGroup, ChunkGroupInfo>} ChunkGroupInfoMap */
  61. /** @typedef {Set<ChunkGroup>} AllCreatedChunkGroups */
  62. /** @typedef {Map<Entrypoint, Module[]>} InputEntrypointsAndModules */
  63. const ZERO_BIGINT = BigInt(0);
  64. const ONE_BIGINT = BigInt(1);
  65. /**
  66. * @param {bigint} mask The mask to test
  67. * @param {number} ordinal The ordinal of the bit to test
  68. * @returns {boolean} If the ordinal-th bit is set in the mask
  69. */
  70. const isOrdinalSetInMask = (mask, ordinal) =>
  71. BigInt.asUintN(1, mask >> BigInt(ordinal)) !== ZERO_BIGINT;
  72. /**
  73. * @param {ModuleGraphConnection[]} connections list of connections
  74. * @param {RuntimeSpec} runtime for which runtime
  75. * @returns {ConnectionState} connection state
  76. */
  77. const getActiveStateOfConnections = (connections, runtime) => {
  78. let merged = connections[0].getActiveState(runtime);
  79. if (merged === true) return true;
  80. for (let i = 1; i < connections.length; i++) {
  81. const c = connections[i];
  82. merged = ModuleGraphConnection.addConnectionStates(
  83. merged,
  84. c.getActiveState(runtime)
  85. );
  86. if (merged === true) return true;
  87. }
  88. return merged;
  89. };
  90. /**
  91. * @param {Module} module module
  92. * @param {ModuleGraph} moduleGraph module graph
  93. * @param {RuntimeSpec} runtime runtime
  94. * @param {BlockModulesMap} blockModulesMap block modules map
  95. */
  96. const extractBlockModules = (module, moduleGraph, runtime, blockModulesMap) => {
  97. /** @type {DependenciesBlock | undefined} */
  98. let blockCache;
  99. /** @type {BlockModulesInTuples | undefined} */
  100. let modules;
  101. /** @type {BlockModulesInTuples[]} */
  102. const arrays = [];
  103. /** @type {DependenciesBlock[]} */
  104. const queue = [module];
  105. while (queue.length > 0) {
  106. const block = /** @type {DependenciesBlock} */ (queue.pop());
  107. /** @type {Module[]} */
  108. const arr = [];
  109. arrays.push(arr);
  110. blockModulesMap.set(block, arr);
  111. for (const b of block.blocks) {
  112. queue.push(b);
  113. }
  114. }
  115. for (const connection of moduleGraph.getOutgoingConnections(module)) {
  116. const d = connection.dependency;
  117. // We skip connections without dependency
  118. if (!d) continue;
  119. const m = connection.module;
  120. // We skip connections without Module pointer
  121. if (!m) continue;
  122. // We skip weak connections
  123. if (connection.weak) continue;
  124. const block = moduleGraph.getParentBlock(d);
  125. let index = moduleGraph.getParentBlockIndex(d);
  126. // deprecated fallback
  127. if (index < 0) {
  128. index = /** @type {DependenciesBlock} */ (block).dependencies.indexOf(d);
  129. }
  130. if (blockCache !== block) {
  131. modules =
  132. /** @type {BlockModulesInTuples} */
  133. (
  134. blockModulesMap.get(
  135. (blockCache = /** @type {DependenciesBlock} */ (block))
  136. )
  137. );
  138. }
  139. const i = index * 3;
  140. /** @type {BlockModulesInTuples} */
  141. (modules)[i] = m;
  142. /** @type {BlockModulesInTuples} */
  143. (modules)[i + 1] = connection.getActiveState(runtime);
  144. /** @type {BlockModulesInTuples} */
  145. (modules)[i + 2] = connection;
  146. }
  147. for (const modules of arrays) {
  148. if (modules.length === 0) continue;
  149. let indexMap;
  150. let length = 0;
  151. outer: for (let j = 0; j < modules.length; j += 3) {
  152. const m = modules[j];
  153. if (m === undefined) continue;
  154. const state = /** @type {ConnectionState} */ (modules[j + 1]);
  155. const connection = /** @type {ModuleGraphConnection} */ (modules[j + 2]);
  156. if (indexMap === undefined) {
  157. let i = 0;
  158. for (; i < length; i += 3) {
  159. if (modules[i] === m) {
  160. const merged = /** @type {ConnectionState} */ (modules[i + 1]);
  161. /** @type {ModuleGraphConnection[]} */
  162. (/** @type {unknown} */ (modules[i + 2])).push(connection);
  163. if (merged === true) continue outer;
  164. modules[i + 1] = ModuleGraphConnection.addConnectionStates(
  165. merged,
  166. state
  167. );
  168. continue outer;
  169. }
  170. }
  171. modules[length] = m;
  172. length++;
  173. modules[length] = state;
  174. length++;
  175. /** @type {ModuleGraphConnection[]} */
  176. (/** @type {unknown} */ (modules[length])) = [connection];
  177. length++;
  178. if (length > 30) {
  179. // To avoid worse case performance, we will use an index map for
  180. // linear cost access, which allows to maintain O(n) complexity
  181. // while keeping allocations down to a minimum
  182. indexMap = new Map();
  183. for (let i = 0; i < length; i += 3) {
  184. indexMap.set(modules[i], i + 1);
  185. }
  186. }
  187. } else {
  188. const idx = indexMap.get(m);
  189. if (idx !== undefined) {
  190. const merged = /** @type {ConnectionState} */ (modules[idx]);
  191. /** @type {ModuleGraphConnection[]} */
  192. (/** @type {unknown} */ (modules[idx + 1])).push(connection);
  193. if (merged === true) continue outer;
  194. modules[idx] = ModuleGraphConnection.addConnectionStates(
  195. merged,
  196. state
  197. );
  198. } else {
  199. modules[length] = m;
  200. length++;
  201. modules[length] = state;
  202. indexMap.set(m, length);
  203. length++;
  204. /** @type {ModuleGraphConnection[]} */
  205. (
  206. /** @type {unknown} */
  207. (modules[length])
  208. ) = [connection];
  209. length++;
  210. }
  211. }
  212. }
  213. modules.length = length;
  214. }
  215. };
  216. /**
  217. *
  218. * @param {Logger} logger a logger
  219. * @param {Compilation} compilation the compilation
  220. * @param {InputEntrypointsAndModules} inputEntrypointsAndModules chunk groups which are processed with the modules
  221. * @param {ChunkGroupInfoMap} chunkGroupInfoMap mapping from chunk group to available modules
  222. * @param {BlockConnections} blockConnections connection for blocks
  223. * @param {BlocksWithNestedBlocks} blocksWithNestedBlocks flag for blocks that have nested blocks
  224. * @param {AllCreatedChunkGroups} allCreatedChunkGroups filled with all chunk groups that are created here
  225. * @param {MaskByChunk} maskByChunk module content mask by chunk
  226. */
  227. const visitModules = (
  228. logger,
  229. compilation,
  230. inputEntrypointsAndModules,
  231. chunkGroupInfoMap,
  232. blockConnections,
  233. blocksWithNestedBlocks,
  234. allCreatedChunkGroups,
  235. maskByChunk
  236. ) => {
  237. const { moduleGraph, chunkGraph, moduleMemCaches } = compilation;
  238. const blockModulesRuntimeMap = new Map();
  239. /** @type {BlockModulesMap | undefined} */
  240. let blockModulesMap;
  241. /** @type {Map<Module, number>} */
  242. const ordinalByModule = new Map();
  243. /**
  244. * @param {Module} module The module to look up
  245. * @returns {number} The ordinal of the module in masks
  246. */
  247. const getModuleOrdinal = module => {
  248. let ordinal = ordinalByModule.get(module);
  249. if (ordinal === undefined) {
  250. ordinal = ordinalByModule.size;
  251. ordinalByModule.set(module, ordinal);
  252. }
  253. return ordinal;
  254. };
  255. for (const chunk of compilation.chunks) {
  256. let mask = ZERO_BIGINT;
  257. for (const m of chunkGraph.getChunkModulesIterable(chunk)) {
  258. mask |= ONE_BIGINT << BigInt(getModuleOrdinal(m));
  259. }
  260. maskByChunk.set(chunk, mask);
  261. }
  262. /**
  263. *
  264. * @param {DependenciesBlock} block block
  265. * @param {RuntimeSpec} runtime runtime
  266. * @returns {BlockModulesInFlattenTuples} block modules in flatten tuples
  267. */
  268. const getBlockModules = (block, runtime) => {
  269. blockModulesMap = blockModulesRuntimeMap.get(runtime);
  270. if (blockModulesMap === undefined) {
  271. blockModulesMap = new Map();
  272. blockModulesRuntimeMap.set(runtime, blockModulesMap);
  273. }
  274. let blockModules = blockModulesMap.get(block);
  275. if (blockModules !== undefined) return blockModules;
  276. const module = /** @type {Module} */ (block.getRootBlock());
  277. const memCache = moduleMemCaches && moduleMemCaches.get(module);
  278. if (memCache !== undefined) {
  279. const map = memCache.provide(
  280. "bundleChunkGraph.blockModules",
  281. runtime,
  282. () => {
  283. logger.time("visitModules: prepare");
  284. const map = new Map();
  285. extractBlockModules(module, moduleGraph, runtime, map);
  286. logger.timeAggregate("visitModules: prepare");
  287. return map;
  288. }
  289. );
  290. for (const [block, blockModules] of map)
  291. blockModulesMap.set(block, blockModules);
  292. return map.get(block);
  293. } else {
  294. logger.time("visitModules: prepare");
  295. extractBlockModules(module, moduleGraph, runtime, blockModulesMap);
  296. blockModules =
  297. /** @type {BlockModulesInFlattenTuples} */
  298. (blockModulesMap.get(block));
  299. logger.timeAggregate("visitModules: prepare");
  300. return blockModules;
  301. }
  302. };
  303. let statProcessedQueueItems = 0;
  304. let statProcessedBlocks = 0;
  305. let statConnectedChunkGroups = 0;
  306. let statProcessedChunkGroupsForMerging = 0;
  307. let statMergedAvailableModuleSets = 0;
  308. let statForkedAvailableModules = 0;
  309. let statForkedAvailableModulesCount = 0;
  310. let statForkedAvailableModulesCountPlus = 0;
  311. let statForkedMergedModulesCount = 0;
  312. let statForkedMergedModulesCountPlus = 0;
  313. let statForkedResultModulesCount = 0;
  314. let statChunkGroupInfoUpdated = 0;
  315. let statChildChunkGroupsReconnected = 0;
  316. let nextChunkGroupIndex = 0;
  317. let nextFreeModulePreOrderIndex = 0;
  318. let nextFreeModulePostOrderIndex = 0;
  319. /** @type {Map<DependenciesBlock, ChunkGroupInfo>} */
  320. const blockChunkGroups = new Map();
  321. /** @type {Map<ChunkGroupInfo, DependenciesBlock>} */
  322. const blockByChunkGroups = new Map();
  323. /** @type {Map<string, ChunkGroupInfo>} */
  324. const namedChunkGroups = new Map();
  325. /** @type {Map<string, ChunkGroupInfo>} */
  326. const namedAsyncEntrypoints = new Map();
  327. /** @type {Set<ChunkGroupInfo>} */
  328. const outdatedOrderIndexChunkGroups = new Set();
  329. const ADD_AND_ENTER_ENTRY_MODULE = 0;
  330. const ADD_AND_ENTER_MODULE = 1;
  331. const ENTER_MODULE = 2;
  332. const PROCESS_BLOCK = 3;
  333. const PROCESS_ENTRY_BLOCK = 4;
  334. const LEAVE_MODULE = 5;
  335. /** @type {QueueItem[]} */
  336. let queue = [];
  337. /** @type {Map<ChunkGroupInfo, Set<ChunkGroupInfo>>} */
  338. const queueConnect = new Map();
  339. /** @type {Set<ChunkGroupInfo>} */
  340. const chunkGroupsForCombining = new Set();
  341. // Fill queue with entrypoint modules
  342. // Create ChunkGroupInfo for entrypoints
  343. for (const [chunkGroup, modules] of inputEntrypointsAndModules) {
  344. const runtime = getEntryRuntime(
  345. compilation,
  346. /** @type {string} */ (chunkGroup.name),
  347. chunkGroup.options
  348. );
  349. /** @type {ChunkGroupInfo} */
  350. const chunkGroupInfo = {
  351. chunkGroup,
  352. runtime,
  353. minAvailableModules: undefined,
  354. availableModulesToBeMerged: [],
  355. skippedItems: undefined,
  356. resultingAvailableModules: undefined,
  357. children: undefined,
  358. availableSources: undefined,
  359. availableChildren: undefined,
  360. preOrderIndex: 0,
  361. postOrderIndex: 0,
  362. chunkLoading:
  363. chunkGroup.options.chunkLoading !== undefined
  364. ? chunkGroup.options.chunkLoading !== false
  365. : compilation.outputOptions.chunkLoading !== false,
  366. asyncChunks:
  367. chunkGroup.options.asyncChunks !== undefined
  368. ? chunkGroup.options.asyncChunks
  369. : compilation.outputOptions.asyncChunks !== false
  370. };
  371. chunkGroup.index = nextChunkGroupIndex++;
  372. if (chunkGroup.getNumberOfParents() > 0) {
  373. // minAvailableModules for child entrypoints are unknown yet, set to undefined.
  374. // This means no module is added until other sets are merged into
  375. // this minAvailableModules (by the parent entrypoints)
  376. const skippedItems = new Set(modules);
  377. chunkGroupInfo.skippedItems = skippedItems;
  378. chunkGroupsForCombining.add(chunkGroupInfo);
  379. } else {
  380. // The application may start here: We start with an empty list of available modules
  381. chunkGroupInfo.minAvailableModules = ZERO_BIGINT;
  382. const chunk = chunkGroup.getEntrypointChunk();
  383. for (const module of modules) {
  384. queue.push({
  385. action: ADD_AND_ENTER_MODULE,
  386. block: module,
  387. module,
  388. chunk,
  389. chunkGroup,
  390. chunkGroupInfo
  391. });
  392. }
  393. }
  394. chunkGroupInfoMap.set(chunkGroup, chunkGroupInfo);
  395. if (chunkGroup.name) {
  396. namedChunkGroups.set(chunkGroup.name, chunkGroupInfo);
  397. }
  398. }
  399. // Fill availableSources with parent-child dependencies between entrypoints
  400. for (const chunkGroupInfo of chunkGroupsForCombining) {
  401. const { chunkGroup } = chunkGroupInfo;
  402. chunkGroupInfo.availableSources = new Set();
  403. for (const parent of chunkGroup.parentsIterable) {
  404. const parentChunkGroupInfo =
  405. /** @type {ChunkGroupInfo} */
  406. (chunkGroupInfoMap.get(parent));
  407. chunkGroupInfo.availableSources.add(parentChunkGroupInfo);
  408. if (parentChunkGroupInfo.availableChildren === undefined) {
  409. parentChunkGroupInfo.availableChildren = new Set();
  410. }
  411. parentChunkGroupInfo.availableChildren.add(chunkGroupInfo);
  412. }
  413. }
  414. // pop() is used to read from the queue
  415. // so it need to be reversed to be iterated in
  416. // correct order
  417. queue.reverse();
  418. /** @type {Set<ChunkGroupInfo>} */
  419. const outdatedChunkGroupInfo = new Set();
  420. /** @type {Set<ChunkGroupInfo>} */
  421. const chunkGroupsForMerging = new Set();
  422. /** @type {QueueItem[]} */
  423. let queueDelayed = [];
  424. /** @type {[Module, ModuleGraphConnection[]][]} */
  425. const skipConnectionBuffer = [];
  426. /** @type {Module[]} */
  427. const skipBuffer = [];
  428. /** @type {QueueItem[]} */
  429. const queueBuffer = [];
  430. /** @type {Module} */
  431. let module;
  432. /** @type {Chunk} */
  433. let chunk;
  434. /** @type {ChunkGroup} */
  435. let chunkGroup;
  436. /** @type {DependenciesBlock} */
  437. let block;
  438. /** @type {ChunkGroupInfo} */
  439. let chunkGroupInfo;
  440. // For each async Block in graph
  441. /**
  442. * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock
  443. * @returns {void}
  444. */
  445. const iteratorBlock = b => {
  446. // 1. We create a chunk group with single chunk in it for this Block
  447. // but only once (blockChunkGroups map)
  448. /** @type {ChunkGroupInfo | undefined} */
  449. let cgi = blockChunkGroups.get(b);
  450. /** @type {ChunkGroup | undefined} */
  451. let c;
  452. /** @type {Entrypoint | undefined} */
  453. let entrypoint;
  454. const entryOptions = b.groupOptions && b.groupOptions.entryOptions;
  455. if (cgi === undefined) {
  456. const chunkName = (b.groupOptions && b.groupOptions.name) || b.chunkName;
  457. if (entryOptions) {
  458. cgi = namedAsyncEntrypoints.get(/** @type {string} */ (chunkName));
  459. if (!cgi) {
  460. entrypoint = compilation.addAsyncEntrypoint(
  461. entryOptions,
  462. module,
  463. /** @type {DependencyLocation} */ (b.loc),
  464. /** @type {string} */ (b.request)
  465. );
  466. maskByChunk.set(entrypoint.chunks[0], ZERO_BIGINT);
  467. entrypoint.index = nextChunkGroupIndex++;
  468. cgi = {
  469. chunkGroup: entrypoint,
  470. runtime: entrypoint.options.runtime || entrypoint.name,
  471. minAvailableModules: ZERO_BIGINT,
  472. availableModulesToBeMerged: [],
  473. skippedItems: undefined,
  474. resultingAvailableModules: undefined,
  475. children: undefined,
  476. availableSources: undefined,
  477. availableChildren: undefined,
  478. preOrderIndex: 0,
  479. postOrderIndex: 0,
  480. chunkLoading:
  481. entryOptions.chunkLoading !== undefined
  482. ? entryOptions.chunkLoading !== false
  483. : chunkGroupInfo.chunkLoading,
  484. asyncChunks:
  485. entryOptions.asyncChunks !== undefined
  486. ? entryOptions.asyncChunks
  487. : chunkGroupInfo.asyncChunks
  488. };
  489. chunkGroupInfoMap.set(entrypoint, cgi);
  490. chunkGraph.connectBlockAndChunkGroup(b, entrypoint);
  491. if (chunkName) {
  492. namedAsyncEntrypoints.set(chunkName, cgi);
  493. }
  494. } else {
  495. entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup);
  496. // TODO merge entryOptions
  497. entrypoint.addOrigin(
  498. module,
  499. /** @type {DependencyLocation} */ (b.loc),
  500. /** @type {string} */ (b.request)
  501. );
  502. chunkGraph.connectBlockAndChunkGroup(b, entrypoint);
  503. }
  504. // 2. We enqueue the DependenciesBlock for traversal
  505. queueDelayed.push({
  506. action: PROCESS_ENTRY_BLOCK,
  507. block: b,
  508. module,
  509. chunk: entrypoint.chunks[0],
  510. chunkGroup: entrypoint,
  511. chunkGroupInfo: cgi
  512. });
  513. } else if (!chunkGroupInfo.asyncChunks || !chunkGroupInfo.chunkLoading) {
  514. // Just queue the block into the current chunk group
  515. queue.push({
  516. action: PROCESS_BLOCK,
  517. block: b,
  518. module,
  519. chunk,
  520. chunkGroup,
  521. chunkGroupInfo
  522. });
  523. } else {
  524. cgi = chunkName ? namedChunkGroups.get(chunkName) : undefined;
  525. if (!cgi) {
  526. c = compilation.addChunkInGroup(
  527. b.groupOptions || b.chunkName,
  528. module,
  529. /** @type {DependencyLocation} */ (b.loc),
  530. /** @type {string} */ (b.request)
  531. );
  532. maskByChunk.set(c.chunks[0], ZERO_BIGINT);
  533. c.index = nextChunkGroupIndex++;
  534. cgi = {
  535. chunkGroup: c,
  536. runtime: chunkGroupInfo.runtime,
  537. minAvailableModules: undefined,
  538. availableModulesToBeMerged: [],
  539. skippedItems: undefined,
  540. resultingAvailableModules: undefined,
  541. children: undefined,
  542. availableSources: undefined,
  543. availableChildren: undefined,
  544. preOrderIndex: 0,
  545. postOrderIndex: 0,
  546. chunkLoading: chunkGroupInfo.chunkLoading,
  547. asyncChunks: chunkGroupInfo.asyncChunks
  548. };
  549. allCreatedChunkGroups.add(c);
  550. chunkGroupInfoMap.set(c, cgi);
  551. if (chunkName) {
  552. namedChunkGroups.set(chunkName, cgi);
  553. }
  554. } else {
  555. c = cgi.chunkGroup;
  556. if (c.isInitial()) {
  557. compilation.errors.push(
  558. new AsyncDependencyToInitialChunkError(
  559. /** @type {string} */ (chunkName),
  560. module,
  561. /** @type {DependencyLocation} */ (b.loc)
  562. )
  563. );
  564. c = chunkGroup;
  565. } else {
  566. c.addOptions(b.groupOptions);
  567. }
  568. c.addOrigin(
  569. module,
  570. /** @type {DependencyLocation} */ (b.loc),
  571. /** @type {string} */ (b.request)
  572. );
  573. }
  574. blockConnections.set(b, []);
  575. }
  576. blockChunkGroups.set(b, /** @type {ChunkGroupInfo} */ (cgi));
  577. blockByChunkGroups.set(/** @type {ChunkGroupInfo} */ (cgi), b);
  578. } else if (entryOptions) {
  579. entrypoint = /** @type {Entrypoint} */ (cgi.chunkGroup);
  580. } else {
  581. c = cgi.chunkGroup;
  582. }
  583. if (c !== undefined) {
  584. // 2. We store the connection for the block
  585. // to connect it later if needed
  586. /** @type {BlockChunkGroupConnection[]} */
  587. (blockConnections.get(b)).push({
  588. originChunkGroupInfo: chunkGroupInfo,
  589. chunkGroup: c
  590. });
  591. // 3. We enqueue the chunk group info creation/updating
  592. let connectList = queueConnect.get(chunkGroupInfo);
  593. if (connectList === undefined) {
  594. connectList = new Set();
  595. queueConnect.set(chunkGroupInfo, connectList);
  596. }
  597. connectList.add(/** @type {ChunkGroupInfo} */ (cgi));
  598. // TODO check if this really need to be done for each traversal
  599. // or if it is enough when it's queued when created
  600. // 4. We enqueue the DependenciesBlock for traversal
  601. queueDelayed.push({
  602. action: PROCESS_BLOCK,
  603. block: b,
  604. module,
  605. chunk: c.chunks[0],
  606. chunkGroup: c,
  607. chunkGroupInfo: /** @type {ChunkGroupInfo} */ (cgi)
  608. });
  609. } else if (entrypoint !== undefined) {
  610. chunkGroupInfo.chunkGroup.addAsyncEntrypoint(entrypoint);
  611. }
  612. };
  613. /**
  614. * @param {DependenciesBlock} block the block
  615. * @returns {void}
  616. */
  617. const processBlock = block => {
  618. statProcessedBlocks++;
  619. // get prepared block info
  620. const blockModules = getBlockModules(block, chunkGroupInfo.runtime);
  621. if (blockModules !== undefined) {
  622. const minAvailableModules =
  623. /** @type {bigint} */
  624. (chunkGroupInfo.minAvailableModules);
  625. // Buffer items because order need to be reversed to get indices correct
  626. // Traverse all referenced modules
  627. for (let i = 0, len = blockModules.length; i < len; i += 3) {
  628. const refModule = /** @type {Module} */ (blockModules[i]);
  629. // For single comparisons this might be cheaper
  630. const isModuleInChunk = chunkGraph.isModuleInChunk(refModule, chunk);
  631. if (isModuleInChunk) {
  632. // skip early if already connected
  633. continue;
  634. }
  635. const refOrdinal = /** @type {number} */ getModuleOrdinal(refModule);
  636. const activeState = /** @type {ConnectionState} */ (
  637. blockModules[i + 1]
  638. );
  639. if (activeState !== true) {
  640. const connections = /** @type {ModuleGraphConnection[]} */ (
  641. blockModules[i + 2]
  642. );
  643. skipConnectionBuffer.push([refModule, connections]);
  644. // We skip inactive connections
  645. if (activeState === false) continue;
  646. } else if (isOrdinalSetInMask(minAvailableModules, refOrdinal)) {
  647. // already in parent chunks, skip it for now
  648. skipBuffer.push(refModule);
  649. continue;
  650. }
  651. // enqueue, then add and enter to be in the correct order
  652. // this is relevant with circular dependencies
  653. queueBuffer.push({
  654. action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK,
  655. block: refModule,
  656. module: refModule,
  657. chunk,
  658. chunkGroup,
  659. chunkGroupInfo
  660. });
  661. }
  662. // Add buffered items in reverse order
  663. if (skipConnectionBuffer.length > 0) {
  664. let { skippedModuleConnections } = chunkGroupInfo;
  665. if (skippedModuleConnections === undefined) {
  666. chunkGroupInfo.skippedModuleConnections = skippedModuleConnections =
  667. new Set();
  668. }
  669. for (let i = skipConnectionBuffer.length - 1; i >= 0; i--) {
  670. skippedModuleConnections.add(skipConnectionBuffer[i]);
  671. }
  672. skipConnectionBuffer.length = 0;
  673. }
  674. if (skipBuffer.length > 0) {
  675. let { skippedItems } = chunkGroupInfo;
  676. if (skippedItems === undefined) {
  677. chunkGroupInfo.skippedItems = skippedItems = new Set();
  678. }
  679. for (let i = skipBuffer.length - 1; i >= 0; i--) {
  680. skippedItems.add(skipBuffer[i]);
  681. }
  682. skipBuffer.length = 0;
  683. }
  684. if (queueBuffer.length > 0) {
  685. for (let i = queueBuffer.length - 1; i >= 0; i--) {
  686. queue.push(queueBuffer[i]);
  687. }
  688. queueBuffer.length = 0;
  689. }
  690. }
  691. // Traverse all Blocks
  692. for (const b of block.blocks) {
  693. iteratorBlock(b);
  694. }
  695. if (block.blocks.length > 0 && module !== block) {
  696. blocksWithNestedBlocks.add(block);
  697. }
  698. };
  699. /**
  700. * @param {DependenciesBlock} block the block
  701. * @returns {void}
  702. */
  703. const processEntryBlock = block => {
  704. statProcessedBlocks++;
  705. // get prepared block info
  706. const blockModules = getBlockModules(block, chunkGroupInfo.runtime);
  707. if (blockModules !== undefined) {
  708. // Traverse all referenced modules in reverse order
  709. for (let i = blockModules.length - 3; i >= 0; i -= 3) {
  710. const refModule = /** @type {Module} */ (blockModules[i]);
  711. const activeState = /** @type {ConnectionState} */ (
  712. blockModules[i + 1]
  713. );
  714. // enqueue, then add and enter to be in the correct order
  715. // this is relevant with circular dependencies
  716. queue.push({
  717. action:
  718. activeState === true ? ADD_AND_ENTER_ENTRY_MODULE : PROCESS_BLOCK,
  719. block: refModule,
  720. module: refModule,
  721. chunk,
  722. chunkGroup,
  723. chunkGroupInfo
  724. });
  725. }
  726. }
  727. // Traverse all Blocks
  728. for (const b of block.blocks) {
  729. iteratorBlock(b);
  730. }
  731. if (block.blocks.length > 0 && module !== block) {
  732. blocksWithNestedBlocks.add(block);
  733. }
  734. };
  735. const processQueue = () => {
  736. while (queue.length) {
  737. statProcessedQueueItems++;
  738. const queueItem = /** @type {QueueItem} */ (queue.pop());
  739. module = queueItem.module;
  740. block = queueItem.block;
  741. chunk = queueItem.chunk;
  742. chunkGroup = queueItem.chunkGroup;
  743. chunkGroupInfo = queueItem.chunkGroupInfo;
  744. switch (queueItem.action) {
  745. case ADD_AND_ENTER_ENTRY_MODULE:
  746. chunkGraph.connectChunkAndEntryModule(
  747. chunk,
  748. module,
  749. /** @type {Entrypoint} */ (chunkGroup)
  750. );
  751. // fallthrough
  752. case ADD_AND_ENTER_MODULE: {
  753. const isModuleInChunk = chunkGraph.isModuleInChunk(module, chunk);
  754. if (isModuleInChunk) {
  755. // already connected, skip it
  756. break;
  757. }
  758. // We connect Module and Chunk
  759. chunkGraph.connectChunkAndModule(chunk, module);
  760. const moduleOrdinal = getModuleOrdinal(module);
  761. let chunkMask = /** @type {bigint} */ (maskByChunk.get(chunk));
  762. chunkMask |= ONE_BIGINT << BigInt(moduleOrdinal);
  763. maskByChunk.set(chunk, chunkMask);
  764. }
  765. // fallthrough
  766. case ENTER_MODULE: {
  767. const index = chunkGroup.getModulePreOrderIndex(module);
  768. if (index === undefined) {
  769. chunkGroup.setModulePreOrderIndex(
  770. module,
  771. chunkGroupInfo.preOrderIndex++
  772. );
  773. }
  774. if (
  775. moduleGraph.setPreOrderIndexIfUnset(
  776. module,
  777. nextFreeModulePreOrderIndex
  778. )
  779. ) {
  780. nextFreeModulePreOrderIndex++;
  781. }
  782. // reuse queueItem
  783. queueItem.action = LEAVE_MODULE;
  784. queue.push(queueItem);
  785. }
  786. // fallthrough
  787. case PROCESS_BLOCK: {
  788. processBlock(block);
  789. break;
  790. }
  791. case PROCESS_ENTRY_BLOCK: {
  792. processEntryBlock(block);
  793. break;
  794. }
  795. case LEAVE_MODULE: {
  796. const index = chunkGroup.getModulePostOrderIndex(module);
  797. if (index === undefined) {
  798. chunkGroup.setModulePostOrderIndex(
  799. module,
  800. chunkGroupInfo.postOrderIndex++
  801. );
  802. }
  803. if (
  804. moduleGraph.setPostOrderIndexIfUnset(
  805. module,
  806. nextFreeModulePostOrderIndex
  807. )
  808. ) {
  809. nextFreeModulePostOrderIndex++;
  810. }
  811. break;
  812. }
  813. }
  814. }
  815. };
  816. /**
  817. * @param {ChunkGroupInfo} chunkGroupInfo The info object for the chunk group
  818. * @returns {bigint} The mask of available modules after the chunk group
  819. */
  820. const calculateResultingAvailableModules = chunkGroupInfo => {
  821. if (chunkGroupInfo.resultingAvailableModules !== undefined)
  822. return chunkGroupInfo.resultingAvailableModules;
  823. let resultingAvailableModules = /** @type {bigint} */ (
  824. chunkGroupInfo.minAvailableModules
  825. );
  826. // add the modules from the chunk group to the set
  827. for (const chunk of chunkGroupInfo.chunkGroup.chunks) {
  828. const mask = /** @type {bigint} */ (maskByChunk.get(chunk));
  829. resultingAvailableModules |= mask;
  830. }
  831. return (chunkGroupInfo.resultingAvailableModules =
  832. resultingAvailableModules);
  833. };
  834. const processConnectQueue = () => {
  835. // Figure out new parents for chunk groups
  836. // to get new available modules for these children
  837. for (const [chunkGroupInfo, targets] of queueConnect) {
  838. // 1. Add new targets to the list of children
  839. if (chunkGroupInfo.children === undefined) {
  840. chunkGroupInfo.children = targets;
  841. } else {
  842. for (const target of targets) {
  843. chunkGroupInfo.children.add(target);
  844. }
  845. }
  846. // 2. Calculate resulting available modules
  847. const resultingAvailableModules =
  848. calculateResultingAvailableModules(chunkGroupInfo);
  849. const runtime = chunkGroupInfo.runtime;
  850. // 3. Update chunk group info
  851. for (const target of targets) {
  852. target.availableModulesToBeMerged.push(resultingAvailableModules);
  853. chunkGroupsForMerging.add(target);
  854. const oldRuntime = target.runtime;
  855. const newRuntime = mergeRuntime(oldRuntime, runtime);
  856. if (oldRuntime !== newRuntime) {
  857. target.runtime = newRuntime;
  858. outdatedChunkGroupInfo.add(target);
  859. }
  860. }
  861. statConnectedChunkGroups += targets.size;
  862. }
  863. queueConnect.clear();
  864. };
  865. const processChunkGroupsForMerging = () => {
  866. statProcessedChunkGroupsForMerging += chunkGroupsForMerging.size;
  867. // Execute the merge
  868. for (const info of chunkGroupsForMerging) {
  869. const availableModulesToBeMerged = info.availableModulesToBeMerged;
  870. const cachedMinAvailableModules = info.minAvailableModules;
  871. let minAvailableModules = cachedMinAvailableModules;
  872. statMergedAvailableModuleSets += availableModulesToBeMerged.length;
  873. for (const availableModules of availableModulesToBeMerged) {
  874. if (minAvailableModules === undefined) {
  875. minAvailableModules = availableModules;
  876. } else {
  877. minAvailableModules &= availableModules;
  878. }
  879. }
  880. const changed = minAvailableModules !== cachedMinAvailableModules;
  881. availableModulesToBeMerged.length = 0;
  882. if (changed) {
  883. info.minAvailableModules = minAvailableModules;
  884. info.resultingAvailableModules = undefined;
  885. outdatedChunkGroupInfo.add(info);
  886. }
  887. }
  888. chunkGroupsForMerging.clear();
  889. };
  890. const processChunkGroupsForCombining = () => {
  891. for (const info of chunkGroupsForCombining) {
  892. for (const source of /** @type {Set<ChunkGroupInfo>} */ (
  893. info.availableSources
  894. )) {
  895. if (source.minAvailableModules === undefined) {
  896. chunkGroupsForCombining.delete(info);
  897. break;
  898. }
  899. }
  900. }
  901. for (const info of chunkGroupsForCombining) {
  902. let availableModules = ZERO_BIGINT;
  903. // combine minAvailableModules from all resultingAvailableModules
  904. for (const source of /** @type {Set<ChunkGroupInfo>} */ (
  905. info.availableSources
  906. )) {
  907. const resultingAvailableModules =
  908. calculateResultingAvailableModules(source);
  909. availableModules |= resultingAvailableModules;
  910. }
  911. info.minAvailableModules = availableModules;
  912. info.resultingAvailableModules = undefined;
  913. outdatedChunkGroupInfo.add(info);
  914. }
  915. chunkGroupsForCombining.clear();
  916. };
  917. const processOutdatedChunkGroupInfo = () => {
  918. statChunkGroupInfoUpdated += outdatedChunkGroupInfo.size;
  919. // Revisit skipped elements
  920. for (const info of outdatedChunkGroupInfo) {
  921. // 1. Reconsider skipped items
  922. if (info.skippedItems !== undefined) {
  923. const minAvailableModules =
  924. /** @type {bigint} */
  925. (info.minAvailableModules);
  926. for (const module of info.skippedItems) {
  927. const ordinal = getModuleOrdinal(module);
  928. if (!isOrdinalSetInMask(minAvailableModules, ordinal)) {
  929. queue.push({
  930. action: ADD_AND_ENTER_MODULE,
  931. block: module,
  932. module,
  933. chunk: info.chunkGroup.chunks[0],
  934. chunkGroup: info.chunkGroup,
  935. chunkGroupInfo: info
  936. });
  937. info.skippedItems.delete(module);
  938. }
  939. }
  940. }
  941. // 2. Reconsider skipped connections
  942. if (info.skippedModuleConnections !== undefined) {
  943. const minAvailableModules =
  944. /** @type {bigint} */
  945. (info.minAvailableModules);
  946. for (const entry of info.skippedModuleConnections) {
  947. const [module, connections] = entry;
  948. const activeState = getActiveStateOfConnections(
  949. connections,
  950. info.runtime
  951. );
  952. if (activeState === false) continue;
  953. if (activeState === true) {
  954. const ordinal = getModuleOrdinal(module);
  955. info.skippedModuleConnections.delete(entry);
  956. if (isOrdinalSetInMask(minAvailableModules, ordinal)) {
  957. /** @type {NonNullable<ChunkGroupInfo["skippedItems"]>} */
  958. (info.skippedItems).add(module);
  959. continue;
  960. }
  961. }
  962. queue.push({
  963. action: activeState === true ? ADD_AND_ENTER_MODULE : PROCESS_BLOCK,
  964. block: module,
  965. module,
  966. chunk: info.chunkGroup.chunks[0],
  967. chunkGroup: info.chunkGroup,
  968. chunkGroupInfo: info
  969. });
  970. }
  971. }
  972. // 2. Reconsider children chunk groups
  973. if (info.children !== undefined) {
  974. statChildChunkGroupsReconnected += info.children.size;
  975. for (const cgi of info.children) {
  976. let connectList = queueConnect.get(info);
  977. if (connectList === undefined) {
  978. connectList = new Set();
  979. queueConnect.set(info, connectList);
  980. }
  981. connectList.add(cgi);
  982. }
  983. }
  984. // 3. Reconsider chunk groups for combining
  985. if (info.availableChildren !== undefined) {
  986. for (const cgi of info.availableChildren) {
  987. chunkGroupsForCombining.add(cgi);
  988. }
  989. }
  990. outdatedOrderIndexChunkGroups.add(info);
  991. }
  992. outdatedChunkGroupInfo.clear();
  993. };
  994. // Iterative traversal of the Module graph
  995. // Recursive would be simpler to write but could result in Stack Overflows
  996. while (queue.length || queueConnect.size) {
  997. logger.time("visitModules: visiting");
  998. processQueue();
  999. logger.timeAggregateEnd("visitModules: prepare");
  1000. logger.timeEnd("visitModules: visiting");
  1001. if (chunkGroupsForCombining.size > 0) {
  1002. logger.time("visitModules: combine available modules");
  1003. processChunkGroupsForCombining();
  1004. logger.timeEnd("visitModules: combine available modules");
  1005. }
  1006. if (queueConnect.size > 0) {
  1007. logger.time("visitModules: calculating available modules");
  1008. processConnectQueue();
  1009. logger.timeEnd("visitModules: calculating available modules");
  1010. if (chunkGroupsForMerging.size > 0) {
  1011. logger.time("visitModules: merging available modules");
  1012. processChunkGroupsForMerging();
  1013. logger.timeEnd("visitModules: merging available modules");
  1014. }
  1015. }
  1016. if (outdatedChunkGroupInfo.size > 0) {
  1017. logger.time("visitModules: check modules for revisit");
  1018. processOutdatedChunkGroupInfo();
  1019. logger.timeEnd("visitModules: check modules for revisit");
  1020. }
  1021. // Run queueDelayed when all items of the queue are processed
  1022. // This is important to get the global indexing correct
  1023. // Async blocks should be processed after all sync blocks are processed
  1024. if (queue.length === 0) {
  1025. const tempQueue = queue;
  1026. queue = queueDelayed.reverse();
  1027. queueDelayed = tempQueue;
  1028. }
  1029. }
  1030. for (const info of outdatedOrderIndexChunkGroups) {
  1031. const { chunkGroup, runtime } = info;
  1032. const block = blockByChunkGroups.get(info);
  1033. if (!block) {
  1034. continue;
  1035. }
  1036. let preOrderIndex = 0;
  1037. let postOrderIndex = 0;
  1038. /**
  1039. * @param {DependenciesBlock} current current
  1040. * @param {BlocksWithNestedBlocks} visited visited dependencies blocks
  1041. */
  1042. const process = (current, visited) => {
  1043. const blockModules = getBlockModules(current, runtime);
  1044. if (blockModules === undefined) {
  1045. return;
  1046. }
  1047. for (let i = 0, len = blockModules.length; i < len; i += 3) {
  1048. const activeState = /** @type {ConnectionState} */ (
  1049. blockModules[i + 1]
  1050. );
  1051. if (activeState === false) {
  1052. continue;
  1053. }
  1054. const refModule = /** @type {Module} */ (blockModules[i]);
  1055. if (visited.has(refModule)) {
  1056. continue;
  1057. }
  1058. visited.add(refModule);
  1059. if (refModule) {
  1060. chunkGroup.setModulePreOrderIndex(refModule, preOrderIndex++);
  1061. process(refModule, visited);
  1062. chunkGroup.setModulePostOrderIndex(refModule, postOrderIndex++);
  1063. }
  1064. }
  1065. };
  1066. process(block, new Set());
  1067. }
  1068. outdatedOrderIndexChunkGroups.clear();
  1069. ordinalByModule.clear();
  1070. logger.log(
  1071. `${statProcessedQueueItems} queue items processed (${statProcessedBlocks} blocks)`
  1072. );
  1073. logger.log(`${statConnectedChunkGroups} chunk groups connected`);
  1074. logger.log(
  1075. `${statProcessedChunkGroupsForMerging} chunk groups processed for merging (${statMergedAvailableModuleSets} module sets, ${statForkedAvailableModules} forked, ${statForkedAvailableModulesCount} + ${statForkedAvailableModulesCountPlus} modules forked, ${statForkedMergedModulesCount} + ${statForkedMergedModulesCountPlus} modules merged into fork, ${statForkedResultModulesCount} resulting modules)`
  1076. );
  1077. logger.log(
  1078. `${statChunkGroupInfoUpdated} chunk group info updated (${statChildChunkGroupsReconnected} already connected chunk groups reconnected)`
  1079. );
  1080. };
  1081. /**
  1082. *
  1083. * @param {Compilation} compilation the compilation
  1084. * @param {BlocksWithNestedBlocks} blocksWithNestedBlocks flag for blocks that have nested blocks
  1085. * @param {BlockConnections} blockConnections connection for blocks
  1086. * @param {MaskByChunk} maskByChunk mapping from chunk to module mask
  1087. */
  1088. const connectChunkGroups = (
  1089. compilation,
  1090. blocksWithNestedBlocks,
  1091. blockConnections,
  1092. maskByChunk
  1093. ) => {
  1094. const { chunkGraph } = compilation;
  1095. /**
  1096. * Helper function to check if all modules of a chunk are available
  1097. *
  1098. * @param {ChunkGroup} chunkGroup the chunkGroup to scan
  1099. * @param {bigint} availableModules the comparator set
  1100. * @returns {boolean} return true if all modules of a chunk are available
  1101. */
  1102. const areModulesAvailable = (chunkGroup, availableModules) => {
  1103. for (const chunk of chunkGroup.chunks) {
  1104. const chunkMask = /** @type {bigint} */ (maskByChunk.get(chunk));
  1105. if ((chunkMask & availableModules) !== chunkMask) return false;
  1106. }
  1107. return true;
  1108. };
  1109. // For each edge in the basic chunk graph
  1110. for (const [block, connections] of blockConnections) {
  1111. // 1. Check if connection is needed
  1112. // When none of the dependencies need to be connected
  1113. // we can skip all of them
  1114. // It's not possible to filter each item so it doesn't create inconsistent
  1115. // connections and modules can only create one version
  1116. // TODO maybe decide this per runtime
  1117. if (
  1118. // TODO is this needed?
  1119. !blocksWithNestedBlocks.has(block) &&
  1120. connections.every(({ chunkGroup, originChunkGroupInfo }) =>
  1121. areModulesAvailable(
  1122. chunkGroup,
  1123. /** @type {bigint} */ (originChunkGroupInfo.resultingAvailableModules)
  1124. )
  1125. )
  1126. ) {
  1127. continue;
  1128. }
  1129. // 2. Foreach edge
  1130. for (let i = 0; i < connections.length; i++) {
  1131. const { chunkGroup, originChunkGroupInfo } = connections[i];
  1132. // 3. Connect block with chunk
  1133. chunkGraph.connectBlockAndChunkGroup(block, chunkGroup);
  1134. // 4. Connect chunk with parent
  1135. connectChunkGroupParentAndChild(
  1136. originChunkGroupInfo.chunkGroup,
  1137. chunkGroup
  1138. );
  1139. }
  1140. }
  1141. };
  1142. /**
  1143. * Remove all unconnected chunk groups
  1144. * @param {Compilation} compilation the compilation
  1145. * @param {Iterable<ChunkGroup>} allCreatedChunkGroups all chunk groups that where created before
  1146. */
  1147. const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => {
  1148. const { chunkGraph } = compilation;
  1149. for (const chunkGroup of allCreatedChunkGroups) {
  1150. if (chunkGroup.getNumberOfParents() === 0) {
  1151. for (const chunk of chunkGroup.chunks) {
  1152. compilation.chunks.delete(chunk);
  1153. chunkGraph.disconnectChunk(chunk);
  1154. }
  1155. chunkGraph.disconnectChunkGroup(chunkGroup);
  1156. chunkGroup.remove();
  1157. }
  1158. }
  1159. };
  1160. /**
  1161. * This method creates the Chunk graph from the Module graph
  1162. * @param {Compilation} compilation the compilation
  1163. * @param {InputEntrypointsAndModules} inputEntrypointsAndModules chunk groups which are processed with the modules
  1164. * @returns {void}
  1165. */
  1166. const buildChunkGraph = (compilation, inputEntrypointsAndModules) => {
  1167. const logger = compilation.getLogger("webpack.buildChunkGraph");
  1168. // SHARED STATE
  1169. /** @type {BlockConnections} */
  1170. const blockConnections = new Map();
  1171. /** @type {AllCreatedChunkGroups} */
  1172. const allCreatedChunkGroups = new Set();
  1173. /** @type {ChunkGroupInfoMap} */
  1174. const chunkGroupInfoMap = new Map();
  1175. /** @type {BlocksWithNestedBlocks} */
  1176. const blocksWithNestedBlocks = new Set();
  1177. /** @type {MaskByChunk} */
  1178. const maskByChunk = new Map();
  1179. // PART ONE
  1180. logger.time("visitModules");
  1181. visitModules(
  1182. logger,
  1183. compilation,
  1184. inputEntrypointsAndModules,
  1185. chunkGroupInfoMap,
  1186. blockConnections,
  1187. blocksWithNestedBlocks,
  1188. allCreatedChunkGroups,
  1189. maskByChunk
  1190. );
  1191. logger.timeEnd("visitModules");
  1192. // PART TWO
  1193. logger.time("connectChunkGroups");
  1194. connectChunkGroups(
  1195. compilation,
  1196. blocksWithNestedBlocks,
  1197. blockConnections,
  1198. maskByChunk
  1199. );
  1200. logger.timeEnd("connectChunkGroups");
  1201. for (const [chunkGroup, chunkGroupInfo] of chunkGroupInfoMap) {
  1202. for (const chunk of chunkGroup.chunks)
  1203. chunk.runtime = mergeRuntime(chunk.runtime, chunkGroupInfo.runtime);
  1204. }
  1205. // Cleanup work
  1206. logger.time("cleanup");
  1207. cleanupUnconnectedGroups(compilation, allCreatedChunkGroups);
  1208. logger.timeEnd("cleanup");
  1209. };
  1210. module.exports = buildChunkGraph;