Module.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  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 ChunkGraph = require("./ChunkGraph");
  8. const DependenciesBlock = require("./DependenciesBlock");
  9. const ModuleGraph = require("./ModuleGraph");
  10. const {
  11. JAVASCRIPT_TYPE,
  12. UNKNOWN_TYPE
  13. } = require("./ModuleSourceTypeConstants");
  14. const { JAVASCRIPT_TYPES } = require("./ModuleSourceTypeConstants");
  15. const RuntimeGlobals = require("./RuntimeGlobals");
  16. const { first } = require("./util/SetHelpers");
  17. const { compareChunksById } = require("./util/comparators");
  18. const makeSerializable = require("./util/makeSerializable");
  19. /** @typedef {import("webpack-sources").Source} Source */
  20. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  21. /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
  22. /** @typedef {import("./Chunk")} Chunk */
  23. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  24. /** @typedef {import("./ChunkGroup")} ChunkGroup */
  25. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  26. /** @typedef {import("./Compilation")} Compilation */
  27. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  28. /** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
  29. /** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */
  30. /** @typedef {import("./ConcatenationScope")} ConcatenationScope */
  31. /** @typedef {import("./Dependency")} Dependency */
  32. /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
  33. /** @typedef {import("./DependencyTemplate").CssData} CssData */
  34. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  35. /** @typedef {import("./ModuleSourceTypeConstants").AllTypes} AllTypes */
  36. /** @typedef {import("./FileSystemInfo")} FileSystemInfo */
  37. /** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
  38. /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
  39. /** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */
  40. /** @typedef {import("./ModuleGraph").OptimizationBailouts} OptimizationBailouts */
  41. /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
  42. /** @typedef {import("./RequestShortener")} RequestShortener */
  43. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  44. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  45. /** @typedef {import("../declarations/WebpackOptions").CssParserExportType} CssParserExportType */
  46. /**
  47. * @template T
  48. * @typedef {import("./InitFragment")<T>} InitFragment
  49. */
  50. /** @typedef {import("./WebpackError")} WebpackError */
  51. /** @typedef {import("./json/JsonData")} JsonData */
  52. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  53. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  54. /** @typedef {import("./util/Hash")} Hash */
  55. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  56. /** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
  57. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  58. /** @typedef {"namespace" | "default-only" | "default-with-named" | "dynamic"} ExportsType */
  59. /**
  60. * @template T
  61. * @typedef {import("./util/LazySet")<T>} LazySet<T>
  62. */
  63. /**
  64. * @typedef {object} SourceContext
  65. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  66. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  67. * @property {ModuleGraph} moduleGraph the module graph
  68. * @property {ChunkGraph} chunkGraph the chunk graph
  69. * @property {RuntimeSpec} runtime the runtimes code should be generated for
  70. * @property {string=} type the type of source that should be generated
  71. */
  72. /** @typedef {AllTypes} KnownSourceType */
  73. /** @typedef {KnownSourceType | string} SourceType */
  74. /** @typedef {ReadonlySet<SourceType>} SourceTypes */
  75. // TODO webpack 6: compilation will be required in CodeGenerationContext
  76. /**
  77. * @typedef {object} CodeGenerationContext
  78. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  79. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  80. * @property {ModuleGraph} moduleGraph the module graph
  81. * @property {ChunkGraph} chunkGraph the chunk graph
  82. * @property {RuntimeSpec} runtime the runtimes code should be generated for
  83. * @property {RuntimeSpec[]} runtimes all runtimes code should be generated for
  84. * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
  85. * @property {CodeGenerationResults | undefined} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
  86. * @property {Compilation=} compilation the compilation
  87. * @property {SourceTypes=} sourceTypes source types
  88. */
  89. /**
  90. * @typedef {object} ConcatenationBailoutReasonContext
  91. * @property {ModuleGraph} moduleGraph the module graph
  92. * @property {ChunkGraph} chunkGraph the chunk graph
  93. */
  94. /** @typedef {Set<string>} RuntimeRequirements */
  95. /** @typedef {ReadonlySet<string>} ReadOnlyRuntimeRequirements */
  96. /** @typedef {Map<"topLevelDeclarations", Set<string>> & Map<"chunkInitFragments", InitFragment<EXPECTED_ANY>[]>} KnownCodeGenerationResultDataForJavascriptModules */
  97. /** @typedef {Map<"url", { ["css-url"]: string }>} KnownCodeGenerationResultDataForCssModules */
  98. /** @typedef {Map<"filename", string> & Map<"assetInfo", AssetInfo> & Map<"fullContentHash", string>} KnownCodeGenerationResultDataForAssetModules */
  99. /** @typedef {Map<"share-init", [{ shareScope: string, initStage: number, init: string }]>} KnownCodeGenerationResultForSharing */
  100. /** @typedef {KnownCodeGenerationResultDataForJavascriptModules & KnownCodeGenerationResultDataForCssModules & KnownCodeGenerationResultDataForAssetModules & KnownCodeGenerationResultForSharing & Map<string, EXPECTED_ANY>} CodeGenerationResultData */
  101. /**
  102. * @typedef {object} CodeGenerationResult
  103. * @property {Map<SourceType, Source>} sources the resulting sources for all source types
  104. * @property {CodeGenerationResultData=} data the resulting data for all source types
  105. * @property {ReadOnlyRuntimeRequirements | null} runtimeRequirements the runtime requirements
  106. * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided)
  107. */
  108. /**
  109. * @typedef {object} LibIdentOptions
  110. * @property {string} context absolute context path to which lib ident is relative to
  111. * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching
  112. */
  113. /**
  114. * @typedef {object} KnownBuildMeta
  115. * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType
  116. * @property {CssParserExportType=} exportType
  117. * @property {(false | "redirect" | "redirect-warn")=} defaultObject
  118. * @property {boolean=} strictHarmonyModule
  119. * @property {boolean=} treatAsCommonJs
  120. * @property {boolean=} async
  121. * @property {boolean=} sideEffectFree
  122. * @property {boolean=} isCSSModule
  123. * @property {Record<string, string>=} jsIncompatibleExports
  124. * @property {Map<RuntimeSpec, Record<string, string>>=} exportsFinalNameByRuntime
  125. * @property {Map<RuntimeSpec, string>=} exportsSourceByRuntime
  126. */
  127. /**
  128. * @typedef {object} KnownBuildInfo
  129. * @property {boolean=} cacheable
  130. * @property {boolean=} parsed
  131. * @property {boolean=} strict
  132. * @property {string=} moduleArgument using in AMD
  133. * @property {string=} exportsArgument using in AMD
  134. * @property {string=} moduleConcatenationBailout using in CommonJs
  135. * @property {boolean=} needCreateRequire using in APIPlugin
  136. * @property {string=} resourceIntegrity using in HttpUriPlugin
  137. * @property {FileSystemDependencies=} fileDependencies using in NormalModule
  138. * @property {FileSystemDependencies=} contextDependencies using in NormalModule
  139. * @property {FileSystemDependencies=} missingDependencies using in NormalModule
  140. * @property {FileSystemDependencies=} buildDependencies using in NormalModule
  141. * @property {ValueCacheVersions=} valueDependencies using in NormalModule
  142. * @property {Record<string, Source>=} assets using in NormalModule
  143. * @property {Map<string, AssetInfo | undefined>=} assetsInfo using in NormalModule
  144. * @property {string=} hash using in NormalModule
  145. * @property {(Snapshot | null)=} snapshot using in ContextModule
  146. * @property {string=} fullContentHash for assets modules
  147. * @property {string=} filename for assets modules
  148. * @property {boolean=} dataUrl for assets modules
  149. * @property {AssetInfo=} assetInfo for assets modules
  150. * @property {boolean=} javascriptModule for external modules
  151. * @property {boolean=} active for lazy compilation modules
  152. * @property {CssData=} cssData for css modules
  153. * @property {JsonData=} jsonData for json modules
  154. * @property {Set<string>=} topLevelDeclarations top level declaration names
  155. */
  156. /** @typedef {string | Set<string>} ValueCacheVersion */
  157. /** @typedef {Map<string, ValueCacheVersion>} ValueCacheVersions */
  158. /**
  159. * @typedef {object} NeedBuildContext
  160. * @property {Compilation} compilation
  161. * @property {FileSystemInfo} fileSystemInfo
  162. * @property {ValueCacheVersions} valueCacheVersions
  163. */
  164. /** @typedef {(err?: WebpackError | null, needBuild?: boolean) => void} NeedBuildCallback */
  165. /** @typedef {(err?: WebpackError) => void} BuildCallback */
  166. /** @typedef {KnownBuildMeta & Record<string, EXPECTED_ANY>} BuildMeta */
  167. /** @typedef {KnownBuildInfo & Record<string, EXPECTED_ANY>} BuildInfo */
  168. /**
  169. * @typedef {object} FactoryMeta
  170. * @property {boolean=} sideEffectFree
  171. */
  172. const EMPTY_RESOLVE_OPTIONS = {};
  173. let debugId = 1000;
  174. /** @type {SourceTypes} */
  175. const DEFAULT_TYPES_UNKNOWN = new Set([UNKNOWN_TYPE]);
  176. const deprecatedNeedRebuild = util.deprecate(
  177. /**
  178. * @param {Module} module the module
  179. * @param {NeedBuildContext} context context info
  180. * @returns {boolean} true, when rebuild is needed
  181. */
  182. (module, context) =>
  183. module.needRebuild(
  184. context.fileSystemInfo.getDeprecatedFileTimestamps(),
  185. context.fileSystemInfo.getDeprecatedContextTimestamps()
  186. ),
  187. "Module.needRebuild is deprecated in favor of Module.needBuild",
  188. "DEP_WEBPACK_MODULE_NEED_REBUILD"
  189. );
  190. /** @typedef {string} LibIdent */
  191. /** @typedef {string} NameForCondition */
  192. /** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */
  193. class Module extends DependenciesBlock {
  194. /**
  195. * @param {ModuleTypes | ""} type the module type, when deserializing the type is not known and is an empty string
  196. * @param {(string | null)=} context an optional context
  197. * @param {(string | null)=} layer an optional layer in which the module is
  198. */
  199. constructor(type, context = null, layer = null) {
  200. super();
  201. /** @type {ModuleTypes} */
  202. this.type = type;
  203. /** @type {string | null} */
  204. this.context = context;
  205. /** @type {string | null} */
  206. this.layer = layer;
  207. /** @type {boolean} */
  208. this.needId = true;
  209. // Unique Id
  210. /** @type {number} */
  211. this.debugId = debugId++;
  212. // Info from Factory
  213. /** @type {ResolveOptions | undefined} */
  214. this.resolveOptions = EMPTY_RESOLVE_OPTIONS;
  215. /** @type {FactoryMeta | undefined} */
  216. this.factoryMeta = undefined;
  217. // TODO refactor this -> options object filled from Factory
  218. // TODO webpack 6: use an enum
  219. /** @type {boolean} */
  220. this.useSourceMap = false;
  221. /** @type {boolean} */
  222. this.useSimpleSourceMap = false;
  223. // Is in hot context, i.e. HotModuleReplacementPlugin.js enabled
  224. // TODO do we need hot here?
  225. /** @type {boolean} */
  226. this.hot = false;
  227. // Info from Build
  228. /** @type {WebpackError[] | undefined} */
  229. this._warnings = undefined;
  230. /** @type {WebpackError[] | undefined} */
  231. this._errors = undefined;
  232. /** @type {BuildMeta | undefined} */
  233. this.buildMeta = undefined;
  234. /** @type {BuildInfo | undefined} */
  235. this.buildInfo = undefined;
  236. /** @type {Dependency[] | undefined} */
  237. this.presentationalDependencies = undefined;
  238. /** @type {Dependency[] | undefined} */
  239. this.codeGenerationDependencies = undefined;
  240. }
  241. // TODO remove in webpack 6
  242. // BACKWARD-COMPAT START
  243. /**
  244. * @returns {ModuleId | null} module id
  245. */
  246. get id() {
  247. return ChunkGraph.getChunkGraphForModule(
  248. this,
  249. "Module.id",
  250. "DEP_WEBPACK_MODULE_ID"
  251. ).getModuleId(this);
  252. }
  253. /**
  254. * @param {ModuleId} value value
  255. */
  256. set id(value) {
  257. if (value === "") {
  258. this.needId = false;
  259. return;
  260. }
  261. ChunkGraph.getChunkGraphForModule(
  262. this,
  263. "Module.id",
  264. "DEP_WEBPACK_MODULE_ID"
  265. ).setModuleId(this, value);
  266. }
  267. /**
  268. * @returns {string} the hash of the module
  269. */
  270. get hash() {
  271. return ChunkGraph.getChunkGraphForModule(
  272. this,
  273. "Module.hash",
  274. "DEP_WEBPACK_MODULE_HASH"
  275. ).getModuleHash(this, undefined);
  276. }
  277. /**
  278. * @returns {string} the shortened hash of the module
  279. */
  280. get renderedHash() {
  281. return ChunkGraph.getChunkGraphForModule(
  282. this,
  283. "Module.renderedHash",
  284. "DEP_WEBPACK_MODULE_RENDERED_HASH"
  285. ).getRenderedModuleHash(this, undefined);
  286. }
  287. get profile() {
  288. return ModuleGraph.getModuleGraphForModule(
  289. this,
  290. "Module.profile",
  291. "DEP_WEBPACK_MODULE_PROFILE"
  292. ).getProfile(this);
  293. }
  294. set profile(value) {
  295. ModuleGraph.getModuleGraphForModule(
  296. this,
  297. "Module.profile",
  298. "DEP_WEBPACK_MODULE_PROFILE"
  299. ).setProfile(this, value);
  300. }
  301. /**
  302. * @returns {number | null} the pre order index
  303. */
  304. get index() {
  305. return ModuleGraph.getModuleGraphForModule(
  306. this,
  307. "Module.index",
  308. "DEP_WEBPACK_MODULE_INDEX"
  309. ).getPreOrderIndex(this);
  310. }
  311. /**
  312. * @param {number} value the pre order index
  313. */
  314. set index(value) {
  315. ModuleGraph.getModuleGraphForModule(
  316. this,
  317. "Module.index",
  318. "DEP_WEBPACK_MODULE_INDEX"
  319. ).setPreOrderIndex(this, value);
  320. }
  321. /**
  322. * @returns {number | null} the post order index
  323. */
  324. get index2() {
  325. return ModuleGraph.getModuleGraphForModule(
  326. this,
  327. "Module.index2",
  328. "DEP_WEBPACK_MODULE_INDEX2"
  329. ).getPostOrderIndex(this);
  330. }
  331. /**
  332. * @param {number} value the post order index
  333. */
  334. set index2(value) {
  335. ModuleGraph.getModuleGraphForModule(
  336. this,
  337. "Module.index2",
  338. "DEP_WEBPACK_MODULE_INDEX2"
  339. ).setPostOrderIndex(this, value);
  340. }
  341. /**
  342. * @returns {number | null} the depth
  343. */
  344. get depth() {
  345. return ModuleGraph.getModuleGraphForModule(
  346. this,
  347. "Module.depth",
  348. "DEP_WEBPACK_MODULE_DEPTH"
  349. ).getDepth(this);
  350. }
  351. /**
  352. * @param {number} value the depth
  353. */
  354. set depth(value) {
  355. ModuleGraph.getModuleGraphForModule(
  356. this,
  357. "Module.depth",
  358. "DEP_WEBPACK_MODULE_DEPTH"
  359. ).setDepth(this, value);
  360. }
  361. /**
  362. * @returns {Module | null | undefined} issuer
  363. */
  364. get issuer() {
  365. return ModuleGraph.getModuleGraphForModule(
  366. this,
  367. "Module.issuer",
  368. "DEP_WEBPACK_MODULE_ISSUER"
  369. ).getIssuer(this);
  370. }
  371. /**
  372. * @param {Module | null} value issuer
  373. */
  374. set issuer(value) {
  375. ModuleGraph.getModuleGraphForModule(
  376. this,
  377. "Module.issuer",
  378. "DEP_WEBPACK_MODULE_ISSUER"
  379. ).setIssuer(this, value);
  380. }
  381. get usedExports() {
  382. return ModuleGraph.getModuleGraphForModule(
  383. this,
  384. "Module.usedExports",
  385. "DEP_WEBPACK_MODULE_USED_EXPORTS"
  386. ).getUsedExports(this, undefined);
  387. }
  388. /**
  389. * @deprecated
  390. * @returns {OptimizationBailouts} list
  391. */
  392. get optimizationBailout() {
  393. return ModuleGraph.getModuleGraphForModule(
  394. this,
  395. "Module.optimizationBailout",
  396. "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT"
  397. ).getOptimizationBailout(this);
  398. }
  399. get optional() {
  400. return this.isOptional(
  401. ModuleGraph.getModuleGraphForModule(
  402. this,
  403. "Module.optional",
  404. "DEP_WEBPACK_MODULE_OPTIONAL"
  405. )
  406. );
  407. }
  408. /**
  409. * @param {Chunk} chunk the chunk
  410. * @returns {boolean} true, when the module was added
  411. */
  412. addChunk(chunk) {
  413. const chunkGraph = ChunkGraph.getChunkGraphForModule(
  414. this,
  415. "Module.addChunk",
  416. "DEP_WEBPACK_MODULE_ADD_CHUNK"
  417. );
  418. if (chunkGraph.isModuleInChunk(this, chunk)) return false;
  419. chunkGraph.connectChunkAndModule(chunk, this);
  420. return true;
  421. }
  422. /**
  423. * @param {Chunk} chunk the chunk
  424. * @returns {void}
  425. */
  426. removeChunk(chunk) {
  427. return ChunkGraph.getChunkGraphForModule(
  428. this,
  429. "Module.removeChunk",
  430. "DEP_WEBPACK_MODULE_REMOVE_CHUNK"
  431. ).disconnectChunkAndModule(chunk, this);
  432. }
  433. /**
  434. * @param {Chunk} chunk the chunk
  435. * @returns {boolean} true, when the module is in the chunk
  436. */
  437. isInChunk(chunk) {
  438. return ChunkGraph.getChunkGraphForModule(
  439. this,
  440. "Module.isInChunk",
  441. "DEP_WEBPACK_MODULE_IS_IN_CHUNK"
  442. ).isModuleInChunk(this, chunk);
  443. }
  444. isEntryModule() {
  445. return ChunkGraph.getChunkGraphForModule(
  446. this,
  447. "Module.isEntryModule",
  448. "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE"
  449. ).isEntryModule(this);
  450. }
  451. getChunks() {
  452. return ChunkGraph.getChunkGraphForModule(
  453. this,
  454. "Module.getChunks",
  455. "DEP_WEBPACK_MODULE_GET_CHUNKS"
  456. ).getModuleChunks(this);
  457. }
  458. getNumberOfChunks() {
  459. return ChunkGraph.getChunkGraphForModule(
  460. this,
  461. "Module.getNumberOfChunks",
  462. "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS"
  463. ).getNumberOfModuleChunks(this);
  464. }
  465. get chunksIterable() {
  466. return ChunkGraph.getChunkGraphForModule(
  467. this,
  468. "Module.chunksIterable",
  469. "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE"
  470. ).getOrderedModuleChunksIterable(this, compareChunksById);
  471. }
  472. /**
  473. * @param {string} exportName a name of an export
  474. * @returns {boolean | null} true, if the export is provided why the module.
  475. * null, if it's unknown.
  476. * false, if it's not provided.
  477. */
  478. isProvided(exportName) {
  479. return ModuleGraph.getModuleGraphForModule(
  480. this,
  481. "Module.usedExports",
  482. "DEP_WEBPACK_MODULE_USED_EXPORTS"
  483. ).isExportProvided(this, exportName);
  484. }
  485. // BACKWARD-COMPAT END
  486. /**
  487. * @returns {string} name of the exports argument
  488. */
  489. get exportsArgument() {
  490. return (this.buildInfo && this.buildInfo.exportsArgument) || "exports";
  491. }
  492. /**
  493. * @returns {string} name of the module argument
  494. */
  495. get moduleArgument() {
  496. return (this.buildInfo && this.buildInfo.moduleArgument) || "module";
  497. }
  498. /**
  499. * @param {ModuleGraph} moduleGraph the module graph
  500. * @param {boolean | undefined} strict the importing module is strict
  501. * @returns {ExportsType} export type
  502. * "namespace": Exports is already a namespace object. namespace = exports.
  503. * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }.
  504. * "default-only": Provide a namespace object with only default export. namespace = { default: exports }
  505. * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports }
  506. */
  507. getExportsType(moduleGraph, strict) {
  508. switch (this.buildMeta && this.buildMeta.exportsType) {
  509. case "flagged":
  510. return strict ? "default-with-named" : "namespace";
  511. case "namespace":
  512. return "namespace";
  513. case "default":
  514. switch (/** @type {BuildMeta} */ (this.buildMeta).defaultObject) {
  515. case "redirect":
  516. return "default-with-named";
  517. case "redirect-warn":
  518. return strict ? "default-only" : "default-with-named";
  519. default:
  520. return "default-only";
  521. }
  522. case "dynamic": {
  523. if (strict) return "default-with-named";
  524. // Try to figure out value of __esModule by following reexports
  525. const handleDefault = () => {
  526. switch (/** @type {BuildMeta} */ (this.buildMeta).defaultObject) {
  527. case "redirect":
  528. case "redirect-warn":
  529. return "default-with-named";
  530. default:
  531. return "default-only";
  532. }
  533. };
  534. const exportInfo = moduleGraph.getReadOnlyExportInfo(
  535. this,
  536. "__esModule"
  537. );
  538. if (exportInfo.provided === false) {
  539. return handleDefault();
  540. }
  541. const target = exportInfo.getTarget(moduleGraph);
  542. if (
  543. !target ||
  544. !target.export ||
  545. target.export.length !== 1 ||
  546. target.export[0] !== "__esModule"
  547. ) {
  548. return "dynamic";
  549. }
  550. switch (
  551. target.module.buildMeta &&
  552. target.module.buildMeta.exportsType
  553. ) {
  554. case "flagged":
  555. case "namespace":
  556. return "namespace";
  557. case "default":
  558. return handleDefault();
  559. default:
  560. return "dynamic";
  561. }
  562. }
  563. default:
  564. return strict ? "default-with-named" : "dynamic";
  565. }
  566. }
  567. /**
  568. * @param {Dependency} presentationalDependency dependency being tied to module.
  569. * This is a Dependency without edge in the module graph. It's only for presentation.
  570. * @returns {void}
  571. */
  572. addPresentationalDependency(presentationalDependency) {
  573. if (this.presentationalDependencies === undefined) {
  574. this.presentationalDependencies = [];
  575. }
  576. this.presentationalDependencies.push(presentationalDependency);
  577. }
  578. /**
  579. * @param {Dependency} codeGenerationDependency dependency being tied to module.
  580. * This is a Dependency where the code generation result of the referenced module is needed during code generation.
  581. * The Dependency should also be added to normal dependencies via addDependency.
  582. * @returns {void}
  583. */
  584. addCodeGenerationDependency(codeGenerationDependency) {
  585. if (this.codeGenerationDependencies === undefined) {
  586. this.codeGenerationDependencies = [];
  587. }
  588. this.codeGenerationDependencies.push(codeGenerationDependency);
  589. }
  590. /**
  591. * Removes all dependencies and blocks
  592. * @returns {void}
  593. */
  594. clearDependenciesAndBlocks() {
  595. if (this.presentationalDependencies !== undefined) {
  596. this.presentationalDependencies.length = 0;
  597. }
  598. if (this.codeGenerationDependencies !== undefined) {
  599. this.codeGenerationDependencies.length = 0;
  600. }
  601. super.clearDependenciesAndBlocks();
  602. }
  603. /**
  604. * @param {WebpackError} warning the warning
  605. * @returns {void}
  606. */
  607. addWarning(warning) {
  608. if (this._warnings === undefined) {
  609. this._warnings = [];
  610. }
  611. this._warnings.push(warning);
  612. }
  613. /**
  614. * @returns {Iterable<WebpackError> | undefined} list of warnings if any
  615. */
  616. getWarnings() {
  617. return this._warnings;
  618. }
  619. /**
  620. * @returns {number} number of warnings
  621. */
  622. getNumberOfWarnings() {
  623. return this._warnings !== undefined ? this._warnings.length : 0;
  624. }
  625. /**
  626. * @param {WebpackError} error the error
  627. * @returns {void}
  628. */
  629. addError(error) {
  630. if (this._errors === undefined) {
  631. this._errors = [];
  632. }
  633. this._errors.push(error);
  634. }
  635. /**
  636. * @returns {Iterable<WebpackError> | undefined} list of errors if any
  637. */
  638. getErrors() {
  639. return this._errors;
  640. }
  641. /**
  642. * @returns {number} number of errors
  643. */
  644. getNumberOfErrors() {
  645. return this._errors !== undefined ? this._errors.length : 0;
  646. }
  647. /**
  648. * removes all warnings and errors
  649. * @returns {void}
  650. */
  651. clearWarningsAndErrors() {
  652. if (this._warnings !== undefined) {
  653. this._warnings.length = 0;
  654. }
  655. if (this._errors !== undefined) {
  656. this._errors.length = 0;
  657. }
  658. }
  659. /**
  660. * @param {ModuleGraph} moduleGraph the module graph
  661. * @returns {boolean} true, if the module is optional
  662. */
  663. isOptional(moduleGraph) {
  664. let hasConnections = false;
  665. for (const r of moduleGraph.getIncomingConnections(this)) {
  666. if (
  667. !r.dependency ||
  668. !r.dependency.optional ||
  669. !r.isTargetActive(undefined)
  670. ) {
  671. return false;
  672. }
  673. hasConnections = true;
  674. }
  675. return hasConnections;
  676. }
  677. /**
  678. * @param {ChunkGraph} chunkGraph the chunk graph
  679. * @param {Chunk} chunk a chunk
  680. * @param {Chunk=} ignoreChunk chunk to be ignored
  681. * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk"
  682. */
  683. isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) {
  684. // Check if module is accessible in ALL chunk groups
  685. for (const chunkGroup of chunk.groupsIterable) {
  686. if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false;
  687. }
  688. return true;
  689. }
  690. /**
  691. * @param {ChunkGraph} chunkGraph the chunk graph
  692. * @param {ChunkGroup} chunkGroup a chunk group
  693. * @param {Chunk=} ignoreChunk chunk to be ignored
  694. * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk"
  695. */
  696. isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) {
  697. const queue = new Set([chunkGroup]);
  698. // Check if module is accessible from all items of the queue
  699. queueFor: for (const cg of queue) {
  700. // 1. If module is in one of the chunks of the group we can continue checking the next items
  701. // because it's accessible.
  702. for (const chunk of cg.chunks) {
  703. if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) {
  704. continue queueFor;
  705. }
  706. }
  707. // 2. If the chunk group is initial, we can break here because it's not accessible.
  708. if (chunkGroup.isInitial()) return false;
  709. // 3. Enqueue all parents because it must be accessible from ALL parents
  710. for (const parent of chunkGroup.parentsIterable) queue.add(parent);
  711. }
  712. // When we processed through the whole list and we didn't bailout, the module is accessible
  713. return true;
  714. }
  715. /**
  716. * @param {Chunk} chunk a chunk
  717. * @param {ModuleGraph} moduleGraph the module graph
  718. * @param {ChunkGraph} chunkGraph the chunk graph
  719. * @returns {boolean} true, if the module has any reason why "chunk" should be included
  720. */
  721. hasReasonForChunk(chunk, moduleGraph, chunkGraph) {
  722. // check for each reason if we need the chunk
  723. for (const [
  724. fromModule,
  725. connections
  726. ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) {
  727. if (!connections.some((c) => c.isTargetActive(chunk.runtime))) continue;
  728. for (const originChunk of chunkGraph.getModuleChunksIterable(
  729. /** @type {Module} */ (fromModule)
  730. )) {
  731. // return true if module this is not reachable from originChunk when ignoring chunk
  732. if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) {
  733. return true;
  734. }
  735. }
  736. }
  737. return false;
  738. }
  739. /**
  740. * @param {ModuleGraph} moduleGraph the module graph
  741. * @param {RuntimeSpec} runtime the runtime
  742. * @returns {boolean} true if at least one other module depends on this module
  743. */
  744. hasReasons(moduleGraph, runtime) {
  745. for (const c of moduleGraph.getIncomingConnections(this)) {
  746. if (c.isTargetActive(runtime)) return true;
  747. }
  748. return false;
  749. }
  750. /**
  751. * @returns {string} for debugging
  752. */
  753. toString() {
  754. return `Module[${this.debugId}: ${this.identifier()}]`;
  755. }
  756. /**
  757. * @param {NeedBuildContext} context context info
  758. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  759. * @returns {void}
  760. */
  761. needBuild(context, callback) {
  762. callback(
  763. null,
  764. !this.buildMeta ||
  765. this.needRebuild === Module.prototype.needRebuild ||
  766. deprecatedNeedRebuild(this, context)
  767. );
  768. }
  769. /**
  770. * @deprecated Use needBuild instead
  771. * @param {Map<string, number | null>} fileTimestamps timestamps of files
  772. * @param {Map<string, number | null>} contextTimestamps timestamps of directories
  773. * @returns {boolean} true, if the module needs a rebuild
  774. */
  775. needRebuild(fileTimestamps, contextTimestamps) {
  776. return true;
  777. }
  778. /**
  779. * @param {Hash} hash the hash used to track dependencies
  780. * @param {UpdateHashContext} context context
  781. * @returns {void}
  782. */
  783. updateHash(
  784. hash,
  785. context = {
  786. chunkGraph: ChunkGraph.getChunkGraphForModule(
  787. this,
  788. "Module.updateHash",
  789. "DEP_WEBPACK_MODULE_UPDATE_HASH"
  790. ),
  791. runtime: undefined
  792. }
  793. ) {
  794. const { chunkGraph, runtime } = context;
  795. hash.update(chunkGraph.getModuleGraphHash(this, runtime));
  796. if (this.presentationalDependencies !== undefined) {
  797. for (const dep of this.presentationalDependencies) {
  798. dep.updateHash(hash, context);
  799. }
  800. }
  801. super.updateHash(hash, context);
  802. }
  803. /**
  804. * @returns {void}
  805. */
  806. invalidateBuild() {
  807. // should be overridden to support this feature
  808. }
  809. /* istanbul ignore next */
  810. /**
  811. * @abstract
  812. * @returns {string} a unique identifier of the module
  813. */
  814. identifier() {
  815. const AbstractMethodError = require("./AbstractMethodError");
  816. throw new AbstractMethodError();
  817. }
  818. /* istanbul ignore next */
  819. /**
  820. * @abstract
  821. * @param {RequestShortener} requestShortener the request shortener
  822. * @returns {string} a user readable identifier of the module
  823. */
  824. readableIdentifier(requestShortener) {
  825. const AbstractMethodError = require("./AbstractMethodError");
  826. throw new AbstractMethodError();
  827. }
  828. /* istanbul ignore next */
  829. /**
  830. * @abstract
  831. * @param {WebpackOptions} options webpack options
  832. * @param {Compilation} compilation the compilation
  833. * @param {ResolverWithOptions} resolver the resolver
  834. * @param {InputFileSystem} fs the file system
  835. * @param {BuildCallback} callback callback function
  836. * @returns {void}
  837. */
  838. build(options, compilation, resolver, fs, callback) {
  839. const AbstractMethodError = require("./AbstractMethodError");
  840. throw new AbstractMethodError();
  841. }
  842. /**
  843. * @abstract
  844. * @returns {SourceTypes} types available (do not mutate)
  845. */
  846. getSourceTypes() {
  847. // Better override this method to return the correct types
  848. if (this.source === Module.prototype.source) {
  849. return DEFAULT_TYPES_UNKNOWN;
  850. }
  851. return JAVASCRIPT_TYPES;
  852. }
  853. /**
  854. * @abstract
  855. * @deprecated Use codeGeneration() instead
  856. * @param {DependencyTemplates} dependencyTemplates the dependency templates
  857. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  858. * @param {SourceType=} type the type of source that should be generated
  859. * @returns {Source} generated source
  860. */
  861. source(dependencyTemplates, runtimeTemplate, type = JAVASCRIPT_TYPE) {
  862. if (this.codeGeneration === Module.prototype.codeGeneration) {
  863. const AbstractMethodError = require("./AbstractMethodError");
  864. throw new AbstractMethodError();
  865. }
  866. const chunkGraph = ChunkGraph.getChunkGraphForModule(
  867. this,
  868. "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead",
  869. "DEP_WEBPACK_MODULE_SOURCE"
  870. );
  871. /** @type {CodeGenerationContext} */
  872. const codeGenContext = {
  873. dependencyTemplates,
  874. runtimeTemplate,
  875. moduleGraph: chunkGraph.moduleGraph,
  876. chunkGraph,
  877. runtime: undefined,
  878. runtimes: [],
  879. codeGenerationResults: undefined
  880. };
  881. const sources = this.codeGeneration(codeGenContext).sources;
  882. return /** @type {Source} */ (
  883. type
  884. ? sources.get(type)
  885. : sources.get(/** @type {SourceType} */ (first(this.getSourceTypes())))
  886. );
  887. }
  888. /* istanbul ignore next */
  889. /**
  890. * @abstract
  891. * @param {string=} type the source type for which the size should be estimated
  892. * @returns {number} the estimated size of the module (must be non-zero)
  893. */
  894. size(type) {
  895. const AbstractMethodError = require("./AbstractMethodError");
  896. throw new AbstractMethodError();
  897. }
  898. /**
  899. * @param {LibIdentOptions} options options
  900. * @returns {LibIdent | null} an identifier for library inclusion
  901. */
  902. libIdent(options) {
  903. return null;
  904. }
  905. /**
  906. * @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
  907. */
  908. nameForCondition() {
  909. return null;
  910. }
  911. /**
  912. * @param {ConcatenationBailoutReasonContext} context context
  913. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  914. */
  915. getConcatenationBailoutReason(context) {
  916. return `Module Concatenation is not implemented for ${this.constructor.name}`;
  917. }
  918. /**
  919. * @param {ModuleGraph} moduleGraph the module graph
  920. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  921. */
  922. getSideEffectsConnectionState(moduleGraph) {
  923. return true;
  924. }
  925. /**
  926. * @param {CodeGenerationContext} context context for code generation
  927. * @returns {CodeGenerationResult} result
  928. */
  929. codeGeneration(context) {
  930. // Best override this method
  931. const sources = new Map();
  932. for (const type of this.getSourceTypes()) {
  933. if (type !== UNKNOWN_TYPE) {
  934. sources.set(
  935. type,
  936. this.source(
  937. context.dependencyTemplates,
  938. context.runtimeTemplate,
  939. type
  940. )
  941. );
  942. }
  943. }
  944. return {
  945. sources,
  946. runtimeRequirements: new Set([
  947. RuntimeGlobals.module,
  948. RuntimeGlobals.exports,
  949. RuntimeGlobals.require
  950. ])
  951. };
  952. }
  953. /**
  954. * @param {Chunk} chunk the chunk which condition should be checked
  955. * @param {Compilation} compilation the compilation
  956. * @returns {boolean} true, if the chunk is ok for the module
  957. */
  958. chunkCondition(chunk, compilation) {
  959. return true;
  960. }
  961. hasChunkCondition() {
  962. return this.chunkCondition !== Module.prototype.chunkCondition;
  963. }
  964. /**
  965. * Assuming this module is in the cache. Update the (cached) module with
  966. * the fresh module from the factory. Usually updates internal references
  967. * and properties.
  968. * @param {Module} module fresh module
  969. * @returns {void}
  970. */
  971. updateCacheModule(module) {
  972. this.type = module.type;
  973. this.layer = module.layer;
  974. this.context = module.context;
  975. this.factoryMeta = module.factoryMeta;
  976. this.resolveOptions = module.resolveOptions;
  977. }
  978. /**
  979. * Module should be unsafe cached. Get data that's needed for that.
  980. * This data will be passed to restoreFromUnsafeCache later.
  981. * @returns {UnsafeCacheData} cached data
  982. */
  983. getUnsafeCacheData() {
  984. return {
  985. factoryMeta: this.factoryMeta,
  986. resolveOptions: this.resolveOptions
  987. };
  988. }
  989. /**
  990. * restore unsafe cache data
  991. * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData
  992. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  993. */
  994. _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  995. this.factoryMeta = unsafeCacheData.factoryMeta;
  996. this.resolveOptions = unsafeCacheData.resolveOptions;
  997. }
  998. /**
  999. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  1000. */
  1001. cleanupForCache() {
  1002. this.factoryMeta = undefined;
  1003. this.resolveOptions = undefined;
  1004. }
  1005. /**
  1006. * @returns {Source | null} the original source for the module before webpack transformation
  1007. */
  1008. originalSource() {
  1009. return null;
  1010. }
  1011. /**
  1012. * @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
  1013. * @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
  1014. * @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
  1015. * @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
  1016. */
  1017. addCacheDependencies(
  1018. fileDependencies,
  1019. contextDependencies,
  1020. missingDependencies,
  1021. buildDependencies
  1022. ) {}
  1023. /**
  1024. * @param {ObjectSerializerContext} context context
  1025. */
  1026. serialize(context) {
  1027. const { write } = context;
  1028. write(this.type);
  1029. write(this.layer);
  1030. write(this.context);
  1031. write(this.resolveOptions);
  1032. write(this.factoryMeta);
  1033. write(this.useSourceMap);
  1034. write(this.useSimpleSourceMap);
  1035. write(this.hot);
  1036. write(
  1037. this._warnings !== undefined && this._warnings.length === 0
  1038. ? undefined
  1039. : this._warnings
  1040. );
  1041. write(
  1042. this._errors !== undefined && this._errors.length === 0
  1043. ? undefined
  1044. : this._errors
  1045. );
  1046. write(this.buildMeta);
  1047. write(this.buildInfo);
  1048. write(this.presentationalDependencies);
  1049. write(this.codeGenerationDependencies);
  1050. super.serialize(context);
  1051. }
  1052. /**
  1053. * @param {ObjectDeserializerContext} context context
  1054. */
  1055. deserialize(context) {
  1056. const { read } = context;
  1057. this.type = read();
  1058. this.layer = read();
  1059. this.context = read();
  1060. this.resolveOptions = read();
  1061. this.factoryMeta = read();
  1062. this.useSourceMap = read();
  1063. this.useSimpleSourceMap = read();
  1064. this.hot = read();
  1065. this._warnings = read();
  1066. this._errors = read();
  1067. this.buildMeta = read();
  1068. this.buildInfo = read();
  1069. this.presentationalDependencies = read();
  1070. this.codeGenerationDependencies = read();
  1071. super.deserialize(context);
  1072. }
  1073. }
  1074. makeSerializable(Module, "webpack/lib/Module");
  1075. // TODO remove in webpack 6
  1076. Object.defineProperty(Module.prototype, "hasEqualsChunks", {
  1077. /**
  1078. * @deprecated
  1079. * @returns {EXPECTED_ANY} throw an error
  1080. */
  1081. get() {
  1082. throw new Error(
  1083. "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)"
  1084. );
  1085. }
  1086. });
  1087. // TODO remove in webpack 6
  1088. Object.defineProperty(Module.prototype, "isUsed", {
  1089. /**
  1090. * @deprecated
  1091. * @returns {EXPECTED_ANY} throw an error
  1092. */
  1093. get() {
  1094. throw new Error(
  1095. "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)"
  1096. );
  1097. }
  1098. });
  1099. // TODO remove in webpack 6
  1100. Object.defineProperty(Module.prototype, "errors", {
  1101. /**
  1102. * @deprecated
  1103. * @returns {WebpackError[]} errors
  1104. */
  1105. get: util.deprecate(
  1106. /**
  1107. * @this {Module}
  1108. * @returns {WebpackError[]} errors
  1109. */
  1110. function errors() {
  1111. if (this._errors === undefined) {
  1112. this._errors = [];
  1113. }
  1114. return this._errors;
  1115. },
  1116. "Module.errors was removed (use getErrors instead)",
  1117. "DEP_WEBPACK_MODULE_ERRORS"
  1118. )
  1119. });
  1120. // TODO remove in webpack 6
  1121. Object.defineProperty(Module.prototype, "warnings", {
  1122. /**
  1123. * @deprecated
  1124. * @returns {WebpackError[]} warnings
  1125. */
  1126. get: util.deprecate(
  1127. /**
  1128. * @this {Module}
  1129. * @returns {WebpackError[]} warnings
  1130. */
  1131. function warnings() {
  1132. if (this._warnings === undefined) {
  1133. this._warnings = [];
  1134. }
  1135. return this._warnings;
  1136. },
  1137. "Module.warnings was removed (use getWarnings instead)",
  1138. "DEP_WEBPACK_MODULE_WARNINGS"
  1139. )
  1140. });
  1141. // TODO remove in webpack 6
  1142. Object.defineProperty(Module.prototype, "used", {
  1143. /**
  1144. * @deprecated
  1145. * @returns {EXPECTED_ANY} throw an error
  1146. */
  1147. get() {
  1148. throw new Error(
  1149. "Module.used was refactored (use ModuleGraph.getUsedExports instead)"
  1150. );
  1151. },
  1152. /**
  1153. * @param {EXPECTED_ANY} value value
  1154. */
  1155. set(value) {
  1156. throw new Error(
  1157. "Module.used was refactored (use ModuleGraph.setUsedExports instead)"
  1158. );
  1159. }
  1160. });
  1161. module.exports = Module;