@module-federation/modern-js 0.14.3 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/cjs/cli/configPlugin.js +17 -13
  2. package/dist/cjs/cli/configPlugin.spec.js +3 -1
  3. package/dist/cjs/cli/index.js +3 -1
  4. package/dist/cjs/cli/mfRuntimePlugins/auto-fetch-data.js +98 -0
  5. package/dist/cjs/cli/server/data-fetch-server-plugin.js +189 -0
  6. package/dist/cjs/cli/ssrPlugin.js +31 -12
  7. package/dist/cjs/cli/utils.js +5 -0
  8. package/dist/cjs/constant.js +49 -2
  9. package/dist/cjs/{ssr-runtime/index.js → interfaces/global.js} +2 -8
  10. package/dist/cjs/{cli/logger.js → logger.js} +1 -1
  11. package/dist/cjs/runtime/AwaitDataFetch.js +144 -0
  12. package/dist/cjs/runtime/createRemoteComponent.js +327 -0
  13. package/dist/cjs/runtime/index.js +15 -3
  14. package/dist/cjs/{cli/constant.js → runtime/wrapNoSSR.js} +13 -6
  15. package/dist/cjs/ssr-runtime/{plugin.js → devPlugin.js} +9 -6
  16. package/dist/cjs/ssr-runtime/downgrade.js +114 -0
  17. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +136 -0
  18. package/dist/cjs/utils/dataFetch.js +211 -0
  19. package/dist/cjs/utils/index.js +54 -0
  20. package/dist/esm/cli/configPlugin.js +18 -14
  21. package/dist/esm/cli/configPlugin.spec.js +3 -1
  22. package/dist/esm/cli/index.js +3 -1
  23. package/dist/esm/cli/mfRuntimePlugins/auto-fetch-data.js +74 -0
  24. package/dist/esm/cli/server/data-fetch-server-plugin.js +237 -0
  25. package/dist/esm/cli/ssrPlugin.js +28 -8
  26. package/dist/esm/cli/utils.js +4 -0
  27. package/dist/esm/constant.js +37 -1
  28. package/dist/esm/interfaces/global.js +0 -0
  29. package/dist/esm/{cli/logger.js → logger.js} +1 -1
  30. package/dist/esm/runtime/AwaitDataFetch.js +131 -0
  31. package/dist/esm/runtime/createRemoteComponent.js +417 -0
  32. package/dist/esm/runtime/index.js +13 -3
  33. package/dist/esm/runtime/wrapNoSSR.js +12 -0
  34. package/dist/esm/ssr-runtime/{plugin.js → devPlugin.js} +5 -2
  35. package/dist/esm/ssr-runtime/downgrade.js +150 -0
  36. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +177 -0
  37. package/dist/esm/utils/dataFetch.js +237 -0
  38. package/dist/esm/utils/index.js +28 -0
  39. package/dist/esm-node/cli/configPlugin.js +18 -14
  40. package/dist/esm-node/cli/configPlugin.spec.js +3 -1
  41. package/dist/esm-node/cli/index.js +3 -1
  42. package/dist/esm-node/cli/mfRuntimePlugins/auto-fetch-data.js +68 -0
  43. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +159 -0
  44. package/dist/esm-node/cli/ssrPlugin.js +27 -8
  45. package/dist/esm-node/cli/utils.js +4 -0
  46. package/dist/esm-node/constant.js +37 -1
  47. package/dist/esm-node/interfaces/global.js +0 -0
  48. package/dist/esm-node/{cli/logger.js → logger.js} +1 -1
  49. package/dist/esm-node/runtime/AwaitDataFetch.js +109 -0
  50. package/dist/esm-node/runtime/createRemoteComponent.js +291 -0
  51. package/dist/esm-node/runtime/index.js +13 -3
  52. package/dist/esm-node/runtime/wrapNoSSR.js +11 -0
  53. package/dist/esm-node/ssr-runtime/{plugin.js → devPlugin.js} +5 -2
  54. package/dist/esm-node/ssr-runtime/downgrade.js +88 -0
  55. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +101 -0
  56. package/dist/esm-node/utils/dataFetch.js +166 -0
  57. package/dist/esm-node/utils/index.js +27 -0
  58. package/dist/types/cli/configPlugin.d.ts +1 -1
  59. package/dist/types/cli/index.d.ts +1 -0
  60. package/dist/types/cli/mfRuntimePlugins/auto-fetch-data.d.ts +3 -0
  61. package/dist/types/cli/server/data-fetch-server-plugin.d.ts +3 -0
  62. package/dist/types/cli/utils.d.ts +1 -0
  63. package/dist/types/constant.d.ts +23 -0
  64. package/dist/types/interfaces/global.d.ts +27 -0
  65. package/dist/types/runtime/AwaitDataFetch.d.ts +19 -0
  66. package/dist/types/runtime/createRemoteComponent.d.ts +26 -0
  67. package/dist/types/runtime/index.d.ts +7 -2
  68. package/dist/types/runtime/wrapNoSSR.d.ts +9 -0
  69. package/dist/types/ssr-runtime/devPlugin.d.ts +2 -0
  70. package/dist/types/ssr-runtime/downgrade.d.ts +4 -0
  71. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +7 -0
  72. package/dist/types/types/index.d.ts +2 -0
  73. package/dist/types/utils/dataFetch.d.ts +26 -0
  74. package/dist/types/utils/index.d.ts +15 -0
  75. package/package.json +37 -12
  76. package/dist/cjs/cli/manifest.js +0 -75
  77. package/dist/cjs/runtime/createRemoteSSRComponent.js +0 -201
  78. package/dist/esm/cli/constant.js +0 -4
  79. package/dist/esm/cli/manifest.js +0 -41
  80. package/dist/esm/runtime/createRemoteSSRComponent.js +0 -191
  81. package/dist/esm/ssr-runtime/index.js +0 -1
  82. package/dist/esm-node/cli/constant.js +0 -4
  83. package/dist/esm-node/cli/manifest.js +0 -41
  84. package/dist/esm-node/runtime/createRemoteSSRComponent.js +0 -166
  85. package/dist/esm-node/ssr-runtime/index.js +0 -1
  86. package/dist/types/cli/constant.d.ts +0 -1
  87. package/dist/types/cli/manifest.d.ts +0 -2
  88. package/dist/types/runtime/createRemoteSSRComponent.d.ts +0 -18
  89. package/dist/types/ssr-runtime/index.d.ts +0 -1
  90. package/dist/types/ssr-runtime/plugin.d.ts +0 -2
  91. /package/dist/types/{cli/logger.d.ts → logger.d.ts} +0 -0
@@ -45,9 +45,9 @@ var import_sdk = require("@module-federation/sdk");
45
45
  var import_node_bundle_require = require("@modern-js/node-bundle-require");
46
46
  var import_constant = require("../constant");
47
47
  var import_utils2 = require("@module-federation/rsbuild-plugin/utils");
48
- var import_logger = __toESM(require("./logger"));
48
+ var import_logger = __toESM(require("../logger"));
49
+ var import_utils3 = require("./utils");
49
50
  const defaultPath = import_path.default.resolve(process.cwd(), "module-federation.config.ts");
50
- const isDev = process.env.NODE_ENV === "development";
51
51
  function setEnv(enableSSR) {
52
52
  if (enableSSR) {
53
53
  process.env["MF_DISABLE_EMIT_STATS"] = "true";
@@ -134,8 +134,9 @@ const patchDTSConfig = (mfConfig, isServer) => {
134
134
  }
135
135
  }
136
136
  };
137
- const patchMFConfig = (mfConfig, isServer, remoteIpStrategy) => {
137
+ const patchMFConfig = (mfConfig, isServer, remoteIpStrategy, enableSSR) => {
138
138
  replaceRemoteUrl(mfConfig, remoteIpStrategy);
139
+ (0, import_utils2.addDataFetchExposes)(mfConfig.exposes, isServer);
139
140
  if (mfConfig.remoteType === void 0) {
140
141
  mfConfig.remoteType = "script";
141
142
  }
@@ -147,12 +148,13 @@ const patchMFConfig = (mfConfig, isServer, remoteIpStrategy) => {
147
148
  ];
148
149
  patchDTSConfig(mfConfig, isServer);
149
150
  injectRuntimePlugins(require.resolve("@module-federation/modern-js/shared-strategy"), runtimePlugins);
150
- if (isDev) {
151
+ injectRuntimePlugins(require.resolve("@module-federation/modern-js/auto-fetch-data"), runtimePlugins);
152
+ if (enableSSR && (0, import_utils3.isDev)()) {
151
153
  injectRuntimePlugins(require.resolve("@module-federation/modern-js/resolve-entry-ipv4"), runtimePlugins);
152
154
  }
153
155
  if (isServer) {
154
156
  injectRuntimePlugins(require.resolve("@module-federation/node/runtimePlugin"), runtimePlugins);
155
- if (isDev) {
157
+ if ((0, import_utils3.isDev)()) {
156
158
  injectRuntimePlugins(require.resolve("@module-federation/node/record-dynamic-remote-entry-hash-plugin"), runtimePlugins);
157
159
  }
158
160
  injectRuntimePlugins(require.resolve("@module-federation/modern-js/inject-node-fetch"), runtimePlugins);
@@ -252,7 +254,7 @@ function patchBundlerConfig(options) {
252
254
  splitChunkConfig.chunks = "async";
253
255
  import_logger.default.warn(`splitChunks.chunks = async is not allowed with stream SSR mode, it will auto changed to "async"`);
254
256
  }
255
- if (isDev && chain.output.get("publicPath") === "auto") {
257
+ if ((0, import_utils3.isDev)() && chain.output.get("publicPath") === "auto") {
256
258
  var _modernjsConfig_dev, _modernjsConfig_server;
257
259
  const port = ((_modernjsConfig_dev = modernjsConfig.dev) === null || _modernjsConfig_dev === void 0 ? void 0 : _modernjsConfig_dev.port) || ((_modernjsConfig_server = modernjsConfig.server) === null || _modernjsConfig_server === void 0 ? void 0 : _modernjsConfig_server.port) || 8080;
258
260
  const publicPath = `http://localhost:${port}/`;
@@ -266,7 +268,7 @@ function patchBundlerConfig(options) {
266
268
  chain.output.chunkFilename(chunkFileName.replace(".js", suffix));
267
269
  }
268
270
  }
269
- if (isDev && enableSSR && !isServer) {
271
+ if ((0, import_utils3.isDev)() && enableSSR && !isServer) {
270
272
  chain.resolve.fallback.set("crypto", false).set("stream", false).set("vm", false);
271
273
  }
272
274
  if (((_modernjsConfig_deploy = modernjsConfig.deploy) === null || _modernjsConfig_deploy === void 0 ? void 0 : _modernjsConfig_deploy.microFrontend) && Object.keys(mfConfig.exposes || {}).length) {
@@ -299,9 +301,8 @@ const moduleFederationConfigPlugin = (userConfig) => ({
299
301
  const isWeb = (0, import_utils.isWebTarget)(target);
300
302
  addMyTypes2Ignored(chain, !isWeb ? ssrConfig : csrConfig);
301
303
  const targetMFConfig = !isWeb ? ssrConfig : csrConfig;
302
- patchMFConfig(targetMFConfig, !isWeb, userConfig.remoteIpStrategy || "ipv4");
304
+ patchMFConfig(targetMFConfig, !isWeb, userConfig.remoteIpStrategy || "ipv4", enableSSR);
303
305
  patchBundlerConfig({
304
- // @ts-expect-error chain type is not correct
305
306
  chain,
306
307
  isServer: !isWeb,
307
308
  modernjsConfig,
@@ -338,6 +339,12 @@ const moduleFederationConfigPlugin = (userConfig) => ({
338
339
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
339
340
  "Access-Control-Allow-Headers": "*"
340
341
  } : void 0;
342
+ const defineConfig = {
343
+ REMOTE_IP_STRATEGY: JSON.stringify(userConfig.remoteIpStrategy)
344
+ };
345
+ if (enableSSR && (0, import_utils3.isDev)()) {
346
+ defineConfig["FEDERATION_IPV4"] = JSON.stringify(ipv4);
347
+ }
341
348
  var _modernjsConfig_source_enableAsyncEntry;
342
349
  return {
343
350
  tools: {
@@ -350,10 +357,7 @@ const moduleFederationConfigPlugin = (userConfig) => ({
350
357
  // TODO: deprecated
351
358
  "@modern-js/runtime/mf": require.resolve("@module-federation/modern-js/runtime")
352
359
  },
353
- define: {
354
- FEDERATION_IPV4: JSON.stringify(ipv4),
355
- REMOTE_IP_STRATEGY: JSON.stringify(userConfig.remoteIpStrategy)
356
- },
360
+ define: defineConfig,
357
361
  enableAsyncEntry: bundlerType === "rspack" ? (_modernjsConfig_source_enableAsyncEntry = (_modernjsConfig_source = modernjsConfig.source) === null || _modernjsConfig_source === void 0 ? void 0 : _modernjsConfig_source.enableAsyncEntry) !== null && _modernjsConfig_source_enableAsyncEntry !== void 0 ? _modernjsConfig_source_enableAsyncEntry : true : (_modernjsConfig_source1 = modernjsConfig.source) === null || _modernjsConfig_source1 === void 0 ? void 0 : _modernjsConfig_source1.enableAsyncEntry
358
362
  },
359
363
  dev: {
@@ -61,6 +61,7 @@ const mfConfig = {
61
61
  remoteType: "script",
62
62
  runtimePlugins: [
63
63
  require.resolve("@module-federation/modern-js/shared-strategy"),
64
+ require.resolve("@module-federation/modern-js/auto-fetch-data"),
64
65
  require.resolve("@module-federation/node/runtimePlugin"),
65
66
  require.resolve("@module-federation/modern-js/inject-node-fetch")
66
67
  ],
@@ -88,7 +89,8 @@ const mfConfig = {
88
89
  },
89
90
  remoteType: "script",
90
91
  runtimePlugins: [
91
- require.resolve("@module-federation/modern-js/shared-strategy")
92
+ require.resolve("@module-federation/modern-js/shared-strategy"),
93
+ require.resolve("@module-federation/modern-js/auto-fetch-data")
92
94
  ],
93
95
  shared: {
94
96
  react: {
@@ -30,6 +30,7 @@ var import_ssrPlugin = require("./ssrPlugin");
30
30
  var import_utils = require("./utils");
31
31
  var import_enhanced2 = require("@module-federation/enhanced");
32
32
  const moduleFederationPlugin = (userConfig = {}) => {
33
+ var _userConfig_fetchServerQuery;
33
34
  const internalModernPluginOptions = {
34
35
  csrConfig: void 0,
35
36
  ssrConfig: void 0,
@@ -38,7 +39,8 @@ const moduleFederationPlugin = (userConfig = {}) => {
38
39
  distOutputDir: "",
39
40
  originPluginOptions: userConfig,
40
41
  remoteIpStrategy: userConfig === null || userConfig === void 0 ? void 0 : userConfig.remoteIpStrategy,
41
- userConfig: userConfig || {}
42
+ userConfig: userConfig || {},
43
+ fetchServerQuery: (_userConfig_fetchServerQuery = userConfig.fetchServerQuery) !== null && _userConfig_fetchServerQuery !== void 0 ? _userConfig_fetchServerQuery : void 0
42
44
  };
43
45
  return {
44
46
  name: "@modern-js/plugin-module-federation",
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var auto_fetch_data_exports = {};
30
+ __export(auto_fetch_data_exports, {
31
+ default: () => auto_fetch_data_default
32
+ });
33
+ module.exports = __toCommonJS(auto_fetch_data_exports);
34
+ var import_utils = require("../../utils");
35
+ var import_logger = __toESM(require("../../logger"));
36
+ var import_dataFetch = require("../../utils/dataFetch");
37
+ var import_constant = require("../../constant");
38
+ var import_constant2 = require("@module-federation/rsbuild-plugin/constant");
39
+ const autoFetchData = () => ({
40
+ name: "auto-fetch-data-plugin",
41
+ beforeInit(args) {
42
+ (0, import_utils.initDataFetchMap)();
43
+ return args;
44
+ },
45
+ afterLoadSnapshot(args) {
46
+ const { id, moduleInfo, remoteSnapshot, host } = args;
47
+ if (typeof id === "string" && (0, import_dataFetch.isDataLoaderExpose)(id)) {
48
+ return args;
49
+ }
50
+ if (!remoteSnapshot || !id || !("modules" in remoteSnapshot)) {
51
+ return args;
52
+ }
53
+ const { name, alias } = moduleInfo;
54
+ const dataFetchInfo = (0, import_utils.getDataFetchInfo)({
55
+ name,
56
+ alias,
57
+ id,
58
+ remoteSnapshot
59
+ });
60
+ if (!dataFetchInfo) {
61
+ return args;
62
+ }
63
+ const { dataFetchId, dataFetchName } = dataFetchInfo;
64
+ const dataFetchMapKey = (0, import_dataFetch.getDataFetchMapKey)(dataFetchInfo, {
65
+ name: host.name,
66
+ version: host.options.version
67
+ });
68
+ import_logger.default.debug("======= auto fetch plugin dataFetchMapKey: ", dataFetchMapKey);
69
+ if (!dataFetchMapKey) {
70
+ return args;
71
+ }
72
+ const dataFetchItem = (0, import_utils.getDataFetchItem)(dataFetchMapKey);
73
+ if (dataFetchItem) {
74
+ return args;
75
+ }
76
+ const dataFetchMap = (0, import_utils.getDataFetchMap)();
77
+ const downgradeType = remoteSnapshot.modules.find((module2) => module2.moduleName === `${dataFetchName}${import_constant2.DATA_FETCH_CLIENT_SUFFIX}`) ? import_constant.MF_DATA_FETCH_TYPE.FETCH_CLIENT : import_constant.MF_DATA_FETCH_TYPE.FETCH_SERVER;
78
+ let finalDataFetchId = dataFetchId;
79
+ if (typeof window !== "undefined") {
80
+ finalDataFetchId = downgradeType === import_constant.MF_DATA_FETCH_TYPE.FETCH_CLIENT ? `${dataFetchId}${import_constant2.DATA_FETCH_CLIENT_SUFFIX}` : dataFetchId;
81
+ }
82
+ const getDataFetchGetter = () => (0, import_dataFetch.loadDataFetchModule)(host, finalDataFetchId);
83
+ const dataFetchFnItem = [
84
+ getDataFetchGetter,
85
+ downgradeType
86
+ ];
87
+ if (typeof window === "undefined" || (0, import_utils.isCSROnly)()) {
88
+ dataFetchFnItem.push(getDataFetchGetter());
89
+ }
90
+ dataFetchMap[dataFetchMapKey] = [
91
+ dataFetchFnItem,
92
+ void 0,
93
+ import_constant.MF_DATA_FETCH_STATUS.AWAIT
94
+ ];
95
+ return args;
96
+ }
97
+ });
98
+ var auto_fetch_data_default = autoFetchData;
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var data_fetch_server_plugin_exports = {};
30
+ __export(data_fetch_server_plugin_exports, {
31
+ default: () => data_fetch_server_plugin_default
32
+ });
33
+ module.exports = __toCommonJS(data_fetch_server_plugin_exports);
34
+ var import_constant = require("../../constant");
35
+ var import_logger = __toESM(require("../../logger"));
36
+ var import_utils = require("../../utils");
37
+ var import_dataFetch = require("../../utils/dataFetch");
38
+ var import_sdk = require("@module-federation/sdk");
39
+ function wrapSetTimeout(targetPromise, delay = 2e4, id) {
40
+ if (targetPromise && typeof targetPromise.then === "function") {
41
+ return new Promise((resolve, reject) => {
42
+ const timeoutId = setTimeout(() => {
43
+ import_logger.default.warn(`Data fetch for ID ${id} timed out after 20 seconds.`);
44
+ reject(new Error(`Data fetch for ID ${id} timed out after 20 seconds`));
45
+ }, delay);
46
+ targetPromise.then((value) => {
47
+ clearTimeout(timeoutId);
48
+ resolve(value);
49
+ }).catch((err) => {
50
+ clearTimeout(timeoutId);
51
+ reject(err);
52
+ });
53
+ });
54
+ }
55
+ }
56
+ function addProtocol(url) {
57
+ if (url.startsWith("//")) {
58
+ return "https:" + url;
59
+ }
60
+ return url;
61
+ }
62
+ const getDecodeQuery = (url, name) => {
63
+ const res = url.searchParams.get(name);
64
+ if (!res) {
65
+ return null;
66
+ }
67
+ return decodeURIComponent(res);
68
+ };
69
+ const middleware = async (ctx, next) => {
70
+ var _globalThis___FEDERATION__;
71
+ let url;
72
+ let dataFetchId;
73
+ let params;
74
+ let remoteInfo;
75
+ try {
76
+ url = new URL(ctx.req.url);
77
+ dataFetchId = getDecodeQuery(url, import_constant.DATA_FETCH_QUERY);
78
+ params = JSON.parse(getDecodeQuery(url, "params") || "{}");
79
+ const remoteInfoQuery = getDecodeQuery(url, "remoteInfo");
80
+ remoteInfo = remoteInfoQuery ? JSON.parse(remoteInfoQuery) : null;
81
+ } catch (e) {
82
+ import_logger.default.error("fetch data from server, error: ", e);
83
+ return next();
84
+ }
85
+ if (!dataFetchId) {
86
+ return next();
87
+ }
88
+ import_logger.default.log("fetch data from server, dataFetchId: ", dataFetchId);
89
+ import_logger.default.debug("fetch data from server, moduleInfo: ", (_globalThis___FEDERATION__ = globalThis.__FEDERATION__) === null || _globalThis___FEDERATION__ === void 0 ? void 0 : _globalThis___FEDERATION__.moduleInfo);
90
+ try {
91
+ var _dataFetchMap_dataFetchId, _dataFetchMap_dataFetchId1;
92
+ const dataFetchMap = (0, import_utils.getDataFetchMap)();
93
+ if (!dataFetchMap) {
94
+ (0, import_dataFetch.initDataFetchMap)();
95
+ }
96
+ const fetchDataPromise = (_dataFetchMap_dataFetchId = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId === void 0 ? void 0 : _dataFetchMap_dataFetchId[1];
97
+ import_logger.default.debug("fetch data from server, fetchDataPromise: ", fetchDataPromise);
98
+ if (fetchDataPromise && ((_dataFetchMap_dataFetchId1 = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId1 === void 0 ? void 0 : _dataFetchMap_dataFetchId1[2]) !== import_constant.MF_DATA_FETCH_STATUS.ERROR) {
99
+ const targetPromise = fetchDataPromise[0];
100
+ const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
101
+ if (wrappedPromise) {
102
+ const res = await wrappedPromise;
103
+ import_logger.default.log("fetch data from server, fetchDataPromise res: ", res);
104
+ return ctx.json(res);
105
+ }
106
+ import_logger.default.error(`Expected a Promise from fetchDataPromise[0] for dataFetchId ${dataFetchId}, but received:`, targetPromise, "Will try call new dataFetch again...");
107
+ }
108
+ if (remoteInfo) {
109
+ try {
110
+ const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
111
+ const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
112
+ if (!hostInstance2) {
113
+ throw new Error("host instance not found!");
114
+ }
115
+ const remote = hostInstance2.options.remotes.find((remote2) => remote2.name === remoteInfo.name);
116
+ import_logger.default.debug("find remote: ", JSON.stringify(remote));
117
+ if (!remote) {
118
+ hostInstance2.registerRemotes([
119
+ {
120
+ name: remoteInfo.name,
121
+ entry: remoteEntry,
122
+ entryGlobalName: remoteInfo.globalName
123
+ }
124
+ ]);
125
+ } else if (!("entry" in remote) || !remote.entry.includes(import_sdk.MANIFEST_EXT)) {
126
+ const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
127
+ import_logger.default.debug("find hostGlobalSnapshot: ", JSON.stringify(hostGlobalSnapshot));
128
+ import_logger.default.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
129
+ if (!hostGlobalSnapshot || !remoteSnapshot) {
130
+ if ("version" in remote) {
131
+ delete remote.version;
132
+ }
133
+ remote.entry = remoteEntry;
134
+ remote.entryGlobalName = remoteInfo.globalName;
135
+ }
136
+ }
137
+ } catch (e) {
138
+ ctx.status(500);
139
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
140
+ ${e}`);
141
+ }
142
+ }
143
+ const dataFetchItem = dataFetchMap[dataFetchId];
144
+ import_logger.default.debug("fetch data from server, dataFetchItem: ", dataFetchItem);
145
+ if (dataFetchItem) {
146
+ const callFetchDataPromise = (0, import_dataFetch.fetchData)(dataFetchId, {
147
+ ...params,
148
+ isDowngrade: !remoteInfo
149
+ });
150
+ const wrappedPromise = wrapSetTimeout(callFetchDataPromise, 2e4, dataFetchId);
151
+ if (wrappedPromise) {
152
+ const res = await wrappedPromise;
153
+ import_logger.default.log("fetch data from server, dataFetchItem res: ", res);
154
+ return ctx.json(res);
155
+ }
156
+ }
157
+ const remoteId = dataFetchId.split(import_sdk.SEPARATOR)[0];
158
+ const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
159
+ if (!hostInstance) {
160
+ throw new Error("host instance not found!");
161
+ }
162
+ const dataFetchFn = await (0, import_dataFetch.loadDataFetchModule)(hostInstance, remoteId);
163
+ const data = await dataFetchFn({
164
+ ...params,
165
+ isDowngrade: !remoteInfo
166
+ });
167
+ import_logger.default.log("fetch data from server, loadDataFetchModule res: ", data);
168
+ return ctx.json(data);
169
+ } catch (e) {
170
+ import_logger.default.error("server plugin data fetch error: ", e);
171
+ ctx.status(500);
172
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
173
+ ${e}`);
174
+ }
175
+ };
176
+ const dataFetchServePlugin = () => ({
177
+ name: "mf-data-fetch-server-plugin",
178
+ setup: (api) => {
179
+ api.onPrepare(() => {
180
+ const { middlewares } = api.getServerContext();
181
+ middlewares.push({
182
+ name: "module-federation-serve-manifest",
183
+ // @ts-ignore type error
184
+ handler: middleware
185
+ });
186
+ });
187
+ }
188
+ });
189
+ var data_fetch_server_plugin_default = dataFetchServePlugin;
@@ -39,10 +39,10 @@ var import_fs_extra = __toESM(require("fs-extra"));
39
39
  var import_webpack = require("@module-federation/enhanced/webpack");
40
40
  var import_rspack = require("@module-federation/enhanced/rspack");
41
41
  var import_universe_entry_chunk_tracker_plugin = __toESM(require("@module-federation/node/universe-entry-chunk-tracker-plugin"));
42
- var import_manifest = require("./manifest");
43
- var import_constant = require("./constant");
44
- var import_logger = __toESM(require("./logger"));
42
+ var import_logger = __toESM(require("../logger"));
45
43
  var import_utils = require("./utils");
44
+ var import_manifest = require("@module-federation/rsbuild-plugin/manifest");
45
+ var import_utils2 = require("./utils");
46
46
  function setEnv() {
47
47
  process.env["MF_DISABLE_EMIT_STATS"] = "true";
48
48
  process.env["MF_SSR_PRJ"] = "true";
@@ -63,10 +63,10 @@ const mfSSRRsbuildPlugin = (pluginOptions) => {
63
63
  let ssrEnv = "";
64
64
  api.modifyEnvironmentConfig((config, { name }) => {
65
65
  const target = config.output.target;
66
- if ((0, import_utils.skipByTarget)(target)) {
66
+ if ((0, import_utils2.skipByTarget)(target)) {
67
67
  return config;
68
68
  }
69
- if ((0, import_utils.isWebTarget)(target)) {
69
+ if ((0, import_utils2.isWebTarget)(target)) {
70
70
  csrOutputPath = config.output.distPath.root;
71
71
  } else {
72
72
  ssrOutputPath = config.output.distPath.root;
@@ -112,15 +112,23 @@ const moduleFederationSSRPlugin = (pluginOptions) => ({
112
112
  }
113
113
  setEnv();
114
114
  api._internalRuntimePlugins(({ entrypoint, plugins }) => {
115
- if (!import_constant.isDev) {
115
+ const { fetchServerQuery } = pluginOptions;
116
+ plugins.push({
117
+ name: "injectDataFetchFunction",
118
+ path: "@module-federation/modern-js/ssr-inject-data-fetch-function-plugin",
119
+ config: {
120
+ fetchServerQuery
121
+ }
122
+ });
123
+ if (!(0, import_utils.isDev)()) {
116
124
  return {
117
125
  entrypoint,
118
126
  plugins
119
127
  };
120
128
  }
121
129
  plugins.push({
122
- name: "mfSSR",
123
- path: "@module-federation/modern-js/ssr-runtime",
130
+ name: "mfSSRDev",
131
+ path: "@module-federation/modern-js/ssr-dev-plugin",
124
132
  config: {}
125
133
  });
126
134
  return {
@@ -128,14 +136,25 @@ const moduleFederationSSRPlugin = (pluginOptions) => ({
128
136
  plugins
129
137
  };
130
138
  });
139
+ if (pluginOptions.ssrConfig.remotes) {
140
+ api._internalServerPlugins(({ plugins }) => {
141
+ plugins.push({
142
+ name: "@module-federation/modern-js/data-fetch-server-plugin",
143
+ options: {}
144
+ });
145
+ return {
146
+ plugins
147
+ };
148
+ });
149
+ }
131
150
  api.modifyBundlerChain((chain) => {
132
151
  const target = chain.get("target");
133
- if ((0, import_utils.skipByTarget)(target)) {
152
+ if ((0, import_utils2.skipByTarget)(target)) {
134
153
  return;
135
154
  }
136
155
  const bundlerType = api.getAppContext().bundlerType === "rspack" ? "rspack" : "webpack";
137
156
  const MFPlugin = bundlerType === "webpack" ? import_webpack.ModuleFederationPlugin : import_rspack.ModuleFederationPlugin;
138
- const isWeb = (0, import_utils.isWebTarget)(target);
157
+ const isWeb = (0, import_utils2.isWebTarget)(target);
139
158
  if (!isWeb) {
140
159
  if (!chain.plugins.has(CHAIN_MF_PLUGIN_ID)) {
141
160
  chain.plugin(CHAIN_MF_PLUGIN_ID).use(MFPlugin, [
@@ -148,7 +167,7 @@ const moduleFederationSSRPlugin = (pluginOptions) => ({
148
167
  }
149
168
  if (!isWeb) {
150
169
  chain.target("async-node");
151
- if (import_constant.isDev) {
170
+ if ((0, import_utils.isDev)()) {
152
171
  chain.plugin("UniverseEntryChunkTrackerPlugin").use(import_universe_entry_chunk_tracker_plugin.default);
153
172
  }
154
173
  const userSSRConfig = pluginOptions.userConfig.ssr ? typeof pluginOptions.userConfig.ssr === "object" ? pluginOptions.userConfig.ssr : {} : {};
@@ -157,7 +176,7 @@ const moduleFederationSSRPlugin = (pluginOptions) => ({
157
176
  chain.output.publicPath(`${publicPath}${userSSRConfig.distOutputDir}/`);
158
177
  }
159
178
  }
160
- if (import_constant.isDev && isWeb) {
179
+ if ((0, import_utils.isDev)() && isWeb) {
161
180
  chain.externals({
162
181
  "@module-federation/node/utils": "NOT_USED_IN_BROWSER"
163
182
  });
@@ -29,6 +29,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var utils_exports = {};
30
30
  __export(utils_exports, {
31
31
  getIPV4: () => getIPV4,
32
+ isDev: () => isDev,
32
33
  isWebTarget: () => isWebTarget,
33
34
  skipByTarget: () => skipByTarget
34
35
  });
@@ -77,9 +78,13 @@ const skipByTarget = (target) => {
77
78
  }
78
79
  return false;
79
80
  };
81
+ function isDev() {
82
+ return process.env.NODE_ENV === "development";
83
+ }
80
84
  // Annotate the CommonJS export names for ESM import in node:
81
85
  0 && (module.exports = {
82
86
  getIPV4,
87
+ isDev,
83
88
  isWebTarget,
84
89
  skipByTarget
85
90
  });
@@ -18,14 +18,61 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var constant_exports = {};
20
20
  __export(constant_exports, {
21
+ DATA_FETCH_ERROR_PREFIX: () => DATA_FETCH_ERROR_PREFIX,
22
+ DATA_FETCH_FUNCTION: () => DATA_FETCH_FUNCTION,
23
+ DATA_FETCH_MAP_KEY: () => DATA_FETCH_MAP_KEY,
24
+ DATA_FETCH_QUERY: () => DATA_FETCH_QUERY,
25
+ DOWNGRADE_KEY: () => DOWNGRADE_KEY,
26
+ ERROR_TYPE: () => ERROR_TYPE,
27
+ FS_HREF: () => FS_HREF,
28
+ LOAD_REMOTE_ERROR_PREFIX: () => LOAD_REMOTE_ERROR_PREFIX,
21
29
  LOCALHOST: () => LOCALHOST,
22
- PLUGIN_IDENTIFIER: () => PLUGIN_IDENTIFIER
30
+ MF_DATA_FETCH_STATUS: () => MF_DATA_FETCH_STATUS,
31
+ MF_DATA_FETCH_TYPE: () => MF_DATA_FETCH_TYPE,
32
+ PLUGIN_IDENTIFIER: () => PLUGIN_IDENTIFIER,
33
+ WRAP_DATA_FETCH_ID_IDENTIFIER: () => WRAP_DATA_FETCH_ID_IDENTIFIER
23
34
  });
24
35
  module.exports = __toCommonJS(constant_exports);
25
36
  const LOCALHOST = "localhost";
26
37
  const PLUGIN_IDENTIFIER = "[ Modern.js Module Federation ]";
38
+ const DATA_FETCH_QUERY = "x-mf-data-fetch";
39
+ const DATA_FETCH_ERROR_PREFIX = "caught the following error during dataFetch: ";
40
+ const LOAD_REMOTE_ERROR_PREFIX = "caught the following error during loadRemote: ";
41
+ const DOWNGRADE_KEY = "_mfSSRDowngrade";
42
+ const DATA_FETCH_MAP_KEY = "__MF_DATA_FETCH_MAP__";
43
+ const DATA_FETCH_FUNCTION = "_mfDataFetch";
44
+ const FS_HREF = "_mfFSHref";
45
+ const ERROR_TYPE = {
46
+ DATA_FETCH: 1,
47
+ LOAD_REMOTE: 2,
48
+ UNKNOWN: 3
49
+ };
50
+ const WRAP_DATA_FETCH_ID_IDENTIFIER = "wrap_dfip_identifier";
51
+ var MF_DATA_FETCH_TYPE;
52
+ (function(MF_DATA_FETCH_TYPE2) {
53
+ MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2["FETCH_SERVER"] = 1] = "FETCH_SERVER";
54
+ MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2["FETCH_CLIENT"] = 2] = "FETCH_CLIENT";
55
+ })(MF_DATA_FETCH_TYPE || (MF_DATA_FETCH_TYPE = {}));
56
+ var MF_DATA_FETCH_STATUS;
57
+ (function(MF_DATA_FETCH_STATUS2) {
58
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["LOADED"] = 1] = "LOADED";
59
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["LOADING"] = 2] = "LOADING";
60
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["AWAIT"] = 0] = "AWAIT";
61
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["ERROR"] = 3] = "ERROR";
62
+ })(MF_DATA_FETCH_STATUS || (MF_DATA_FETCH_STATUS = {}));
27
63
  // Annotate the CommonJS export names for ESM import in node:
28
64
  0 && (module.exports = {
65
+ DATA_FETCH_ERROR_PREFIX,
66
+ DATA_FETCH_FUNCTION,
67
+ DATA_FETCH_MAP_KEY,
68
+ DATA_FETCH_QUERY,
69
+ DOWNGRADE_KEY,
70
+ ERROR_TYPE,
71
+ FS_HREF,
72
+ LOAD_REMOTE_ERROR_PREFIX,
29
73
  LOCALHOST,
30
- PLUGIN_IDENTIFIER
74
+ MF_DATA_FETCH_STATUS,
75
+ MF_DATA_FETCH_TYPE,
76
+ PLUGIN_IDENTIFIER,
77
+ WRAP_DATA_FETCH_ID_IDENTIFIER
31
78
  });
@@ -11,12 +11,6 @@ var __copyProps = (to, from, except, desc) => {
11
11
  }
12
12
  return to;
13
13
  };
14
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
14
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
- var ssr_runtime_exports = {};
17
- module.exports = __toCommonJS(ssr_runtime_exports);
18
- __reExport(ssr_runtime_exports, require("./plugin"), module.exports);
19
- // Annotate the CommonJS export names for ESM import in node:
20
- 0 && (module.exports = {
21
- ...require("./plugin")
22
- });
15
+ var global_exports = {};
16
+ module.exports = __toCommonJS(global_exports);
@@ -22,6 +22,6 @@ __export(logger_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(logger_exports);
24
24
  var import_sdk = require("@module-federation/sdk");
25
- var import_constant = require("../constant");
25
+ var import_constant = require("./constant");
26
26
  const logger = (0, import_sdk.createLogger)(import_constant.PLUGIN_IDENTIFIER);
27
27
  var logger_default = logger;