ContainerEntryModule.js 8.8 KB

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