@module-federation/modern-js 0.0.0-next-20250526025159 → 0.0.0-next-20250526035905

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 (82) hide show
  1. package/dist/cjs/cli/configPlugin.js +6 -8
  2. package/dist/cjs/cli/configPlugin.spec.js +1 -3
  3. package/dist/cjs/{runtime/wrapNoSSR.js → cli/constant.js} +6 -13
  4. package/dist/cjs/{logger.js → cli/logger.js} +1 -1
  5. package/dist/cjs/cli/ssrPlugin.js +11 -27
  6. package/dist/cjs/cli/utils.js +0 -5
  7. package/dist/cjs/constant.js +2 -49
  8. package/dist/cjs/runtime/createRemoteSSRComponent.js +210 -0
  9. package/dist/cjs/runtime/index.js +2 -11
  10. package/dist/cjs/{interfaces/global.js → ssr-runtime/index.js} +8 -2
  11. package/dist/cjs/ssr-runtime/{devPlugin.js → plugin.js} +6 -9
  12. package/dist/esm/cli/configPlugin.js +7 -9
  13. package/dist/esm/cli/configPlugin.spec.js +1 -3
  14. package/dist/esm/cli/constant.js +4 -0
  15. package/dist/esm/{logger.js → cli/logger.js} +1 -1
  16. package/dist/esm/cli/ssrPlugin.js +7 -24
  17. package/dist/esm/cli/utils.js +0 -4
  18. package/dist/esm/constant.js +1 -37
  19. package/dist/esm/runtime/createRemoteSSRComponent.js +263 -0
  20. package/dist/esm/runtime/index.js +2 -10
  21. package/dist/esm/ssr-runtime/index.js +1 -0
  22. package/dist/esm/ssr-runtime/{devPlugin.js → plugin.js} +2 -5
  23. package/dist/esm-node/cli/configPlugin.js +7 -9
  24. package/dist/esm-node/cli/configPlugin.spec.js +1 -3
  25. package/dist/esm-node/cli/constant.js +4 -0
  26. package/dist/esm-node/{logger.js → cli/logger.js} +1 -1
  27. package/dist/esm-node/cli/ssrPlugin.js +7 -23
  28. package/dist/esm-node/cli/utils.js +0 -4
  29. package/dist/esm-node/constant.js +1 -37
  30. package/dist/esm-node/runtime/createRemoteSSRComponent.js +175 -0
  31. package/dist/esm-node/runtime/index.js +2 -10
  32. package/dist/esm-node/ssr-runtime/index.js +1 -0
  33. package/dist/esm-node/ssr-runtime/{devPlugin.js → plugin.js} +2 -5
  34. package/dist/types/cli/constant.d.ts +1 -0
  35. package/dist/types/cli/index.d.ts +0 -1
  36. package/dist/types/cli/utils.d.ts +0 -1
  37. package/dist/types/constant.d.ts +0 -23
  38. package/dist/types/runtime/createRemoteSSRComponent.d.ts +19 -0
  39. package/dist/types/runtime/index.d.ts +2 -6
  40. package/dist/types/ssr-runtime/index.d.ts +1 -0
  41. package/dist/types/ssr-runtime/plugin.d.ts +2 -0
  42. package/package.json +17 -41
  43. package/dist/cjs/cli/mfRuntimePlugins/auto-fetch-data.js +0 -98
  44. package/dist/cjs/cli/server/data-fetch-server-plugin.js +0 -192
  45. package/dist/cjs/runtime/AwaitDataFetch.js +0 -144
  46. package/dist/cjs/runtime/createRemoteComponent.js +0 -327
  47. package/dist/cjs/ssr-runtime/downgrade.js +0 -108
  48. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +0 -128
  49. package/dist/cjs/utils/dataFetch.js +0 -211
  50. package/dist/cjs/utils/index.js +0 -54
  51. package/dist/esm/cli/mfRuntimePlugins/auto-fetch-data.js +0 -74
  52. package/dist/esm/cli/server/data-fetch-server-plugin.js +0 -240
  53. package/dist/esm/interfaces/global.js +0 -0
  54. package/dist/esm/runtime/AwaitDataFetch.js +0 -131
  55. package/dist/esm/runtime/createRemoteComponent.js +0 -417
  56. package/dist/esm/runtime/wrapNoSSR.js +0 -12
  57. package/dist/esm/ssr-runtime/downgrade.js +0 -143
  58. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +0 -168
  59. package/dist/esm/utils/dataFetch.js +0 -237
  60. package/dist/esm/utils/index.js +0 -28
  61. package/dist/esm-node/cli/mfRuntimePlugins/auto-fetch-data.js +0 -68
  62. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +0 -162
  63. package/dist/esm-node/interfaces/global.js +0 -0
  64. package/dist/esm-node/runtime/AwaitDataFetch.js +0 -109
  65. package/dist/esm-node/runtime/createRemoteComponent.js +0 -291
  66. package/dist/esm-node/runtime/wrapNoSSR.js +0 -11
  67. package/dist/esm-node/ssr-runtime/downgrade.js +0 -82
  68. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +0 -94
  69. package/dist/esm-node/utils/dataFetch.js +0 -166
  70. package/dist/esm-node/utils/index.js +0 -27
  71. package/dist/types/cli/mfRuntimePlugins/auto-fetch-data.d.ts +0 -3
  72. package/dist/types/cli/server/data-fetch-server-plugin.d.ts +0 -3
  73. package/dist/types/interfaces/global.d.ts +0 -27
  74. package/dist/types/runtime/AwaitDataFetch.d.ts +0 -19
  75. package/dist/types/runtime/createRemoteComponent.d.ts +0 -26
  76. package/dist/types/runtime/wrapNoSSR.d.ts +0 -9
  77. package/dist/types/ssr-runtime/devPlugin.d.ts +0 -2
  78. package/dist/types/ssr-runtime/downgrade.d.ts +0 -4
  79. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +0 -2
  80. package/dist/types/utils/dataFetch.d.ts +0 -26
  81. package/dist/types/utils/index.d.ts +0 -15
  82. /package/dist/types/{logger.d.ts → cli/logger.d.ts} +0 -0
@@ -1,192 +0,0 @@
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
- console.log("fetch data from server, error: ", e);
83
- console.error(e);
84
- return next();
85
- }
86
- if (!dataFetchId) {
87
- return next();
88
- }
89
- import_logger.default.log("fetch data from server, dataFetchId: ", dataFetchId);
90
- console.log("fetch data from server, moduleInfo: ", (_globalThis___FEDERATION__ = globalThis.__FEDERATION__) === null || _globalThis___FEDERATION__ === void 0 ? void 0 : _globalThis___FEDERATION__.moduleInfo);
91
- try {
92
- var _dataFetchMap_dataFetchId, _dataFetchMap_dataFetchId1;
93
- const dataFetchMap = (0, import_utils.getDataFetchMap)();
94
- if (!dataFetchMap) {
95
- (0, import_dataFetch.initDataFetchMap)();
96
- }
97
- const fetchDataPromise = (_dataFetchMap_dataFetchId = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId === void 0 ? void 0 : _dataFetchMap_dataFetchId[1];
98
- console.log("fetch data from server, fetchDataPromise: ", fetchDataPromise);
99
- if (fetchDataPromise && ((_dataFetchMap_dataFetchId1 = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId1 === void 0 ? void 0 : _dataFetchMap_dataFetchId1[2]) !== import_constant.MF_DATA_FETCH_STATUS.ERROR) {
100
- import_logger.default.log("fetch data from server, fetchDataPromise: ", fetchDataPromise);
101
- const targetPromise = fetchDataPromise[0];
102
- const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
103
- if (wrappedPromise) {
104
- const res = await wrappedPromise;
105
- import_logger.default.log("fetch data from server, fetchDataPromise res: ", res);
106
- return ctx.json(res);
107
- }
108
- import_logger.default.error(`Expected a Promise from fetchDataPromise[0] for dataFetchId ${dataFetchId}, but received:`, targetPromise, "Will try call new dataFetch again...");
109
- }
110
- if (remoteInfo) {
111
- try {
112
- const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
113
- const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
114
- if (!hostInstance2) {
115
- throw new Error("host instance not found!");
116
- }
117
- const remote = hostInstance2.options.remotes.find((remote2) => remote2.name === remoteInfo.name);
118
- import_logger.default.debug("find remote: ", JSON.stringify(remote));
119
- if (!remote) {
120
- hostInstance2.registerRemotes([
121
- {
122
- name: remoteInfo.name,
123
- entry: remoteEntry,
124
- entryGlobalName: remoteInfo.globalName
125
- }
126
- ]);
127
- } else if (!("entry" in remote) || !remote.entry.includes(import_sdk.MANIFEST_EXT)) {
128
- const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
129
- import_logger.default.debug("find hostGlobalSnapshot: ", JSON.stringify(hostGlobalSnapshot));
130
- import_logger.default.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
131
- if (!hostGlobalSnapshot || !remoteSnapshot) {
132
- if ("version" in remote) {
133
- delete remote.version;
134
- }
135
- remote.entry = remoteEntry;
136
- remote.entryGlobalName = remoteInfo.globalName;
137
- }
138
- }
139
- } catch (e) {
140
- ctx.status(500);
141
- return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
142
- ${e}`);
143
- }
144
- }
145
- const dataFetchItem = dataFetchMap[dataFetchId];
146
- console.log("fetch data from server, dataFetchItem: ", dataFetchItem);
147
- if (dataFetchItem) {
148
- import_logger.default.log("fetch data from server, dataFetchItem: ", dataFetchItem);
149
- const callFetchDataPromise = (0, import_dataFetch.fetchData)(dataFetchId, {
150
- ...params,
151
- isDowngrade: true
152
- });
153
- const wrappedPromise = wrapSetTimeout(callFetchDataPromise, 2e4, dataFetchId);
154
- if (wrappedPromise) {
155
- const res = await wrappedPromise;
156
- import_logger.default.log("fetch data from server, dataFetchItem res: ", res);
157
- return ctx.json(res);
158
- }
159
- }
160
- const remoteId = dataFetchId.split(import_sdk.SEPARATOR)[0];
161
- const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
162
- if (!hostInstance) {
163
- throw new Error("host instance not found!");
164
- }
165
- const dataFetchFn = await (0, import_dataFetch.loadDataFetchModule)(hostInstance, remoteId);
166
- const data = await dataFetchFn({
167
- ...params,
168
- isDowngrade: !remoteInfo
169
- });
170
- import_logger.default.log("fetch data from server, loadDataFetchModule res: ", data);
171
- return ctx.json(data);
172
- } catch (e) {
173
- console.log("server plugin data fetch error: ", e);
174
- ctx.status(500);
175
- return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
176
- ${e}`);
177
- }
178
- };
179
- const dataFetchServePlugin = () => ({
180
- name: "mf-data-fetch-server-plugin",
181
- setup: (api) => {
182
- api.onPrepare(() => {
183
- const { middlewares } = api.getServerContext();
184
- middlewares.push({
185
- name: "module-federation-serve-manifest",
186
- // @ts-ignore type error
187
- handler: middleware
188
- });
189
- });
190
- }
191
- });
192
- var data_fetch_server_plugin_default = dataFetchServePlugin;
@@ -1,144 +0,0 @@
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 AwaitDataFetch_exports = {};
30
- __export(AwaitDataFetch_exports, {
31
- AwaitDataFetch: () => AwaitDataFetch,
32
- transformError: () => transformError
33
- });
34
- module.exports = __toCommonJS(AwaitDataFetch_exports);
35
- var import_jsx_runtime = require("react/jsx-runtime");
36
- var import_react = require("react");
37
- var import_logger = __toESM(require("../logger"));
38
- var import_constant = require("../constant");
39
- var import_utils = require("../utils");
40
- function isPromise(obj) {
41
- return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
42
- }
43
- const AWAIT_ERROR_PREFIX = "<Await /> caught the following error during render: ";
44
- const transformError = (err) => {
45
- const errMsg = err instanceof Error ? err.message : err;
46
- const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, "");
47
- const dataFetchMapKey = (0, import_utils.getDataFetchIdWithErrorMsgs)(originalMsg);
48
- if (originalMsg.indexOf(import_constant.DATA_FETCH_ERROR_PREFIX) === 0) {
49
- return {
50
- error: new Error(originalMsg.replace(import_constant.DATA_FETCH_ERROR_PREFIX, "").replace((0, import_utils.wrapDataFetchId)(dataFetchMapKey), "")),
51
- errorType: import_constant.ERROR_TYPE.DATA_FETCH,
52
- dataFetchMapKey
53
- };
54
- }
55
- if (originalMsg.indexOf(import_constant.LOAD_REMOTE_ERROR_PREFIX) === 0) {
56
- return {
57
- error: new Error(originalMsg.replace(import_constant.LOAD_REMOTE_ERROR_PREFIX, "").replace((0, import_utils.wrapDataFetchId)(dataFetchMapKey), "")),
58
- errorType: import_constant.ERROR_TYPE.LOAD_REMOTE,
59
- dataFetchMapKey
60
- };
61
- }
62
- return {
63
- error: new Error(originalMsg.replace((0, import_utils.wrapDataFetchId)(dataFetchMapKey), "")),
64
- errorType: import_constant.ERROR_TYPE.UNKNOWN,
65
- dataFetchMapKey
66
- };
67
- };
68
- const DefaultLoading = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {});
69
- const DefaultErrorElement = (_data) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
70
- children: "Error"
71
- });
72
- function AwaitDataFetch({ resolve, loading = DefaultLoading, errorElement = DefaultErrorElement, children, params }) {
73
- const dataRef = (0, import_react.useRef)();
74
- const data = dataRef.current || resolve;
75
- const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;
76
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(AwaitSuspense, {
77
- params,
78
- loading,
79
- errorElement,
80
- // @ts-ignore
81
- resolve: getData,
82
- children
83
- });
84
- }
85
- function AwaitSuspense({ resolve, children, loading = DefaultLoading, errorElement = DefaultErrorElement }) {
86
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react.Suspense, {
87
- fallback: loading,
88
- children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ResolveAwait, {
89
- resolve,
90
- errorElement,
91
- children
92
- })
93
- });
94
- }
95
- function ResolveAwait({ children, resolve, errorElement, params }) {
96
- const data = resolve();
97
- import_logger.default.debug("resolve data: ", data);
98
- if (typeof data === "string" && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {
99
- const transformedError = transformError(data);
100
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {
101
- children: typeof errorElement === "function" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, {
102
- children: [
103
- globalThis.FEDERATION_SSR && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("script", {
104
- suppressHydrationWarning: true,
105
- dangerouslySetInnerHTML: {
106
- __html: String.raw`
107
- globalThis['${import_constant.DATA_FETCH_FUNCTION}'] = globalThis['${import_constant.DATA_FETCH_FUNCTION}'] || []
108
- globalThis['${import_constant.DATA_FETCH_FUNCTION}'].push([${transformedError.dataFetchMapKey ? `'${transformedError.dataFetchMapKey}'` : ""},${params ? JSON.stringify(params) : null},true]);`
109
- }
110
- }),
111
- errorElement(transformedError)
112
- ]
113
- }) : errorElement
114
- });
115
- }
116
- const toRender = typeof children === "function" ? children(data) : children;
117
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {
118
- children: toRender
119
- });
120
- }
121
- const fetchData = (promise, ref) => {
122
- let data;
123
- let status = "pending";
124
- const suspender = promise.then((res) => {
125
- status = "success";
126
- data = res;
127
- ref.current = res;
128
- }).catch((e) => {
129
- status = "success";
130
- console.warn(e);
131
- data = AWAIT_ERROR_PREFIX + e;
132
- });
133
- return () => {
134
- if (status === "pending") {
135
- throw suspender;
136
- }
137
- return data;
138
- };
139
- };
140
- // Annotate the CommonJS export names for ESM import in node:
141
- 0 && (module.exports = {
142
- AwaitDataFetch,
143
- transformError
144
- });
@@ -1,327 +0,0 @@
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 createRemoteComponent_exports = {};
30
- __export(createRemoteComponent_exports, {
31
- collectSSRAssets: () => collectSSRAssets,
32
- createRemoteComponent: () => createRemoteComponent,
33
- createRemoteSSRComponent: () => createRemoteSSRComponent
34
- });
35
- module.exports = __toCommonJS(createRemoteComponent_exports);
36
- var import_jsx_runtime = require("react/jsx-runtime");
37
- var import_react = __toESM(require("react"));
38
- var import_logger = __toESM(require("../logger"));
39
- var import_runtime = require("@module-federation/enhanced/runtime");
40
- var import_AwaitDataFetch = require("./AwaitDataFetch");
41
- var import_dataFetch = require("../utils/dataFetch");
42
- var import_utils = require("../utils");
43
- var import_constant = require("../constant");
44
- function getTargetModuleInfo(id) {
45
- const instance = (0, import_runtime.getInstance)();
46
- if (!instance) {
47
- return;
48
- }
49
- const loadedRemoteInfo = (0, import_utils.getLoadedRemoteInfos)(id, instance);
50
- if (!loadedRemoteInfo) {
51
- return;
52
- }
53
- const snapshot = loadedRemoteInfo.snapshot;
54
- if (!snapshot) {
55
- return;
56
- }
57
- const publicPath = "publicPath" in snapshot ? snapshot.publicPath : "getPublicPath" in snapshot ? new Function(snapshot.getPublicPath)() : "";
58
- if (!publicPath) {
59
- return;
60
- }
61
- const modules = "modules" in snapshot ? snapshot.modules : [];
62
- const targetModule = modules.find((m) => m.modulePath === loadedRemoteInfo.expose);
63
- if (!targetModule) {
64
- return;
65
- }
66
- const remoteEntry = "remoteEntry" in snapshot ? snapshot.remoteEntry : "";
67
- if (!remoteEntry) {
68
- return;
69
- }
70
- return {
71
- module: targetModule,
72
- publicPath,
73
- remoteEntry
74
- };
75
- }
76
- function collectSSRAssets(options) {
77
- const { id, injectLink = true, injectScript = false } = typeof options === "string" ? {
78
- id: options
79
- } : options;
80
- const links = [];
81
- const scripts = [];
82
- const instance = (0, import_runtime.getInstance)();
83
- if (!instance || !injectLink && !injectScript) {
84
- return [
85
- ...scripts,
86
- ...links
87
- ];
88
- }
89
- const moduleAndPublicPath = getTargetModuleInfo(id);
90
- if (!moduleAndPublicPath) {
91
- return [
92
- ...scripts,
93
- ...links
94
- ];
95
- }
96
- const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
97
- if (injectLink) {
98
- [
99
- ...targetModule.assets.css.sync,
100
- ...targetModule.assets.css.async
101
- ].sort().forEach((file, index) => {
102
- links.push(/* @__PURE__ */ (0, import_jsx_runtime.jsx)("link", {
103
- href: `${publicPath}${file}`,
104
- rel: "stylesheet",
105
- type: "text/css"
106
- }, `${file.split(".")[0]}_${index}`));
107
- });
108
- }
109
- if (injectScript) {
110
- scripts.push(/* @__PURE__ */ (0, import_jsx_runtime.jsx)("script", {
111
- async: true,
112
- src: `${publicPath}${remoteEntry}`,
113
- crossOrigin: "anonymous"
114
- }, remoteEntry.split(".")[0]));
115
- [
116
- ...targetModule.assets.js.sync
117
- ].sort().forEach((file, index) => {
118
- scripts.push(/* @__PURE__ */ (0, import_jsx_runtime.jsx)("script", {
119
- async: true,
120
- src: `${publicPath}${file}`,
121
- crossOrigin: "anonymous"
122
- }, `${file.split(".")[0]}_${index}`));
123
- });
124
- }
125
- return [
126
- ...scripts,
127
- ...links
128
- ];
129
- }
130
- function getServerNeedRemoteInfo(loadedRemoteInfo, id, noSSR) {
131
- if (noSSR || typeof window !== "undefined" && window.location.href !== window[import_constant.FS_HREF]) {
132
- var _dataFetchItem_;
133
- if (!(loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.version)) {
134
- throw new Error(`${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} version is empty`);
135
- }
136
- const { snapshot } = loadedRemoteInfo;
137
- if (!snapshot) {
138
- throw new Error(`${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} snapshot is empty`);
139
- }
140
- const dataFetchItem = (0, import_dataFetch.getDataFetchItem)(id);
141
- const isFetchServer = (dataFetchItem === null || dataFetchItem === void 0 ? void 0 : (_dataFetchItem_ = dataFetchItem[0]) === null || _dataFetchItem_ === void 0 ? void 0 : _dataFetchItem_[1]) === import_constant.MF_DATA_FETCH_TYPE.FETCH_SERVER;
142
- if (isFetchServer && (!("ssrPublicPath" in snapshot) || !snapshot.ssrPublicPath)) {
143
- throw new Error(`ssrPublicPath is required while fetching ${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} data in SSR project!`);
144
- }
145
- if (isFetchServer && (!("ssrRemoteEntry" in snapshot) || !snapshot.ssrRemoteEntry)) {
146
- throw new Error(`ssrRemoteEntry is required while loading ${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} data loader in SSR project!`);
147
- }
148
- return {
149
- name: loadedRemoteInfo.name,
150
- version: loadedRemoteInfo.version,
151
- ssrPublicPath: "ssrPublicPath" in snapshot ? snapshot.ssrPublicPath || "" : "",
152
- ssrRemoteEntry: "ssrRemoteEntry" in snapshot ? snapshot.ssrRemoteEntry || "" : "",
153
- globalName: loadedRemoteInfo.entryGlobalName
154
- };
155
- }
156
- return;
157
- }
158
- function createRemoteComponent(options) {
159
- const exportName = (options === null || options === void 0 ? void 0 : options.export) || "default";
160
- const callLoader = async () => {
161
- import_logger.default.debug("callLoader start", Date.now());
162
- const m = await options.loader();
163
- import_logger.default.debug("callLoader end", Date.now());
164
- if (!m) {
165
- throw new Error("load remote failed");
166
- }
167
- return m;
168
- };
169
- const getData = async (noSSR) => {
170
- let loadedRemoteInfo;
171
- let moduleId;
172
- const instance = (0, import_runtime.getInstance)();
173
- try {
174
- const m = await callLoader();
175
- moduleId = m && m[Symbol.for("mf_module_id")];
176
- if (!moduleId) {
177
- throw new Error("moduleId is empty");
178
- }
179
- loadedRemoteInfo = (0, import_utils.getLoadedRemoteInfos)(moduleId, instance);
180
- if (!loadedRemoteInfo) {
181
- throw new Error(`can not find loaded remote('${moduleId}') info!`);
182
- }
183
- } catch (e) {
184
- const errMsg = `${import_constant.LOAD_REMOTE_ERROR_PREFIX}${e}`;
185
- import_logger.default.debug(e);
186
- throw new Error(errMsg);
187
- }
188
- let dataFetchMapKey;
189
- try {
190
- dataFetchMapKey = (0, import_dataFetch.getDataFetchMapKey)((0, import_utils.getDataFetchInfo)({
191
- name: loadedRemoteInfo.name,
192
- alias: loadedRemoteInfo.alias,
193
- id: moduleId,
194
- remoteSnapshot: loadedRemoteInfo.snapshot
195
- }), {
196
- name: instance.name,
197
- version: instance === null || instance === void 0 ? void 0 : instance.options.version
198
- });
199
- import_logger.default.debug("getData dataFetchMapKey: ", dataFetchMapKey);
200
- if (!dataFetchMapKey) {
201
- return;
202
- }
203
- const data = await (0, import_dataFetch.fetchData)(dataFetchMapKey, {
204
- ...options.dataFetchParams,
205
- isDowngrade: false
206
- }, getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR));
207
- (0, import_utils.setDataFetchItemLoadedStatus)(dataFetchMapKey);
208
- import_logger.default.debug("get data res: \n", data);
209
- return data;
210
- } catch (err) {
211
- const errMsg = `${import_constant.DATA_FETCH_ERROR_PREFIX}${(0, import_utils.wrapDataFetchId)(dataFetchMapKey)}${err}`;
212
- import_logger.default.debug(errMsg);
213
- throw new Error(errMsg);
214
- }
215
- };
216
- const LazyComponent = /* @__PURE__ */ import_react.default.lazy(async () => {
217
- const m = await callLoader();
218
- const moduleId = m && m[Symbol.for("mf_module_id")];
219
- const instance = (0, import_runtime.getInstance)();
220
- const loadedRemoteInfo = (0, import_utils.getLoadedRemoteInfos)(moduleId, instance);
221
- loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.snapshot;
222
- const dataFetchMapKey = loadedRemoteInfo ? (0, import_dataFetch.getDataFetchMapKey)((0, import_utils.getDataFetchInfo)({
223
- name: loadedRemoteInfo.name,
224
- alias: loadedRemoteInfo.alias,
225
- id: moduleId,
226
- remoteSnapshot: loadedRemoteInfo.snapshot
227
- }), {
228
- name: instance.name,
229
- version: instance === null || instance === void 0 ? void 0 : instance.options.version
230
- }) : void 0;
231
- import_logger.default.debug("LazyComponent dataFetchMapKey: ", dataFetchMapKey);
232
- const assets = collectSSRAssets({
233
- id: moduleId
234
- });
235
- const Com = m[exportName];
236
- if (exportName in m && typeof Com === "function") {
237
- return {
238
- default: (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, {
239
- children: [
240
- globalThis.FEDERATION_SSR && dataFetchMapKey && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("script", {
241
- suppressHydrationWarning: true,
242
- dangerouslySetInnerHTML: {
243
- __html: String.raw`
244
- globalThis['${import_constant.DATA_FETCH_FUNCTION}'] = globalThis['${import_constant.DATA_FETCH_FUNCTION}'] || [];
245
- globalThis['${import_constant.DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
246
- `
247
- }
248
- }),
249
- globalThis.FEDERATION_SSR && assets,
250
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Com, {
251
- ...props
252
- })
253
- ]
254
- })
255
- };
256
- } else {
257
- throw Error(`Make sure that ${moduleId} has the correct export when export is ${String(exportName)}`);
258
- }
259
- });
260
- return (props) => {
261
- const { key, ...args } = props;
262
- if (globalThis.FEDERATION_SSR && !options.noSSR) {
263
- const { key: key2, ...args2 } = props;
264
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_AwaitDataFetch.AwaitDataFetch, {
265
- resolve: getData(options.noSSR),
266
- loading: options.loading,
267
- errorElement: options.fallback,
268
- children: (data) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComponent, {
269
- ...args2,
270
- mfData: data
271
- })
272
- });
273
- } else {
274
- const [data, setData] = (0, import_react.useState)(null);
275
- const [loading, setLoading] = (0, import_react.useState)(true);
276
- const [error, setError] = (0, import_react.useState)(null);
277
- (0, import_react.useEffect)(() => {
278
- let isMounted = true;
279
- const fetchDataAsync = async () => {
280
- try {
281
- setLoading(true);
282
- const result = await getData(options.noSSR);
283
- if (isMounted) {
284
- setData(result);
285
- }
286
- } catch (e) {
287
- if (isMounted) {
288
- setError((0, import_AwaitDataFetch.transformError)(e));
289
- }
290
- } finally {
291
- if (isMounted) {
292
- setLoading(false);
293
- }
294
- }
295
- };
296
- fetchDataAsync();
297
- return () => {
298
- isMounted = false;
299
- };
300
- }, []);
301
- if (loading) {
302
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {
303
- children: options.loading
304
- });
305
- }
306
- if (error) {
307
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {
308
- children: typeof options.fallback === "function" ? options.fallback(error) : options.fallback
309
- });
310
- }
311
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComponent, {
312
- ...args,
313
- mfData: data
314
- });
315
- }
316
- };
317
- }
318
- function createRemoteSSRComponent(options) {
319
- import_logger.default.warn("createRemoteSSRComponent is deprecated, please use createRemoteComponent instead!");
320
- return createRemoteComponent(options);
321
- }
322
- // Annotate the CommonJS export names for ESM import in node:
323
- 0 && (module.exports = {
324
- collectSSRAssets,
325
- createRemoteComponent,
326
- createRemoteSSRComponent
327
- });