ChunkGroup.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const SortableSet = require("./util/SortableSet");
  8. const {
  9. compareChunks,
  10. compareIterables,
  11. compareLocations
  12. } = require("./util/comparators");
  13. /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
  14. /** @typedef {import("./Chunk")} Chunk */
  15. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  16. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  17. /** @typedef {import("./Entrypoint")} Entrypoint */
  18. /** @typedef {import("./Module")} Module */
  19. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  20. /** @typedef {{ module: Module | null, loc: DependencyLocation, request: string }} OriginRecord */
  21. /**
  22. * @typedef {object} RawChunkGroupOptions
  23. * @property {number=} preloadOrder
  24. * @property {number=} prefetchOrder
  25. * @property {("low" | "high" | "auto")=} fetchPriority
  26. */
  27. /** @typedef {RawChunkGroupOptions & { name?: string | null }} ChunkGroupOptions */
  28. let debugId = 5000;
  29. /**
  30. * @template T
  31. * @param {SortableSet<T>} set set to convert to array.
  32. * @returns {T[]} the array format of existing set
  33. */
  34. const getArray = (set) => [...set];
  35. /**
  36. * A convenience method used to sort chunks based on their id's
  37. * @param {ChunkGroup} a first sorting comparator
  38. * @param {ChunkGroup} b second sorting comparator
  39. * @returns {1 | 0 | -1} a sorting index to determine order
  40. */
  41. const sortById = (a, b) => {
  42. if (a.id < b.id) return -1;
  43. if (b.id < a.id) return 1;
  44. return 0;
  45. };
  46. /**
  47. * @param {OriginRecord} a the first comparator in sort
  48. * @param {OriginRecord} b the second comparator in sort
  49. * @returns {1 | -1 | 0} returns sorting order as index
  50. */
  51. const sortOrigin = (a, b) => {
  52. const aIdent = a.module ? a.module.identifier() : "";
  53. const bIdent = b.module ? b.module.identifier() : "";
  54. if (aIdent < bIdent) return -1;
  55. if (aIdent > bIdent) return 1;
  56. return compareLocations(a.loc, b.loc);
  57. };
  58. class ChunkGroup {
  59. /**
  60. * Creates an instance of ChunkGroup.
  61. * @param {string | ChunkGroupOptions=} options chunk group options passed to chunkGroup
  62. */
  63. constructor(options) {
  64. if (typeof options === "string") {
  65. options = { name: options };
  66. } else if (!options) {
  67. options = { name: undefined };
  68. }
  69. /** @type {number} */
  70. this.groupDebugId = debugId++;
  71. /** @type {ChunkGroupOptions} */
  72. this.options = options;
  73. /** @type {SortableSet<ChunkGroup>} */
  74. this._children = new SortableSet(undefined, sortById);
  75. /** @type {SortableSet<ChunkGroup>} */
  76. this._parents = new SortableSet(undefined, sortById);
  77. /** @type {SortableSet<ChunkGroup>} */
  78. this._asyncEntrypoints = new SortableSet(undefined, sortById);
  79. /** @type {SortableSet<AsyncDependenciesBlock>} */
  80. this._blocks = new SortableSet();
  81. /** @type {Chunk[]} */
  82. this.chunks = [];
  83. /** @type {OriginRecord[]} */
  84. this.origins = [];
  85. /** @typedef {Map<Module, number>} OrderIndices */
  86. /** Indices in top-down order */
  87. /**
  88. * @private
  89. * @type {OrderIndices}
  90. */
  91. this._modulePreOrderIndices = new Map();
  92. /** Indices in bottom-up order */
  93. /**
  94. * @private
  95. * @type {OrderIndices}
  96. */
  97. this._modulePostOrderIndices = new Map();
  98. /** @type {number | undefined} */
  99. this.index = undefined;
  100. }
  101. /**
  102. * when a new chunk is added to a chunkGroup, addingOptions will occur.
  103. * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions
  104. * @returns {void}
  105. */
  106. addOptions(options) {
  107. for (const key of /** @type {(keyof ChunkGroupOptions)[]} */ (
  108. Object.keys(options)
  109. )) {
  110. if (this.options[key] === undefined) {
  111. /** @type {ChunkGroupOptions[keyof ChunkGroupOptions]} */
  112. (this.options[key]) = options[key];
  113. } else if (this.options[key] !== options[key]) {
  114. if (key.endsWith("Order")) {
  115. const orderKey =
  116. /** @type {Exclude<keyof ChunkGroupOptions, "name" | "fetchPriority">} */
  117. (key);
  118. this.options[orderKey] = Math.max(
  119. /** @type {number} */
  120. (this.options[orderKey]),
  121. /** @type {number} */
  122. (options[orderKey])
  123. );
  124. } else {
  125. throw new Error(
  126. `ChunkGroup.addOptions: No option merge strategy for ${key}`
  127. );
  128. }
  129. }
  130. }
  131. }
  132. /**
  133. * returns the name of current ChunkGroup
  134. * @returns {ChunkGroupOptions["name"]} returns the ChunkGroup name
  135. */
  136. get name() {
  137. return this.options.name;
  138. }
  139. /**
  140. * sets a new name for current ChunkGroup
  141. * @param {string | undefined} value the new name for ChunkGroup
  142. * @returns {void}
  143. */
  144. set name(value) {
  145. this.options.name = value;
  146. }
  147. /* istanbul ignore next */
  148. /**
  149. * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's
  150. * @returns {string} a unique concatenation of chunk debugId's
  151. */
  152. get debugId() {
  153. return Array.from(this.chunks, (x) => x.debugId).join("+");
  154. }
  155. /**
  156. * get a unique id for ChunkGroup, made up of its member Chunk id's
  157. * @returns {string} a unique concatenation of chunk ids
  158. */
  159. get id() {
  160. return Array.from(this.chunks, (x) => x.id).join("+");
  161. }
  162. /**
  163. * Performs an unshift of a specific chunk
  164. * @param {Chunk} chunk chunk being unshifted
  165. * @returns {boolean} returns true if attempted chunk shift is accepted
  166. */
  167. unshiftChunk(chunk) {
  168. const oldIdx = this.chunks.indexOf(chunk);
  169. if (oldIdx > 0) {
  170. this.chunks.splice(oldIdx, 1);
  171. this.chunks.unshift(chunk);
  172. } else if (oldIdx < 0) {
  173. this.chunks.unshift(chunk);
  174. return true;
  175. }
  176. return false;
  177. }
  178. /**
  179. * inserts a chunk before another existing chunk in group
  180. * @param {Chunk} chunk Chunk being inserted
  181. * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point
  182. * @returns {boolean} return true if insertion was successful
  183. */
  184. insertChunk(chunk, before) {
  185. const oldIdx = this.chunks.indexOf(chunk);
  186. const idx = this.chunks.indexOf(before);
  187. if (idx < 0) {
  188. throw new Error("before chunk not found");
  189. }
  190. if (oldIdx >= 0 && oldIdx > idx) {
  191. this.chunks.splice(oldIdx, 1);
  192. this.chunks.splice(idx, 0, chunk);
  193. } else if (oldIdx < 0) {
  194. this.chunks.splice(idx, 0, chunk);
  195. return true;
  196. }
  197. return false;
  198. }
  199. /**
  200. * add a chunk into ChunkGroup. Is pushed on or prepended
  201. * @param {Chunk} chunk chunk being pushed into ChunkGroupS
  202. * @returns {boolean} returns true if chunk addition was successful.
  203. */
  204. pushChunk(chunk) {
  205. const oldIdx = this.chunks.indexOf(chunk);
  206. if (oldIdx >= 0) {
  207. return false;
  208. }
  209. this.chunks.push(chunk);
  210. return true;
  211. }
  212. /**
  213. * @param {Chunk} oldChunk chunk to be replaced
  214. * @param {Chunk} newChunk New chunk that will be replaced with
  215. * @returns {boolean | undefined} returns true if the replacement was successful
  216. */
  217. replaceChunk(oldChunk, newChunk) {
  218. const oldIdx = this.chunks.indexOf(oldChunk);
  219. if (oldIdx < 0) return false;
  220. const newIdx = this.chunks.indexOf(newChunk);
  221. if (newIdx < 0) {
  222. this.chunks[oldIdx] = newChunk;
  223. return true;
  224. }
  225. if (newIdx < oldIdx) {
  226. this.chunks.splice(oldIdx, 1);
  227. return true;
  228. } else if (newIdx !== oldIdx) {
  229. this.chunks[oldIdx] = newChunk;
  230. this.chunks.splice(newIdx, 1);
  231. return true;
  232. }
  233. }
  234. /**
  235. * @param {Chunk} chunk chunk to remove
  236. * @returns {boolean} returns true if chunk was removed
  237. */
  238. removeChunk(chunk) {
  239. const idx = this.chunks.indexOf(chunk);
  240. if (idx >= 0) {
  241. this.chunks.splice(idx, 1);
  242. return true;
  243. }
  244. return false;
  245. }
  246. /**
  247. * @returns {boolean} true, when this chunk group will be loaded on initial page load
  248. */
  249. isInitial() {
  250. return false;
  251. }
  252. /**
  253. * @param {ChunkGroup} group chunk group to add
  254. * @returns {boolean} returns true if chunk group was added
  255. */
  256. addChild(group) {
  257. const size = this._children.size;
  258. this._children.add(group);
  259. return size !== this._children.size;
  260. }
  261. /**
  262. * @returns {ChunkGroup[]} returns the children of this group
  263. */
  264. getChildren() {
  265. return this._children.getFromCache(getArray);
  266. }
  267. getNumberOfChildren() {
  268. return this._children.size;
  269. }
  270. get childrenIterable() {
  271. return this._children;
  272. }
  273. /**
  274. * @param {ChunkGroup} group the chunk group to remove
  275. * @returns {boolean} returns true if the chunk group was removed
  276. */
  277. removeChild(group) {
  278. if (!this._children.has(group)) {
  279. return false;
  280. }
  281. this._children.delete(group);
  282. group.removeParent(this);
  283. return true;
  284. }
  285. /**
  286. * @param {ChunkGroup} parentChunk the parent group to be added into
  287. * @returns {boolean} returns true if this chunk group was added to the parent group
  288. */
  289. addParent(parentChunk) {
  290. if (!this._parents.has(parentChunk)) {
  291. this._parents.add(parentChunk);
  292. return true;
  293. }
  294. return false;
  295. }
  296. /**
  297. * @returns {ChunkGroup[]} returns the parents of this group
  298. */
  299. getParents() {
  300. return this._parents.getFromCache(getArray);
  301. }
  302. getNumberOfParents() {
  303. return this._parents.size;
  304. }
  305. /**
  306. * @param {ChunkGroup} parent the parent group
  307. * @returns {boolean} returns true if the parent group contains this group
  308. */
  309. hasParent(parent) {
  310. return this._parents.has(parent);
  311. }
  312. get parentsIterable() {
  313. return this._parents;
  314. }
  315. /**
  316. * @param {ChunkGroup} chunkGroup the parent group
  317. * @returns {boolean} returns true if this group has been removed from the parent
  318. */
  319. removeParent(chunkGroup) {
  320. if (this._parents.delete(chunkGroup)) {
  321. chunkGroup.removeChild(this);
  322. return true;
  323. }
  324. return false;
  325. }
  326. /**
  327. * @param {Entrypoint} entrypoint entrypoint to add
  328. * @returns {boolean} returns true if entrypoint was added
  329. */
  330. addAsyncEntrypoint(entrypoint) {
  331. const size = this._asyncEntrypoints.size;
  332. this._asyncEntrypoints.add(entrypoint);
  333. return size !== this._asyncEntrypoints.size;
  334. }
  335. get asyncEntrypointsIterable() {
  336. return this._asyncEntrypoints;
  337. }
  338. /**
  339. * @returns {AsyncDependenciesBlock[]} an array containing the blocks
  340. */
  341. getBlocks() {
  342. return this._blocks.getFromCache(getArray);
  343. }
  344. getNumberOfBlocks() {
  345. return this._blocks.size;
  346. }
  347. /**
  348. * @param {AsyncDependenciesBlock} block block
  349. * @returns {boolean} true, if block exists
  350. */
  351. hasBlock(block) {
  352. return this._blocks.has(block);
  353. }
  354. /**
  355. * @returns {Iterable<AsyncDependenciesBlock>} blocks
  356. */
  357. get blocksIterable() {
  358. return this._blocks;
  359. }
  360. /**
  361. * @param {AsyncDependenciesBlock} block a block
  362. * @returns {boolean} false, if block was already added
  363. */
  364. addBlock(block) {
  365. if (!this._blocks.has(block)) {
  366. this._blocks.add(block);
  367. return true;
  368. }
  369. return false;
  370. }
  371. /**
  372. * @param {Module | null} module origin module
  373. * @param {DependencyLocation} loc location of the reference in the origin module
  374. * @param {string} request request name of the reference
  375. * @returns {void}
  376. */
  377. addOrigin(module, loc, request) {
  378. this.origins.push({
  379. module,
  380. loc,
  381. request
  382. });
  383. }
  384. /**
  385. * @returns {string[]} the files contained this chunk group
  386. */
  387. getFiles() {
  388. /** @type {Set<string>} */
  389. const files = new Set();
  390. for (const chunk of this.chunks) {
  391. for (const file of chunk.files) {
  392. files.add(file);
  393. }
  394. }
  395. return [...files];
  396. }
  397. /**
  398. * @returns {void}
  399. */
  400. remove() {
  401. // cleanup parents
  402. for (const parentChunkGroup of this._parents) {
  403. // remove this chunk from its parents
  404. parentChunkGroup._children.delete(this);
  405. // cleanup "sub chunks"
  406. for (const chunkGroup of this._children) {
  407. /**
  408. * remove this chunk as "intermediary" and connect
  409. * it "sub chunks" and parents directly
  410. */
  411. // add parent to each "sub chunk"
  412. chunkGroup.addParent(parentChunkGroup);
  413. // add "sub chunk" to parent
  414. parentChunkGroup.addChild(chunkGroup);
  415. }
  416. }
  417. /**
  418. * we need to iterate again over the children
  419. * to remove this from the child's parents.
  420. * This can not be done in the above loop
  421. * as it is not guaranteed that `this._parents` contains anything.
  422. */
  423. for (const chunkGroup of this._children) {
  424. // remove this as parent of every "sub chunk"
  425. chunkGroup._parents.delete(this);
  426. }
  427. // remove chunks
  428. for (const chunk of this.chunks) {
  429. chunk.removeGroup(this);
  430. }
  431. }
  432. sortItems() {
  433. this.origins.sort(sortOrigin);
  434. }
  435. /**
  436. * Sorting predicate which allows current ChunkGroup to be compared against another.
  437. * Sorting values are based off of number of chunks in ChunkGroup.
  438. * @param {ChunkGraph} chunkGraph the chunk graph
  439. * @param {ChunkGroup} otherGroup the chunkGroup to compare this against
  440. * @returns {-1 | 0 | 1} sort position for comparison
  441. */
  442. compareTo(chunkGraph, otherGroup) {
  443. if (this.chunks.length > otherGroup.chunks.length) return -1;
  444. if (this.chunks.length < otherGroup.chunks.length) return 1;
  445. return compareIterables(compareChunks(chunkGraph))(
  446. this.chunks,
  447. otherGroup.chunks
  448. );
  449. }
  450. /**
  451. * @param {ModuleGraph} moduleGraph the module graph
  452. * @param {ChunkGraph} chunkGraph the chunk graph
  453. * @returns {Record<string, ChunkGroup[]>} mapping from children type to ordered list of ChunkGroups
  454. */
  455. getChildrenByOrders(moduleGraph, chunkGraph) {
  456. /** @type {Map<string, { order: number, group: ChunkGroup }[]>} */
  457. const lists = new Map();
  458. for (const childGroup of this._children) {
  459. for (const key of Object.keys(childGroup.options)) {
  460. if (key.endsWith("Order")) {
  461. const name = key.slice(0, key.length - "Order".length);
  462. let list = lists.get(name);
  463. if (list === undefined) {
  464. lists.set(name, (list = []));
  465. }
  466. list.push({
  467. order:
  468. /** @type {number} */
  469. (
  470. childGroup.options[/** @type {keyof ChunkGroupOptions} */ (key)]
  471. ),
  472. group: childGroup
  473. });
  474. }
  475. }
  476. }
  477. /** @type {Record<string, ChunkGroup[]>} */
  478. const result = Object.create(null);
  479. for (const [name, list] of lists) {
  480. list.sort((a, b) => {
  481. const cmp = b.order - a.order;
  482. if (cmp !== 0) return cmp;
  483. return a.group.compareTo(chunkGraph, b.group);
  484. });
  485. result[name] = list.map((i) => i.group);
  486. }
  487. return result;
  488. }
  489. /**
  490. * Sets the top-down index of a module in this ChunkGroup
  491. * @param {Module} module module for which the index should be set
  492. * @param {number} index the index of the module
  493. * @returns {void}
  494. */
  495. setModulePreOrderIndex(module, index) {
  496. this._modulePreOrderIndices.set(module, index);
  497. }
  498. /**
  499. * Gets the top-down index of a module in this ChunkGroup
  500. * @param {Module} module the module
  501. * @returns {number | undefined} index
  502. */
  503. getModulePreOrderIndex(module) {
  504. return this._modulePreOrderIndices.get(module);
  505. }
  506. /**
  507. * Sets the bottom-up index of a module in this ChunkGroup
  508. * @param {Module} module module for which the index should be set
  509. * @param {number} index the index of the module
  510. * @returns {void}
  511. */
  512. setModulePostOrderIndex(module, index) {
  513. this._modulePostOrderIndices.set(module, index);
  514. }
  515. /**
  516. * Gets the bottom-up index of a module in this ChunkGroup
  517. * @param {Module} module the module
  518. * @returns {number | undefined} index
  519. */
  520. getModulePostOrderIndex(module) {
  521. return this._modulePostOrderIndices.get(module);
  522. }
  523. /* istanbul ignore next */
  524. checkConstraints() {
  525. const chunk = this;
  526. for (const child of chunk._children) {
  527. if (!child._parents.has(chunk)) {
  528. throw new Error(
  529. `checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`
  530. );
  531. }
  532. }
  533. for (const parentChunk of chunk._parents) {
  534. if (!parentChunk._children.has(chunk)) {
  535. throw new Error(
  536. `checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`
  537. );
  538. }
  539. }
  540. }
  541. }
  542. ChunkGroup.prototype.getModuleIndex = util.deprecate(
  543. ChunkGroup.prototype.getModulePreOrderIndex,
  544. "ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex",
  545. "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX"
  546. );
  547. ChunkGroup.prototype.getModuleIndex2 = util.deprecate(
  548. ChunkGroup.prototype.getModulePostOrderIndex,
  549. "ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex",
  550. "DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2"
  551. );
  552. module.exports = ChunkGroup;