ContainerEntryModule.js 8.2 KB

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