DelegatedModule.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 Module = require("./Module");
  8. const {
  9. JAVASCRIPT_TYPE,
  10. JAVASCRIPT_TYPES
  11. } = require("./ModuleSourceTypeConstants");
  12. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
  13. const RuntimeGlobals = require("./RuntimeGlobals");
  14. const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
  15. const StaticExportsDependency = require("./dependencies/StaticExportsDependency");
  16. const makeSerializable = require("./util/makeSerializable");
  17. /** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
  18. /** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
  19. /** @typedef {import("./Compilation")} Compilation */
  20. /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
  21. /** @typedef {import("./Generator").SourceTypes} SourceTypes */
  22. /** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */
  23. /** @typedef {import("./Module").ModuleId} ModuleId */
  24. /** @typedef {import("./Module").BuildCallback} BuildCallback */
  25. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  26. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  27. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  28. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  29. /** @typedef {import("./Module").LibIdent} LibIdent */
  30. /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
  31. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  32. /** @typedef {import("./Module").Sources} Sources */
  33. /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
  34. /** @typedef {import("./RequestShortener")} RequestShortener */
  35. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  36. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  37. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  38. /** @typedef {import("./dependencies/StaticExportsDependency").Exports} Exports */
  39. /** @typedef {import("./util/Hash")} Hash */
  40. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  41. /** @typedef {string} DelegatedModuleSourceRequest */
  42. /** @typedef {NonNullable<DllReferencePluginOptions["type"]>} DelegatedModuleType */
  43. /**
  44. * Defines the delegated module data type used by this module.
  45. * @typedef {object} DelegatedModuleData
  46. * @property {BuildMeta=} buildMeta build meta
  47. * @property {Exports=} exports exports
  48. * @property {ModuleId} id module id
  49. */
  50. const RUNTIME_REQUIREMENTS = new Set([
  51. RuntimeGlobals.module,
  52. RuntimeGlobals.require
  53. ]);
  54. class DelegatedModule extends Module {
  55. /**
  56. * Creates an instance of DelegatedModule.
  57. * @param {DelegatedModuleSourceRequest} sourceRequest source request
  58. * @param {DelegatedModuleData} data data
  59. * @param {DelegatedModuleType} type type
  60. * @param {string} userRequest user request
  61. * @param {string | Module} originalRequest original request
  62. */
  63. constructor(sourceRequest, data, type, userRequest, originalRequest) {
  64. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
  65. // Info from Factory
  66. this.sourceRequest = sourceRequest;
  67. this.request = data.id;
  68. this.delegationType = type;
  69. this.userRequest = userRequest;
  70. this.originalRequest = originalRequest;
  71. this.delegateData = data;
  72. // Build info
  73. /** @type {undefined | DelegatedSourceDependency} */
  74. this.delegatedSourceDependency = undefined;
  75. }
  76. /**
  77. * Returns the source types this module can generate.
  78. * @returns {SourceTypes} types available (do not mutate)
  79. */
  80. getSourceTypes() {
  81. return JAVASCRIPT_TYPES;
  82. }
  83. /**
  84. * Gets the library identifier.
  85. * @param {LibIdentOptions} options options
  86. * @returns {LibIdent | null} an identifier for library inclusion
  87. */
  88. libIdent(options) {
  89. return typeof this.originalRequest === "string"
  90. ? this.originalRequest
  91. : this.originalRequest.libIdent(options);
  92. }
  93. /**
  94. * Returns the unique identifier used to reference this module.
  95. * @returns {string} a unique identifier of the module
  96. */
  97. identifier() {
  98. return `delegated ${JSON.stringify(this.request)} from ${
  99. this.sourceRequest
  100. }`;
  101. }
  102. /**
  103. * Returns a human-readable identifier for this module.
  104. * @param {RequestShortener} requestShortener the request shortener
  105. * @returns {string} a user readable identifier of the module
  106. */
  107. readableIdentifier(requestShortener) {
  108. return `delegated ${this.userRequest} from ${this.sourceRequest}`;
  109. }
  110. /**
  111. * Checks whether the module needs to be rebuilt for the current build state.
  112. * @param {NeedBuildContext} context context info
  113. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  114. * @returns {void}
  115. */
  116. needBuild(context, callback) {
  117. return callback(null, !this.buildMeta);
  118. }
  119. /**
  120. * Builds the module using the provided compilation context.
  121. * @param {WebpackOptions} options webpack options
  122. * @param {Compilation} compilation the compilation
  123. * @param {ResolverWithOptions} resolver the resolver
  124. * @param {InputFileSystem} fs the file system
  125. * @param {BuildCallback} callback callback function
  126. * @returns {void}
  127. */
  128. build(options, compilation, resolver, fs, callback) {
  129. const delegateData = /** @type {ManifestModuleData} */ (this.delegateData);
  130. this.buildMeta = { ...delegateData.buildMeta };
  131. this.buildInfo = {};
  132. this.dependencies.length = 0;
  133. this.delegatedSourceDependency = new DelegatedSourceDependency(
  134. this.sourceRequest
  135. );
  136. this.addDependency(this.delegatedSourceDependency);
  137. this.addDependency(
  138. new StaticExportsDependency(delegateData.exports || true, false)
  139. );
  140. callback();
  141. }
  142. /**
  143. * Generates code and runtime requirements for this module.
  144. * @param {CodeGenerationContext} context context for code generation
  145. * @returns {CodeGenerationResult} result
  146. */
  147. codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
  148. const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]);
  149. const sourceModule = moduleGraph.getModule(dep);
  150. /** @type {string} */
  151. let str;
  152. if (!sourceModule) {
  153. str = runtimeTemplate.throwMissingModuleErrorBlock({
  154. request: this.sourceRequest
  155. });
  156. } else {
  157. str = `module.exports = (${runtimeTemplate.moduleExports({
  158. module: sourceModule,
  159. chunkGraph,
  160. request: dep.request,
  161. /** @type {RuntimeRequirements} */
  162. runtimeRequirements: new Set()
  163. })})`;
  164. switch (this.delegationType) {
  165. case "require":
  166. str += `(${JSON.stringify(this.request)})`;
  167. break;
  168. case "object":
  169. str += `[${JSON.stringify(this.request)}]`;
  170. break;
  171. }
  172. str += ";";
  173. }
  174. /** @type {Sources} */
  175. const sources = new Map();
  176. if (this.useSourceMap || this.useSimpleSourceMap) {
  177. sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier()));
  178. } else {
  179. sources.set(JAVASCRIPT_TYPE, new RawSource(str));
  180. }
  181. return {
  182. sources,
  183. runtimeRequirements: RUNTIME_REQUIREMENTS
  184. };
  185. }
  186. /**
  187. * Returns the estimated size for the requested source type.
  188. * @param {string=} type the source type for which the size should be estimated
  189. * @returns {number} the estimated size of the module (must be non-zero)
  190. */
  191. size(type) {
  192. return 42;
  193. }
  194. /**
  195. * Updates the hash with the data contributed by this instance.
  196. * @param {Hash} hash the hash used to track dependencies
  197. * @param {UpdateHashContext} context context
  198. * @returns {void}
  199. */
  200. updateHash(hash, context) {
  201. hash.update(this.delegationType);
  202. hash.update(JSON.stringify(this.request));
  203. super.updateHash(hash, context);
  204. }
  205. /**
  206. * Serializes this instance into the provided serializer context.
  207. * @param {ObjectSerializerContext} context context
  208. */
  209. serialize(context) {
  210. const { write } = context;
  211. // constructor
  212. write(this.sourceRequest);
  213. write(this.delegateData);
  214. write(this.delegationType);
  215. write(this.userRequest);
  216. write(this.originalRequest);
  217. super.serialize(context);
  218. }
  219. /**
  220. * Restores this instance from the provided deserializer context.
  221. * @param {ObjectDeserializerContext} context context\
  222. * @returns {DelegatedModule} DelegatedModule
  223. */
  224. static deserialize(context) {
  225. const { read } = context;
  226. const obj = new DelegatedModule(
  227. read(), // sourceRequest
  228. read(), // delegateData
  229. read(), // delegationType
  230. read(), // userRequest
  231. read() // originalRequest
  232. );
  233. obj.deserialize(context);
  234. return obj;
  235. }
  236. /**
  237. * Assuming this module is in the cache. Update the (cached) module with
  238. * the fresh module from the factory. Usually updates internal references
  239. * and properties.
  240. * @param {Module} module fresh module
  241. * @returns {void}
  242. */
  243. updateCacheModule(module) {
  244. super.updateCacheModule(module);
  245. const m = /** @type {DelegatedModule} */ (module);
  246. this.delegationType = m.delegationType;
  247. this.userRequest = m.userRequest;
  248. this.originalRequest = m.originalRequest;
  249. this.delegateData = m.delegateData;
  250. }
  251. /**
  252. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  253. */
  254. cleanupForCache() {
  255. super.cleanupForCache();
  256. this.delegateData =
  257. /** @type {EXPECTED_ANY} */
  258. (undefined);
  259. }
  260. }
  261. makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule");
  262. module.exports = DelegatedModule;