ContainerEntryModule.js 8.7 KB

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