NormalModule.js 41 KB

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