ModuleConcatenationPlugin.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const asyncLib = require("neo-async");
  7. const ChunkGraph = require("../ChunkGraph");
  8. const ModuleGraph = require("../ModuleGraph");
  9. const { STAGE_DEFAULT } = require("../OptimizationStages");
  10. const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency");
  11. const { compareModulesByIdentifier } = require("../util/comparators");
  12. const {
  13. intersectRuntime,
  14. mergeRuntimeOwned,
  15. filterRuntime,
  16. runtimeToString,
  17. mergeRuntime
  18. } = require("../util/runtime");
  19. const ConcatenatedModule = require("./ConcatenatedModule");
  20. /** @typedef {import("../Compilation")} Compilation */
  21. /** @typedef {import("../Compiler")} Compiler */
  22. /** @typedef {import("../Module")} Module */
  23. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  24. /** @typedef {import("../RequestShortener")} RequestShortener */
  25. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  26. /**
  27. * @typedef {object} Statistics
  28. * @property {number} cached
  29. * @property {number} alreadyInConfig
  30. * @property {number} invalidModule
  31. * @property {number} incorrectChunks
  32. * @property {number} incorrectDependency
  33. * @property {number} incorrectModuleDependency
  34. * @property {number} incorrectChunksOfImporter
  35. * @property {number} incorrectRuntimeCondition
  36. * @property {number} importerFailed
  37. * @property {number} added
  38. */
  39. /**
  40. * @param {string} msg message
  41. * @returns {string} formatted message
  42. */
  43. const formatBailoutReason = msg => {
  44. return "ModuleConcatenation bailout: " + msg;
  45. };
  46. class ModuleConcatenationPlugin {
  47. /**
  48. * @param {TODO} options options
  49. */
  50. constructor(options) {
  51. if (typeof options !== "object") options = {};
  52. this.options = options;
  53. }
  54. /**
  55. * Apply the plugin
  56. * @param {Compiler} compiler the compiler instance
  57. * @returns {void}
  58. */
  59. apply(compiler) {
  60. const { _backCompat: backCompat } = compiler;
  61. compiler.hooks.compilation.tap("ModuleConcatenationPlugin", compilation => {
  62. if (compilation.moduleMemCaches) {
  63. throw new Error(
  64. "optimization.concatenateModules can't be used with cacheUnaffected as module concatenation is a global effect"
  65. );
  66. }
  67. const moduleGraph = compilation.moduleGraph;
  68. /** @type {Map<Module, string | ((requestShortener: RequestShortener) => string)>} */
  69. const bailoutReasonMap = new Map();
  70. /**
  71. * @param {Module} module the module
  72. * @param {string | ((requestShortener: RequestShortener) => string)} reason the reason
  73. */
  74. const setBailoutReason = (module, reason) => {
  75. setInnerBailoutReason(module, reason);
  76. moduleGraph
  77. .getOptimizationBailout(module)
  78. .push(
  79. typeof reason === "function"
  80. ? rs => formatBailoutReason(reason(rs))
  81. : formatBailoutReason(reason)
  82. );
  83. };
  84. /**
  85. * @param {Module} module the module
  86. * @param {string | ((requestShortener: RequestShortener) => string)} reason the reason
  87. */
  88. const setInnerBailoutReason = (module, reason) => {
  89. bailoutReasonMap.set(module, reason);
  90. };
  91. /**
  92. * @param {Module} module the module
  93. * @param {RequestShortener} requestShortener the request shortener
  94. * @returns {string | ((requestShortener: RequestShortener) => string) | undefined} the reason
  95. */
  96. const getInnerBailoutReason = (module, requestShortener) => {
  97. const reason = bailoutReasonMap.get(module);
  98. if (typeof reason === "function") return reason(requestShortener);
  99. return reason;
  100. };
  101. /**
  102. * @param {Module} module the module
  103. * @param {Module | function(RequestShortener): string} problem the problem
  104. * @returns {(requestShortener: RequestShortener) => string} the reason
  105. */
  106. const formatBailoutWarning = (module, problem) => requestShortener => {
  107. if (typeof problem === "function") {
  108. return formatBailoutReason(
  109. `Cannot concat with ${module.readableIdentifier(
  110. requestShortener
  111. )}: ${problem(requestShortener)}`
  112. );
  113. }
  114. const reason = getInnerBailoutReason(module, requestShortener);
  115. const reasonWithPrefix = reason ? `: ${reason}` : "";
  116. if (module === problem) {
  117. return formatBailoutReason(
  118. `Cannot concat with ${module.readableIdentifier(
  119. requestShortener
  120. )}${reasonWithPrefix}`
  121. );
  122. } else {
  123. return formatBailoutReason(
  124. `Cannot concat with ${module.readableIdentifier(
  125. requestShortener
  126. )} because of ${problem.readableIdentifier(
  127. requestShortener
  128. )}${reasonWithPrefix}`
  129. );
  130. }
  131. };
  132. compilation.hooks.optimizeChunkModules.tapAsync(
  133. {
  134. name: "ModuleConcatenationPlugin",
  135. stage: STAGE_DEFAULT
  136. },
  137. (allChunks, modules, callback) => {
  138. const logger = compilation.getLogger(
  139. "webpack.ModuleConcatenationPlugin"
  140. );
  141. const { chunkGraph, moduleGraph } = compilation;
  142. const relevantModules = [];
  143. const possibleInners = new Set();
  144. const context = {
  145. chunkGraph,
  146. moduleGraph
  147. };
  148. logger.time("select relevant modules");
  149. for (const module of modules) {
  150. let canBeRoot = true;
  151. let canBeInner = true;
  152. const bailoutReason = module.getConcatenationBailoutReason(context);
  153. if (bailoutReason) {
  154. setBailoutReason(module, bailoutReason);
  155. continue;
  156. }
  157. // Must not be an async module
  158. if (moduleGraph.isAsync(module)) {
  159. setBailoutReason(module, `Module is async`);
  160. continue;
  161. }
  162. // Must be in strict mode
  163. if (!(/** @type {BuildInfo} */ (module.buildInfo).strict)) {
  164. setBailoutReason(module, `Module is not in strict mode`);
  165. continue;
  166. }
  167. // Module must be in any chunk (we don't want to do useless work)
  168. if (chunkGraph.getNumberOfModuleChunks(module) === 0) {
  169. setBailoutReason(module, "Module is not in any chunk");
  170. continue;
  171. }
  172. // Exports must be known (and not dynamic)
  173. const exportsInfo = moduleGraph.getExportsInfo(module);
  174. const relevantExports = exportsInfo.getRelevantExports(undefined);
  175. const unknownReexports = relevantExports.filter(exportInfo => {
  176. return (
  177. exportInfo.isReexport() && !exportInfo.getTarget(moduleGraph)
  178. );
  179. });
  180. if (unknownReexports.length > 0) {
  181. setBailoutReason(
  182. module,
  183. `Reexports in this module do not have a static target (${Array.from(
  184. unknownReexports,
  185. exportInfo =>
  186. `${
  187. exportInfo.name || "other exports"
  188. }: ${exportInfo.getUsedInfo()}`
  189. ).join(", ")})`
  190. );
  191. continue;
  192. }
  193. // Root modules must have a static list of exports
  194. const unknownProvidedExports = relevantExports.filter(
  195. exportInfo => {
  196. return exportInfo.provided !== true;
  197. }
  198. );
  199. if (unknownProvidedExports.length > 0) {
  200. setBailoutReason(
  201. module,
  202. `List of module exports is dynamic (${Array.from(
  203. unknownProvidedExports,
  204. exportInfo =>
  205. `${
  206. exportInfo.name || "other exports"
  207. }: ${exportInfo.getProvidedInfo()} and ${exportInfo.getUsedInfo()}`
  208. ).join(", ")})`
  209. );
  210. canBeRoot = false;
  211. }
  212. // Module must not be an entry point
  213. if (chunkGraph.isEntryModule(module)) {
  214. setInnerBailoutReason(module, "Module is an entry point");
  215. canBeInner = false;
  216. }
  217. if (canBeRoot) relevantModules.push(module);
  218. if (canBeInner) possibleInners.add(module);
  219. }
  220. logger.timeEnd("select relevant modules");
  221. logger.debug(
  222. `${relevantModules.length} potential root modules, ${possibleInners.size} potential inner modules`
  223. );
  224. // sort by depth
  225. // modules with lower depth are more likely suited as roots
  226. // this improves performance, because modules already selected as inner are skipped
  227. logger.time("sort relevant modules");
  228. relevantModules.sort((a, b) => {
  229. return (
  230. /** @type {number} */ (moduleGraph.getDepth(a)) -
  231. /** @type {number} */ (moduleGraph.getDepth(b))
  232. );
  233. });
  234. logger.timeEnd("sort relevant modules");
  235. /** @type {Statistics} */
  236. const stats = {
  237. cached: 0,
  238. alreadyInConfig: 0,
  239. invalidModule: 0,
  240. incorrectChunks: 0,
  241. incorrectDependency: 0,
  242. incorrectModuleDependency: 0,
  243. incorrectChunksOfImporter: 0,
  244. incorrectRuntimeCondition: 0,
  245. importerFailed: 0,
  246. added: 0
  247. };
  248. let statsCandidates = 0;
  249. let statsSizeSum = 0;
  250. let statsEmptyConfigurations = 0;
  251. logger.time("find modules to concatenate");
  252. const concatConfigurations = [];
  253. const usedAsInner = new Set();
  254. for (const currentRoot of relevantModules) {
  255. // when used by another configuration as inner:
  256. // the other configuration is better and we can skip this one
  257. // TODO reconsider that when it's only used in a different runtime
  258. if (usedAsInner.has(currentRoot)) continue;
  259. let chunkRuntime = undefined;
  260. for (const r of chunkGraph.getModuleRuntimes(currentRoot)) {
  261. chunkRuntime = mergeRuntimeOwned(chunkRuntime, r);
  262. }
  263. const exportsInfo = moduleGraph.getExportsInfo(currentRoot);
  264. const filteredRuntime = filterRuntime(chunkRuntime, r =>
  265. exportsInfo.isModuleUsed(r)
  266. );
  267. const activeRuntime =
  268. filteredRuntime === true
  269. ? chunkRuntime
  270. : filteredRuntime === false
  271. ? undefined
  272. : filteredRuntime;
  273. // create a configuration with the root
  274. const currentConfiguration = new ConcatConfiguration(
  275. currentRoot,
  276. activeRuntime
  277. );
  278. // cache failures to add modules
  279. const failureCache = new Map();
  280. // potential optional import candidates
  281. /** @type {Set<Module>} */
  282. const candidates = new Set();
  283. // try to add all imports
  284. for (const imp of this._getImports(
  285. compilation,
  286. currentRoot,
  287. activeRuntime
  288. )) {
  289. candidates.add(imp);
  290. }
  291. for (const imp of candidates) {
  292. const impCandidates = new Set();
  293. const problem = this._tryToAdd(
  294. compilation,
  295. currentConfiguration,
  296. imp,
  297. chunkRuntime,
  298. activeRuntime,
  299. possibleInners,
  300. impCandidates,
  301. failureCache,
  302. chunkGraph,
  303. true,
  304. stats
  305. );
  306. if (problem) {
  307. failureCache.set(imp, problem);
  308. currentConfiguration.addWarning(imp, problem);
  309. } else {
  310. for (const c of impCandidates) {
  311. candidates.add(c);
  312. }
  313. }
  314. }
  315. statsCandidates += candidates.size;
  316. if (!currentConfiguration.isEmpty()) {
  317. const modules = currentConfiguration.getModules();
  318. statsSizeSum += modules.size;
  319. concatConfigurations.push(currentConfiguration);
  320. for (const module of modules) {
  321. if (module !== currentConfiguration.rootModule) {
  322. usedAsInner.add(module);
  323. }
  324. }
  325. } else {
  326. statsEmptyConfigurations++;
  327. const optimizationBailouts =
  328. moduleGraph.getOptimizationBailout(currentRoot);
  329. for (const warning of currentConfiguration.getWarningsSorted()) {
  330. optimizationBailouts.push(
  331. formatBailoutWarning(warning[0], warning[1])
  332. );
  333. }
  334. }
  335. }
  336. logger.timeEnd("find modules to concatenate");
  337. logger.debug(
  338. `${
  339. concatConfigurations.length
  340. } successful concat configurations (avg size: ${
  341. statsSizeSum / concatConfigurations.length
  342. }), ${statsEmptyConfigurations} bailed out completely`
  343. );
  344. logger.debug(
  345. `${statsCandidates} candidates were considered for adding (${stats.cached} cached failure, ${stats.alreadyInConfig} already in config, ${stats.invalidModule} invalid module, ${stats.incorrectChunks} incorrect chunks, ${stats.incorrectDependency} incorrect dependency, ${stats.incorrectChunksOfImporter} incorrect chunks of importer, ${stats.incorrectModuleDependency} incorrect module dependency, ${stats.incorrectRuntimeCondition} incorrect runtime condition, ${stats.importerFailed} importer failed, ${stats.added} added)`
  346. );
  347. // HACK: Sort configurations by length and start with the longest one
  348. // to get the biggest groups possible. Used modules are marked with usedModules
  349. // TODO: Allow to reuse existing configuration while trying to add dependencies.
  350. // This would improve performance. O(n^2) -> O(n)
  351. logger.time(`sort concat configurations`);
  352. concatConfigurations.sort((a, b) => {
  353. return b.modules.size - a.modules.size;
  354. });
  355. logger.timeEnd(`sort concat configurations`);
  356. const usedModules = new Set();
  357. logger.time("create concatenated modules");
  358. asyncLib.each(
  359. concatConfigurations,
  360. (concatConfiguration, callback) => {
  361. const rootModule = concatConfiguration.rootModule;
  362. // Avoid overlapping configurations
  363. // TODO: remove this when todo above is fixed
  364. if (usedModules.has(rootModule)) return callback();
  365. const modules = concatConfiguration.getModules();
  366. for (const m of modules) {
  367. usedModules.add(m);
  368. }
  369. // Create a new ConcatenatedModule
  370. let newModule = ConcatenatedModule.create(
  371. rootModule,
  372. modules,
  373. concatConfiguration.runtime,
  374. compiler.root,
  375. compilation.outputOptions.hashFunction
  376. );
  377. const build = () => {
  378. newModule.build(
  379. compiler.options,
  380. compilation,
  381. null,
  382. null,
  383. err => {
  384. if (err) {
  385. if (!err.module) {
  386. err.module = newModule;
  387. }
  388. return callback(err);
  389. }
  390. integrate();
  391. }
  392. );
  393. };
  394. const integrate = () => {
  395. if (backCompat) {
  396. ChunkGraph.setChunkGraphForModule(newModule, chunkGraph);
  397. ModuleGraph.setModuleGraphForModule(newModule, moduleGraph);
  398. }
  399. for (const warning of concatConfiguration.getWarningsSorted()) {
  400. moduleGraph
  401. .getOptimizationBailout(newModule)
  402. .push(formatBailoutWarning(warning[0], warning[1]));
  403. }
  404. moduleGraph.cloneModuleAttributes(rootModule, newModule);
  405. for (const m of modules) {
  406. // add to builtModules when one of the included modules was built
  407. if (compilation.builtModules.has(m)) {
  408. compilation.builtModules.add(newModule);
  409. }
  410. if (m !== rootModule) {
  411. // attach external references to the concatenated module too
  412. moduleGraph.copyOutgoingModuleConnections(
  413. m,
  414. newModule,
  415. c => {
  416. return (
  417. c.originModule === m &&
  418. !(
  419. c.dependency instanceof HarmonyImportDependency &&
  420. modules.has(c.module)
  421. )
  422. );
  423. }
  424. );
  425. // remove module from chunk
  426. for (const chunk of chunkGraph.getModuleChunksIterable(
  427. rootModule
  428. )) {
  429. const sourceTypes = chunkGraph.getChunkModuleSourceTypes(
  430. chunk,
  431. m
  432. );
  433. if (sourceTypes.size === 1) {
  434. chunkGraph.disconnectChunkAndModule(chunk, m);
  435. } else {
  436. const newSourceTypes = new Set(sourceTypes);
  437. newSourceTypes.delete("javascript");
  438. chunkGraph.setChunkModuleSourceTypes(
  439. chunk,
  440. m,
  441. newSourceTypes
  442. );
  443. }
  444. }
  445. }
  446. }
  447. compilation.modules.delete(rootModule);
  448. ChunkGraph.clearChunkGraphForModule(rootModule);
  449. ModuleGraph.clearModuleGraphForModule(rootModule);
  450. // remove module from chunk
  451. chunkGraph.replaceModule(rootModule, newModule);
  452. // replace module references with the concatenated module
  453. moduleGraph.moveModuleConnections(rootModule, newModule, c => {
  454. const otherModule =
  455. c.module === rootModule ? c.originModule : c.module;
  456. const innerConnection =
  457. c.dependency instanceof HarmonyImportDependency &&
  458. modules.has(/** @type {Module} */ (otherModule));
  459. return !innerConnection;
  460. });
  461. // add concatenated module to the compilation
  462. compilation.modules.add(newModule);
  463. callback();
  464. };
  465. build();
  466. },
  467. err => {
  468. logger.timeEnd("create concatenated modules");
  469. process.nextTick(callback.bind(null, err));
  470. }
  471. );
  472. }
  473. );
  474. });
  475. }
  476. /**
  477. * @param {Compilation} compilation the compilation
  478. * @param {Module} module the module to be added
  479. * @param {RuntimeSpec} runtime the runtime scope
  480. * @returns {Set<Module>} the imported modules
  481. */
  482. _getImports(compilation, module, runtime) {
  483. const moduleGraph = compilation.moduleGraph;
  484. const set = new Set();
  485. for (const dep of module.dependencies) {
  486. // Get reference info only for harmony Dependencies
  487. if (!(dep instanceof HarmonyImportDependency)) continue;
  488. const connection = moduleGraph.getConnection(dep);
  489. // Reference is valid and has a module
  490. if (
  491. !connection ||
  492. !connection.module ||
  493. !connection.isTargetActive(runtime)
  494. ) {
  495. continue;
  496. }
  497. const importedNames = compilation.getDependencyReferencedExports(
  498. dep,
  499. undefined
  500. );
  501. if (
  502. importedNames.every(i =>
  503. Array.isArray(i) ? i.length > 0 : i.name.length > 0
  504. ) ||
  505. Array.isArray(moduleGraph.getProvidedExports(module))
  506. ) {
  507. set.add(connection.module);
  508. }
  509. }
  510. return set;
  511. }
  512. /**
  513. * @param {Compilation} compilation webpack compilation
  514. * @param {ConcatConfiguration} config concat configuration (will be modified when added)
  515. * @param {Module} module the module to be added
  516. * @param {RuntimeSpec} runtime the runtime scope of the generated code
  517. * @param {RuntimeSpec} activeRuntime the runtime scope of the root module
  518. * @param {Set<Module>} possibleModules modules that are candidates
  519. * @param {Set<Module>} candidates list of potential candidates (will be added to)
  520. * @param {Map<Module, Module | function(RequestShortener): string>} failureCache cache for problematic modules to be more performant
  521. * @param {ChunkGraph} chunkGraph the chunk graph
  522. * @param {boolean} avoidMutateOnFailure avoid mutating the config when adding fails
  523. * @param {Statistics} statistics gathering metrics
  524. * @returns {null | Module | function(RequestShortener): string} the problematic module
  525. */
  526. _tryToAdd(
  527. compilation,
  528. config,
  529. module,
  530. runtime,
  531. activeRuntime,
  532. possibleModules,
  533. candidates,
  534. failureCache,
  535. chunkGraph,
  536. avoidMutateOnFailure,
  537. statistics
  538. ) {
  539. const cacheEntry = failureCache.get(module);
  540. if (cacheEntry) {
  541. statistics.cached++;
  542. return cacheEntry;
  543. }
  544. // Already added?
  545. if (config.has(module)) {
  546. statistics.alreadyInConfig++;
  547. return null;
  548. }
  549. // Not possible to add?
  550. if (!possibleModules.has(module)) {
  551. statistics.invalidModule++;
  552. failureCache.set(module, module); // cache failures for performance
  553. return module;
  554. }
  555. // Module must be in the correct chunks
  556. const missingChunks = Array.from(
  557. chunkGraph.getModuleChunksIterable(config.rootModule)
  558. ).filter(chunk => !chunkGraph.isModuleInChunk(module, chunk));
  559. if (missingChunks.length > 0) {
  560. /**
  561. * @param {RequestShortener} requestShortener request shortener
  562. * @returns {string} problem description
  563. */
  564. const problem = requestShortener => {
  565. const missingChunksList = Array.from(
  566. new Set(missingChunks.map(chunk => chunk.name || "unnamed chunk(s)"))
  567. ).sort();
  568. const chunks = Array.from(
  569. new Set(
  570. Array.from(chunkGraph.getModuleChunksIterable(module)).map(
  571. chunk => chunk.name || "unnamed chunk(s)"
  572. )
  573. )
  574. ).sort();
  575. return `Module ${module.readableIdentifier(
  576. requestShortener
  577. )} is not in the same chunk(s) (expected in chunk(s) ${missingChunksList.join(
  578. ", "
  579. )}, module is in chunk(s) ${chunks.join(", ")})`;
  580. };
  581. statistics.incorrectChunks++;
  582. failureCache.set(module, problem); // cache failures for performance
  583. return problem;
  584. }
  585. const moduleGraph = compilation.moduleGraph;
  586. const incomingConnections =
  587. moduleGraph.getIncomingConnectionsByOriginModule(module);
  588. const incomingConnectionsFromNonModules =
  589. incomingConnections.get(null) || incomingConnections.get(undefined);
  590. if (incomingConnectionsFromNonModules) {
  591. const activeNonModulesConnections =
  592. incomingConnectionsFromNonModules.filter(connection => {
  593. // We are not interested in inactive connections
  594. // or connections without dependency
  595. return connection.isActive(runtime);
  596. });
  597. if (activeNonModulesConnections.length > 0) {
  598. /**
  599. * @param {RequestShortener} requestShortener request shortener
  600. * @returns {string} problem description
  601. */
  602. const problem = requestShortener => {
  603. const importingExplanations = new Set(
  604. activeNonModulesConnections.map(c => c.explanation).filter(Boolean)
  605. );
  606. const explanations = Array.from(importingExplanations).sort();
  607. return `Module ${module.readableIdentifier(
  608. requestShortener
  609. )} is referenced ${
  610. explanations.length > 0
  611. ? `by: ${explanations.join(", ")}`
  612. : "in an unsupported way"
  613. }`;
  614. };
  615. statistics.incorrectDependency++;
  616. failureCache.set(module, problem); // cache failures for performance
  617. return problem;
  618. }
  619. }
  620. /** @type {Map<Module, readonly ModuleGraph.ModuleGraphConnection[]>} */
  621. const incomingConnectionsFromModules = new Map();
  622. for (const [originModule, connections] of incomingConnections) {
  623. if (originModule) {
  624. // Ignore connection from orphan modules
  625. if (chunkGraph.getNumberOfModuleChunks(originModule) === 0) continue;
  626. // We don't care for connections from other runtimes
  627. let originRuntime = undefined;
  628. for (const r of chunkGraph.getModuleRuntimes(originModule)) {
  629. originRuntime = mergeRuntimeOwned(originRuntime, r);
  630. }
  631. if (!intersectRuntime(runtime, originRuntime)) continue;
  632. // We are not interested in inactive connections
  633. const activeConnections = connections.filter(connection =>
  634. connection.isActive(runtime)
  635. );
  636. if (activeConnections.length > 0)
  637. incomingConnectionsFromModules.set(originModule, activeConnections);
  638. }
  639. }
  640. const incomingModules = Array.from(incomingConnectionsFromModules.keys());
  641. // Module must be in the same chunks like the referencing module
  642. const otherChunkModules = incomingModules.filter(originModule => {
  643. for (const chunk of chunkGraph.getModuleChunksIterable(
  644. config.rootModule
  645. )) {
  646. if (!chunkGraph.isModuleInChunk(originModule, chunk)) {
  647. return true;
  648. }
  649. }
  650. return false;
  651. });
  652. if (otherChunkModules.length > 0) {
  653. /**
  654. * @param {RequestShortener} requestShortener request shortener
  655. * @returns {string} problem description
  656. */
  657. const problem = requestShortener => {
  658. const names = otherChunkModules
  659. .map(m => m.readableIdentifier(requestShortener))
  660. .sort();
  661. return `Module ${module.readableIdentifier(
  662. requestShortener
  663. )} is referenced from different chunks by these modules: ${names.join(
  664. ", "
  665. )}`;
  666. };
  667. statistics.incorrectChunksOfImporter++;
  668. failureCache.set(module, problem); // cache failures for performance
  669. return problem;
  670. }
  671. /** @type {Map<Module, readonly ModuleGraph.ModuleGraphConnection[]>} */
  672. const nonHarmonyConnections = new Map();
  673. for (const [originModule, connections] of incomingConnectionsFromModules) {
  674. const selected = connections.filter(
  675. connection =>
  676. !connection.dependency ||
  677. !(connection.dependency instanceof HarmonyImportDependency)
  678. );
  679. if (selected.length > 0)
  680. nonHarmonyConnections.set(originModule, connections);
  681. }
  682. if (nonHarmonyConnections.size > 0) {
  683. /**
  684. * @param {RequestShortener} requestShortener request shortener
  685. * @returns {string} problem description
  686. */
  687. const problem = requestShortener => {
  688. const names = Array.from(nonHarmonyConnections)
  689. .map(([originModule, connections]) => {
  690. return `${originModule.readableIdentifier(
  691. requestShortener
  692. )} (referenced with ${Array.from(
  693. new Set(
  694. connections
  695. .map(c => c.dependency && c.dependency.type)
  696. .filter(Boolean)
  697. )
  698. )
  699. .sort()
  700. .join(", ")})`;
  701. })
  702. .sort();
  703. return `Module ${module.readableIdentifier(
  704. requestShortener
  705. )} is referenced from these modules with unsupported syntax: ${names.join(
  706. ", "
  707. )}`;
  708. };
  709. statistics.incorrectModuleDependency++;
  710. failureCache.set(module, problem); // cache failures for performance
  711. return problem;
  712. }
  713. if (runtime !== undefined && typeof runtime !== "string") {
  714. // Module must be consistently referenced in the same runtimes
  715. /** @type {{ originModule: Module, runtimeCondition: RuntimeSpec }[]} */
  716. const otherRuntimeConnections = [];
  717. outer: for (const [
  718. originModule,
  719. connections
  720. ] of incomingConnectionsFromModules) {
  721. /** @type {false | RuntimeSpec} */
  722. let currentRuntimeCondition = false;
  723. for (const connection of connections) {
  724. const runtimeCondition = filterRuntime(runtime, runtime => {
  725. return connection.isTargetActive(runtime);
  726. });
  727. if (runtimeCondition === false) continue;
  728. if (runtimeCondition === true) continue outer;
  729. if (currentRuntimeCondition !== false) {
  730. currentRuntimeCondition = mergeRuntime(
  731. currentRuntimeCondition,
  732. runtimeCondition
  733. );
  734. } else {
  735. currentRuntimeCondition = runtimeCondition;
  736. }
  737. }
  738. if (currentRuntimeCondition !== false) {
  739. otherRuntimeConnections.push({
  740. originModule,
  741. runtimeCondition: currentRuntimeCondition
  742. });
  743. }
  744. }
  745. if (otherRuntimeConnections.length > 0) {
  746. /**
  747. * @param {RequestShortener} requestShortener request shortener
  748. * @returns {string} problem description
  749. */
  750. const problem = requestShortener => {
  751. return `Module ${module.readableIdentifier(
  752. requestShortener
  753. )} is runtime-dependent referenced by these modules: ${Array.from(
  754. otherRuntimeConnections,
  755. ({ originModule, runtimeCondition }) =>
  756. `${originModule.readableIdentifier(
  757. requestShortener
  758. )} (expected runtime ${runtimeToString(
  759. runtime
  760. )}, module is only referenced in ${runtimeToString(
  761. /** @type {RuntimeSpec} */ (runtimeCondition)
  762. )})`
  763. ).join(", ")}`;
  764. };
  765. statistics.incorrectRuntimeCondition++;
  766. failureCache.set(module, problem); // cache failures for performance
  767. return problem;
  768. }
  769. }
  770. let backup;
  771. if (avoidMutateOnFailure) {
  772. backup = config.snapshot();
  773. }
  774. // Add the module
  775. config.add(module);
  776. incomingModules.sort(compareModulesByIdentifier);
  777. // Every module which depends on the added module must be in the configuration too.
  778. for (const originModule of incomingModules) {
  779. const problem = this._tryToAdd(
  780. compilation,
  781. config,
  782. originModule,
  783. runtime,
  784. activeRuntime,
  785. possibleModules,
  786. candidates,
  787. failureCache,
  788. chunkGraph,
  789. false,
  790. statistics
  791. );
  792. if (problem) {
  793. if (backup !== undefined) config.rollback(backup);
  794. statistics.importerFailed++;
  795. failureCache.set(module, problem); // cache failures for performance
  796. return problem;
  797. }
  798. }
  799. // Add imports to possible candidates list
  800. for (const imp of this._getImports(compilation, module, runtime)) {
  801. candidates.add(imp);
  802. }
  803. statistics.added++;
  804. return null;
  805. }
  806. }
  807. class ConcatConfiguration {
  808. /**
  809. * @param {Module} rootModule the root module
  810. * @param {RuntimeSpec} runtime the runtime
  811. */
  812. constructor(rootModule, runtime) {
  813. this.rootModule = rootModule;
  814. this.runtime = runtime;
  815. /** @type {Set<Module>} */
  816. this.modules = new Set();
  817. this.modules.add(rootModule);
  818. /** @type {Map<Module, Module | function(RequestShortener): string>} */
  819. this.warnings = new Map();
  820. }
  821. /**
  822. * @param {Module} module the module
  823. */
  824. add(module) {
  825. this.modules.add(module);
  826. }
  827. /**
  828. * @param {Module} module the module
  829. * @returns {boolean} true, when the module is in the module set
  830. */
  831. has(module) {
  832. return this.modules.has(module);
  833. }
  834. isEmpty() {
  835. return this.modules.size === 1;
  836. }
  837. /**
  838. * @param {Module} module the module
  839. * @param {Module | function(RequestShortener): string} problem the problem
  840. */
  841. addWarning(module, problem) {
  842. this.warnings.set(module, problem);
  843. }
  844. /**
  845. * @returns {Map<Module, Module | function(RequestShortener): string>} warnings
  846. */
  847. getWarningsSorted() {
  848. return new Map(
  849. Array.from(this.warnings).sort((a, b) => {
  850. const ai = a[0].identifier();
  851. const bi = b[0].identifier();
  852. if (ai < bi) return -1;
  853. if (ai > bi) return 1;
  854. return 0;
  855. })
  856. );
  857. }
  858. /**
  859. * @returns {Set<Module>} modules as set
  860. */
  861. getModules() {
  862. return this.modules;
  863. }
  864. snapshot() {
  865. return this.modules.size;
  866. }
  867. /**
  868. * @param {number} snapshot snapshot
  869. */
  870. rollback(snapshot) {
  871. const modules = this.modules;
  872. for (const m of modules) {
  873. if (snapshot === 0) {
  874. modules.delete(m);
  875. } else {
  876. snapshot--;
  877. }
  878. }
  879. }
  880. }
  881. module.exports = ModuleConcatenationPlugin;