ContainerEntryModule.js 8.9 KB

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