RemoteRuntimeModule.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const RuntimeModule = require("../RuntimeModule");
  8. const Template = require("../Template");
  9. const { compareModulesByIdentifier } = require("../util/comparators");
  10. /** @import Chunk, { ChunkId } from "../Chunk" */
  11. /** @import ChunkGraph, { ModuleId } from "../ChunkGraph" */
  12. /** @import Compilation from "../Compilation" */
  13. /** @import RemoteModule from "./RemoteModule" */
  14. class RemoteRuntimeModule extends RuntimeModule {
  15. constructor() {
  16. super("remotes loading");
  17. }
  18. /**
  19. * Generates runtime code for this runtime module.
  20. * @returns {string | null} runtime code
  21. */
  22. generate() {
  23. const compilation = /** @type {Compilation} */ (this.compilation);
  24. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  25. const { runtimeTemplate, moduleGraph } = compilation;
  26. /** @type {Record<ChunkId, ModuleId[]>} */
  27. const chunkToRemotesMapping = {};
  28. /** @type {Record<ModuleId, [string, string, ModuleId]>} */
  29. const idToExternalAndNameMapping = {};
  30. for (const chunk of /** @type {Chunk} */ (
  31. this.chunk
  32. ).getAllReferencedChunks()) {
  33. // ordered explicitly: an unordered read reflects whichever comparator
  34. // last sorted the chunk's modules, which is not ours to depend on
  35. const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType(
  36. chunk,
  37. "remote",
  38. compareModulesByIdentifier
  39. );
  40. if (!modules) continue;
  41. /** @type {ModuleId[]} */
  42. const remotes = (chunkToRemotesMapping[
  43. /** @type {ChunkId} */
  44. (chunk.id)
  45. ] = []);
  46. for (const m of modules) {
  47. const module = /** @type {RemoteModule} */ (m);
  48. const name = module.internalRequest;
  49. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  50. const shareScope = module.shareScope;
  51. const dep = module.dependencies[0];
  52. const externalModule = moduleGraph.getModule(dep);
  53. const externalModuleId =
  54. /** @type {ModuleId} */
  55. (externalModule && chunkGraph.getModuleId(externalModule));
  56. remotes.push(id);
  57. idToExternalAndNameMapping[id] = [shareScope, name, externalModuleId];
  58. }
  59. }
  60. const cst = runtimeTemplate.renderConst();
  61. const lt = runtimeTemplate.renderLet();
  62. return Template.asString([
  63. `${cst} chunkMapping = ${JSON.stringify(
  64. chunkToRemotesMapping,
  65. null,
  66. "\t"
  67. )};`,
  68. `${cst} idToExternalAndNameMapping = ${JSON.stringify(
  69. idToExternalAndNameMapping,
  70. null,
  71. "\t"
  72. )};`,
  73. `${
  74. RuntimeGlobals.ensureChunkHandlers
  75. }.remotes = ${runtimeTemplate.basicFunction("chunkId, promises", [
  76. `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`,
  77. Template.indent([
  78. `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [
  79. `${lt} getScope = ${RuntimeGlobals.currentRemoteGetScope};`,
  80. "if(!getScope) getScope = [];",
  81. `${cst} data = idToExternalAndNameMapping[id];`,
  82. "if(getScope.indexOf(data) >= 0) return;",
  83. "getScope.push(data);",
  84. "if(data.p) return promises.push(data.p);",
  85. `${cst} onError = ${runtimeTemplate.basicFunction("error", [
  86. 'if(!error) error = new Error("Container missing");',
  87. 'if(typeof error.message === "string")',
  88. Template.indent(
  89. "error.message += '\\nwhile loading \"' + data[1] + '\" from ' + data[2];"
  90. ),
  91. `${
  92. RuntimeGlobals.moduleFactories
  93. }[id] = ${runtimeTemplate.basicFunction("", ["throw error;"])}`,
  94. "data.p = 0;"
  95. ])};`,
  96. `${cst} handleFunction = ${runtimeTemplate.basicFunction(
  97. "fn, arg1, arg2, d, next, first",
  98. [
  99. "try {",
  100. Template.indent([
  101. `${cst} promise = fn(arg1, arg2);`,
  102. `if(${runtimeTemplate.optionalChaining("promise", "then")}) {`,
  103. Template.indent([
  104. `${cst} p = promise.then(${runtimeTemplate.returningFunction(
  105. "next(result, d)",
  106. "result"
  107. )}, onError);`,
  108. "if(first) promises.push(data.p = p); else return p;"
  109. ]),
  110. "} else {",
  111. Template.indent(["return next(promise, d, first);"]),
  112. "}"
  113. ]),
  114. "} catch(error) {",
  115. Template.indent(["onError(error);"]),
  116. "}"
  117. ]
  118. )}`,
  119. `${cst} onExternal = ${runtimeTemplate.returningFunction(
  120. `external ? handleFunction(${RuntimeGlobals.initializeSharing}, data[0], 0, external, onInitialized, first) : onError()`,
  121. "external, _, first"
  122. )};`,
  123. `${cst} onInitialized = ${runtimeTemplate.returningFunction(
  124. "handleFunction(external.get, data[1], getScope, 0, onFactory, first)",
  125. "_, external, first"
  126. )};`,
  127. `${cst} onFactory = ${runtimeTemplate.basicFunction("factory", [
  128. "data.p = 1;",
  129. `${
  130. RuntimeGlobals.moduleFactories
  131. }[id] = ${runtimeTemplate.basicFunction("module", [
  132. "module.exports = factory();"
  133. ])}`
  134. ])};`,
  135. `handleFunction(${RuntimeGlobals.require}, data[2], 0, 0, onExternal, 1);`
  136. ])});`
  137. ]),
  138. "}"
  139. ])}`
  140. ]);
  141. }
  142. }
  143. module.exports = RemoteRuntimeModule;