ConsumeSharedModule.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const Module = require("../Module");
  9. const {
  10. CONSUME_SHARED_TYPES,
  11. JAVASCRIPT_TYPES
  12. } = require("../ModuleSourceTypeConstants");
  13. const {
  14. WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE
  15. } = require("../ModuleTypeConstants");
  16. const RuntimeGlobals = require("../RuntimeGlobals");
  17. const makeSerializable = require("../util/makeSerializable");
  18. const { rangeToString, stringifyHoley } = require("../util/semver");
  19. const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependency");
  20. /** @type {WeakMap<ModuleGraph, WeakMap<ConsumeSharedModule, Module | null>>} */
  21. const fallbackModuleCache = new WeakMap();
  22. /** @typedef {import("../config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
  23. /** @typedef {import("../Compilation")} Compilation */
  24. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  25. /** @typedef {import("../Module").BuildCallback} BuildCallback */
  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").SourceTypes} SourceTypes */
  34. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  35. /** @typedef {import("../Module").ExportsType} ExportsType */
  36. /** @typedef {import("../RequestShortener")} RequestShortener */
  37. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  38. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  39. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  40. /** @typedef {import("../util/Hash")} Hash */
  41. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  42. /** @typedef {import("../util/semver").SemVerRange} SemVerRange */
  43. /** @typedef {import("../Module").BasicSourceTypes} BasicSourceTypes */
  44. /**
  45. * Represents the consume shared module runtime component.
  46. * @typedef {object} ConsumeOptions
  47. * @property {string=} import fallback request
  48. * @property {string=} importResolved resolved fallback request
  49. * @property {string} shareKey global share key
  50. * @property {string} shareScope share scope
  51. * @property {SemVerRange | false | undefined} requiredVersion version requirement
  52. * @property {string=} packageName package name to determine required version automatically
  53. * @property {boolean} strictVersion don't use shared version even if version isn't valid
  54. * @property {boolean} singleton use single global version
  55. * @property {boolean} eager include the fallback module in a sync way
  56. */
  57. class ConsumeSharedModule extends Module {
  58. /**
  59. * Creates an instance of ConsumeSharedModule.
  60. * @param {string} context context
  61. * @param {ConsumeOptions} options consume options
  62. */
  63. constructor(context, options) {
  64. super(WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE, context);
  65. this.options = options;
  66. }
  67. /**
  68. * Returns the unique identifier used to reference this module.
  69. * @returns {string} a unique identifier of the module
  70. */
  71. identifier() {
  72. const {
  73. shareKey,
  74. shareScope,
  75. importResolved,
  76. requiredVersion,
  77. strictVersion,
  78. singleton,
  79. eager
  80. } = this.options;
  81. return `${WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE}|${shareScope}|${shareKey}|${
  82. requiredVersion && rangeToString(requiredVersion)
  83. }|${strictVersion}|${importResolved}|${singleton}|${eager}`;
  84. }
  85. /**
  86. * Returns a human-readable identifier for this module.
  87. * @param {RequestShortener} requestShortener the request shortener
  88. * @returns {string} a user readable identifier of the module
  89. */
  90. readableIdentifier(requestShortener) {
  91. const {
  92. shareKey,
  93. shareScope,
  94. importResolved,
  95. requiredVersion,
  96. strictVersion,
  97. singleton,
  98. eager
  99. } = this.options;
  100. return `consume shared module (${shareScope}) ${shareKey}@${
  101. requiredVersion ? rangeToString(requiredVersion) : "*"
  102. }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${
  103. importResolved
  104. ? ` (fallback: ${requestShortener.shorten(importResolved)})`
  105. : ""
  106. }${eager ? " (eager)" : ""}`;
  107. }
  108. /**
  109. * Gets the library identifier.
  110. * @param {LibIdentOptions} options options
  111. * @returns {LibIdent | null} an identifier for library inclusion
  112. */
  113. libIdent(options) {
  114. const { shareKey, shareScope, import: request } = this.options;
  115. return `${
  116. this.layer ? `(${this.layer})/` : ""
  117. }webpack/sharing/consume/${shareScope}/${shareKey}${
  118. request ? `/${request}` : ""
  119. }`;
  120. }
  121. /**
  122. * Checks whether the module needs to be rebuilt for the current build state.
  123. * @param {NeedBuildContext} context context info
  124. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  125. * @returns {void}
  126. */
  127. needBuild(context, callback) {
  128. callback(null, !this.buildInfo);
  129. }
  130. /**
  131. * Builds the module using the provided compilation context.
  132. * @param {WebpackOptions} options webpack options
  133. * @param {Compilation} compilation the compilation
  134. * @param {ResolverWithOptions} resolver the resolver
  135. * @param {InputFileSystem} fs the file system
  136. * @param {BuildCallback} callback callback function
  137. * @returns {void}
  138. */
  139. build(options, compilation, resolver, fs, callback) {
  140. this.buildMeta = {};
  141. this.buildInfo = {};
  142. if (this.options.import) {
  143. const dep = new ConsumeSharedFallbackDependency(this.options.import);
  144. if (this.options.eager) {
  145. this.addDependency(dep);
  146. } else {
  147. const block = new AsyncDependenciesBlock({});
  148. block.addDependency(dep);
  149. this.addBlock(block);
  150. }
  151. }
  152. callback();
  153. }
  154. /**
  155. * Returns the source types this module can generate.
  156. * @returns {SourceTypes} types available (do not mutate)
  157. */
  158. getSourceTypes() {
  159. return CONSUME_SHARED_TYPES;
  160. }
  161. /**
  162. * Basic source types are high-level categories like javascript, css, webassembly, etc.
  163. * We only have built-in knowledge about the javascript basic type here; other basic types may be
  164. * added or changed over time by generators and do not need to be handled or detected here.
  165. *
  166. * Some modules, e.g. RemoteModule, may return non-basic source types like "remote" and "share-init"
  167. * from getSourceTypes(), but their generated output is still JavaScript, i.e. their basic type is JS.
  168. * @returns {BasicSourceTypes} types available (do not mutate)
  169. */
  170. getSourceBasicTypes() {
  171. return JAVASCRIPT_TYPES;
  172. }
  173. /**
  174. * Get fallback module.
  175. * @param {ModuleGraph} moduleGraph the module graph
  176. * @returns {Module | null} fallback module
  177. */
  178. _getFallbackModule(moduleGraph) {
  179. let moduleCache = fallbackModuleCache.get(moduleGraph);
  180. if (!moduleCache) {
  181. moduleCache = new WeakMap();
  182. fallbackModuleCache.set(moduleGraph, moduleCache);
  183. }
  184. const cached = moduleCache.get(this);
  185. if (cached !== undefined) {
  186. return cached;
  187. }
  188. /** @type {undefined | null | Module} */
  189. let fallbackModule = null;
  190. if (this.options.import) {
  191. if (this.options.eager) {
  192. const dep = this.dependencies[0];
  193. if (dep) {
  194. fallbackModule = moduleGraph.getModule(dep);
  195. }
  196. } else {
  197. const block = this.blocks[0];
  198. if (block && block.dependencies.length > 0) {
  199. fallbackModule = moduleGraph.getModule(block.dependencies[0]);
  200. }
  201. }
  202. }
  203. moduleCache.set(this, fallbackModule);
  204. return fallbackModule;
  205. }
  206. /**
  207. * Returns export type.
  208. * @param {ModuleGraph} moduleGraph the module graph
  209. * @param {boolean | undefined} strict the importing module is strict
  210. * @returns {ExportsType} export type
  211. * "namespace": Exports is already a namespace object. namespace = exports.
  212. * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }.
  213. * "default-only": Provide a namespace object with only default export. namespace = { default: exports }
  214. * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports }
  215. */
  216. getExportsType(moduleGraph, strict) {
  217. const fallbackModule = this._getFallbackModule(moduleGraph);
  218. if (!fallbackModule) return "dynamic";
  219. return fallbackModule.getExportsType(moduleGraph, strict);
  220. }
  221. /**
  222. * Returns the estimated size for the requested source type.
  223. * @param {string=} type the source type for which the size should be estimated
  224. * @returns {number} the estimated size of the module (must be non-zero)
  225. */
  226. size(type) {
  227. return 42;
  228. }
  229. /**
  230. * Updates the hash with the data contributed by this instance.
  231. * @param {Hash} hash the hash used to track dependencies
  232. * @param {UpdateHashContext} context context
  233. * @returns {void}
  234. */
  235. updateHash(hash, context) {
  236. hash.update(JSON.stringify(this.options));
  237. super.updateHash(hash, context);
  238. }
  239. /**
  240. * Generates code and runtime requirements for this module.
  241. * @param {CodeGenerationContext} context context for code generation
  242. * @returns {CodeGenerationResult} result
  243. */
  244. codeGeneration({ chunkGraph, runtimeTemplate }) {
  245. const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]);
  246. const {
  247. shareScope,
  248. shareKey,
  249. strictVersion,
  250. requiredVersion,
  251. import: request,
  252. singleton,
  253. eager
  254. } = this.options;
  255. /** @type {undefined | string} */
  256. let fallbackCode;
  257. if (request) {
  258. if (eager) {
  259. const dep = this.dependencies[0];
  260. fallbackCode = runtimeTemplate.syncModuleFactory({
  261. dependency: dep,
  262. chunkGraph,
  263. runtimeRequirements,
  264. request: this.options.import
  265. });
  266. } else {
  267. const block = this.blocks[0];
  268. fallbackCode = runtimeTemplate.asyncModuleFactory({
  269. block,
  270. chunkGraph,
  271. runtimeRequirements,
  272. request: this.options.import
  273. });
  274. }
  275. }
  276. const args = [
  277. JSON.stringify(shareScope),
  278. JSON.stringify(shareKey),
  279. JSON.stringify(eager)
  280. ];
  281. if (requiredVersion) {
  282. args.push(stringifyHoley(requiredVersion));
  283. }
  284. if (fallbackCode) {
  285. args.push(fallbackCode);
  286. }
  287. /** @type {string} */
  288. let fn;
  289. if (requiredVersion) {
  290. if (strictVersion) {
  291. fn = singleton ? "loadStrictSingletonVersion" : "loadStrictVersion";
  292. } else {
  293. fn = singleton ? "loadSingletonVersion" : "loadVersion";
  294. }
  295. } else {
  296. fn = singleton ? "loadSingleton" : "load";
  297. }
  298. const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`);
  299. /** @type {Sources} */
  300. const sources = new Map();
  301. sources.set("consume-shared", new RawSource(code));
  302. return {
  303. runtimeRequirements,
  304. sources
  305. };
  306. }
  307. /**
  308. * Serializes this instance into the provided serializer context.
  309. * @param {ObjectSerializerContext} context context
  310. */
  311. serialize(context) {
  312. const { write } = context;
  313. write(this.options);
  314. super.serialize(context);
  315. }
  316. /**
  317. * Restores this instance from the provided deserializer context.
  318. * @param {ObjectDeserializerContext} context context
  319. */
  320. deserialize(context) {
  321. const { read } = context;
  322. this.options = read();
  323. super.deserialize(context);
  324. }
  325. }
  326. makeSerializable(
  327. ConsumeSharedModule,
  328. "webpack/lib/sharing/ConsumeSharedModule"
  329. );
  330. module.exports = ConsumeSharedModule;