ContextModule.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { OriginalSource, RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
  8. const { makeWebpackError } = require("./HookWebpackError");
  9. const Module = require("./Module");
  10. const { JS_TYPES } = require("./ModuleSourceTypesConstants");
  11. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
  12. const RuntimeGlobals = require("./RuntimeGlobals");
  13. const Template = require("./Template");
  14. const WebpackError = require("./WebpackError");
  15. const {
  16. compareLocations,
  17. compareModulesById,
  18. compareSelect,
  19. concatComparators,
  20. keepOriginalOrder
  21. } = require("./util/comparators");
  22. const {
  23. contextify,
  24. makePathsRelative,
  25. parseResource
  26. } = require("./util/identifier");
  27. const makeSerializable = require("./util/makeSerializable");
  28. /** @typedef {import("webpack-sources").Source} Source */
  29. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  30. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  31. /** @typedef {import("./Chunk")} Chunk */
  32. /** @typedef {import("./Chunk").ChunkId} ChunkId */
  33. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  34. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  35. /** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
  36. /** @typedef {import("./Compilation")} Compilation */
  37. /** @typedef {import("./Dependency")} Dependency */
  38. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  39. /** @typedef {import("./Generator").SourceTypes} SourceTypes */
  40. /** @typedef {import("./Module").BuildCallback} BuildCallback */
  41. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  42. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  43. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  44. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  45. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  46. /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
  47. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  48. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  49. /** @typedef {import("./RequestShortener")} RequestShortener */
  50. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  51. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  52. /** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */
  53. /** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */
  54. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  55. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  56. /** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */
  57. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  58. /** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */
  59. /**
  60. * @typedef {object} ContextOptions
  61. * @property {ContextMode} mode
  62. * @property {boolean} recursive
  63. * @property {RegExp} regExp
  64. * @property {("strict" | boolean)=} namespaceObject
  65. * @property {string=} addon
  66. * @property {(string | null)=} chunkName
  67. * @property {(RegExp | null)=} include
  68. * @property {(RegExp | null)=} exclude
  69. * @property {RawChunkGroupOptions=} groupOptions
  70. * @property {string=} typePrefix
  71. * @property {string=} category
  72. * @property {(string[][] | null)=} referencedExports exports referenced from modules (won't be mangled)
  73. * @property {string=} layer
  74. * @property {ImportAttributes=} attributes
  75. */
  76. /**
  77. * @typedef {object} ContextModuleOptionsExtras
  78. * @property {false | string | string[]} resource
  79. * @property {string=} resourceQuery
  80. * @property {string=} resourceFragment
  81. * @property {ResolveOptions=} resolveOptions
  82. */
  83. /** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */
  84. /**
  85. * @callback ResolveDependenciesCallback
  86. * @param {Error | null} err
  87. * @param {ContextElementDependency[]=} dependencies
  88. */
  89. /**
  90. * @callback ResolveDependencies
  91. * @param {InputFileSystem} fs
  92. * @param {ContextModuleOptions} options
  93. * @param {ResolveDependenciesCallback} callback
  94. */
  95. /** @typedef {1 | 3 | 7 | 9} FakeMapType */
  96. /** @typedef {Record<ModuleId, FakeMapType>} FakeMap */
  97. const SNAPSHOT_OPTIONS = { timestamp: true };
  98. class ContextModule extends Module {
  99. /**
  100. * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
  101. * @param {ContextModuleOptions} options options object
  102. */
  103. constructor(resolveDependencies, options) {
  104. if (!options || typeof options.resource === "string") {
  105. const parsed = parseResource(
  106. options ? /** @type {string} */ (options.resource) : ""
  107. );
  108. const resource = parsed.path;
  109. const resourceQuery = (options && options.resourceQuery) || parsed.query;
  110. const resourceFragment =
  111. (options && options.resourceFragment) || parsed.fragment;
  112. const layer = options && options.layer;
  113. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, resource, layer);
  114. /** @type {ContextModuleOptions} */
  115. this.options = {
  116. ...options,
  117. resource,
  118. resourceQuery,
  119. resourceFragment
  120. };
  121. } else {
  122. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, undefined, options.layer);
  123. /** @type {ContextModuleOptions} */
  124. this.options = {
  125. ...options,
  126. resource: options.resource,
  127. resourceQuery: options.resourceQuery || "",
  128. resourceFragment: options.resourceFragment || ""
  129. };
  130. }
  131. // Info from Factory
  132. /** @type {ResolveDependencies | undefined} */
  133. this.resolveDependencies = resolveDependencies;
  134. if (options && options.resolveOptions !== undefined) {
  135. this.resolveOptions = options.resolveOptions;
  136. }
  137. if (options && typeof options.mode !== "string") {
  138. throw new Error("options.mode is a required option");
  139. }
  140. this._identifier = this._createIdentifier();
  141. this._forceBuild = true;
  142. }
  143. /**
  144. * @returns {SourceTypes} types available (do not mutate)
  145. */
  146. getSourceTypes() {
  147. return JS_TYPES;
  148. }
  149. /**
  150. * Assuming this module is in the cache. Update the (cached) module with
  151. * the fresh module from the factory. Usually updates internal references
  152. * and properties.
  153. * @param {Module} module fresh module
  154. * @returns {void}
  155. */
  156. updateCacheModule(module) {
  157. const m = /** @type {ContextModule} */ (module);
  158. this.resolveDependencies = m.resolveDependencies;
  159. this.options = m.options;
  160. }
  161. /**
  162. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  163. */
  164. cleanupForCache() {
  165. super.cleanupForCache();
  166. this.resolveDependencies = undefined;
  167. }
  168. /**
  169. * @private
  170. * @param {RegExp} regexString RegExp as a string
  171. * @param {boolean=} stripSlash do we need to strip a slsh
  172. * @returns {string} pretty RegExp
  173. */
  174. _prettyRegExp(regexString, stripSlash = true) {
  175. const str = stripSlash
  176. ? regexString.source + regexString.flags
  177. : `${regexString}`;
  178. return str.replace(/!/g, "%21").replace(/\|/g, "%7C");
  179. }
  180. _createIdentifier() {
  181. let identifier =
  182. this.context ||
  183. (typeof this.options.resource === "string" ||
  184. this.options.resource === false
  185. ? `${this.options.resource}`
  186. : this.options.resource.join("|"));
  187. if (this.options.resourceQuery) {
  188. identifier += `|${this.options.resourceQuery}`;
  189. }
  190. if (this.options.resourceFragment) {
  191. identifier += `|${this.options.resourceFragment}`;
  192. }
  193. if (this.options.mode) {
  194. identifier += `|${this.options.mode}`;
  195. }
  196. if (!this.options.recursive) {
  197. identifier += "|nonrecursive";
  198. }
  199. if (this.options.addon) {
  200. identifier += `|${this.options.addon}`;
  201. }
  202. if (this.options.regExp) {
  203. identifier += `|${this._prettyRegExp(this.options.regExp, false)}`;
  204. }
  205. if (this.options.include) {
  206. identifier += `|include: ${this._prettyRegExp(
  207. this.options.include,
  208. false
  209. )}`;
  210. }
  211. if (this.options.exclude) {
  212. identifier += `|exclude: ${this._prettyRegExp(
  213. this.options.exclude,
  214. false
  215. )}`;
  216. }
  217. if (this.options.referencedExports) {
  218. identifier += `|referencedExports: ${JSON.stringify(
  219. this.options.referencedExports
  220. )}`;
  221. }
  222. if (this.options.chunkName) {
  223. identifier += `|chunkName: ${this.options.chunkName}`;
  224. }
  225. if (this.options.groupOptions) {
  226. identifier += `|groupOptions: ${JSON.stringify(
  227. this.options.groupOptions
  228. )}`;
  229. }
  230. if (this.options.namespaceObject === "strict") {
  231. identifier += "|strict namespace object";
  232. } else if (this.options.namespaceObject) {
  233. identifier += "|namespace object";
  234. }
  235. if (this.layer) {
  236. identifier += `|layer: ${this.layer}`;
  237. }
  238. return identifier;
  239. }
  240. /**
  241. * @returns {string} a unique identifier of the module
  242. */
  243. identifier() {
  244. return this._identifier;
  245. }
  246. /**
  247. * @param {RequestShortener} requestShortener the request shortener
  248. * @returns {string} a user readable identifier of the module
  249. */
  250. readableIdentifier(requestShortener) {
  251. let identifier;
  252. if (this.context) {
  253. identifier = `${requestShortener.shorten(this.context)}/`;
  254. } else if (
  255. typeof this.options.resource === "string" ||
  256. this.options.resource === false
  257. ) {
  258. identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`;
  259. } else {
  260. identifier = this.options.resource
  261. .map((r) => `${requestShortener.shorten(r)}/`)
  262. .join(" ");
  263. }
  264. if (this.options.resourceQuery) {
  265. identifier += ` ${this.options.resourceQuery}`;
  266. }
  267. if (this.options.mode) {
  268. identifier += ` ${this.options.mode}`;
  269. }
  270. if (!this.options.recursive) {
  271. identifier += " nonrecursive";
  272. }
  273. if (this.options.addon) {
  274. identifier += ` ${requestShortener.shorten(this.options.addon)}`;
  275. }
  276. if (this.options.regExp) {
  277. identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
  278. }
  279. if (this.options.include) {
  280. identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
  281. }
  282. if (this.options.exclude) {
  283. identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
  284. }
  285. if (this.options.referencedExports) {
  286. identifier += ` referencedExports: ${this.options.referencedExports
  287. .map((e) => e.join("."))
  288. .join(", ")}`;
  289. }
  290. if (this.options.chunkName) {
  291. identifier += ` chunkName: ${this.options.chunkName}`;
  292. }
  293. if (this.options.groupOptions) {
  294. const groupOptions = this.options.groupOptions;
  295. for (const key of Object.keys(groupOptions)) {
  296. identifier += ` ${key}: ${
  297. groupOptions[/** @type {keyof RawChunkGroupOptions} */ (key)]
  298. }`;
  299. }
  300. }
  301. if (this.options.namespaceObject === "strict") {
  302. identifier += " strict namespace object";
  303. } else if (this.options.namespaceObject) {
  304. identifier += " namespace object";
  305. }
  306. return identifier;
  307. }
  308. /**
  309. * @param {LibIdentOptions} options options
  310. * @returns {string | null} an identifier for library inclusion
  311. */
  312. libIdent(options) {
  313. let identifier;
  314. if (this.context) {
  315. identifier = contextify(
  316. options.context,
  317. this.context,
  318. options.associatedObjectForCache
  319. );
  320. } else if (typeof this.options.resource === "string") {
  321. identifier = contextify(
  322. options.context,
  323. this.options.resource,
  324. options.associatedObjectForCache
  325. );
  326. } else if (this.options.resource === false) {
  327. identifier = "false";
  328. } else {
  329. identifier = this.options.resource
  330. .map((res) =>
  331. contextify(options.context, res, options.associatedObjectForCache)
  332. )
  333. .join(" ");
  334. }
  335. if (this.layer) identifier = `(${this.layer})/${identifier}`;
  336. if (this.options.mode) {
  337. identifier += ` ${this.options.mode}`;
  338. }
  339. if (this.options.recursive) {
  340. identifier += " recursive";
  341. }
  342. if (this.options.addon) {
  343. identifier += ` ${contextify(
  344. options.context,
  345. this.options.addon,
  346. options.associatedObjectForCache
  347. )}`;
  348. }
  349. if (this.options.regExp) {
  350. identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
  351. }
  352. if (this.options.include) {
  353. identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
  354. }
  355. if (this.options.exclude) {
  356. identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
  357. }
  358. if (this.options.referencedExports) {
  359. identifier += ` referencedExports: ${this.options.referencedExports
  360. .map((e) => e.join("."))
  361. .join(", ")}`;
  362. }
  363. return identifier;
  364. }
  365. /**
  366. * @returns {void}
  367. */
  368. invalidateBuild() {
  369. this._forceBuild = true;
  370. }
  371. /**
  372. * @param {NeedBuildContext} context context info
  373. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  374. * @returns {void}
  375. */
  376. needBuild({ fileSystemInfo }, callback) {
  377. // build if enforced
  378. if (this._forceBuild) return callback(null, true);
  379. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  380. // always build when we have no snapshot and context
  381. if (!buildInfo.snapshot) {
  382. return callback(null, Boolean(this.context || this.options.resource));
  383. }
  384. fileSystemInfo.checkSnapshotValid(buildInfo.snapshot, (err, valid) => {
  385. callback(err, !valid);
  386. });
  387. }
  388. /**
  389. * @param {WebpackOptions} options webpack options
  390. * @param {Compilation} compilation the compilation
  391. * @param {ResolverWithOptions} resolver the resolver
  392. * @param {InputFileSystem} fs the file system
  393. * @param {BuildCallback} callback callback function
  394. * @returns {void}
  395. */
  396. build(options, compilation, resolver, fs, callback) {
  397. this._forceBuild = false;
  398. /** @type {BuildMeta} */
  399. this.buildMeta = {
  400. exportsType: "default",
  401. defaultObject: "redirect-warn"
  402. };
  403. this.buildInfo = {
  404. snapshot: undefined
  405. };
  406. this.dependencies.length = 0;
  407. this.blocks.length = 0;
  408. const startTime = Date.now();
  409. /** @type {ResolveDependencies} */
  410. (this.resolveDependencies)(fs, this.options, (err, dependencies) => {
  411. if (err) {
  412. return callback(
  413. makeWebpackError(err, "ContextModule.resolveDependencies")
  414. );
  415. }
  416. // abort if something failed
  417. // this will create an empty context
  418. if (!dependencies) {
  419. callback();
  420. return;
  421. }
  422. // enhance dependencies with meta info
  423. for (const dep of dependencies) {
  424. dep.loc = {
  425. name: dep.userRequest
  426. };
  427. dep.request = this.options.addon + dep.request;
  428. }
  429. dependencies.sort(
  430. concatComparators(
  431. compareSelect((a) => a.loc, compareLocations),
  432. keepOriginalOrder(this.dependencies)
  433. )
  434. );
  435. if (this.options.mode === "sync" || this.options.mode === "eager") {
  436. // if we have an sync or eager context
  437. // just add all dependencies and continue
  438. this.dependencies = dependencies;
  439. } else if (this.options.mode === "lazy-once") {
  440. // for the lazy-once mode create a new async dependency block
  441. // and add that block to this context
  442. if (dependencies.length > 0) {
  443. const block = new AsyncDependenciesBlock({
  444. ...this.options.groupOptions,
  445. name: this.options.chunkName
  446. });
  447. for (const dep of dependencies) {
  448. block.addDependency(dep);
  449. }
  450. this.addBlock(block);
  451. }
  452. } else if (
  453. this.options.mode === "weak" ||
  454. this.options.mode === "async-weak"
  455. ) {
  456. // we mark all dependencies as weak
  457. for (const dep of dependencies) {
  458. dep.weak = true;
  459. }
  460. this.dependencies = dependencies;
  461. } else if (this.options.mode === "lazy") {
  462. // if we are lazy create a new async dependency block per dependency
  463. // and add all blocks to this context
  464. let index = 0;
  465. for (const dep of dependencies) {
  466. let chunkName = this.options.chunkName;
  467. if (chunkName) {
  468. if (!/\[(index|request)\]/.test(chunkName)) {
  469. chunkName += "[index]";
  470. }
  471. chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
  472. chunkName = chunkName.replace(
  473. /\[request\]/g,
  474. Template.toPath(dep.userRequest)
  475. );
  476. }
  477. const block = new AsyncDependenciesBlock(
  478. {
  479. ...this.options.groupOptions,
  480. name: chunkName
  481. },
  482. dep.loc,
  483. dep.userRequest
  484. );
  485. block.addDependency(dep);
  486. this.addBlock(block);
  487. }
  488. } else {
  489. callback(
  490. new WebpackError(`Unsupported mode "${this.options.mode}" in context`)
  491. );
  492. return;
  493. }
  494. if (!this.context && !this.options.resource) return callback();
  495. compilation.fileSystemInfo.createSnapshot(
  496. startTime,
  497. null,
  498. this.context
  499. ? [this.context]
  500. : typeof this.options.resource === "string"
  501. ? [this.options.resource]
  502. : /** @type {string[]} */ (this.options.resource),
  503. null,
  504. SNAPSHOT_OPTIONS,
  505. (err, snapshot) => {
  506. if (err) return callback(err);
  507. /** @type {BuildInfo} */
  508. (this.buildInfo).snapshot = snapshot;
  509. callback();
  510. }
  511. );
  512. });
  513. }
  514. /**
  515. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  516. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  517. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  518. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  519. */
  520. addCacheDependencies(
  521. fileDependencies,
  522. contextDependencies,
  523. missingDependencies,
  524. buildDependencies
  525. ) {
  526. if (this.context) {
  527. contextDependencies.add(this.context);
  528. } else if (typeof this.options.resource === "string") {
  529. contextDependencies.add(this.options.resource);
  530. } else if (this.options.resource === false) {
  531. // Do nothing
  532. } else {
  533. for (const res of this.options.resource) contextDependencies.add(res);
  534. }
  535. }
  536. /**
  537. * @param {Dependency[]} dependencies all dependencies
  538. * @param {ChunkGraph} chunkGraph chunk graph
  539. * @returns {Map<string, string | number>} map with user requests
  540. */
  541. getUserRequestMap(dependencies, chunkGraph) {
  542. const moduleGraph = chunkGraph.moduleGraph;
  543. // if we filter first we get a new array
  544. // therefore we don't need to create a clone of dependencies explicitly
  545. // therefore the order of this is !important!
  546. const sortedDependencies =
  547. /** @type {ContextElementDependency[]} */
  548. (dependencies)
  549. .filter((dependency) => moduleGraph.getModule(dependency))
  550. .sort((a, b) => {
  551. if (a.userRequest === b.userRequest) {
  552. return 0;
  553. }
  554. return a.userRequest < b.userRequest ? -1 : 1;
  555. });
  556. const map = Object.create(null);
  557. for (const dep of sortedDependencies) {
  558. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  559. map[dep.userRequest] = chunkGraph.getModuleId(module);
  560. }
  561. return map;
  562. }
  563. /**
  564. * @param {Dependency[]} dependencies all dependencies
  565. * @param {ChunkGraph} chunkGraph chunk graph
  566. * @returns {FakeMap | FakeMapType} fake map
  567. */
  568. getFakeMap(dependencies, chunkGraph) {
  569. if (!this.options.namespaceObject) {
  570. return 9;
  571. }
  572. const moduleGraph = chunkGraph.moduleGraph;
  573. // bitfield
  574. let hasType = 0;
  575. const comparator = compareModulesById(chunkGraph);
  576. // if we filter first we get a new array
  577. // therefore we don't need to create a clone of dependencies explicitly
  578. // therefore the order of this is !important!
  579. const sortedModules = dependencies
  580. .map(
  581. (dependency) =>
  582. /** @type {Module} */ (moduleGraph.getModule(dependency))
  583. )
  584. .filter(Boolean)
  585. .sort(comparator);
  586. /** @type {FakeMap} */
  587. const fakeMap = Object.create(null);
  588. for (const module of sortedModules) {
  589. const exportsType = module.getExportsType(
  590. moduleGraph,
  591. this.options.namespaceObject === "strict"
  592. );
  593. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  594. switch (exportsType) {
  595. case "namespace":
  596. fakeMap[id] = 9;
  597. hasType |= 1;
  598. break;
  599. case "dynamic":
  600. fakeMap[id] = 7;
  601. hasType |= 2;
  602. break;
  603. case "default-only":
  604. fakeMap[id] = 1;
  605. hasType |= 4;
  606. break;
  607. case "default-with-named":
  608. fakeMap[id] = 3;
  609. hasType |= 8;
  610. break;
  611. default:
  612. throw new Error(`Unexpected exports type ${exportsType}`);
  613. }
  614. }
  615. if (hasType === 1) {
  616. return 9;
  617. }
  618. if (hasType === 2) {
  619. return 7;
  620. }
  621. if (hasType === 4) {
  622. return 1;
  623. }
  624. if (hasType === 8) {
  625. return 3;
  626. }
  627. if (hasType === 0) {
  628. return 9;
  629. }
  630. return fakeMap;
  631. }
  632. /**
  633. * @param {FakeMap | FakeMapType} fakeMap fake map
  634. * @returns {string} fake map init statement
  635. */
  636. getFakeMapInitStatement(fakeMap) {
  637. return typeof fakeMap === "object"
  638. ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
  639. : "";
  640. }
  641. /**
  642. * @param {FakeMapType} type type
  643. * @param {boolean=} asyncModule is async module
  644. * @returns {string} return result
  645. */
  646. getReturn(type, asyncModule) {
  647. if (type === 9) {
  648. return `${RuntimeGlobals.require}(id)`;
  649. }
  650. return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${
  651. asyncModule ? " | 16" : ""
  652. })`;
  653. }
  654. /**
  655. * @param {FakeMap | FakeMapType} fakeMap fake map
  656. * @param {boolean=} asyncModule us async module
  657. * @param {string=} fakeMapDataExpression fake map data expression
  658. * @returns {string} module object source
  659. */
  660. getReturnModuleObjectSource(
  661. fakeMap,
  662. asyncModule,
  663. fakeMapDataExpression = "fakeMap[id]"
  664. ) {
  665. if (typeof fakeMap === "number") {
  666. return `return ${this.getReturn(fakeMap, asyncModule)};`;
  667. }
  668. return `return ${
  669. RuntimeGlobals.createFakeNamespaceObject
  670. }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`;
  671. }
  672. /**
  673. * @param {Dependency[]} dependencies dependencies
  674. * @param {ModuleId} id module id
  675. * @param {ChunkGraph} chunkGraph the chunk graph
  676. * @returns {string} source code
  677. */
  678. getSyncSource(dependencies, id, chunkGraph) {
  679. const map = this.getUserRequestMap(dependencies, chunkGraph);
  680. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  681. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  682. return `var map = ${JSON.stringify(map, null, "\t")};
  683. ${this.getFakeMapInitStatement(fakeMap)}
  684. function webpackContext(req) {
  685. var id = webpackContextResolve(req);
  686. ${returnModuleObject}
  687. }
  688. function webpackContextResolve(req) {
  689. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  690. var e = new Error("Cannot find module '" + req + "'");
  691. e.code = 'MODULE_NOT_FOUND';
  692. throw e;
  693. }
  694. return map[req];
  695. }
  696. webpackContext.keys = function webpackContextKeys() {
  697. return Object.keys(map);
  698. };
  699. webpackContext.resolve = webpackContextResolve;
  700. module.exports = webpackContext;
  701. webpackContext.id = ${JSON.stringify(id)};`;
  702. }
  703. /**
  704. * @param {Dependency[]} dependencies dependencies
  705. * @param {ModuleId} id module id
  706. * @param {ChunkGraph} chunkGraph the chunk graph
  707. * @returns {string} source code
  708. */
  709. getWeakSyncSource(dependencies, id, chunkGraph) {
  710. const map = this.getUserRequestMap(dependencies, chunkGraph);
  711. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  712. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  713. return `var map = ${JSON.stringify(map, null, "\t")};
  714. ${this.getFakeMapInitStatement(fakeMap)}
  715. function webpackContext(req) {
  716. var id = webpackContextResolve(req);
  717. if(!${RuntimeGlobals.moduleFactories}[id]) {
  718. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  719. e.code = 'MODULE_NOT_FOUND';
  720. throw e;
  721. }
  722. ${returnModuleObject}
  723. }
  724. function webpackContextResolve(req) {
  725. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  726. var e = new Error("Cannot find module '" + req + "'");
  727. e.code = 'MODULE_NOT_FOUND';
  728. throw e;
  729. }
  730. return map[req];
  731. }
  732. webpackContext.keys = function webpackContextKeys() {
  733. return Object.keys(map);
  734. };
  735. webpackContext.resolve = webpackContextResolve;
  736. webpackContext.id = ${JSON.stringify(id)};
  737. module.exports = webpackContext;`;
  738. }
  739. /**
  740. * @param {Dependency[]} dependencies dependencies
  741. * @param {ModuleId} id module id
  742. * @param {object} context context
  743. * @param {ChunkGraph} context.chunkGraph the chunk graph
  744. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  745. * @returns {string} source code
  746. */
  747. getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  748. const arrow = runtimeTemplate.supportsArrowFunction();
  749. const map = this.getUserRequestMap(dependencies, chunkGraph);
  750. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  751. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true);
  752. return `var map = ${JSON.stringify(map, null, "\t")};
  753. ${this.getFakeMapInitStatement(fakeMap)}
  754. function webpackAsyncContext(req) {
  755. return webpackAsyncContextResolve(req).then(${
  756. arrow ? "id =>" : "function(id)"
  757. } {
  758. if(!${RuntimeGlobals.moduleFactories}[id]) {
  759. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  760. e.code = 'MODULE_NOT_FOUND';
  761. throw e;
  762. }
  763. ${returnModuleObject}
  764. });
  765. }
  766. function webpackAsyncContextResolve(req) {
  767. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  768. // uncaught exception popping up in devtools
  769. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  770. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  771. var e = new Error("Cannot find module '" + req + "'");
  772. e.code = 'MODULE_NOT_FOUND';
  773. throw e;
  774. }
  775. return map[req];
  776. });
  777. }
  778. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  779. "Object.keys(map)"
  780. )};
  781. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  782. webpackAsyncContext.id = ${JSON.stringify(id)};
  783. module.exports = webpackAsyncContext;`;
  784. }
  785. /**
  786. * @param {Dependency[]} dependencies dependencies
  787. * @param {ModuleId} id module id
  788. * @param {object} context context
  789. * @param {ChunkGraph} context.chunkGraph the chunk graph
  790. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  791. * @returns {string} source code
  792. */
  793. getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  794. const arrow = runtimeTemplate.supportsArrowFunction();
  795. const map = this.getUserRequestMap(dependencies, chunkGraph);
  796. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  797. const thenFunction =
  798. fakeMap !== 9
  799. ? `${arrow ? "id =>" : "function(id)"} {
  800. ${this.getReturnModuleObjectSource(fakeMap, true)}
  801. }`
  802. : RuntimeGlobals.require;
  803. return `var map = ${JSON.stringify(map, null, "\t")};
  804. ${this.getFakeMapInitStatement(fakeMap)}
  805. function webpackAsyncContext(req) {
  806. return webpackAsyncContextResolve(req).then(${thenFunction});
  807. }
  808. function webpackAsyncContextResolve(req) {
  809. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  810. // uncaught exception popping up in devtools
  811. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  812. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  813. var e = new Error("Cannot find module '" + req + "'");
  814. e.code = 'MODULE_NOT_FOUND';
  815. throw e;
  816. }
  817. return map[req];
  818. });
  819. }
  820. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  821. "Object.keys(map)"
  822. )};
  823. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  824. webpackAsyncContext.id = ${JSON.stringify(id)};
  825. module.exports = webpackAsyncContext;`;
  826. }
  827. /**
  828. * @param {AsyncDependenciesBlock} block block
  829. * @param {Dependency[]} dependencies dependencies
  830. * @param {ModuleId} id module id
  831. * @param {object} options options object
  832. * @param {RuntimeTemplate} options.runtimeTemplate the runtime template
  833. * @param {ChunkGraph} options.chunkGraph the chunk graph
  834. * @returns {string} source code
  835. */
  836. getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) {
  837. const promise = runtimeTemplate.blockPromise({
  838. chunkGraph,
  839. block,
  840. message: "lazy-once context",
  841. runtimeRequirements: new Set()
  842. });
  843. const arrow = runtimeTemplate.supportsArrowFunction();
  844. const map = this.getUserRequestMap(dependencies, chunkGraph);
  845. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  846. const thenFunction =
  847. fakeMap !== 9
  848. ? `${arrow ? "id =>" : "function(id)"} {
  849. ${this.getReturnModuleObjectSource(fakeMap, true)};
  850. }`
  851. : RuntimeGlobals.require;
  852. return `var map = ${JSON.stringify(map, null, "\t")};
  853. ${this.getFakeMapInitStatement(fakeMap)}
  854. function webpackAsyncContext(req) {
  855. return webpackAsyncContextResolve(req).then(${thenFunction});
  856. }
  857. function webpackAsyncContextResolve(req) {
  858. return ${promise}.then(${arrow ? "() =>" : "function()"} {
  859. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  860. var e = new Error("Cannot find module '" + req + "'");
  861. e.code = 'MODULE_NOT_FOUND';
  862. throw e;
  863. }
  864. return map[req];
  865. });
  866. }
  867. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  868. "Object.keys(map)"
  869. )};
  870. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  871. webpackAsyncContext.id = ${JSON.stringify(id)};
  872. module.exports = webpackAsyncContext;`;
  873. }
  874. /**
  875. * @param {AsyncDependenciesBlock[]} blocks blocks
  876. * @param {ModuleId} id module id
  877. * @param {object} context context
  878. * @param {ChunkGraph} context.chunkGraph the chunk graph
  879. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  880. * @returns {string} source code
  881. */
  882. getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) {
  883. const moduleGraph = chunkGraph.moduleGraph;
  884. const arrow = runtimeTemplate.supportsArrowFunction();
  885. let hasMultipleOrNoChunks = false;
  886. let hasNoChunk = true;
  887. const fakeMap = this.getFakeMap(
  888. blocks.map((b) => b.dependencies[0]),
  889. chunkGraph
  890. );
  891. const hasFakeMap = typeof fakeMap === "object";
  892. /** @typedef {{userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock}} Item */
  893. /**
  894. * @type {Item[]}
  895. */
  896. const items = blocks
  897. .map((block) => {
  898. const dependency =
  899. /** @type {ContextElementDependency} */
  900. (block.dependencies[0]);
  901. return {
  902. dependency,
  903. module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
  904. block,
  905. userRequest: dependency.userRequest,
  906. chunks: undefined
  907. };
  908. })
  909. .filter((item) => item.module);
  910. for (const item of items) {
  911. const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
  912. const chunks = (chunkGroup && chunkGroup.chunks) || [];
  913. item.chunks = chunks;
  914. if (chunks.length > 0) {
  915. hasNoChunk = false;
  916. }
  917. if (chunks.length !== 1) {
  918. hasMultipleOrNoChunks = true;
  919. }
  920. }
  921. const shortMode = hasNoChunk && !hasFakeMap;
  922. const sortedItems = items.sort((a, b) => {
  923. if (a.userRequest === b.userRequest) return 0;
  924. return a.userRequest < b.userRequest ? -1 : 1;
  925. });
  926. /** @type {Record<string, ModuleId | (ModuleId[] | ChunkId[])>} */
  927. const map = Object.create(null);
  928. for (const item of sortedItems) {
  929. const moduleId =
  930. /** @type {ModuleId} */
  931. (chunkGraph.getModuleId(item.module));
  932. if (shortMode) {
  933. map[item.userRequest] = moduleId;
  934. } else {
  935. /** @type {(ModuleId | ChunkId)[]} */
  936. const arrayStart = [moduleId];
  937. if (hasFakeMap) {
  938. arrayStart.push(fakeMap[moduleId]);
  939. }
  940. map[item.userRequest] = [
  941. ...arrayStart,
  942. .../** @type {Chunk[]} */
  943. (item.chunks).map((chunk) => /** @type {ChunkId} */ (chunk.id))
  944. ];
  945. }
  946. }
  947. const chunksStartPosition = hasFakeMap ? 2 : 1;
  948. const requestPrefix = hasNoChunk
  949. ? "Promise.resolve()"
  950. : hasMultipleOrNoChunks
  951. ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
  952. : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
  953. const returnModuleObject = this.getReturnModuleObjectSource(
  954. fakeMap,
  955. true,
  956. shortMode ? "invalid" : "ids[1]"
  957. );
  958. const webpackAsyncContext =
  959. requestPrefix === "Promise.resolve()"
  960. ? `
  961. function webpackAsyncContext(req) {
  962. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  963. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  964. var e = new Error("Cannot find module '" + req + "'");
  965. e.code = 'MODULE_NOT_FOUND';
  966. throw e;
  967. }
  968. ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"}
  969. ${returnModuleObject}
  970. });
  971. }`
  972. : `function webpackAsyncContext(req) {
  973. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  974. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  975. var e = new Error("Cannot find module '" + req + "'");
  976. e.code = 'MODULE_NOT_FOUND';
  977. throw e;
  978. });
  979. }
  980. var ids = map[req], id = ids[0];
  981. return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} {
  982. ${returnModuleObject}
  983. });
  984. }`;
  985. return `var map = ${JSON.stringify(map, null, "\t")};
  986. ${webpackAsyncContext}
  987. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  988. "Object.keys(map)"
  989. )};
  990. webpackAsyncContext.id = ${JSON.stringify(id)};
  991. module.exports = webpackAsyncContext;`;
  992. }
  993. /**
  994. * @param {ModuleId} id module id
  995. * @param {RuntimeTemplate} runtimeTemplate runtime template
  996. * @returns {string} source for empty async context
  997. */
  998. getSourceForEmptyContext(id, runtimeTemplate) {
  999. return `function webpackEmptyContext(req) {
  1000. var e = new Error("Cannot find module '" + req + "'");
  1001. e.code = 'MODULE_NOT_FOUND';
  1002. throw e;
  1003. }
  1004. webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1005. webpackEmptyContext.resolve = webpackEmptyContext;
  1006. webpackEmptyContext.id = ${JSON.stringify(id)};
  1007. module.exports = webpackEmptyContext;`;
  1008. }
  1009. /**
  1010. * @param {ModuleId} id module id
  1011. * @param {RuntimeTemplate} runtimeTemplate runtime template
  1012. * @returns {string} source for empty async context
  1013. */
  1014. getSourceForEmptyAsyncContext(id, runtimeTemplate) {
  1015. const arrow = runtimeTemplate.supportsArrowFunction();
  1016. return `function webpackEmptyAsyncContext(req) {
  1017. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  1018. // uncaught exception popping up in devtools
  1019. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  1020. var e = new Error("Cannot find module '" + req + "'");
  1021. e.code = 'MODULE_NOT_FOUND';
  1022. throw e;
  1023. });
  1024. }
  1025. webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1026. webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
  1027. webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
  1028. module.exports = webpackEmptyAsyncContext;`;
  1029. }
  1030. /**
  1031. * @param {string} asyncMode module mode
  1032. * @param {CodeGenerationContext} context context info
  1033. * @returns {string} the source code
  1034. */
  1035. getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
  1036. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
  1037. if (asyncMode === "lazy") {
  1038. if (this.blocks && this.blocks.length > 0) {
  1039. return this.getLazySource(this.blocks, id, {
  1040. runtimeTemplate,
  1041. chunkGraph
  1042. });
  1043. }
  1044. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1045. }
  1046. if (asyncMode === "eager") {
  1047. if (this.dependencies && this.dependencies.length > 0) {
  1048. return this.getEagerSource(this.dependencies, id, {
  1049. chunkGraph,
  1050. runtimeTemplate
  1051. });
  1052. }
  1053. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1054. }
  1055. if (asyncMode === "lazy-once") {
  1056. const block = this.blocks[0];
  1057. if (block) {
  1058. return this.getLazyOnceSource(block, block.dependencies, id, {
  1059. runtimeTemplate,
  1060. chunkGraph
  1061. });
  1062. }
  1063. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1064. }
  1065. if (asyncMode === "async-weak") {
  1066. if (this.dependencies && this.dependencies.length > 0) {
  1067. return this.getAsyncWeakSource(this.dependencies, id, {
  1068. chunkGraph,
  1069. runtimeTemplate
  1070. });
  1071. }
  1072. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1073. }
  1074. if (
  1075. asyncMode === "weak" &&
  1076. this.dependencies &&
  1077. this.dependencies.length > 0
  1078. ) {
  1079. return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
  1080. }
  1081. if (this.dependencies && this.dependencies.length > 0) {
  1082. return this.getSyncSource(this.dependencies, id, chunkGraph);
  1083. }
  1084. return this.getSourceForEmptyContext(id, runtimeTemplate);
  1085. }
  1086. /**
  1087. * @param {string} sourceString source content
  1088. * @param {Compilation=} compilation the compilation
  1089. * @returns {Source} generated source
  1090. */
  1091. getSource(sourceString, compilation) {
  1092. if (this.useSourceMap || this.useSimpleSourceMap) {
  1093. return new OriginalSource(
  1094. sourceString,
  1095. `webpack://${makePathsRelative(
  1096. (compilation && compilation.compiler.context) || "",
  1097. this.identifier(),
  1098. compilation && compilation.compiler.root
  1099. )}`
  1100. );
  1101. }
  1102. return new RawSource(sourceString);
  1103. }
  1104. /**
  1105. * @param {CodeGenerationContext} context context for code generation
  1106. * @returns {CodeGenerationResult} result
  1107. */
  1108. codeGeneration(context) {
  1109. const { chunkGraph, compilation } = context;
  1110. const sources = new Map();
  1111. sources.set(
  1112. "javascript",
  1113. this.getSource(
  1114. this.getSourceString(this.options.mode, context),
  1115. compilation
  1116. )
  1117. );
  1118. const set = new Set();
  1119. const allDeps =
  1120. this.dependencies.length > 0
  1121. ? /** @type {ContextElementDependency[]} */ [...this.dependencies]
  1122. : [];
  1123. for (const block of this.blocks) {
  1124. for (const dep of block.dependencies) {
  1125. allDeps.push(/** @type {ContextElementDependency} */ (dep));
  1126. }
  1127. }
  1128. set.add(RuntimeGlobals.module);
  1129. set.add(RuntimeGlobals.hasOwnProperty);
  1130. if (allDeps.length > 0) {
  1131. const asyncMode = this.options.mode;
  1132. set.add(RuntimeGlobals.require);
  1133. if (asyncMode === "weak") {
  1134. set.add(RuntimeGlobals.moduleFactories);
  1135. } else if (asyncMode === "async-weak") {
  1136. set.add(RuntimeGlobals.moduleFactories);
  1137. set.add(RuntimeGlobals.ensureChunk);
  1138. } else if (asyncMode === "lazy" || asyncMode === "lazy-once") {
  1139. set.add(RuntimeGlobals.ensureChunk);
  1140. }
  1141. if (this.getFakeMap(allDeps, chunkGraph) !== 9) {
  1142. set.add(RuntimeGlobals.createFakeNamespaceObject);
  1143. }
  1144. }
  1145. return {
  1146. sources,
  1147. runtimeRequirements: set
  1148. };
  1149. }
  1150. /**
  1151. * @param {string=} type the source type for which the size should be estimated
  1152. * @returns {number} the estimated size of the module (must be non-zero)
  1153. */
  1154. size(type) {
  1155. // base penalty
  1156. let size = 160;
  1157. // if we don't have dependencies we stop here.
  1158. for (const dependency of this.dependencies) {
  1159. const element = /** @type {ContextElementDependency} */ (dependency);
  1160. size += 5 + element.userRequest.length;
  1161. }
  1162. return size;
  1163. }
  1164. /**
  1165. * @param {ObjectSerializerContext} context context
  1166. */
  1167. serialize(context) {
  1168. const { write } = context;
  1169. write(this._identifier);
  1170. write(this._forceBuild);
  1171. super.serialize(context);
  1172. }
  1173. /**
  1174. * @param {ObjectDeserializerContext} context context
  1175. */
  1176. deserialize(context) {
  1177. const { read } = context;
  1178. this._identifier = read();
  1179. this._forceBuild = read();
  1180. super.deserialize(context);
  1181. }
  1182. }
  1183. makeSerializable(ContextModule, "webpack/lib/ContextModule");
  1184. module.exports = ContextModule;