ContainerEntryModule.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
  4. */
  5. "use strict";
  6. const { OriginalSource, RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const Module = require("../Module");
  9. const {
  10. JAVASCRIPT_TYPE,
  11. JAVASCRIPT_TYPES
  12. } = require("../ModuleSourceTypeConstants");
  13. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("../ModuleTypeConstants");
  14. const RuntimeGlobals = require("../RuntimeGlobals");
  15. const Template = require("../Template");
  16. const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
  17. const makeSerializable = require("../util/makeSerializable");
  18. const ContainerExposedDependency = require("./ContainerExposedDependency");
  19. /**
  20. * @import {
  21. * WebpackOptionsNormalizedWithDefaults as WebpackOptions
  22. * } from "../config/defaults"
  23. */
  24. /** @import Compilation from "../Compilation" */
  25. /**
  26. * @import {
  27. * BuildCallback,
  28. * CodeGenerationContext,
  29. * CodeGenerationResult,
  30. * LibIdentOptions,
  31. * LibIdent,
  32. * NeedBuildCallback,
  33. * NeedBuildContext,
  34. * Sources,
  35. * SourceTypes
  36. * } from "../Module"
  37. */
  38. /** @import RequestShortener from "../RequestShortener" */
  39. /** @import { ResolverWithOptions } from "../ResolverFactory" */
  40. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<[string, ExposesList, string]>} ObjectDeserializerContext */
  41. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<[string, ExposesList, string]>} ObjectSerializerContext */
  42. /** @import { InputFileSystem } from "../util/fs" */
  43. /**
  44. * Defines the expose options type used by this module.
  45. * @typedef {object} ExposeOptions
  46. * @property {string[]} import requests to exposed modules (last one is exported)
  47. * @property {string} name custom chunk name for the exposed module
  48. */
  49. /** @typedef {[string, ExposeOptions][]} ExposesList */
  50. class ContainerEntryModule extends Module {
  51. /**
  52. * Creates an instance of ContainerEntryModule.
  53. * @param {string} name container entry name
  54. * @param {ExposesList} exposes list of exposed modules
  55. * @param {string} shareScope name of the share scope
  56. */
  57. constructor(name, exposes, shareScope) {
  58. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
  59. /** @type {string} */
  60. this._name = name;
  61. /** @type {ExposesList} */
  62. this._exposes = exposes;
  63. /** @type {string} */
  64. this._shareScope = shareScope;
  65. }
  66. /**
  67. * Returns the source types this module can generate.
  68. * @returns {SourceTypes} types available (do not mutate)
  69. */
  70. getSourceTypes() {
  71. return JAVASCRIPT_TYPES;
  72. }
  73. /**
  74. * Returns the unique identifier used to reference this module.
  75. * @returns {string} a unique identifier of the module
  76. */
  77. identifier() {
  78. return `container entry (${this._shareScope}) ${JSON.stringify(
  79. this._exposes
  80. )}`;
  81. }
  82. /**
  83. * Returns a human-readable identifier for this module.
  84. * @param {RequestShortener} requestShortener the request shortener
  85. * @returns {string} a user readable identifier of the module
  86. */
  87. readableIdentifier(requestShortener) {
  88. return "container entry";
  89. }
  90. /**
  91. * Gets the library identifier.
  92. * @param {LibIdentOptions} options options
  93. * @returns {LibIdent | null} an identifier for library inclusion
  94. */
  95. libIdent(options) {
  96. return `${this.layer ? `(${this.layer})/` : ""}webpack/container/entry/${
  97. this._name
  98. }`;
  99. }
  100. /**
  101. * Checks whether the module needs to be rebuilt for the current build state.
  102. * @param {NeedBuildContext} context context info
  103. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  104. * @returns {void}
  105. */
  106. needBuild(context, callback) {
  107. return callback(null, !this.buildMeta);
  108. }
  109. /**
  110. * Builds the module using the provided compilation context.
  111. * @param {WebpackOptions} options webpack options
  112. * @param {Compilation} compilation the compilation
  113. * @param {ResolverWithOptions} resolver the resolver
  114. * @param {InputFileSystem} fs the file system
  115. * @param {BuildCallback} callback callback function
  116. * @returns {void}
  117. */
  118. build(options, compilation, resolver, fs, callback) {
  119. this.buildMeta = {};
  120. this.buildInfo = {
  121. strict: true,
  122. topLevelDeclarations: new Set(["moduleMap", "get", "init"])
  123. };
  124. this.buildMeta.exportsType = "namespace";
  125. this.clearDependenciesAndBlocks();
  126. for (const [name, options] of this._exposes) {
  127. const block = new AsyncDependenciesBlock(
  128. {
  129. name: options.name
  130. },
  131. { name },
  132. options.import[options.import.length - 1]
  133. );
  134. let idx = 0;
  135. for (const request of options.import) {
  136. const dep = new ContainerExposedDependency(name, request);
  137. dep.loc = {
  138. name,
  139. index: idx++
  140. };
  141. block.addDependency(dep);
  142. }
  143. this.addBlock(block);
  144. }
  145. this.addDependency(new StaticExportsDependency(["get", "init"], false));
  146. callback();
  147. }
  148. /**
  149. * Generates code and runtime requirements for this module.
  150. * @param {CodeGenerationContext} context context for code generation
  151. * @returns {CodeGenerationResult} result
  152. */
  153. codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) {
  154. /** @type {Sources} */
  155. const sources = new Map();
  156. const runtimeRequirements = new Set([
  157. RuntimeGlobals.definePropertyGetters,
  158. RuntimeGlobals.hasOwnProperty,
  159. RuntimeGlobals.exports
  160. ]);
  161. /** @type {string[]} */
  162. const getters = [];
  163. for (const block of this.blocks) {
  164. const { dependencies } = block;
  165. const modules = dependencies.map((dependency) => {
  166. const dep = /** @type {ContainerExposedDependency} */ (dependency);
  167. return {
  168. name: dep.exposedName,
  169. module: moduleGraph.getModule(dep),
  170. request: dep.userRequest
  171. };
  172. });
  173. /** @type {string} */
  174. let str;
  175. if (modules.some((m) => !m.module)) {
  176. str = runtimeTemplate.throwMissingModuleErrorBlock({
  177. request: modules.map((m) => m.request).join(", ")
  178. });
  179. } else {
  180. str = `return ${runtimeTemplate.blockPromise({
  181. block,
  182. message: "",
  183. chunkGraph,
  184. runtimeRequirements,
  185. originModule: this
  186. })}.then(${runtimeTemplate.returningFunction(
  187. runtimeTemplate.returningFunction(
  188. `(${modules
  189. .map(({ module, request }) =>
  190. runtimeTemplate.moduleRaw({
  191. module,
  192. chunkGraph,
  193. request,
  194. weak: false,
  195. runtimeRequirements
  196. })
  197. )
  198. .join(", ")})`
  199. )
  200. )});`;
  201. }
  202. getters.push(
  203. `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction(
  204. "",
  205. str
  206. )}`
  207. );
  208. }
  209. const cst = runtimeTemplate.renderConst();
  210. const source = Template.asString([
  211. `${cst} moduleMap = {`,
  212. Template.indent(getters.join(",\n")),
  213. "};",
  214. `${cst} get = ${runtimeTemplate.basicFunction("module, getScope", [
  215. `${RuntimeGlobals.currentRemoteGetScope} = getScope;`,
  216. // reusing the getScope variable to avoid creating a new var (and module is also used later)
  217. "getScope = (",
  218. Template.indent([
  219. `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`,
  220. Template.indent([
  221. "? moduleMap[module]()",
  222. `: Promise.resolve().then(${runtimeTemplate.basicFunction(
  223. "",
  224. "throw new Error('Module \"' + module + '\" does not exist in container.');"
  225. )})`
  226. ])
  227. ]),
  228. ");",
  229. `${RuntimeGlobals.currentRemoteGetScope} = undefined;`,
  230. "return getScope;"
  231. ])};`,
  232. `${cst} init = ${runtimeTemplate.basicFunction("shareScope, initScope", [
  233. `if (!${RuntimeGlobals.shareScopeMap}) return;`,
  234. `${cst} name = ${JSON.stringify(this._shareScope)}`,
  235. `${cst} oldScope = ${RuntimeGlobals.shareScopeMap}[name];`,
  236. 'if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");',
  237. `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`,
  238. `return ${RuntimeGlobals.initializeSharing}(name, initScope);`
  239. ])};`,
  240. "",
  241. "// This exports getters to disallow modifications",
  242. `${RuntimeGlobals.definePropertyGetters}(exports, {`,
  243. Template.indent([
  244. `get: ${runtimeTemplate.returningFunction("get")},`,
  245. `init: ${runtimeTemplate.returningFunction("init")}`
  246. ]),
  247. "});"
  248. ]);
  249. sources.set(
  250. JAVASCRIPT_TYPE,
  251. this.useSourceMap || this.useSimpleSourceMap
  252. ? new OriginalSource(source, "webpack/container-entry")
  253. : new RawSource(source)
  254. );
  255. return {
  256. sources,
  257. runtimeRequirements
  258. };
  259. }
  260. /**
  261. * Returns the estimated size for the requested source type.
  262. * @param {string=} type the source type for which the size should be estimated
  263. * @returns {number} the estimated size of the module (must be non-zero)
  264. */
  265. size(type) {
  266. return 42;
  267. }
  268. /**
  269. * Serializes this instance into the provided serializer context.
  270. * @param {ObjectSerializerContext} context context
  271. */
  272. serialize(context) {
  273. context.write(this._name).write(this._exposes).write(this._shareScope);
  274. super.serialize(context);
  275. }
  276. /**
  277. * Restores this instance from the provided deserializer context.
  278. * @param {ObjectDeserializerContext} context context
  279. * @returns {ContainerEntryModule} deserialized container entry module
  280. */
  281. static deserialize(context) {
  282. const name = context.read();
  283. const c1 = context.rest;
  284. const exposes = c1.read();
  285. const c2 = c1.rest;
  286. const obj = new ContainerEntryModule(name, exposes, c2.read());
  287. obj.deserialize(c2.rest);
  288. return obj;
  289. }
  290. }
  291. makeSerializable(
  292. ContainerEntryModule,
  293. "webpack/lib/container/ContainerEntryModule"
  294. );
  295. module.exports = ContainerEntryModule;