@module-federation/modern-js 0.0.0-next-20250708134245 → 0.0.0-next-20250709032753

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 (65) hide show
  1. package/dist/cjs/cli/configPlugin.js +1 -0
  2. package/dist/cjs/cli/configPlugin.spec.js +2 -1
  3. package/dist/cjs/cli/mfRuntimePlugins/auto-fetch-data.js +100 -0
  4. package/dist/cjs/cli/server/data-fetch-server-plugin.js +143 -2
  5. package/dist/cjs/constant.js +49 -2
  6. package/dist/cjs/interfaces/global.js +16 -0
  7. package/dist/cjs/runtime/AwaitDataFetch.js +144 -0
  8. package/dist/cjs/runtime/createRemoteComponent.js +327 -0
  9. package/dist/cjs/runtime/index.js +28 -0
  10. package/dist/cjs/runtime/{plugin.js → wrapNoSSR.js} +12 -20
  11. package/dist/cjs/ssr-runtime/devPlugin.js +2 -2
  12. package/dist/cjs/ssr-runtime/downgrade.js +114 -0
  13. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +102 -6
  14. package/dist/cjs/utils/dataFetch.js +211 -0
  15. package/dist/cjs/utils/index.js +54 -0
  16. package/dist/esm/cli/configPlugin.js +1 -0
  17. package/dist/esm/cli/configPlugin.spec.js +2 -1
  18. package/dist/esm/cli/mfRuntimePlugins/auto-fetch-data.js +76 -0
  19. package/dist/esm/cli/server/data-fetch-server-plugin.js +219 -2
  20. package/dist/esm/constant.js +37 -1
  21. package/dist/esm/interfaces/global.js +0 -0
  22. package/dist/esm/runtime/AwaitDataFetch.js +131 -0
  23. package/dist/esm/runtime/createRemoteComponent.js +417 -0
  24. package/dist/esm/runtime/index.js +21 -0
  25. package/dist/esm/runtime/wrapNoSSR.js +12 -0
  26. package/dist/esm/ssr-runtime/devPlugin.js +1 -1
  27. package/dist/esm/ssr-runtime/downgrade.js +150 -0
  28. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +147 -4
  29. package/dist/esm/utils/dataFetch.js +237 -0
  30. package/dist/esm/utils/index.js +28 -0
  31. package/dist/esm-node/cli/configPlugin.js +1 -0
  32. package/dist/esm-node/cli/configPlugin.spec.js +2 -1
  33. package/dist/esm-node/cli/mfRuntimePlugins/auto-fetch-data.js +70 -0
  34. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +143 -2
  35. package/dist/esm-node/constant.js +37 -1
  36. package/dist/esm-node/interfaces/global.js +0 -0
  37. package/dist/esm-node/runtime/AwaitDataFetch.js +109 -0
  38. package/dist/esm-node/runtime/createRemoteComponent.js +291 -0
  39. package/dist/esm-node/runtime/index.js +21 -0
  40. package/dist/esm-node/runtime/wrapNoSSR.js +11 -0
  41. package/dist/esm-node/ssr-runtime/devPlugin.js +1 -1
  42. package/dist/esm-node/ssr-runtime/downgrade.js +88 -0
  43. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +89 -4
  44. package/dist/esm-node/utils/dataFetch.js +166 -0
  45. package/dist/esm-node/utils/index.js +27 -0
  46. package/dist/types/cli/mfRuntimePlugins/auto-fetch-data.d.ts +3 -0
  47. package/dist/types/constant.d.ts +23 -0
  48. package/dist/types/interfaces/global.d.ts +27 -0
  49. package/dist/types/runtime/AwaitDataFetch.d.ts +19 -0
  50. package/dist/types/runtime/createRemoteComponent.d.ts +26 -0
  51. package/dist/types/runtime/index.d.ts +9 -0
  52. package/dist/types/runtime/wrapNoSSR.d.ts +9 -0
  53. package/dist/types/ssr-runtime/SSRLiveReload.d.ts +1 -1
  54. package/dist/types/ssr-runtime/downgrade.d.ts +4 -0
  55. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +3 -0
  56. package/dist/types/utils/dataFetch.d.ts +26 -0
  57. package/dist/types/utils/index.d.ts +15 -0
  58. package/package.json +18 -23
  59. package/dist/cjs/react/index.js +0 -44
  60. package/dist/esm/react/index.js +0 -12
  61. package/dist/esm/runtime/plugin.js +0 -19
  62. package/dist/esm-node/react/index.js +0 -12
  63. package/dist/esm-node/runtime/plugin.js +0 -19
  64. package/dist/types/react/index.d.ts +0 -2
  65. package/dist/types/runtime/plugin.d.ts +0 -2
@@ -0,0 +1,211 @@
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 dataFetch_exports = {};
30
+ __export(dataFetch_exports, {
31
+ fetchData: () => fetchData,
32
+ flushDataFetch: () => flushDataFetch,
33
+ getDataFetchIdWithErrorMsgs: () => getDataFetchIdWithErrorMsgs,
34
+ getDataFetchInfo: () => getDataFetchInfo,
35
+ getDataFetchItem: () => getDataFetchItem,
36
+ getDataFetchMap: () => getDataFetchMap,
37
+ getDataFetchMapKey: () => getDataFetchMapKey,
38
+ initDataFetchMap: () => initDataFetchMap,
39
+ isDataLoaderExpose: () => isDataLoaderExpose,
40
+ loadDataFetchModule: () => loadDataFetchModule,
41
+ setDataFetchItemLoadedStatus: () => setDataFetchItemLoadedStatus,
42
+ wrapDataFetchId: () => wrapDataFetchId
43
+ });
44
+ module.exports = __toCommonJS(dataFetch_exports);
45
+ var import_sdk = require("@module-federation/sdk");
46
+ var import_utils = require("../utils");
47
+ var import_logger = __toESM(require("../logger"));
48
+ var import_downgrade = require("../ssr-runtime/downgrade");
49
+ var import_constant = require("../constant");
50
+ var import_constant2 = require("@module-federation/rsbuild-plugin/constant");
51
+ const getDataFetchInfo = ({ name, alias, id, remoteSnapshot }) => {
52
+ if (!remoteSnapshot) {
53
+ return;
54
+ }
55
+ if (!("modules" in remoteSnapshot)) {
56
+ return;
57
+ }
58
+ const regex = new RegExp(`^${name}(/[^/].*|)$`);
59
+ const nameOrAlias = regex.test(id) ? name : alias || name;
60
+ const expose = id.replace(nameOrAlias, "");
61
+ let dataFetchName = "";
62
+ let dataFetchId = "";
63
+ if (expose.startsWith("/")) {
64
+ dataFetchName = `${expose.slice(1)}.${import_constant2.DATA_FETCH_IDENTIFIER}`;
65
+ dataFetchId = `${id}.${import_constant2.DATA_FETCH_IDENTIFIER}`;
66
+ } else if (expose === "") {
67
+ dataFetchName = import_constant2.DATA_FETCH_IDENTIFIER;
68
+ dataFetchId = `${id}/${import_constant2.DATA_FETCH_IDENTIFIER}`;
69
+ } else {
70
+ return;
71
+ }
72
+ if (!dataFetchName || !dataFetchId) {
73
+ return;
74
+ }
75
+ if (!remoteSnapshot.modules.find((module2) => module2.moduleName === dataFetchName)) {
76
+ return;
77
+ }
78
+ return {
79
+ dataFetchName,
80
+ dataFetchId
81
+ };
82
+ };
83
+ function initDataFetchMap() {
84
+ var _globalThis;
85
+ (_globalThis = globalThis).__MF_DATA_FETCH_MAP__ || (_globalThis.__MF_DATA_FETCH_MAP__ = {});
86
+ }
87
+ function getDataFetchItem(id) {
88
+ var _globalThis___MF_DATA_FETCH_MAP__;
89
+ return (_globalThis___MF_DATA_FETCH_MAP__ = globalThis.__MF_DATA_FETCH_MAP__) === null || _globalThis___MF_DATA_FETCH_MAP__ === void 0 ? void 0 : _globalThis___MF_DATA_FETCH_MAP__[id];
90
+ }
91
+ function getDataFetchMap() {
92
+ return globalThis.__MF_DATA_FETCH_MAP__;
93
+ }
94
+ const flushDataFetch = () => {
95
+ globalThis.__MF_DATA_FETCH_MAP__ = {};
96
+ globalThis[import_constant.DOWNGRADE_KEY] = void 0;
97
+ };
98
+ function setDataFetchItemLoadedStatus(id) {
99
+ const dataFetchItem = getDataFetchItem(id);
100
+ if (!dataFetchItem) {
101
+ return;
102
+ }
103
+ dataFetchItem[2] = import_constant.MF_DATA_FETCH_STATUS.LOADED;
104
+ }
105
+ const wrapDataFetchId = (id) => {
106
+ return `${import_constant.WRAP_DATA_FETCH_ID_IDENTIFIER}${id}${import_constant.WRAP_DATA_FETCH_ID_IDENTIFIER}`;
107
+ };
108
+ const getDataFetchIdWithErrorMsgs = (errMsgs) => {
109
+ const firstIdentifierIndex = errMsgs.indexOf(import_constant.WRAP_DATA_FETCH_ID_IDENTIFIER);
110
+ if (firstIdentifierIndex === -1) {
111
+ return void 0;
112
+ }
113
+ const secondIdentifierIndex = errMsgs.indexOf(import_constant.WRAP_DATA_FETCH_ID_IDENTIFIER, firstIdentifierIndex + import_constant.WRAP_DATA_FETCH_ID_IDENTIFIER.length);
114
+ if (secondIdentifierIndex === -1) {
115
+ return void 0;
116
+ }
117
+ return errMsgs.substring(firstIdentifierIndex + import_constant.WRAP_DATA_FETCH_ID_IDENTIFIER.length, secondIdentifierIndex);
118
+ };
119
+ async function fetchData(id, params, remoteInfo) {
120
+ const callFetchData = async () => {
121
+ const item = getDataFetchItem(id);
122
+ if (!item) {
123
+ return;
124
+ }
125
+ const [fetchDataFnArr, ..._rest] = item;
126
+ const fetchDataFn = await fetchDataFnArr[2];
127
+ if (!fetchDataFn) {
128
+ return;
129
+ }
130
+ return fetchDataFn(params);
131
+ };
132
+ if ((0, import_sdk.isBrowserEnv)()) {
133
+ var _dataFetchItem_;
134
+ const dataFetchItem = getDataFetchItem(id);
135
+ if (!dataFetchItem) {
136
+ throw new Error(`dataFetchItem not found, id: ${id}`);
137
+ }
138
+ if ((_dataFetchItem_ = dataFetchItem[1]) === null || _dataFetchItem_ === void 0 ? void 0 : _dataFetchItem_[0]) {
139
+ return dataFetchItem[1][0];
140
+ }
141
+ if ((0, import_utils.isCSROnly)()) {
142
+ import_logger.default.debug("==========csr only!");
143
+ return callFetchData();
144
+ }
145
+ if (remoteInfo) {
146
+ return (0, import_downgrade.callDowngrade)(id, params, remoteInfo);
147
+ }
148
+ const mfDowngrade = (0, import_downgrade.getDowngradeTag)();
149
+ if (mfDowngrade) {
150
+ if (typeof mfDowngrade === "boolean") {
151
+ return (0, import_downgrade.callDowngrade)(id, {
152
+ ...params,
153
+ isDowngrade: true
154
+ });
155
+ }
156
+ if (mfDowngrade.includes(id)) {
157
+ return (0, import_downgrade.callDowngrade)(id, {
158
+ ...params,
159
+ isDowngrade: true
160
+ });
161
+ }
162
+ }
163
+ let res;
164
+ let rej;
165
+ const p = new Promise((resolve, reject) => {
166
+ res = resolve;
167
+ rej = reject;
168
+ });
169
+ dataFetchItem[1] = [
170
+ p,
171
+ res,
172
+ rej
173
+ ];
174
+ dataFetchItem[2] = import_constant.MF_DATA_FETCH_STATUS.AWAIT;
175
+ return dataFetchItem[1][0];
176
+ }
177
+ return callFetchData();
178
+ }
179
+ function getDataFetchMapKey(dataFetchInfo, hostInfo) {
180
+ if (!dataFetchInfo || !hostInfo) {
181
+ return;
182
+ }
183
+ const { dataFetchId } = dataFetchInfo;
184
+ return (0, import_sdk.composeKeyWithSeparator)(dataFetchId, hostInfo.name, hostInfo.version);
185
+ }
186
+ async function loadDataFetchModule(instance, id) {
187
+ return instance.loadRemote(id).then((m) => {
188
+ if (m && typeof m === "object" && "fetchData" in m && typeof m.fetchData === "function") {
189
+ return m.fetchData;
190
+ }
191
+ throw new Error(`fetchData not found in remote ${id}, ${JSON.stringify(m)}`);
192
+ });
193
+ }
194
+ function isDataLoaderExpose(exposeKey) {
195
+ return exposeKey.endsWith(import_constant2.DATA_FETCH_IDENTIFIER) || exposeKey.endsWith(import_constant2.DATA_FETCH_CLIENT_SUFFIX);
196
+ }
197
+ // Annotate the CommonJS export names for ESM import in node:
198
+ 0 && (module.exports = {
199
+ fetchData,
200
+ flushDataFetch,
201
+ getDataFetchIdWithErrorMsgs,
202
+ getDataFetchInfo,
203
+ getDataFetchItem,
204
+ getDataFetchMap,
205
+ getDataFetchMapKey,
206
+ initDataFetchMap,
207
+ isDataLoaderExpose,
208
+ loadDataFetchModule,
209
+ setDataFetchItemLoadedStatus,
210
+ wrapDataFetchId
211
+ });
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var utils_exports = {};
21
+ __export(utils_exports, {
22
+ getLoadedRemoteInfos: () => getLoadedRemoteInfos,
23
+ isCSROnly: () => isCSROnly
24
+ });
25
+ module.exports = __toCommonJS(utils_exports);
26
+ __reExport(utils_exports, require("./dataFetch"), module.exports);
27
+ function getLoadedRemoteInfos(id, instance) {
28
+ if (!instance) {
29
+ return;
30
+ }
31
+ const { name, expose } = instance.remoteHandler.idToRemoteMap[id] || {};
32
+ if (!name) {
33
+ return;
34
+ }
35
+ const module2 = instance.moduleCache.get(name);
36
+ if (!module2) {
37
+ return;
38
+ }
39
+ const { remoteSnapshot } = instance.snapshotHandler.getGlobalRemoteInfo(module2.remoteInfo);
40
+ return {
41
+ ...module2.remoteInfo,
42
+ snapshot: remoteSnapshot,
43
+ expose
44
+ };
45
+ }
46
+ function isCSROnly() {
47
+ return window._SSR_DATA === void 0;
48
+ }
49
+ // Annotate the CommonJS export names for ESM import in node:
50
+ 0 && (module.exports = {
51
+ getLoadedRemoteInfos,
52
+ isCSROnly,
53
+ ...require("./dataFetch")
54
+ });
@@ -138,6 +138,7 @@ var patchMFConfig = function(mfConfig, isServer, remoteIpStrategy, enableSSR) {
138
138
  var runtimePlugins = _to_consumable_array(mfConfig.runtimePlugins || []);
139
139
  patchDTSConfig(mfConfig, isServer);
140
140
  injectRuntimePlugins(require.resolve("@module-federation/modern-js/shared-strategy"), runtimePlugins);
141
+ injectRuntimePlugins(require.resolve("@module-federation/modern-js/auto-fetch-data"), runtimePlugins);
141
142
  if (enableSSR && isDev()) {
142
143
  injectRuntimePlugins(require.resolve("@module-federation/modern-js/resolve-entry-ipv4"), runtimePlugins);
143
144
  }
@@ -43,6 +43,7 @@ describe("patchMFConfig", /* @__PURE__ */ _async_to_generator(function() {
43
43
  remoteType: "script",
44
44
  runtimePlugins: [
45
45
  require.resolve("@module-federation/modern-js/shared-strategy"),
46
+ require.resolve("@module-federation/modern-js/auto-fetch-data"),
46
47
  require.resolve("@module-federation/node/runtimePlugin"),
47
48
  require.resolve("@module-federation/modern-js/inject-node-fetch")
48
49
  ],
@@ -77,7 +78,7 @@ describe("patchMFConfig", /* @__PURE__ */ _async_to_generator(function() {
77
78
  remoteType: "script",
78
79
  runtimePlugins: [
79
80
  require.resolve("@module-federation/modern-js/shared-strategy"),
80
- require.resolve("@module-federation/bridge-react/lazy-load-component-plugin")
81
+ require.resolve("@module-federation/modern-js/auto-fetch-data")
81
82
  ],
82
83
  shared: {
83
84
  react: {
@@ -0,0 +1,76 @@
1
+ import { getDataFetchInfo, initDataFetchMap, getDataFetchItem, getDataFetchMap, isCSROnly } from "../../utils";
2
+ import logger from "../../logger";
3
+ import { getDataFetchMapKey, isDataLoaderExpose, loadDataFetchModule } from "../../utils/dataFetch";
4
+ import { MF_DATA_FETCH_TYPE, MF_DATA_FETCH_STATUS } from "../../constant";
5
+ import { DATA_FETCH_CLIENT_SUFFIX } from "@module-federation/rsbuild-plugin/constant";
6
+ var autoFetchData = function() {
7
+ return {
8
+ name: "auto-fetch-data-plugin",
9
+ beforeInit: function beforeInit(args) {
10
+ initDataFetchMap();
11
+ return args;
12
+ },
13
+ afterLoadSnapshot: function afterLoadSnapshot(args) {
14
+ var id = args.id, moduleInfo = args.moduleInfo, remoteSnapshot = args.remoteSnapshot, host = args.host;
15
+ if (typeof id === "string" && isDataLoaderExpose(id)) {
16
+ return args;
17
+ }
18
+ if (!remoteSnapshot || !id || !("modules" in remoteSnapshot)) {
19
+ return args;
20
+ }
21
+ var name = moduleInfo.name, alias = moduleInfo.alias;
22
+ var dataFetchInfo = getDataFetchInfo({
23
+ name,
24
+ alias,
25
+ id,
26
+ remoteSnapshot
27
+ });
28
+ if (!dataFetchInfo) {
29
+ return args;
30
+ }
31
+ var dataFetchId = dataFetchInfo.dataFetchId, dataFetchName = dataFetchInfo.dataFetchName;
32
+ var dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {
33
+ name: host.name,
34
+ version: host.options.version
35
+ });
36
+ logger.debug("======= auto fetch plugin dataFetchMapKey: ", dataFetchMapKey);
37
+ if (!dataFetchMapKey) {
38
+ return args;
39
+ }
40
+ var dataFetchItem = getDataFetchItem(dataFetchMapKey);
41
+ if (dataFetchItem) {
42
+ return args;
43
+ }
44
+ var dataFetchMap = getDataFetchMap();
45
+ var hasSSRAsset = Boolean(remoteSnapshot.ssrRemoteEntry);
46
+ var hasDataFetchClient = Boolean(remoteSnapshot.modules.find(function(module) {
47
+ return module.moduleName === "".concat(dataFetchName).concat(DATA_FETCH_CLIENT_SUFFIX);
48
+ }));
49
+ var downgradeType = hasDataFetchClient ? MF_DATA_FETCH_TYPE.FETCH_CLIENT : hasSSRAsset ? MF_DATA_FETCH_TYPE.FETCH_SERVER : MF_DATA_FETCH_TYPE.FETCH_CLIENT;
50
+ var finalDataFetchId = dataFetchId;
51
+ if (typeof window !== "undefined") {
52
+ finalDataFetchId = downgradeType === MF_DATA_FETCH_TYPE.FETCH_CLIENT ? hasDataFetchClient ? "".concat(dataFetchId).concat(DATA_FETCH_CLIENT_SUFFIX) : dataFetchId : dataFetchId;
53
+ }
54
+ var getDataFetchGetter = function() {
55
+ return loadDataFetchModule(host, finalDataFetchId);
56
+ };
57
+ var dataFetchFnItem = [
58
+ getDataFetchGetter,
59
+ downgradeType
60
+ ];
61
+ if (typeof window === "undefined" || isCSROnly()) {
62
+ dataFetchFnItem.push(getDataFetchGetter());
63
+ }
64
+ dataFetchMap[dataFetchMapKey] = [
65
+ dataFetchFnItem,
66
+ void 0,
67
+ MF_DATA_FETCH_STATUS.AWAIT
68
+ ];
69
+ return args;
70
+ }
71
+ };
72
+ };
73
+ var auto_fetch_data_default = autoFetchData;
74
+ export {
75
+ auto_fetch_data_default as default
76
+ };
@@ -1,4 +1,221 @@
1
- import dataFetchMiddleWare from "@module-federation/bridge-react/data-fetch-server-middleware";
1
+ import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
2
+ import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
3
+ import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
4
+ import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
5
+ import { DATA_FETCH_QUERY, MF_DATA_FETCH_STATUS } from "../../constant";
6
+ import logger from "../../logger";
7
+ import { getDataFetchMap } from "../../utils";
8
+ import { fetchData, initDataFetchMap, loadDataFetchModule } from "../../utils/dataFetch";
9
+ import { SEPARATOR, MANIFEST_EXT } from "@module-federation/sdk";
10
+ function wrapSetTimeout(targetPromise) {
11
+ var delay = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 2e4, id = arguments.length > 2 ? arguments[2] : void 0;
12
+ if (targetPromise && typeof targetPromise.then === "function") {
13
+ return new Promise(function(resolve, reject) {
14
+ var timeoutId = setTimeout(function() {
15
+ logger.warn("Data fetch for ID ".concat(id, " timed out after 20 seconds."));
16
+ reject(new Error("Data fetch for ID ".concat(id, " timed out after 20 seconds")));
17
+ }, delay);
18
+ targetPromise.then(function(value) {
19
+ clearTimeout(timeoutId);
20
+ resolve(value);
21
+ }).catch(function(err) {
22
+ clearTimeout(timeoutId);
23
+ reject(err);
24
+ });
25
+ });
26
+ }
27
+ }
28
+ function addProtocol(url) {
29
+ if (url.startsWith("//")) {
30
+ return "https:" + url;
31
+ }
32
+ return url;
33
+ }
34
+ var getDecodeQuery = function(url, name) {
35
+ var res = url.searchParams.get(name);
36
+ if (!res) {
37
+ return null;
38
+ }
39
+ return decodeURIComponent(res);
40
+ };
41
+ var middleware = function() {
42
+ var _ref = _async_to_generator(function(ctx, next) {
43
+ var _globalThis___FEDERATION__, url, dataFetchId, params, remoteInfo, remoteInfoQuery, _dataFetchMap_dataFetchId, _dataFetchMap_dataFetchId1, dataFetchMap, fetchDataPromise, targetPromise, wrappedPromise, res, hostInstance, remoteEntry, remote, _hostInstance_snapshotHandler_getGlobalRemoteInfo, hostGlobalSnapshot, remoteSnapshot, dataFetchItem, callFetchDataPromise, wrappedPromise1, res1, remoteId, hostInstance1, dataFetchFn, data, e;
44
+ return _ts_generator(this, function(_state) {
45
+ switch (_state.label) {
46
+ case 0:
47
+ try {
48
+ url = new URL(ctx.req.url);
49
+ dataFetchId = getDecodeQuery(url, DATA_FETCH_QUERY);
50
+ params = JSON.parse(getDecodeQuery(url, "params") || "{}");
51
+ remoteInfoQuery = getDecodeQuery(url, "remoteInfo");
52
+ remoteInfo = remoteInfoQuery ? JSON.parse(remoteInfoQuery) : null;
53
+ } catch (e2) {
54
+ logger.error("fetch data from server, error: ", e2);
55
+ return [
56
+ 2,
57
+ next()
58
+ ];
59
+ }
60
+ if (!dataFetchId) {
61
+ return [
62
+ 2,
63
+ next()
64
+ ];
65
+ }
66
+ logger.log("fetch data from server, dataFetchId: ", dataFetchId);
67
+ logger.debug("fetch data from server, moduleInfo: ", (_globalThis___FEDERATION__ = globalThis.__FEDERATION__) === null || _globalThis___FEDERATION__ === void 0 ? void 0 : _globalThis___FEDERATION__.moduleInfo);
68
+ _state.label = 1;
69
+ case 1:
70
+ _state.trys.push([
71
+ 1,
72
+ 9,
73
+ ,
74
+ 10
75
+ ]);
76
+ dataFetchMap = getDataFetchMap();
77
+ if (!dataFetchMap) {
78
+ initDataFetchMap();
79
+ }
80
+ fetchDataPromise = (_dataFetchMap_dataFetchId = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId === void 0 ? void 0 : _dataFetchMap_dataFetchId[1];
81
+ logger.debug("fetch data from server, fetchDataPromise: ", fetchDataPromise);
82
+ if (!(fetchDataPromise && ((_dataFetchMap_dataFetchId1 = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId1 === void 0 ? void 0 : _dataFetchMap_dataFetchId1[2]) !== MF_DATA_FETCH_STATUS.ERROR))
83
+ return [
84
+ 3,
85
+ 4
86
+ ];
87
+ targetPromise = fetchDataPromise[0];
88
+ wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
89
+ if (!wrappedPromise)
90
+ return [
91
+ 3,
92
+ 3
93
+ ];
94
+ return [
95
+ 4,
96
+ wrappedPromise
97
+ ];
98
+ case 2:
99
+ res = _state.sent();
100
+ logger.log("fetch data from server, fetchDataPromise res: ", res);
101
+ return [
102
+ 2,
103
+ ctx.json(res)
104
+ ];
105
+ case 3:
106
+ logger.error("Expected a Promise from fetchDataPromise[0] for dataFetchId ".concat(dataFetchId, ", but received:"), targetPromise, "Will try call new dataFetch again...");
107
+ _state.label = 4;
108
+ case 4:
109
+ if (remoteInfo) {
110
+ try {
111
+ hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
112
+ remoteEntry = "".concat(addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry);
113
+ if (!hostInstance) {
114
+ throw new Error("host instance not found!");
115
+ }
116
+ remote = hostInstance.options.remotes.find(function(remote2) {
117
+ return remote2.name === remoteInfo.name;
118
+ });
119
+ logger.debug("find remote: ", JSON.stringify(remote));
120
+ if (!remote) {
121
+ hostInstance.registerRemotes([
122
+ {
123
+ name: remoteInfo.name,
124
+ entry: remoteEntry,
125
+ entryGlobalName: remoteInfo.globalName
126
+ }
127
+ ]);
128
+ } else if (!("entry" in remote) || !remote.entry.includes(MANIFEST_EXT)) {
129
+ _hostInstance_snapshotHandler_getGlobalRemoteInfo = hostInstance.snapshotHandler.getGlobalRemoteInfo(remoteInfo), hostGlobalSnapshot = _hostInstance_snapshotHandler_getGlobalRemoteInfo.hostGlobalSnapshot, remoteSnapshot = _hostInstance_snapshotHandler_getGlobalRemoteInfo.remoteSnapshot;
130
+ logger.debug("find hostGlobalSnapshot: ", JSON.stringify(hostGlobalSnapshot));
131
+ logger.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
132
+ if (!hostGlobalSnapshot || !remoteSnapshot) {
133
+ if ("version" in remote) {
134
+ delete remote.version;
135
+ }
136
+ remote.entry = remoteEntry;
137
+ remote.entryGlobalName = remoteInfo.globalName;
138
+ }
139
+ }
140
+ } catch (e2) {
141
+ ctx.status(500);
142
+ return [
143
+ 2,
144
+ ctx.text("failed to fetch ".concat(remoteInfo.name, " data, error:\n ").concat(e2))
145
+ ];
146
+ }
147
+ }
148
+ dataFetchItem = dataFetchMap[dataFetchId];
149
+ logger.debug("fetch data from server, dataFetchItem: ", dataFetchItem);
150
+ if (!dataFetchItem)
151
+ return [
152
+ 3,
153
+ 6
154
+ ];
155
+ callFetchDataPromise = fetchData(dataFetchId, _object_spread_props(_object_spread({}, params), {
156
+ isDowngrade: !remoteInfo
157
+ }));
158
+ wrappedPromise1 = wrapSetTimeout(callFetchDataPromise, 2e4, dataFetchId);
159
+ if (!wrappedPromise1)
160
+ return [
161
+ 3,
162
+ 6
163
+ ];
164
+ return [
165
+ 4,
166
+ wrappedPromise1
167
+ ];
168
+ case 5:
169
+ res1 = _state.sent();
170
+ logger.log("fetch data from server, dataFetchItem res: ", res1);
171
+ return [
172
+ 2,
173
+ ctx.json(res1)
174
+ ];
175
+ case 6:
176
+ remoteId = dataFetchId.split(SEPARATOR)[0];
177
+ hostInstance1 = globalThis.__FEDERATION__.__INSTANCES__[0];
178
+ if (!hostInstance1) {
179
+ throw new Error("host instance not found!");
180
+ }
181
+ return [
182
+ 4,
183
+ loadDataFetchModule(hostInstance1, remoteId)
184
+ ];
185
+ case 7:
186
+ dataFetchFn = _state.sent();
187
+ return [
188
+ 4,
189
+ dataFetchFn(_object_spread_props(_object_spread({}, params), {
190
+ isDowngrade: !remoteInfo
191
+ }))
192
+ ];
193
+ case 8:
194
+ data = _state.sent();
195
+ logger.log("fetch data from server, loadDataFetchModule res: ", data);
196
+ return [
197
+ 2,
198
+ ctx.json(data)
199
+ ];
200
+ case 9:
201
+ e = _state.sent();
202
+ logger.error("server plugin data fetch error: ", e);
203
+ ctx.status(500);
204
+ return [
205
+ 2,
206
+ ctx.text("failed to fetch ".concat(remoteInfo.name, " data, error:\n ").concat(e))
207
+ ];
208
+ case 10:
209
+ return [
210
+ 2
211
+ ];
212
+ }
213
+ });
214
+ });
215
+ return function middleware2(ctx, next) {
216
+ return _ref.apply(this, arguments);
217
+ };
218
+ }();
2
219
  var dataFetchServePlugin = function() {
3
220
  return {
4
221
  name: "mf-data-fetch-server-plugin",
@@ -8,7 +225,7 @@ var dataFetchServePlugin = function() {
8
225
  middlewares.push({
9
226
  name: "module-federation-serve-manifest",
10
227
  // @ts-ignore type error
11
- handler: dataFetchMiddleWare
228
+ handler: middleware
12
229
  });
13
230
  });
14
231
  }
@@ -1,6 +1,42 @@
1
1
  var LOCALHOST = "localhost";
2
2
  var PLUGIN_IDENTIFIER = "[ Modern.js Module Federation ]";
3
+ var DATA_FETCH_QUERY = "x-mf-data-fetch";
4
+ var DATA_FETCH_ERROR_PREFIX = "caught the following error during dataFetch: ";
5
+ var LOAD_REMOTE_ERROR_PREFIX = "caught the following error during loadRemote: ";
6
+ var DOWNGRADE_KEY = "_mfSSRDowngrade";
7
+ var DATA_FETCH_MAP_KEY = "__MF_DATA_FETCH_MAP__";
8
+ var DATA_FETCH_FUNCTION = "_mfDataFetch";
9
+ var FS_HREF = "_mfFSHref";
10
+ var ERROR_TYPE = {
11
+ DATA_FETCH: 1,
12
+ LOAD_REMOTE: 2,
13
+ UNKNOWN: 3
14
+ };
15
+ var WRAP_DATA_FETCH_ID_IDENTIFIER = "wrap_dfip_identifier";
16
+ var MF_DATA_FETCH_TYPE;
17
+ (function(MF_DATA_FETCH_TYPE2) {
18
+ MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2["FETCH_SERVER"] = 1] = "FETCH_SERVER";
19
+ MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2["FETCH_CLIENT"] = 2] = "FETCH_CLIENT";
20
+ })(MF_DATA_FETCH_TYPE || (MF_DATA_FETCH_TYPE = {}));
21
+ var MF_DATA_FETCH_STATUS;
22
+ (function(MF_DATA_FETCH_STATUS2) {
23
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["LOADED"] = 1] = "LOADED";
24
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["LOADING"] = 2] = "LOADING";
25
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["AWAIT"] = 0] = "AWAIT";
26
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["ERROR"] = 3] = "ERROR";
27
+ })(MF_DATA_FETCH_STATUS || (MF_DATA_FETCH_STATUS = {}));
3
28
  export {
29
+ DATA_FETCH_ERROR_PREFIX,
30
+ DATA_FETCH_FUNCTION,
31
+ DATA_FETCH_MAP_KEY,
32
+ DATA_FETCH_QUERY,
33
+ DOWNGRADE_KEY,
34
+ ERROR_TYPE,
35
+ FS_HREF,
36
+ LOAD_REMOTE_ERROR_PREFIX,
4
37
  LOCALHOST,
5
- PLUGIN_IDENTIFIER
38
+ MF_DATA_FETCH_STATUS,
39
+ MF_DATA_FETCH_TYPE,
40
+ PLUGIN_IDENTIFIER,
41
+ WRAP_DATA_FETCH_ID_IDENTIFIER
6
42
  };
File without changes