@module-federation/bridge-react 0.0.0-next-20250618090118 → 0.0.0-next-20250620084158

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 (53) hide show
  1. package/CHANGELOG.md +3 -8
  2. package/__tests__/bridge.spec.tsx +7 -7
  3. package/dist/{bridge-base-DKPEvcPJ.js → bridge-base-BBH982Tz.cjs} +1 -1
  4. package/dist/{bridge-base-YDjQh_vg.mjs → bridge-base-P6pEjY1q.js} +1 -1
  5. package/dist/{index.esm-BjwhLgko.js → index-Cv3p6r66.cjs} +43 -21
  6. package/dist/{index.esm-nDSYG6Nj.mjs → index-D4yt7Udv.js} +43 -21
  7. package/dist/index.cjs.js +9 -427
  8. package/dist/index.d.ts +0 -77
  9. package/dist/index.es.js +11 -430
  10. package/dist/router-v5.cjs.js +1 -1
  11. package/dist/router-v5.es.js +1 -1
  12. package/dist/router-v6.cjs.js +1 -1
  13. package/dist/router-v6.es.js +1 -1
  14. package/dist/router.cjs.js +1 -1
  15. package/dist/router.es.js +1 -1
  16. package/dist/v18.cjs.js +1 -1
  17. package/dist/v18.es.js +1 -1
  18. package/dist/v19.cjs.js +1 -1
  19. package/dist/v19.es.js +1 -1
  20. package/package.json +5 -44
  21. package/src/index.ts +1 -21
  22. package/src/remote/component.tsx +3 -3
  23. package/src/remote/create.tsx +4 -17
  24. package/vite.config.ts +0 -13
  25. package/dist/data-fetch-runtime-plugin.cjs.js +0 -71
  26. package/dist/data-fetch-runtime-plugin.d.ts +0 -6
  27. package/dist/data-fetch-runtime-plugin.es.js +0 -72
  28. package/dist/data-fetch-server-middleware.cjs.js +0 -158
  29. package/dist/data-fetch-server-middleware.d.ts +0 -6
  30. package/dist/data-fetch-server-middleware.es.js +0 -159
  31. package/dist/data-fetch-utils.cjs.js +0 -90
  32. package/dist/data-fetch-utils.d.ts +0 -5
  33. package/dist/data-fetch-utils.es.js +0 -90
  34. package/dist/index-BYOQ_Qrb.js +0 -45
  35. package/dist/index-CUrEc0Q1.mjs +0 -46
  36. package/dist/lazy-utils.cjs.js +0 -22
  37. package/dist/lazy-utils.d.ts +0 -114
  38. package/dist/lazy-utils.es.js +0 -22
  39. package/dist/utils-DhtukXOQ.mjs +0 -327
  40. package/dist/utils-YoyAVYsh.js +0 -326
  41. package/src/lazy/AwaitDataFetch.tsx +0 -176
  42. package/src/lazy/constant.ts +0 -30
  43. package/src/lazy/createLazyComponent.tsx +0 -390
  44. package/src/lazy/data-fetch/call-data-fetch.ts +0 -13
  45. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +0 -191
  46. package/src/lazy/data-fetch/index.ts +0 -2
  47. package/src/lazy/data-fetch/inject-data-fetch.ts +0 -109
  48. package/src/lazy/data-fetch/runtime-plugin.ts +0 -113
  49. package/src/lazy/index.ts +0 -18
  50. package/src/lazy/logger.ts +0 -6
  51. package/src/lazy/types.ts +0 -49
  52. package/src/lazy/utils.ts +0 -355
  53. package/src/lazy/wrapNoSSR.tsx +0 -10
package/src/index.ts CHANGED
@@ -3,21 +3,7 @@
3
3
  * This file provides support for React 16 and 17 versions, using the traditional ReactDOM.render API
4
4
  */
5
5
  export { createBridgeComponent } from './provider/versions/legacy';
6
- export {
7
- createRemoteComponent,
8
- createRemoteAppComponent,
9
- } from './remote/create';
10
- export {
11
- ERROR_TYPE,
12
- createLazyComponent,
13
- collectSSRAssets,
14
- wrapNoSSR,
15
- injectDataFetch,
16
- callDataFetch,
17
- setSSREnv,
18
- autoFetchDataPlugin,
19
- } from './lazy';
20
-
6
+ export { createRemoteComponent } from './remote/create';
21
7
  export type { CreateRootOptions, Root } from './provider/versions/legacy';
22
8
  export type {
23
9
  ProviderParams,
@@ -26,9 +12,3 @@ export type {
26
12
  DestroyParams,
27
13
  RenderParams,
28
14
  } from './types';
29
- export type {
30
- DataFetchParams,
31
- NoSSRRemoteInfo,
32
- CollectSSRAssetsOptions,
33
- CreateLazyComponentOptions,
34
- } from './lazy';
@@ -48,7 +48,7 @@ const RemoteAppWrapper = forwardRef(function (
48
48
  return () => {
49
49
  if (providerInfoRef.current?.destroy) {
50
50
  LoggerInstance.debug(
51
- `createRemoteAppComponent LazyComponent destroy >>>`,
51
+ `createRemoteComponent LazyComponent destroy >>>`,
52
52
  { moduleName, basename, dom: renderDom.current },
53
53
  );
54
54
 
@@ -171,7 +171,7 @@ export function withRouterData<
171
171
  }
172
172
  }
173
173
 
174
- LoggerInstance.debug(`createRemoteAppComponent withRouterData >>>`, {
174
+ LoggerInstance.debug(`createRemoteComponent withRouterData >>>`, {
175
175
  ...props,
176
176
  basename,
177
177
  routerContextVal,
@@ -185,7 +185,7 @@ export function withRouterData<
185
185
  useEffect(() => {
186
186
  if (pathname !== '' && pathname !== location.pathname) {
187
187
  LoggerInstance.debug(
188
- `createRemoteAppComponent dispatchPopstateEnv >>>`,
188
+ `createRemoteComponent dispatchPopstateEnv >>>`,
189
189
  {
190
190
  name: props.name,
191
191
  pathname: location.pathname,
@@ -16,7 +16,7 @@ function createLazyRemoteComponent<
16
16
  >(info: LazyRemoteComponentInfo<T, E>) {
17
17
  const exportName = info?.export || 'default';
18
18
  return React.lazy(async () => {
19
- LoggerInstance.debug(`createRemoteAppComponent LazyComponent create >>>`, {
19
+ LoggerInstance.debug(`createRemoteComponent LazyComponent create >>>`, {
20
20
  lazyComponent: info.loader,
21
21
  exportName,
22
22
  });
@@ -26,7 +26,7 @@ function createLazyRemoteComponent<
26
26
  // @ts-ignore
27
27
  const moduleName = m && m[Symbol.for('mf_module_id')];
28
28
  LoggerInstance.debug(
29
- `createRemoteAppComponent LazyComponent loadRemote info >>>`,
29
+ `createRemoteComponent LazyComponent loadRemote info >>>`,
30
30
  { name: moduleName, module: m, exportName },
31
31
  );
32
32
 
@@ -55,7 +55,7 @@ function createLazyRemoteComponent<
55
55
  };
56
56
  } else {
57
57
  LoggerInstance.debug(
58
- `createRemoteAppComponent LazyComponent module not found >>>`,
58
+ `createRemoteComponent LazyComponent module not found >>>`,
59
59
  { name: moduleName, module: m, exportName },
60
60
  );
61
61
  throw Error(
@@ -70,7 +70,7 @@ function createLazyRemoteComponent<
70
70
  });
71
71
  }
72
72
 
73
- export function createRemoteAppComponent<
73
+ export function createRemoteComponent<
74
74
  T = Record<string, unknown>,
75
75
  E extends keyof T = keyof T,
76
76
  >(info: LazyRemoteComponentInfo<T, E>) {
@@ -87,16 +87,3 @@ export function createRemoteAppComponent<
87
87
  );
88
88
  });
89
89
  }
90
-
91
- /**
92
- * @deprecated createRemoteAppComponent is deprecated, please use createRemoteAppComponent instead!
93
- */
94
- export function createRemoteComponent<
95
- T = Record<string, unknown>,
96
- E extends keyof T = keyof T,
97
- >(info: LazyRemoteComponentInfo<T, E>) {
98
- LoggerInstance.warn(
99
- `createRemoteAppComponent is deprecated, please use createRemoteAppComponent instead!`,
100
- );
101
- return createRemoteAppComponent(info);
102
- }
package/vite.config.ts CHANGED
@@ -26,19 +26,6 @@ export default defineConfig({
26
26
  'router-v6': path.resolve(__dirname, 'src/router/v6.tsx'),
27
27
  v18: path.resolve(__dirname, 'src/v18.ts'),
28
28
  v19: path.resolve(__dirname, 'src/v19.ts'),
29
- 'data-fetch-runtime-plugin': path.resolve(
30
- __dirname,
31
- 'src/lazy/data-fetch/runtime-plugin.ts',
32
- ),
33
- 'data-fetch-server-middleware': path.resolve(
34
- __dirname,
35
- 'src/lazy/data-fetch/data-fetch-server-middleware.ts',
36
- ),
37
- 'lazy-utils': path.resolve(__dirname, 'src/lazy/utils.ts'),
38
- 'data-fetch-utils': path.resolve(
39
- __dirname,
40
- 'src/lazy/data-fetch/index.ts',
41
- ),
42
29
  },
43
30
  formats: ['cjs', 'es'],
44
31
  fileName: (format, entryName) => `${entryName}.${format}.js`,
@@ -1,71 +0,0 @@
1
- "use strict";
2
- const lazyUtils = require("./utils-YoyAVYsh.js");
3
- const autoFetchData = () => ({
4
- name: "auto-fetch-data-plugin",
5
- beforeInit(args) {
6
- lazyUtils.initDataFetchMap();
7
- return args;
8
- },
9
- afterLoadSnapshot(args) {
10
- const { id, moduleInfo, remoteSnapshot, host } = args;
11
- if (typeof id === "string" && lazyUtils.isDataLoaderExpose(id)) {
12
- return args;
13
- }
14
- if (!remoteSnapshot || !id || !("modules" in remoteSnapshot)) {
15
- return args;
16
- }
17
- const { name, alias } = moduleInfo;
18
- const dataFetchInfo = lazyUtils.getDataFetchInfo({
19
- name,
20
- alias,
21
- id,
22
- remoteSnapshot
23
- });
24
- if (!dataFetchInfo) {
25
- return args;
26
- }
27
- const { dataFetchId, dataFetchName } = dataFetchInfo;
28
- const dataFetchMapKey = lazyUtils.getDataFetchMapKey(dataFetchInfo, {
29
- name: host.name,
30
- version: host.options.version
31
- });
32
- lazyUtils.logger.debug(
33
- "======= auto fetch plugin dataFetchMapKey: ",
34
- dataFetchMapKey
35
- );
36
- if (!dataFetchMapKey) {
37
- return args;
38
- }
39
- const dataFetchItem = lazyUtils.getDataFetchItem(dataFetchMapKey);
40
- if (dataFetchItem) {
41
- return args;
42
- }
43
- const dataFetchMap = lazyUtils.getDataFetchMap();
44
- const hasSSRAsset = Boolean(remoteSnapshot.ssrRemoteEntry);
45
- const hasDataFetchClient = Boolean(
46
- remoteSnapshot.modules.find(
47
- (module2) => module2.moduleName === `${dataFetchName}${lazyUtils.DATA_FETCH_CLIENT_SUFFIX}`
48
- )
49
- );
50
- const downgradeType = hasDataFetchClient ? lazyUtils.MF_DATA_FETCH_TYPE.FETCH_CLIENT : hasSSRAsset ? lazyUtils.MF_DATA_FETCH_TYPE.FETCH_SERVER : lazyUtils.MF_DATA_FETCH_TYPE.FETCH_CLIENT;
51
- let finalDataFetchId = dataFetchId;
52
- if (typeof window !== "undefined") {
53
- finalDataFetchId = downgradeType === lazyUtils.MF_DATA_FETCH_TYPE.FETCH_CLIENT ? hasDataFetchClient ? `${dataFetchId}${lazyUtils.DATA_FETCH_CLIENT_SUFFIX}` : dataFetchId : dataFetchId;
54
- }
55
- const getDataFetchGetter = () => lazyUtils.loadDataFetchModule(host, finalDataFetchId);
56
- const dataFetchFnItem = [
57
- getDataFetchGetter,
58
- downgradeType
59
- ];
60
- if (typeof window === "undefined" || lazyUtils.isCSROnly()) {
61
- dataFetchFnItem.push(getDataFetchGetter());
62
- }
63
- dataFetchMap[dataFetchMapKey] = [
64
- dataFetchFnItem,
65
- void 0,
66
- lazyUtils.MF_DATA_FETCH_STATUS.AWAIT
67
- ];
68
- return args;
69
- }
70
- });
71
- module.exports = autoFetchData;
@@ -1,6 +0,0 @@
1
- import { FederationRuntimePlugin } from '@module-federation/runtime';
2
-
3
- declare const autoFetchData: () => FederationRuntimePlugin;
4
- export default autoFetchData;
5
-
6
- export { }
@@ -1,72 +0,0 @@
1
- import { i as isDataLoaderExpose, g as getDataFetchInfo, a as getDataFetchMapKey, l as logger, b as getDataFetchItem, D as DATA_FETCH_CLIENT_SUFFIX, M as MF_DATA_FETCH_TYPE, c as isCSROnly, d as loadDataFetchModule, e as MF_DATA_FETCH_STATUS, f as getDataFetchMap, h as initDataFetchMap } from "./utils-DhtukXOQ.mjs";
2
- const autoFetchData = () => ({
3
- name: "auto-fetch-data-plugin",
4
- beforeInit(args) {
5
- initDataFetchMap();
6
- return args;
7
- },
8
- afterLoadSnapshot(args) {
9
- const { id, moduleInfo, remoteSnapshot, host } = args;
10
- if (typeof id === "string" && isDataLoaderExpose(id)) {
11
- return args;
12
- }
13
- if (!remoteSnapshot || !id || !("modules" in remoteSnapshot)) {
14
- return args;
15
- }
16
- const { name, alias } = moduleInfo;
17
- const dataFetchInfo = getDataFetchInfo({
18
- name,
19
- alias,
20
- id,
21
- remoteSnapshot
22
- });
23
- if (!dataFetchInfo) {
24
- return args;
25
- }
26
- const { dataFetchId, dataFetchName } = dataFetchInfo;
27
- const dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {
28
- name: host.name,
29
- version: host.options.version
30
- });
31
- logger.debug(
32
- "======= auto fetch plugin dataFetchMapKey: ",
33
- dataFetchMapKey
34
- );
35
- if (!dataFetchMapKey) {
36
- return args;
37
- }
38
- const dataFetchItem = getDataFetchItem(dataFetchMapKey);
39
- if (dataFetchItem) {
40
- return args;
41
- }
42
- const dataFetchMap = getDataFetchMap();
43
- const hasSSRAsset = Boolean(remoteSnapshot.ssrRemoteEntry);
44
- const hasDataFetchClient = Boolean(
45
- remoteSnapshot.modules.find(
46
- (module) => module.moduleName === `${dataFetchName}${DATA_FETCH_CLIENT_SUFFIX}`
47
- )
48
- );
49
- const downgradeType = hasDataFetchClient ? MF_DATA_FETCH_TYPE.FETCH_CLIENT : hasSSRAsset ? MF_DATA_FETCH_TYPE.FETCH_SERVER : MF_DATA_FETCH_TYPE.FETCH_CLIENT;
50
- let finalDataFetchId = dataFetchId;
51
- if (typeof window !== "undefined") {
52
- finalDataFetchId = downgradeType === MF_DATA_FETCH_TYPE.FETCH_CLIENT ? hasDataFetchClient ? `${dataFetchId}${DATA_FETCH_CLIENT_SUFFIX}` : dataFetchId : dataFetchId;
53
- }
54
- const getDataFetchGetter = () => loadDataFetchModule(host, finalDataFetchId);
55
- const dataFetchFnItem = [
56
- getDataFetchGetter,
57
- downgradeType
58
- ];
59
- if (typeof window === "undefined" || isCSROnly()) {
60
- dataFetchFnItem.push(getDataFetchGetter());
61
- }
62
- dataFetchMap[dataFetchMapKey] = [
63
- dataFetchFnItem,
64
- void 0,
65
- MF_DATA_FETCH_STATUS.AWAIT
66
- ];
67
- return args;
68
- }
69
- });
70
- export {
71
- autoFetchData as default
72
- };
@@ -1,158 +0,0 @@
1
- "use strict";
2
- const lazyUtils = require("./utils-YoyAVYsh.js");
3
- const index_esm = require("./index.esm-BjwhLgko.js");
4
- function wrapSetTimeout(targetPromise, delay = 2e4, id) {
5
- if (targetPromise && typeof targetPromise.then === "function") {
6
- return new Promise((resolve, reject) => {
7
- const timeoutId = setTimeout(() => {
8
- lazyUtils.logger.warn(`Data fetch for ID ${id} timed out after 20 seconds.`);
9
- reject(new Error(`Data fetch for ID ${id} timed out after 20 seconds`));
10
- }, delay);
11
- targetPromise.then((value) => {
12
- clearTimeout(timeoutId);
13
- resolve(value);
14
- }).catch((err) => {
15
- clearTimeout(timeoutId);
16
- reject(err);
17
- });
18
- });
19
- }
20
- }
21
- function addProtocol(url) {
22
- if (url.startsWith("//")) {
23
- return "https:" + url;
24
- }
25
- return url;
26
- }
27
- const getDecodeQuery = (url, name) => {
28
- const res = url.searchParams.get(name);
29
- if (!res) {
30
- return null;
31
- }
32
- return decodeURIComponent(res);
33
- };
34
- const dataFetchServerMiddleware = async (ctx, next) => {
35
- var _a, _b, _c;
36
- let url;
37
- let dataFetchId;
38
- let params;
39
- let remoteInfo;
40
- try {
41
- url = new URL(ctx.req.url);
42
- dataFetchId = getDecodeQuery(url, lazyUtils.DATA_FETCH_QUERY);
43
- params = JSON.parse(getDecodeQuery(url, "params") || "{}");
44
- const remoteInfoQuery = getDecodeQuery(url, "remoteInfo");
45
- remoteInfo = remoteInfoQuery ? JSON.parse(remoteInfoQuery) : null;
46
- } catch (e) {
47
- lazyUtils.logger.error("fetch data from server, error: ", e);
48
- return next();
49
- }
50
- if (!dataFetchId) {
51
- return next();
52
- }
53
- lazyUtils.logger.log("fetch data from server, dataFetchId: ", dataFetchId);
54
- lazyUtils.logger.debug(
55
- "fetch data from server, moduleInfo: ",
56
- (_a = globalThis.__FEDERATION__) == null ? void 0 : _a.moduleInfo
57
- );
58
- try {
59
- const dataFetchMap = lazyUtils.getDataFetchMap();
60
- if (!dataFetchMap) {
61
- lazyUtils.initDataFetchMap();
62
- }
63
- const fetchDataPromise = (_b = dataFetchMap[dataFetchId]) == null ? void 0 : _b[1];
64
- lazyUtils.logger.debug(
65
- "fetch data from server, fetchDataPromise: ",
66
- fetchDataPromise
67
- );
68
- if (fetchDataPromise && ((_c = dataFetchMap[dataFetchId]) == null ? void 0 : _c[2]) !== lazyUtils.MF_DATA_FETCH_STATUS.ERROR) {
69
- const targetPromise = fetchDataPromise[0];
70
- const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
71
- if (wrappedPromise) {
72
- const res = await wrappedPromise;
73
- lazyUtils.logger.log("fetch data from server, fetchDataPromise res: ", res);
74
- return ctx.json(res);
75
- }
76
- lazyUtils.logger.error(
77
- `Expected a Promise from fetchDataPromise[0] for dataFetchId ${dataFetchId}, but received:`,
78
- targetPromise,
79
- "Will try call new dataFetch again..."
80
- );
81
- }
82
- if (remoteInfo) {
83
- try {
84
- const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
85
- const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
86
- if (!hostInstance2) {
87
- throw new Error("host instance not found!");
88
- }
89
- const remote = hostInstance2.options.remotes.find(
90
- (remote2) => remote2.name === remoteInfo.name
91
- );
92
- lazyUtils.logger.debug("find remote: ", JSON.stringify(remote));
93
- if (!remote) {
94
- hostInstance2.registerRemotes([
95
- {
96
- name: remoteInfo.name,
97
- entry: remoteEntry,
98
- entryGlobalName: remoteInfo.globalName
99
- }
100
- ]);
101
- } else if (!("entry" in remote) || !remote.entry.includes(index_esm.MANIFEST_EXT)) {
102
- const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
103
- lazyUtils.logger.debug(
104
- "find hostGlobalSnapshot: ",
105
- JSON.stringify(hostGlobalSnapshot)
106
- );
107
- lazyUtils.logger.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
108
- if (!hostGlobalSnapshot || !remoteSnapshot) {
109
- if ("version" in remote) {
110
- delete remote.version;
111
- }
112
- remote.entry = remoteEntry;
113
- remote.entryGlobalName = remoteInfo.globalName;
114
- }
115
- }
116
- } catch (e) {
117
- ctx.status(500);
118
- return ctx.text(
119
- `failed to fetch ${remoteInfo.name} data, error:
120
- ${e}`
121
- );
122
- }
123
- }
124
- const dataFetchItem = dataFetchMap[dataFetchId];
125
- lazyUtils.logger.debug("fetch data from server, dataFetchItem: ", dataFetchItem);
126
- if (dataFetchItem) {
127
- const callFetchDataPromise = lazyUtils.fetchData(dataFetchId, {
128
- ...params,
129
- isDowngrade: !remoteInfo
130
- });
131
- const wrappedPromise = wrapSetTimeout(
132
- callFetchDataPromise,
133
- 2e4,
134
- dataFetchId
135
- );
136
- if (wrappedPromise) {
137
- const res = await wrappedPromise;
138
- lazyUtils.logger.log("fetch data from server, dataFetchItem res: ", res);
139
- return ctx.json(res);
140
- }
141
- }
142
- const remoteId = dataFetchId.split(index_esm.SEPARATOR)[0];
143
- const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
144
- if (!hostInstance) {
145
- throw new Error("host instance not found!");
146
- }
147
- const dataFetchFn = await lazyUtils.loadDataFetchModule(hostInstance, remoteId);
148
- const data = await dataFetchFn({ ...params, isDowngrade: !remoteInfo });
149
- lazyUtils.logger.log("fetch data from server, loadDataFetchModule res: ", data);
150
- return ctx.json(data);
151
- } catch (e) {
152
- lazyUtils.logger.error("server plugin data fetch error: ", e);
153
- ctx.status(500);
154
- return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
155
- ${e}`);
156
- }
157
- };
158
- module.exports = dataFetchServerMiddleware;
@@ -1,6 +0,0 @@
1
- import { MiddlewareHandler } from 'hono';
2
-
3
- declare const dataFetchServerMiddleware: MiddlewareHandler;
4
- export default dataFetchServerMiddleware;
5
-
6
- export { }
@@ -1,159 +0,0 @@
1
- import { j as DATA_FETCH_QUERY, l as logger, f as getDataFetchMap, h as initDataFetchMap, e as MF_DATA_FETCH_STATUS, k as fetchData, d as loadDataFetchModule } from "./utils-DhtukXOQ.mjs";
2
- import { M as MANIFEST_EXT, S as SEPARATOR } from "./index.esm-nDSYG6Nj.mjs";
3
- function wrapSetTimeout(targetPromise, delay = 2e4, id) {
4
- if (targetPromise && typeof targetPromise.then === "function") {
5
- return new Promise((resolve, reject) => {
6
- const timeoutId = setTimeout(() => {
7
- logger.warn(`Data fetch for ID ${id} timed out after 20 seconds.`);
8
- reject(new Error(`Data fetch for ID ${id} timed out after 20 seconds`));
9
- }, delay);
10
- targetPromise.then((value) => {
11
- clearTimeout(timeoutId);
12
- resolve(value);
13
- }).catch((err) => {
14
- clearTimeout(timeoutId);
15
- reject(err);
16
- });
17
- });
18
- }
19
- }
20
- function addProtocol(url) {
21
- if (url.startsWith("//")) {
22
- return "https:" + url;
23
- }
24
- return url;
25
- }
26
- const getDecodeQuery = (url, name) => {
27
- const res = url.searchParams.get(name);
28
- if (!res) {
29
- return null;
30
- }
31
- return decodeURIComponent(res);
32
- };
33
- const dataFetchServerMiddleware = async (ctx, next) => {
34
- var _a, _b, _c;
35
- let url;
36
- let dataFetchId;
37
- let params;
38
- let remoteInfo;
39
- try {
40
- url = new URL(ctx.req.url);
41
- dataFetchId = getDecodeQuery(url, DATA_FETCH_QUERY);
42
- params = JSON.parse(getDecodeQuery(url, "params") || "{}");
43
- const remoteInfoQuery = getDecodeQuery(url, "remoteInfo");
44
- remoteInfo = remoteInfoQuery ? JSON.parse(remoteInfoQuery) : null;
45
- } catch (e) {
46
- logger.error("fetch data from server, error: ", e);
47
- return next();
48
- }
49
- if (!dataFetchId) {
50
- return next();
51
- }
52
- logger.log("fetch data from server, dataFetchId: ", dataFetchId);
53
- logger.debug(
54
- "fetch data from server, moduleInfo: ",
55
- (_a = globalThis.__FEDERATION__) == null ? void 0 : _a.moduleInfo
56
- );
57
- try {
58
- const dataFetchMap = getDataFetchMap();
59
- if (!dataFetchMap) {
60
- initDataFetchMap();
61
- }
62
- const fetchDataPromise = (_b = dataFetchMap[dataFetchId]) == null ? void 0 : _b[1];
63
- logger.debug(
64
- "fetch data from server, fetchDataPromise: ",
65
- fetchDataPromise
66
- );
67
- if (fetchDataPromise && ((_c = dataFetchMap[dataFetchId]) == null ? void 0 : _c[2]) !== MF_DATA_FETCH_STATUS.ERROR) {
68
- const targetPromise = fetchDataPromise[0];
69
- const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
70
- if (wrappedPromise) {
71
- const res = await wrappedPromise;
72
- logger.log("fetch data from server, fetchDataPromise res: ", res);
73
- return ctx.json(res);
74
- }
75
- logger.error(
76
- `Expected a Promise from fetchDataPromise[0] for dataFetchId ${dataFetchId}, but received:`,
77
- targetPromise,
78
- "Will try call new dataFetch again..."
79
- );
80
- }
81
- if (remoteInfo) {
82
- try {
83
- const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
84
- const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
85
- if (!hostInstance2) {
86
- throw new Error("host instance not found!");
87
- }
88
- const remote = hostInstance2.options.remotes.find(
89
- (remote2) => remote2.name === remoteInfo.name
90
- );
91
- logger.debug("find remote: ", JSON.stringify(remote));
92
- if (!remote) {
93
- hostInstance2.registerRemotes([
94
- {
95
- name: remoteInfo.name,
96
- entry: remoteEntry,
97
- entryGlobalName: remoteInfo.globalName
98
- }
99
- ]);
100
- } else if (!("entry" in remote) || !remote.entry.includes(MANIFEST_EXT)) {
101
- const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
102
- logger.debug(
103
- "find hostGlobalSnapshot: ",
104
- JSON.stringify(hostGlobalSnapshot)
105
- );
106
- logger.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
107
- if (!hostGlobalSnapshot || !remoteSnapshot) {
108
- if ("version" in remote) {
109
- delete remote.version;
110
- }
111
- remote.entry = remoteEntry;
112
- remote.entryGlobalName = remoteInfo.globalName;
113
- }
114
- }
115
- } catch (e) {
116
- ctx.status(500);
117
- return ctx.text(
118
- `failed to fetch ${remoteInfo.name} data, error:
119
- ${e}`
120
- );
121
- }
122
- }
123
- const dataFetchItem = dataFetchMap[dataFetchId];
124
- logger.debug("fetch data from server, dataFetchItem: ", dataFetchItem);
125
- if (dataFetchItem) {
126
- const callFetchDataPromise = fetchData(dataFetchId, {
127
- ...params,
128
- isDowngrade: !remoteInfo
129
- });
130
- const wrappedPromise = wrapSetTimeout(
131
- callFetchDataPromise,
132
- 2e4,
133
- dataFetchId
134
- );
135
- if (wrappedPromise) {
136
- const res = await wrappedPromise;
137
- logger.log("fetch data from server, dataFetchItem res: ", res);
138
- return ctx.json(res);
139
- }
140
- }
141
- const remoteId = dataFetchId.split(SEPARATOR)[0];
142
- const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
143
- if (!hostInstance) {
144
- throw new Error("host instance not found!");
145
- }
146
- const dataFetchFn = await loadDataFetchModule(hostInstance, remoteId);
147
- const data = await dataFetchFn({ ...params, isDowngrade: !remoteInfo });
148
- logger.log("fetch data from server, loadDataFetchModule res: ", data);
149
- return ctx.json(data);
150
- } catch (e) {
151
- logger.error("server plugin data fetch error: ", e);
152
- ctx.status(500);
153
- return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
154
- ${e}`);
155
- }
156
- };
157
- export {
158
- dataFetchServerMiddleware as default
159
- };