NormalModule.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const parseJson = require("json-parse-even-better-errors");
  7. const { getContext, runLoaders } = require("loader-runner");
  8. const querystring = require("querystring");
  9. const { HookMap, SyncHook, AsyncSeriesBailHook } = require("tapable");
  10. const {
  11. CachedSource,
  12. OriginalSource,
  13. RawSource,
  14. SourceMapSource
  15. } = require("webpack-sources");
  16. const Compilation = require("./Compilation");
  17. const HookWebpackError = require("./HookWebpackError");
  18. const Module = require("./Module");
  19. const ModuleBuildError = require("./ModuleBuildError");
  20. const ModuleError = require("./ModuleError");
  21. const ModuleGraphConnection = require("./ModuleGraphConnection");
  22. const ModuleParseError = require("./ModuleParseError");
  23. const { JAVASCRIPT_MODULE_TYPE_AUTO } = require("./ModuleTypeConstants");
  24. const ModuleWarning = require("./ModuleWarning");
  25. const RuntimeGlobals = require("./RuntimeGlobals");
  26. const UnhandledSchemeError = require("./UnhandledSchemeError");
  27. const WebpackError = require("./WebpackError");
  28. const formatLocation = require("./formatLocation");
  29. const LazySet = require("./util/LazySet");
  30. const { isSubset } = require("./util/SetHelpers");
  31. const { getScheme } = require("./util/URLAbsoluteSpecifier");
  32. const {
  33. compareLocations,
  34. concatComparators,
  35. compareSelect,
  36. keepOriginalOrder
  37. } = require("./util/comparators");
  38. const createHash = require("./util/createHash");
  39. const { createFakeHook } = require("./util/deprecation");
  40. const { join } = require("./util/fs");
  41. const {
  42. contextify,
  43. absolutify,
  44. makePathsRelative
  45. } = require("./util/identifier");
  46. const makeSerializable = require("./util/makeSerializable");
  47. const memoize = require("./util/memoize");
  48. /** @typedef {import("webpack-sources").Source} Source */
  49. /** @typedef {import("../declarations/WebpackOptions").Mode} Mode */
  50. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  51. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  52. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  53. /** @typedef {import("./Compiler")} Compiler */
  54. /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
  55. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  56. /** @typedef {import("./Generator")} Generator */
  57. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  58. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  59. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  60. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  61. /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
  62. /** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */
  63. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  64. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  65. /** @typedef {import("./Module").SourceTypes} SourceTypes */
  66. /** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */
  67. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  68. /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
  69. /** @typedef {import("./ModuleTypeConstants").JavaScriptModuleTypes} JavaScriptModuleTypes */
  70. /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
  71. /** @typedef {import("./Parser")} Parser */
  72. /** @typedef {import("./RequestShortener")} RequestShortener */
  73. /** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */
  74. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  75. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  76. /** @typedef {import("./logging/Logger").Logger} WebpackLogger */
  77. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  78. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  79. /** @typedef {import("./util/Hash")} Hash */
  80. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  81. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  82. /** @typedef {{[k: string]: any}} ParserOptions */
  83. /** @typedef {{[k: string]: any}} GeneratorOptions */
  84. /** @typedef {UnsafeCacheData & { parser: undefined | Parser, parserOptions: undefined | ParserOptions, generator: undefined | Generator, generatorOptions: undefined | GeneratorOptions }} NormalModuleUnsafeCacheData */
  85. /**
  86. * @typedef {Object} SourceMap
  87. * @property {number} version
  88. * @property {string[]} sources
  89. * @property {string} mappings
  90. * @property {string=} file
  91. * @property {string=} sourceRoot
  92. * @property {string[]=} sourcesContent
  93. * @property {string[]=} names
  94. */
  95. const getInvalidDependenciesModuleWarning = memoize(() =>
  96. require("./InvalidDependenciesModuleWarning")
  97. );
  98. const getValidate = memoize(() => require("schema-utils").validate);
  99. const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
  100. /**
  101. * @typedef {Object} LoaderItem
  102. * @property {string} loader
  103. * @property {any} options
  104. * @property {string?} ident
  105. * @property {string?} type
  106. */
  107. /**
  108. * @param {string} context absolute context path
  109. * @param {string} source a source path
  110. * @param {Object=} associatedObjectForCache an object to which the cache will be attached
  111. * @returns {string} new source path
  112. */
  113. const contextifySourceUrl = (context, source, associatedObjectForCache) => {
  114. if (source.startsWith("webpack://")) return source;
  115. return `webpack://${makePathsRelative(
  116. context,
  117. source,
  118. associatedObjectForCache
  119. )}`;
  120. };
  121. /**
  122. * @param {string} context absolute context path
  123. * @param {SourceMap} sourceMap a source map
  124. * @param {Object=} associatedObjectForCache an object to which the cache will be attached
  125. * @returns {SourceMap} new source map
  126. */
  127. const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
  128. if (!Array.isArray(sourceMap.sources)) return sourceMap;
  129. const { sourceRoot } = sourceMap;
  130. /** @type {function(string): string} */
  131. const mapper = !sourceRoot
  132. ? source => source
  133. : sourceRoot.endsWith("/")
  134. ? source =>
  135. source.startsWith("/")
  136. ? `${sourceRoot.slice(0, -1)}${source}`
  137. : `${sourceRoot}${source}`
  138. : source =>
  139. source.startsWith("/")
  140. ? `${sourceRoot}${source}`
  141. : `${sourceRoot}/${source}`;
  142. const newSources = sourceMap.sources.map(source =>
  143. contextifySourceUrl(context, mapper(source), associatedObjectForCache)
  144. );
  145. return {
  146. ...sourceMap,
  147. file: "x",
  148. sourceRoot: undefined,
  149. sources: newSources
  150. };
  151. };
  152. /**
  153. * @param {string | Buffer} input the input
  154. * @returns {string} the converted string
  155. */
  156. const asString = input => {
  157. if (Buffer.isBuffer(input)) {
  158. return input.toString("utf-8");
  159. }
  160. return input;
  161. };
  162. /**
  163. * @param {string | Buffer} input the input
  164. * @returns {Buffer} the converted buffer
  165. */
  166. const asBuffer = input => {
  167. if (!Buffer.isBuffer(input)) {
  168. return Buffer.from(input, "utf-8");
  169. }
  170. return input;
  171. };
  172. class NonErrorEmittedError extends WebpackError {
  173. constructor(error) {
  174. super();
  175. this.name = "NonErrorEmittedError";
  176. this.message = "(Emitted value instead of an instance of Error) " + error;
  177. }
  178. }
  179. makeSerializable(
  180. NonErrorEmittedError,
  181. "webpack/lib/NormalModule",
  182. "NonErrorEmittedError"
  183. );
  184. /**
  185. * @typedef {Object} NormalModuleCompilationHooks
  186. * @property {SyncHook<[object, NormalModule]>} loader
  187. * @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders
  188. * @property {SyncHook<[NormalModule]>} beforeParse
  189. * @property {SyncHook<[NormalModule]>} beforeSnapshot
  190. * @property {HookMap<AsyncSeriesBailHook<[string, NormalModule], string | Buffer>>} readResourceForScheme
  191. * @property {HookMap<AsyncSeriesBailHook<[object], string | Buffer>>} readResource
  192. * @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
  193. */
  194. /**
  195. * @typedef {Object} NormalModuleCreateData
  196. * @property {string=} layer an optional layer in which the module is
  197. * @property {JavaScriptModuleTypes | ""} type module type. When deserializing, this is set to an empty string "".
  198. * @property {string} request request string
  199. * @property {string} userRequest request intended by user (without loaders from config)
  200. * @property {string} rawRequest request without resolving
  201. * @property {LoaderItem[]} loaders list of loaders
  202. * @property {string} resource path + query of the real resource
  203. * @property {Record<string, any>=} resourceResolveData resource resolve data
  204. * @property {string} context context directory for resolving
  205. * @property {string=} matchResource path + query of the matched resource (virtual)
  206. * @property {Parser} parser the parser used
  207. * @property {ParserOptions=} parserOptions the options of the parser used
  208. * @property {Generator} generator the generator used
  209. * @property {GeneratorOptions=} generatorOptions the options of the generator used
  210. * @property {ResolveOptions=} resolveOptions options used for resolving requests from this module
  211. */
  212. /** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
  213. const compilationHooksMap = new WeakMap();
  214. class NormalModule extends Module {
  215. /**
  216. * @param {Compilation} compilation the compilation
  217. * @returns {NormalModuleCompilationHooks} the attached hooks
  218. */
  219. static getCompilationHooks(compilation) {
  220. if (!(compilation instanceof Compilation)) {
  221. throw new TypeError(
  222. "The 'compilation' argument must be an instance of Compilation"
  223. );
  224. }
  225. let hooks = compilationHooksMap.get(compilation);
  226. if (hooks === undefined) {
  227. hooks = {
  228. loader: new SyncHook(["loaderContext", "module"]),
  229. beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]),
  230. beforeParse: new SyncHook(["module"]),
  231. beforeSnapshot: new SyncHook(["module"]),
  232. // TODO webpack 6 deprecate
  233. readResourceForScheme: new HookMap(scheme => {
  234. const hook = hooks.readResource.for(scheme);
  235. return createFakeHook(
  236. /** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({
  237. tap: (options, fn) =>
  238. hook.tap(options, loaderContext =>
  239. fn(loaderContext.resource, loaderContext._module)
  240. ),
  241. tapAsync: (options, fn) =>
  242. hook.tapAsync(options, (loaderContext, callback) =>
  243. fn(loaderContext.resource, loaderContext._module, callback)
  244. ),
  245. tapPromise: (options, fn) =>
  246. hook.tapPromise(options, loaderContext =>
  247. fn(loaderContext.resource, loaderContext._module)
  248. )
  249. })
  250. );
  251. }),
  252. readResource: new HookMap(
  253. () => new AsyncSeriesBailHook(["loaderContext"])
  254. ),
  255. needBuild: new AsyncSeriesBailHook(["module", "context"])
  256. };
  257. compilationHooksMap.set(
  258. compilation,
  259. /** @type {NormalModuleCompilationHooks} */ (hooks)
  260. );
  261. }
  262. return /** @type {NormalModuleCompilationHooks} */ (hooks);
  263. }
  264. /**
  265. * @param {NormalModuleCreateData} options options object
  266. */
  267. constructor({
  268. layer,
  269. type,
  270. request,
  271. userRequest,
  272. rawRequest,
  273. loaders,
  274. resource,
  275. resourceResolveData,
  276. context,
  277. matchResource,
  278. parser,
  279. parserOptions,
  280. generator,
  281. generatorOptions,
  282. resolveOptions
  283. }) {
  284. super(type, context || getContext(resource), layer);
  285. // Info from Factory
  286. /** @type {string} */
  287. this.request = request;
  288. /** @type {string} */
  289. this.userRequest = userRequest;
  290. /** @type {string} */
  291. this.rawRequest = rawRequest;
  292. /** @type {boolean} */
  293. this.binary = /^(asset|webassembly)\b/.test(type);
  294. /** @type {undefined | Parser} */
  295. this.parser = parser;
  296. /** @type {undefined | ParserOptions} */
  297. this.parserOptions = parserOptions;
  298. /** @type {undefined | Generator} */
  299. this.generator = generator;
  300. /** @type {undefined | GeneratorOptions} */
  301. this.generatorOptions = generatorOptions;
  302. /** @type {string} */
  303. this.resource = resource;
  304. this.resourceResolveData = resourceResolveData;
  305. /** @type {string | undefined} */
  306. this.matchResource = matchResource;
  307. /** @type {LoaderItem[]} */
  308. this.loaders = loaders;
  309. if (resolveOptions !== undefined) {
  310. // already declared in super class
  311. this.resolveOptions = resolveOptions;
  312. }
  313. // Info from Build
  314. /** @type {WebpackError | null} */
  315. this.error = null;
  316. /**
  317. * @private
  318. * @type {Source | null}
  319. */
  320. this._source = null;
  321. /**
  322. * @private
  323. * @type {Map<string, number> | undefined}
  324. **/
  325. this._sourceSizes = undefined;
  326. /**
  327. * @private
  328. * @type {undefined | SourceTypes}
  329. **/
  330. this._sourceTypes = undefined;
  331. // Cache
  332. this._lastSuccessfulBuildMeta = {};
  333. this._forceBuild = true;
  334. this._isEvaluatingSideEffects = false;
  335. /** @type {WeakSet<ModuleGraph> | undefined} */
  336. this._addedSideEffectsBailout = undefined;
  337. /** @type {Map<string, any>} */
  338. this._codeGeneratorData = new Map();
  339. }
  340. /**
  341. * @returns {string} a unique identifier of the module
  342. */
  343. identifier() {
  344. if (this.layer === null) {
  345. if (this.type === JAVASCRIPT_MODULE_TYPE_AUTO) {
  346. return this.request;
  347. } else {
  348. return `${this.type}|${this.request}`;
  349. }
  350. } else {
  351. return `${this.type}|${this.request}|${this.layer}`;
  352. }
  353. }
  354. /**
  355. * @param {RequestShortener} requestShortener the request shortener
  356. * @returns {string} a user readable identifier of the module
  357. */
  358. readableIdentifier(requestShortener) {
  359. return requestShortener.shorten(this.userRequest);
  360. }
  361. /**
  362. * @param {LibIdentOptions} options options
  363. * @returns {string | null} an identifier for library inclusion
  364. */
  365. libIdent(options) {
  366. let ident = contextify(
  367. options.context,
  368. this.userRequest,
  369. options.associatedObjectForCache
  370. );
  371. if (this.layer) ident = `(${this.layer})/${ident}`;
  372. return ident;
  373. }
  374. /**
  375. * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
  376. */
  377. nameForCondition() {
  378. const resource = this.matchResource || this.resource;
  379. const idx = resource.indexOf("?");
  380. if (idx >= 0) return resource.slice(0, idx);
  381. return resource;
  382. }
  383. /**
  384. * Assuming this module is in the cache. Update the (cached) module with
  385. * the fresh module from the factory. Usually updates internal references
  386. * and properties.
  387. * @param {Module} module fresh module
  388. * @returns {void}
  389. */
  390. updateCacheModule(module) {
  391. super.updateCacheModule(module);
  392. const m = /** @type {NormalModule} */ (module);
  393. this.binary = m.binary;
  394. this.request = m.request;
  395. this.userRequest = m.userRequest;
  396. this.rawRequest = m.rawRequest;
  397. this.parser = m.parser;
  398. this.parserOptions = m.parserOptions;
  399. this.generator = m.generator;
  400. this.generatorOptions = m.generatorOptions;
  401. this.resource = m.resource;
  402. this.resourceResolveData = m.resourceResolveData;
  403. this.context = m.context;
  404. this.matchResource = m.matchResource;
  405. this.loaders = m.loaders;
  406. }
  407. /**
  408. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  409. */
  410. cleanupForCache() {
  411. // Make sure to cache types and sizes before cleanup when this module has been built
  412. // They are accessed by the stats and we don't want them to crash after cleanup
  413. // TODO reconsider this for webpack 6
  414. if (this.buildInfo) {
  415. if (this._sourceTypes === undefined) this.getSourceTypes();
  416. for (const type of /** @type {SourceTypes} */ (this._sourceTypes)) {
  417. this.size(type);
  418. }
  419. }
  420. super.cleanupForCache();
  421. this.parser = undefined;
  422. this.parserOptions = undefined;
  423. this.generator = undefined;
  424. this.generatorOptions = undefined;
  425. }
  426. /**
  427. * Module should be unsafe cached. Get data that's needed for that.
  428. * This data will be passed to restoreFromUnsafeCache later.
  429. * @returns {UnsafeCacheData} cached data
  430. */
  431. getUnsafeCacheData() {
  432. const data =
  433. /** @type {NormalModuleUnsafeCacheData} */
  434. (super.getUnsafeCacheData());
  435. data.parserOptions = this.parserOptions;
  436. data.generatorOptions = this.generatorOptions;
  437. return data;
  438. }
  439. /**
  440. * restore unsafe cache data
  441. * @param {NormalModuleUnsafeCacheData} unsafeCacheData data from getUnsafeCacheData
  442. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  443. */
  444. restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  445. this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  446. }
  447. /**
  448. * restore unsafe cache data
  449. * @param {object} unsafeCacheData data from getUnsafeCacheData
  450. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  451. */
  452. _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  453. super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
  454. this.parserOptions = unsafeCacheData.parserOptions;
  455. this.parser = normalModuleFactory.getParser(this.type, this.parserOptions);
  456. this.generatorOptions = unsafeCacheData.generatorOptions;
  457. this.generator = normalModuleFactory.getGenerator(
  458. this.type,
  459. this.generatorOptions
  460. );
  461. // we assume the generator behaves identically and keep cached sourceTypes/Sizes
  462. }
  463. /**
  464. * @param {string} context the compilation context
  465. * @param {string} name the asset name
  466. * @param {string | Buffer} content the content
  467. * @param {(string | SourceMap)=} sourceMap an optional source map
  468. * @param {Object=} associatedObjectForCache object for caching
  469. * @returns {Source} the created source
  470. */
  471. createSourceForAsset(
  472. context,
  473. name,
  474. content,
  475. sourceMap,
  476. associatedObjectForCache
  477. ) {
  478. if (sourceMap) {
  479. if (
  480. typeof sourceMap === "string" &&
  481. (this.useSourceMap || this.useSimpleSourceMap)
  482. ) {
  483. return new OriginalSource(
  484. content,
  485. contextifySourceUrl(context, sourceMap, associatedObjectForCache)
  486. );
  487. }
  488. if (this.useSourceMap) {
  489. return new SourceMapSource(
  490. content,
  491. name,
  492. contextifySourceMap(
  493. context,
  494. /** @type {SourceMap} */ (sourceMap),
  495. associatedObjectForCache
  496. )
  497. );
  498. }
  499. }
  500. return new RawSource(content);
  501. }
  502. /**
  503. * @private
  504. * @template T
  505. * @param {ResolverWithOptions} resolver a resolver
  506. * @param {WebpackOptions} options webpack options
  507. * @param {Compilation} compilation the compilation
  508. * @param {InputFileSystem} fs file system from reading
  509. * @param {NormalModuleCompilationHooks} hooks the hooks
  510. * @returns {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} loader context
  511. */
  512. _createLoaderContext(resolver, options, compilation, fs, hooks) {
  513. const { requestShortener } = compilation.runtimeTemplate;
  514. const getCurrentLoaderName = () => {
  515. const currentLoader = this.getCurrentLoader(loaderContext);
  516. if (!currentLoader) return "(not in loader scope)";
  517. return requestShortener.shorten(currentLoader.loader);
  518. };
  519. /**
  520. * @returns {ResolveContext} resolve context
  521. */
  522. const getResolveContext = () => {
  523. return {
  524. fileDependencies: {
  525. add: d => /** @type {TODO} */ (loaderContext).addDependency(d)
  526. },
  527. contextDependencies: {
  528. add: d => /** @type {TODO} */ (loaderContext).addContextDependency(d)
  529. },
  530. missingDependencies: {
  531. add: d => /** @type {TODO} */ (loaderContext).addMissingDependency(d)
  532. }
  533. };
  534. };
  535. const getAbsolutify = memoize(() =>
  536. absolutify.bindCache(compilation.compiler.root)
  537. );
  538. const getAbsolutifyInContext = memoize(() =>
  539. absolutify.bindContextCache(this.context, compilation.compiler.root)
  540. );
  541. const getContextify = memoize(() =>
  542. contextify.bindCache(compilation.compiler.root)
  543. );
  544. const getContextifyInContext = memoize(() =>
  545. contextify.bindContextCache(this.context, compilation.compiler.root)
  546. );
  547. const utils = {
  548. /**
  549. * @param {string} context context
  550. * @param {string} request request
  551. * @returns {string} result
  552. */
  553. absolutify: (context, request) => {
  554. return context === this.context
  555. ? getAbsolutifyInContext()(request)
  556. : getAbsolutify()(context, request);
  557. },
  558. /**
  559. * @param {string} context context
  560. * @param {string} request request
  561. * @returns {string} result
  562. */
  563. contextify: (context, request) => {
  564. return context === this.context
  565. ? getContextifyInContext()(request)
  566. : getContextify()(context, request);
  567. },
  568. /**
  569. * @param {(string | typeof import("./util/Hash"))=} type type
  570. * @returns {Hash} hash
  571. */
  572. createHash: type => {
  573. return createHash(type || compilation.outputOptions.hashFunction);
  574. }
  575. };
  576. /** @type {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} */
  577. const loaderContext = {
  578. version: 2,
  579. getOptions: schema => {
  580. const loader = this.getCurrentLoader(loaderContext);
  581. let { options } = /** @type {LoaderItem} */ (loader);
  582. if (typeof options === "string") {
  583. if (options.startsWith("{") && options.endsWith("}")) {
  584. try {
  585. options = parseJson(options);
  586. } catch (e) {
  587. throw new Error(`Cannot parse string options: ${e.message}`);
  588. }
  589. } else {
  590. options = querystring.parse(options, "&", "=", {
  591. maxKeys: 0
  592. });
  593. }
  594. }
  595. if (options === null || options === undefined) {
  596. options = {};
  597. }
  598. if (schema) {
  599. let name = "Loader";
  600. let baseDataPath = "options";
  601. let match;
  602. if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
  603. [, name, baseDataPath] = match;
  604. }
  605. getValidate()(schema, options, {
  606. name,
  607. baseDataPath
  608. });
  609. }
  610. return options;
  611. },
  612. emitWarning: warning => {
  613. if (!(warning instanceof Error)) {
  614. warning = new NonErrorEmittedError(warning);
  615. }
  616. this.addWarning(
  617. new ModuleWarning(warning, {
  618. from: getCurrentLoaderName()
  619. })
  620. );
  621. },
  622. emitError: error => {
  623. if (!(error instanceof Error)) {
  624. error = new NonErrorEmittedError(error);
  625. }
  626. this.addError(
  627. new ModuleError(error, {
  628. from: getCurrentLoaderName()
  629. })
  630. );
  631. },
  632. getLogger: name => {
  633. const currentLoader = this.getCurrentLoader(loaderContext);
  634. return compilation.getLogger(() =>
  635. [currentLoader && currentLoader.loader, name, this.identifier()]
  636. .filter(Boolean)
  637. .join("|")
  638. );
  639. },
  640. resolve(context, request, callback) {
  641. resolver.resolve({}, context, request, getResolveContext(), callback);
  642. },
  643. getResolve(options) {
  644. const child = options ? resolver.withOptions(options) : resolver;
  645. return (context, request, callback) => {
  646. if (callback) {
  647. child.resolve({}, context, request, getResolveContext(), callback);
  648. } else {
  649. return new Promise((resolve, reject) => {
  650. child.resolve(
  651. {},
  652. context,
  653. request,
  654. getResolveContext(),
  655. (err, result) => {
  656. if (err) reject(err);
  657. else resolve(result);
  658. }
  659. );
  660. });
  661. }
  662. };
  663. },
  664. emitFile: (name, content, sourceMap, assetInfo) => {
  665. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  666. if (!buildInfo.assets) {
  667. buildInfo.assets = Object.create(null);
  668. buildInfo.assetsInfo = new Map();
  669. }
  670. const assets =
  671. /** @type {NonNullable<KnownBuildInfo["assets"]>} */
  672. (buildInfo.assets);
  673. const assetsInfo =
  674. /** @type {NonNullable<KnownBuildInfo["assetsInfo"]>} */
  675. (buildInfo.assetsInfo);
  676. assets[name] = this.createSourceForAsset(
  677. /** @type {string} */ (options.context),
  678. name,
  679. content,
  680. sourceMap,
  681. compilation.compiler.root
  682. );
  683. assetsInfo.set(name, assetInfo);
  684. },
  685. addBuildDependency: dep => {
  686. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  687. if (buildInfo.buildDependencies === undefined) {
  688. buildInfo.buildDependencies = new LazySet();
  689. }
  690. buildInfo.buildDependencies.add(dep);
  691. },
  692. utils,
  693. rootContext: /** @type {string} */ (options.context),
  694. webpack: true,
  695. sourceMap: !!this.useSourceMap,
  696. mode: options.mode || "production",
  697. _module: this,
  698. _compilation: compilation,
  699. _compiler: compilation.compiler,
  700. fs: fs
  701. };
  702. Object.assign(loaderContext, options.loader);
  703. hooks.loader.call(loaderContext, this);
  704. return loaderContext;
  705. }
  706. // TODO remove `loaderContext` in webpack@6
  707. /**
  708. * @param {TODO} loaderContext loader context
  709. * @param {number} index index
  710. * @returns {LoaderItem | null} loader
  711. */
  712. getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
  713. if (
  714. this.loaders &&
  715. this.loaders.length &&
  716. index < this.loaders.length &&
  717. index >= 0 &&
  718. this.loaders[index]
  719. ) {
  720. return this.loaders[index];
  721. }
  722. return null;
  723. }
  724. /**
  725. * @param {string} context the compilation context
  726. * @param {string | Buffer} content the content
  727. * @param {(string | SourceMapSource)=} sourceMap an optional source map
  728. * @param {Object=} associatedObjectForCache object for caching
  729. * @returns {Source} the created source
  730. */
  731. createSource(context, content, sourceMap, associatedObjectForCache) {
  732. if (Buffer.isBuffer(content)) {
  733. return new RawSource(content);
  734. }
  735. // if there is no identifier return raw source
  736. if (!this.identifier) {
  737. return new RawSource(content);
  738. }
  739. // from here on we assume we have an identifier
  740. const identifier = this.identifier();
  741. if (this.useSourceMap && sourceMap) {
  742. return new SourceMapSource(
  743. content,
  744. contextifySourceUrl(context, identifier, associatedObjectForCache),
  745. contextifySourceMap(
  746. context,
  747. /** @type {TODO} */ (sourceMap),
  748. associatedObjectForCache
  749. )
  750. );
  751. }
  752. if (this.useSourceMap || this.useSimpleSourceMap) {
  753. return new OriginalSource(
  754. content,
  755. contextifySourceUrl(context, identifier, associatedObjectForCache)
  756. );
  757. }
  758. return new RawSource(content);
  759. }
  760. /**
  761. * @param {WebpackOptions} options webpack options
  762. * @param {Compilation} compilation the compilation
  763. * @param {ResolverWithOptions} resolver the resolver
  764. * @param {InputFileSystem} fs the file system
  765. * @param {NormalModuleCompilationHooks} hooks the hooks
  766. * @param {function((WebpackError | null)=): void} callback callback function
  767. * @returns {void}
  768. */
  769. _doBuild(options, compilation, resolver, fs, hooks, callback) {
  770. const loaderContext = this._createLoaderContext(
  771. resolver,
  772. options,
  773. compilation,
  774. fs,
  775. hooks
  776. );
  777. const processResult = (err, result) => {
  778. if (err) {
  779. if (!(err instanceof Error)) {
  780. err = new NonErrorEmittedError(err);
  781. }
  782. const currentLoader = this.getCurrentLoader(loaderContext);
  783. const error = new ModuleBuildError(err, {
  784. from:
  785. currentLoader &&
  786. compilation.runtimeTemplate.requestShortener.shorten(
  787. currentLoader.loader
  788. )
  789. });
  790. return callback(error);
  791. }
  792. const source = result[0];
  793. const sourceMap = result.length >= 1 ? result[1] : null;
  794. const extraInfo = result.length >= 2 ? result[2] : null;
  795. if (!Buffer.isBuffer(source) && typeof source !== "string") {
  796. const currentLoader = this.getCurrentLoader(loaderContext, 0);
  797. const err = new Error(
  798. `Final loader (${
  799. currentLoader
  800. ? compilation.runtimeTemplate.requestShortener.shorten(
  801. currentLoader.loader
  802. )
  803. : "unknown"
  804. }) didn't return a Buffer or String`
  805. );
  806. const error = new ModuleBuildError(err);
  807. return callback(error);
  808. }
  809. this._source = this.createSource(
  810. /** @type {string} */ (options.context),
  811. this.binary ? asBuffer(source) : asString(source),
  812. sourceMap,
  813. compilation.compiler.root
  814. );
  815. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  816. this._ast =
  817. typeof extraInfo === "object" &&
  818. extraInfo !== null &&
  819. extraInfo.webpackAST !== undefined
  820. ? extraInfo.webpackAST
  821. : null;
  822. return callback();
  823. };
  824. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  825. buildInfo.fileDependencies = new LazySet();
  826. buildInfo.contextDependencies = new LazySet();
  827. buildInfo.missingDependencies = new LazySet();
  828. buildInfo.cacheable = true;
  829. try {
  830. hooks.beforeLoaders.call(this.loaders, this, loaderContext);
  831. } catch (err) {
  832. processResult(err);
  833. return;
  834. }
  835. if (this.loaders.length > 0) {
  836. /** @type {BuildInfo} */
  837. (this.buildInfo).buildDependencies = new LazySet();
  838. }
  839. runLoaders(
  840. {
  841. resource: this.resource,
  842. loaders: this.loaders,
  843. context: loaderContext,
  844. processResource: (loaderContext, resourcePath, callback) => {
  845. const resource = loaderContext.resource;
  846. const scheme = getScheme(resource);
  847. hooks.readResource
  848. .for(scheme)
  849. .callAsync(loaderContext, (err, result) => {
  850. if (err) return callback(err);
  851. if (typeof result !== "string" && !result) {
  852. return callback(new UnhandledSchemeError(scheme, resource));
  853. }
  854. return callback(null, result);
  855. });
  856. }
  857. },
  858. (err, result) => {
  859. // Cleanup loaderContext to avoid leaking memory in ICs
  860. loaderContext._compilation =
  861. loaderContext._compiler =
  862. loaderContext._module =
  863. // eslint-disable-next-line no-warning-comments
  864. // @ts-ignore
  865. loaderContext.fs =
  866. undefined;
  867. if (!result) {
  868. /** @type {BuildInfo} */
  869. (this.buildInfo).cacheable = false;
  870. return processResult(
  871. err || new Error("No result from loader-runner processing"),
  872. null
  873. );
  874. }
  875. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  876. const fileDependencies =
  877. /** @type {NonNullable<KnownBuildInfo["fileDependencies"]>} */
  878. (buildInfo.fileDependencies);
  879. const contextDependencies =
  880. /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
  881. (buildInfo.contextDependencies);
  882. const missingDependencies =
  883. /** @type {NonNullable<KnownBuildInfo["missingDependencies"]>} */
  884. (buildInfo.missingDependencies);
  885. fileDependencies.addAll(result.fileDependencies);
  886. contextDependencies.addAll(result.contextDependencies);
  887. missingDependencies.addAll(result.missingDependencies);
  888. for (const loader of this.loaders) {
  889. const buildDependencies =
  890. /** @type {NonNullable<KnownBuildInfo["buildDependencies"]>} */
  891. (buildInfo.buildDependencies);
  892. buildDependencies.add(loader.loader);
  893. }
  894. buildInfo.cacheable = buildInfo.cacheable && result.cacheable;
  895. processResult(err, result.result);
  896. }
  897. );
  898. }
  899. /**
  900. * @param {WebpackError} error the error
  901. * @returns {void}
  902. */
  903. markModuleAsErrored(error) {
  904. // Restore build meta from successful build to keep importing state
  905. this.buildMeta = { ...this._lastSuccessfulBuildMeta };
  906. this.error = error;
  907. this.addError(error);
  908. }
  909. /**
  910. * @param {TODO} rule rule
  911. * @param {string} content content
  912. * @returns {boolean} result
  913. */
  914. applyNoParseRule(rule, content) {
  915. // must start with "rule" if rule is a string
  916. if (typeof rule === "string") {
  917. return content.startsWith(rule);
  918. }
  919. if (typeof rule === "function") {
  920. return rule(content);
  921. }
  922. // we assume rule is a regexp
  923. return rule.test(content);
  924. }
  925. /**
  926. * @param {TODO} noParseRule no parse rule
  927. * @param {string} request request
  928. * @returns {boolean} check if module should not be parsed, returns "true" if the module should !not! be parsed, returns "false" if the module !must! be parsed
  929. */
  930. shouldPreventParsing(noParseRule, request) {
  931. // if no noParseRule exists, return false
  932. // the module !must! be parsed.
  933. if (!noParseRule) {
  934. return false;
  935. }
  936. // we only have one rule to check
  937. if (!Array.isArray(noParseRule)) {
  938. // returns "true" if the module is !not! to be parsed
  939. return this.applyNoParseRule(noParseRule, request);
  940. }
  941. for (let i = 0; i < noParseRule.length; i++) {
  942. const rule = noParseRule[i];
  943. // early exit on first truthy match
  944. // this module is !not! to be parsed
  945. if (this.applyNoParseRule(rule, request)) {
  946. return true;
  947. }
  948. }
  949. // no match found, so this module !should! be parsed
  950. return false;
  951. }
  952. /**
  953. * @param {Compilation} compilation compilation
  954. * @private
  955. */
  956. _initBuildHash(compilation) {
  957. const hash = createHash(compilation.outputOptions.hashFunction);
  958. if (this._source) {
  959. hash.update("source");
  960. this._source.updateHash(hash);
  961. }
  962. hash.update("meta");
  963. hash.update(JSON.stringify(this.buildMeta));
  964. /** @type {BuildInfo} */
  965. (this.buildInfo).hash = /** @type {string} */ (hash.digest("hex"));
  966. }
  967. /**
  968. * @param {WebpackOptions} options webpack options
  969. * @param {Compilation} compilation the compilation
  970. * @param {ResolverWithOptions} resolver the resolver
  971. * @param {InputFileSystem} fs the file system
  972. * @param {function(WebpackError=): void} callback callback function
  973. * @returns {void}
  974. */
  975. build(options, compilation, resolver, fs, callback) {
  976. this._forceBuild = false;
  977. this._source = null;
  978. if (this._sourceSizes !== undefined) this._sourceSizes.clear();
  979. this._sourceTypes = undefined;
  980. this._ast = null;
  981. this.error = null;
  982. this.clearWarningsAndErrors();
  983. this.clearDependenciesAndBlocks();
  984. this.buildMeta = {};
  985. this.buildInfo = {
  986. cacheable: false,
  987. parsed: true,
  988. fileDependencies: undefined,
  989. contextDependencies: undefined,
  990. missingDependencies: undefined,
  991. buildDependencies: undefined,
  992. valueDependencies: undefined,
  993. hash: undefined,
  994. assets: undefined,
  995. assetsInfo: undefined
  996. };
  997. const startTime = compilation.compiler.fsStartTime || Date.now();
  998. const hooks = NormalModule.getCompilationHooks(compilation);
  999. return this._doBuild(options, compilation, resolver, fs, hooks, err => {
  1000. // if we have an error mark module as failed and exit
  1001. if (err) {
  1002. this.markModuleAsErrored(err);
  1003. this._initBuildHash(compilation);
  1004. return callback();
  1005. }
  1006. /**
  1007. * @param {Error} e error
  1008. * @returns {void}
  1009. */
  1010. const handleParseError = e => {
  1011. const source = /** @type {Source} */ (this._source).source();
  1012. const loaders = this.loaders.map(item =>
  1013. contextify(
  1014. /** @type {string} */ (options.context),
  1015. item.loader,
  1016. compilation.compiler.root
  1017. )
  1018. );
  1019. const error = new ModuleParseError(source, e, loaders, this.type);
  1020. this.markModuleAsErrored(error);
  1021. this._initBuildHash(compilation);
  1022. return callback();
  1023. };
  1024. const handleParseResult = () => {
  1025. this.dependencies.sort(
  1026. concatComparators(
  1027. compareSelect(a => a.loc, compareLocations),
  1028. keepOriginalOrder(this.dependencies)
  1029. )
  1030. );
  1031. this._initBuildHash(compilation);
  1032. this._lastSuccessfulBuildMeta =
  1033. /** @type {BuildMeta} */
  1034. (this.buildMeta);
  1035. return handleBuildDone();
  1036. };
  1037. const handleBuildDone = () => {
  1038. try {
  1039. hooks.beforeSnapshot.call(this);
  1040. } catch (err) {
  1041. this.markModuleAsErrored(err);
  1042. return callback();
  1043. }
  1044. const snapshotOptions = compilation.options.snapshot.module;
  1045. const { cacheable } = /** @type {BuildInfo} */ (this.buildInfo);
  1046. if (!cacheable || !snapshotOptions) {
  1047. return callback();
  1048. }
  1049. // add warning for all non-absolute paths in fileDependencies, etc
  1050. // This makes it easier to find problems with watching and/or caching
  1051. /** @type {undefined | Set<string>} */
  1052. let nonAbsoluteDependencies = undefined;
  1053. /**
  1054. * @param {LazySet<string>} deps deps
  1055. */
  1056. const checkDependencies = deps => {
  1057. for (const dep of deps) {
  1058. if (!ABSOLUTE_PATH_REGEX.test(dep)) {
  1059. if (nonAbsoluteDependencies === undefined)
  1060. nonAbsoluteDependencies = new Set();
  1061. nonAbsoluteDependencies.add(dep);
  1062. deps.delete(dep);
  1063. try {
  1064. const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, "");
  1065. const absolute = join(
  1066. compilation.fileSystemInfo.fs,
  1067. this.context,
  1068. depWithoutGlob
  1069. );
  1070. if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) {
  1071. (depWithoutGlob !== dep
  1072. ? /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
  1073. (
  1074. /** @type {BuildInfo} */ (this.buildInfo)
  1075. .contextDependencies
  1076. )
  1077. : deps
  1078. ).add(absolute);
  1079. }
  1080. } catch (e) {
  1081. // ignore
  1082. }
  1083. }
  1084. }
  1085. };
  1086. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  1087. const fileDependencies =
  1088. /** @type {NonNullable<KnownBuildInfo["fileDependencies"]>} */
  1089. (buildInfo.fileDependencies);
  1090. const contextDependencies =
  1091. /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
  1092. (buildInfo.contextDependencies);
  1093. const missingDependencies =
  1094. /** @type {NonNullable<KnownBuildInfo["missingDependencies"]>} */
  1095. (buildInfo.missingDependencies);
  1096. checkDependencies(fileDependencies);
  1097. checkDependencies(missingDependencies);
  1098. checkDependencies(contextDependencies);
  1099. if (nonAbsoluteDependencies !== undefined) {
  1100. const InvalidDependenciesModuleWarning =
  1101. getInvalidDependenciesModuleWarning();
  1102. this.addWarning(
  1103. new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies)
  1104. );
  1105. }
  1106. // convert file/context/missingDependencies into filesystem snapshot
  1107. compilation.fileSystemInfo.createSnapshot(
  1108. startTime,
  1109. fileDependencies,
  1110. contextDependencies,
  1111. missingDependencies,
  1112. snapshotOptions,
  1113. (err, snapshot) => {
  1114. if (err) {
  1115. this.markModuleAsErrored(err);
  1116. return;
  1117. }
  1118. buildInfo.fileDependencies = undefined;
  1119. buildInfo.contextDependencies = undefined;
  1120. buildInfo.missingDependencies = undefined;
  1121. buildInfo.snapshot = snapshot;
  1122. return callback();
  1123. }
  1124. );
  1125. };
  1126. try {
  1127. hooks.beforeParse.call(this);
  1128. } catch (err) {
  1129. this.markModuleAsErrored(err);
  1130. this._initBuildHash(compilation);
  1131. return callback();
  1132. }
  1133. // check if this module should !not! be parsed.
  1134. // if so, exit here;
  1135. const noParseRule = options.module && options.module.noParse;
  1136. if (this.shouldPreventParsing(noParseRule, this.request)) {
  1137. // We assume that we need module and exports
  1138. /** @type {BuildInfo} */
  1139. (this.buildInfo).parsed = false;
  1140. this._initBuildHash(compilation);
  1141. return handleBuildDone();
  1142. }
  1143. try {
  1144. const source = /** @type {Source} */ (this._source).source();
  1145. /** @type {Parser} */
  1146. (this.parser).parse(this._ast || source, {
  1147. source,
  1148. current: this,
  1149. module: this,
  1150. compilation: compilation,
  1151. options: options
  1152. });
  1153. } catch (e) {
  1154. handleParseError(/** @type {Error} */ (e));
  1155. return;
  1156. }
  1157. handleParseResult();
  1158. });
  1159. }
  1160. /**
  1161. * @param {ConcatenationBailoutReasonContext} context context
  1162. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  1163. */
  1164. getConcatenationBailoutReason(context) {
  1165. return /** @type {Generator} */ (
  1166. this.generator
  1167. ).getConcatenationBailoutReason(this, context);
  1168. }
  1169. /**
  1170. * @param {ModuleGraph} moduleGraph the module graph
  1171. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  1172. */
  1173. getSideEffectsConnectionState(moduleGraph) {
  1174. if (this.factoryMeta !== undefined) {
  1175. if (this.factoryMeta.sideEffectFree) return false;
  1176. if (this.factoryMeta.sideEffectFree === false) return true;
  1177. }
  1178. if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) {
  1179. if (this._isEvaluatingSideEffects)
  1180. return ModuleGraphConnection.CIRCULAR_CONNECTION;
  1181. this._isEvaluatingSideEffects = true;
  1182. /** @type {ConnectionState} */
  1183. let current = false;
  1184. for (const dep of this.dependencies) {
  1185. const state = dep.getModuleEvaluationSideEffectsState(moduleGraph);
  1186. if (state === true) {
  1187. if (
  1188. this._addedSideEffectsBailout === undefined
  1189. ? ((this._addedSideEffectsBailout = new WeakSet()), true)
  1190. : !this._addedSideEffectsBailout.has(moduleGraph)
  1191. ) {
  1192. this._addedSideEffectsBailout.add(moduleGraph);
  1193. moduleGraph
  1194. .getOptimizationBailout(this)
  1195. .push(
  1196. () =>
  1197. `Dependency (${
  1198. dep.type
  1199. }) with side effects at ${formatLocation(dep.loc)}`
  1200. );
  1201. }
  1202. this._isEvaluatingSideEffects = false;
  1203. return true;
  1204. } else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) {
  1205. current = ModuleGraphConnection.addConnectionStates(current, state);
  1206. }
  1207. }
  1208. this._isEvaluatingSideEffects = false;
  1209. // When caching is implemented here, make sure to not cache when
  1210. // at least one circular connection was in the loop above
  1211. return current;
  1212. } else {
  1213. return true;
  1214. }
  1215. }
  1216. /**
  1217. * @returns {SourceTypes} types available (do not mutate)
  1218. */
  1219. getSourceTypes() {
  1220. if (this._sourceTypes === undefined) {
  1221. this._sourceTypes = /** @type {Generator} */ (this.generator).getTypes(
  1222. this
  1223. );
  1224. }
  1225. return this._sourceTypes;
  1226. }
  1227. /**
  1228. * @param {CodeGenerationContext} context context for code generation
  1229. * @returns {CodeGenerationResult} result
  1230. */
  1231. codeGeneration({
  1232. dependencyTemplates,
  1233. runtimeTemplate,
  1234. moduleGraph,
  1235. chunkGraph,
  1236. runtime,
  1237. runtimes,
  1238. concatenationScope,
  1239. codeGenerationResults,
  1240. sourceTypes
  1241. }) {
  1242. /** @type {Set<string>} */
  1243. const runtimeRequirements = new Set();
  1244. const { parsed } = /** @type {BuildInfo} */ (this.buildInfo);
  1245. if (!parsed) {
  1246. runtimeRequirements.add(RuntimeGlobals.module);
  1247. runtimeRequirements.add(RuntimeGlobals.exports);
  1248. runtimeRequirements.add(RuntimeGlobals.thisAsExports);
  1249. }
  1250. /** @type {function(): Map<string, any>} */
  1251. const getData = () => {
  1252. return this._codeGeneratorData;
  1253. };
  1254. const sources = new Map();
  1255. for (const type of sourceTypes || chunkGraph.getModuleSourceTypes(this)) {
  1256. const source = this.error
  1257. ? new RawSource(
  1258. "throw new Error(" + JSON.stringify(this.error.message) + ");"
  1259. )
  1260. : /** @type {Generator} */ (this.generator).generate(this, {
  1261. dependencyTemplates,
  1262. runtimeTemplate,
  1263. moduleGraph,
  1264. chunkGraph,
  1265. runtimeRequirements,
  1266. runtime,
  1267. runtimes,
  1268. concatenationScope,
  1269. codeGenerationResults,
  1270. getData,
  1271. type
  1272. });
  1273. if (source) {
  1274. sources.set(type, new CachedSource(source));
  1275. }
  1276. }
  1277. /** @type {CodeGenerationResult} */
  1278. const resultEntry = {
  1279. sources,
  1280. runtimeRequirements,
  1281. data: this._codeGeneratorData
  1282. };
  1283. return resultEntry;
  1284. }
  1285. /**
  1286. * @returns {Source | null} the original source for the module before webpack transformation
  1287. */
  1288. originalSource() {
  1289. return this._source;
  1290. }
  1291. /**
  1292. * @returns {void}
  1293. */
  1294. invalidateBuild() {
  1295. this._forceBuild = true;
  1296. }
  1297. /**
  1298. * @param {NeedBuildContext} context context info
  1299. * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
  1300. * @returns {void}
  1301. */
  1302. needBuild(context, callback) {
  1303. const { fileSystemInfo, compilation, valueCacheVersions } = context;
  1304. // build if enforced
  1305. if (this._forceBuild) return callback(null, true);
  1306. // always try to build in case of an error
  1307. if (this.error) return callback(null, true);
  1308. const { cacheable, snapshot, valueDependencies } =
  1309. /** @type {BuildInfo} */ (this.buildInfo);
  1310. // always build when module is not cacheable
  1311. if (!cacheable) return callback(null, true);
  1312. // build when there is no snapshot to check
  1313. if (!snapshot) return callback(null, true);
  1314. // build when valueDependencies have changed
  1315. if (valueDependencies) {
  1316. if (!valueCacheVersions) return callback(null, true);
  1317. for (const [key, value] of valueDependencies) {
  1318. if (value === undefined) return callback(null, true);
  1319. const current = valueCacheVersions.get(key);
  1320. if (
  1321. value !== current &&
  1322. (typeof value === "string" ||
  1323. typeof current === "string" ||
  1324. current === undefined ||
  1325. !isSubset(value, current))
  1326. ) {
  1327. return callback(null, true);
  1328. }
  1329. }
  1330. }
  1331. // check snapshot for validity
  1332. fileSystemInfo.checkSnapshotValid(snapshot, (err, valid) => {
  1333. if (err) return callback(err);
  1334. if (!valid) return callback(null, true);
  1335. const hooks = NormalModule.getCompilationHooks(compilation);
  1336. hooks.needBuild.callAsync(this, context, (err, needBuild) => {
  1337. if (err) {
  1338. return callback(
  1339. HookWebpackError.makeWebpackError(
  1340. err,
  1341. "NormalModule.getCompilationHooks().needBuild"
  1342. )
  1343. );
  1344. }
  1345. callback(null, !!needBuild);
  1346. });
  1347. });
  1348. }
  1349. /**
  1350. * @param {string=} type the source type for which the size should be estimated
  1351. * @returns {number} the estimated size of the module (must be non-zero)
  1352. */
  1353. size(type) {
  1354. const cachedSize =
  1355. this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type);
  1356. if (cachedSize !== undefined) {
  1357. return cachedSize;
  1358. }
  1359. const size = Math.max(
  1360. 1,
  1361. /** @type {Generator} */ (this.generator).getSize(this, type)
  1362. );
  1363. if (this._sourceSizes === undefined) {
  1364. this._sourceSizes = new Map();
  1365. }
  1366. this._sourceSizes.set(type, size);
  1367. return size;
  1368. }
  1369. /**
  1370. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  1371. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  1372. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  1373. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  1374. */
  1375. addCacheDependencies(
  1376. fileDependencies,
  1377. contextDependencies,
  1378. missingDependencies,
  1379. buildDependencies
  1380. ) {
  1381. const { snapshot, buildDependencies: buildDeps } =
  1382. /** @type {BuildInfo} */ (this.buildInfo);
  1383. if (snapshot) {
  1384. fileDependencies.addAll(snapshot.getFileIterable());
  1385. contextDependencies.addAll(snapshot.getContextIterable());
  1386. missingDependencies.addAll(snapshot.getMissingIterable());
  1387. } else {
  1388. const {
  1389. fileDependencies: fileDeps,
  1390. contextDependencies: contextDeps,
  1391. missingDependencies: missingDeps
  1392. } = /** @type {BuildInfo} */ (this.buildInfo);
  1393. if (fileDeps !== undefined) fileDependencies.addAll(fileDeps);
  1394. if (contextDeps !== undefined) contextDependencies.addAll(contextDeps);
  1395. if (missingDeps !== undefined) missingDependencies.addAll(missingDeps);
  1396. }
  1397. if (buildDeps !== undefined) {
  1398. buildDependencies.addAll(buildDeps);
  1399. }
  1400. }
  1401. /**
  1402. * @param {Hash} hash the hash used to track dependencies
  1403. * @param {UpdateHashContext} context context
  1404. * @returns {void}
  1405. */
  1406. updateHash(hash, context) {
  1407. hash.update(/** @type {BuildInfo} */ (this.buildInfo).hash);
  1408. this.generator.updateHash(hash, {
  1409. module: this,
  1410. ...context
  1411. });
  1412. super.updateHash(hash, context);
  1413. }
  1414. /**
  1415. * @param {ObjectSerializerContext} context context
  1416. */
  1417. serialize(context) {
  1418. const { write } = context;
  1419. // deserialize
  1420. write(this._source);
  1421. write(this.error);
  1422. write(this._lastSuccessfulBuildMeta);
  1423. write(this._forceBuild);
  1424. write(this._codeGeneratorData);
  1425. super.serialize(context);
  1426. }
  1427. static deserialize(context) {
  1428. const obj = new NormalModule({
  1429. // will be deserialized by Module
  1430. layer: null,
  1431. type: "",
  1432. // will be filled by updateCacheModule
  1433. resource: "",
  1434. context: "",
  1435. request: null,
  1436. userRequest: null,
  1437. rawRequest: null,
  1438. loaders: null,
  1439. matchResource: null,
  1440. parser: null,
  1441. parserOptions: null,
  1442. generator: null,
  1443. generatorOptions: null,
  1444. resolveOptions: null
  1445. });
  1446. obj.deserialize(context);
  1447. return obj;
  1448. }
  1449. /**
  1450. * @param {ObjectDeserializerContext} context context
  1451. */
  1452. deserialize(context) {
  1453. const { read } = context;
  1454. this._source = read();
  1455. this.error = read();
  1456. this._lastSuccessfulBuildMeta = read();
  1457. this._forceBuild = read();
  1458. this._codeGeneratorData = read();
  1459. super.deserialize(context);
  1460. }
  1461. }
  1462. makeSerializable(NormalModule, "webpack/lib/NormalModule");
  1463. module.exports = NormalModule;