ContextModule.js 35 KB

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