@module-federation/modern-js 0.14.2 → 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 (122) hide show
  1. package/dist/LICENSE +21 -0
  2. package/dist/cjs/cli/configPlugin.js +381 -0
  3. package/dist/cjs/cli/configPlugin.spec.js +114 -0
  4. package/dist/cjs/cli/index.js +95 -0
  5. package/dist/cjs/cli/mfRuntimePlugins/auto-fetch-data.js +98 -0
  6. package/dist/cjs/cli/mfRuntimePlugins/inject-node-fetch.js +44 -0
  7. package/dist/cjs/cli/mfRuntimePlugins/resolve-entry-ipv4.js +82 -0
  8. package/dist/cjs/cli/mfRuntimePlugins/shared-strategy.js +43 -0
  9. package/dist/cjs/cli/server/data-fetch-server-plugin.js +189 -0
  10. package/dist/cjs/cli/ssrPlugin.js +236 -0
  11. package/dist/cjs/cli/utils.js +90 -0
  12. package/dist/cjs/constant.js +78 -0
  13. package/dist/cjs/interfaces/bundler.js +16 -0
  14. package/dist/cjs/interfaces/global.js +16 -0
  15. package/dist/cjs/logger.js +27 -0
  16. package/dist/cjs/runtime/AwaitDataFetch.js +144 -0
  17. package/dist/cjs/runtime/createRemoteComponent.js +327 -0
  18. package/dist/cjs/runtime/index.js +50 -0
  19. package/dist/cjs/runtime/wrapNoSSR.js +35 -0
  20. package/dist/cjs/server/fileCache.js +84 -0
  21. package/dist/cjs/server/fileCache.spec.js +28 -0
  22. package/dist/cjs/server/index.js +58 -0
  23. package/dist/cjs/server/staticMiddleware.js +77 -0
  24. package/dist/cjs/server/staticMiddleware.spec.js +185 -0
  25. package/dist/cjs/ssr-runtime/SSRLiveReload.js +43 -0
  26. package/dist/cjs/ssr-runtime/devPlugin.js +71 -0
  27. package/dist/cjs/ssr-runtime/downgrade.js +114 -0
  28. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +136 -0
  29. package/dist/cjs/types/index.js +16 -0
  30. package/dist/cjs/utils/dataFetch.js +211 -0
  31. package/dist/cjs/utils/index.js +54 -0
  32. package/dist/esm/cli/configPlugin.js +388 -0
  33. package/dist/esm/cli/configPlugin.spec.js +110 -0
  34. package/dist/esm/cli/index.js +90 -0
  35. package/dist/esm/cli/mfRuntimePlugins/auto-fetch-data.js +74 -0
  36. package/dist/esm/cli/mfRuntimePlugins/inject-node-fetch.js +16 -0
  37. package/dist/esm/cli/mfRuntimePlugins/resolve-entry-ipv4.js +74 -0
  38. package/dist/esm/cli/mfRuntimePlugins/shared-strategy.js +25 -0
  39. package/dist/esm/cli/server/data-fetch-server-plugin.js +237 -0
  40. package/dist/esm/cli/ssrPlugin.js +219 -0
  41. package/dist/esm/cli/utils.js +53 -0
  42. package/dist/esm/constant.js +42 -0
  43. package/dist/esm/interfaces/bundler.js +0 -0
  44. package/dist/esm/interfaces/global.js +0 -0
  45. package/dist/esm/logger.js +7 -0
  46. package/dist/esm/runtime/AwaitDataFetch.js +131 -0
  47. package/dist/esm/runtime/createRemoteComponent.js +417 -0
  48. package/dist/esm/runtime/index.js +22 -0
  49. package/dist/esm/runtime/wrapNoSSR.js +12 -0
  50. package/dist/esm/server/fileCache.js +98 -0
  51. package/dist/esm/server/fileCache.spec.js +50 -0
  52. package/dist/esm/server/index.js +36 -0
  53. package/dist/esm/server/staticMiddleware.js +81 -0
  54. package/dist/esm/server/staticMiddleware.spec.js +328 -0
  55. package/dist/esm/ssr-runtime/SSRLiveReload.js +26 -0
  56. package/dist/esm/ssr-runtime/devPlugin.js +73 -0
  57. package/dist/esm/ssr-runtime/downgrade.js +150 -0
  58. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +177 -0
  59. package/dist/esm/types/index.js +0 -0
  60. package/dist/esm/utils/dataFetch.js +237 -0
  61. package/dist/esm/utils/index.js +28 -0
  62. package/dist/esm-node/cli/configPlugin.js +340 -0
  63. package/dist/esm-node/cli/configPlugin.spec.js +91 -0
  64. package/dist/esm-node/cli/index.js +70 -0
  65. package/dist/esm-node/cli/mfRuntimePlugins/auto-fetch-data.js +68 -0
  66. package/dist/esm-node/cli/mfRuntimePlugins/inject-node-fetch.js +14 -0
  67. package/dist/esm-node/cli/mfRuntimePlugins/resolve-entry-ipv4.js +62 -0
  68. package/dist/esm-node/cli/mfRuntimePlugins/shared-strategy.js +23 -0
  69. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +159 -0
  70. package/dist/esm-node/cli/ssrPlugin.js +200 -0
  71. package/dist/esm-node/cli/utils.js +53 -0
  72. package/dist/esm-node/constant.js +42 -0
  73. package/dist/esm-node/interfaces/bundler.js +0 -0
  74. package/dist/esm-node/interfaces/global.js +0 -0
  75. package/dist/esm-node/logger.js +7 -0
  76. package/dist/esm-node/runtime/AwaitDataFetch.js +109 -0
  77. package/dist/esm-node/runtime/createRemoteComponent.js +291 -0
  78. package/dist/esm-node/runtime/index.js +22 -0
  79. package/dist/esm-node/runtime/wrapNoSSR.js +11 -0
  80. package/dist/esm-node/server/fileCache.js +49 -0
  81. package/dist/esm-node/server/fileCache.spec.js +27 -0
  82. package/dist/esm-node/server/index.js +34 -0
  83. package/dist/esm-node/server/staticMiddleware.js +43 -0
  84. package/dist/esm-node/server/staticMiddleware.spec.js +162 -0
  85. package/dist/esm-node/ssr-runtime/SSRLiveReload.js +19 -0
  86. package/dist/esm-node/ssr-runtime/devPlugin.js +37 -0
  87. package/dist/esm-node/ssr-runtime/downgrade.js +88 -0
  88. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +101 -0
  89. package/dist/esm-node/types/index.js +0 -0
  90. package/dist/esm-node/utils/dataFetch.js +166 -0
  91. package/dist/esm-node/utils/index.js +27 -0
  92. package/dist/types/cli/configPlugin.d.ts +21 -0
  93. package/dist/types/cli/configPlugin.spec.d.ts +1 -0
  94. package/dist/types/cli/index.d.ts +6 -0
  95. package/dist/types/cli/mfRuntimePlugins/auto-fetch-data.d.ts +3 -0
  96. package/dist/types/cli/mfRuntimePlugins/inject-node-fetch.d.ts +3 -0
  97. package/dist/types/cli/mfRuntimePlugins/resolve-entry-ipv4.d.ts +3 -0
  98. package/dist/types/cli/mfRuntimePlugins/shared-strategy.d.ts +3 -0
  99. package/dist/types/cli/server/data-fetch-server-plugin.d.ts +3 -0
  100. package/dist/types/cli/ssrPlugin.d.ts +6 -0
  101. package/dist/types/cli/utils.d.ts +6 -0
  102. package/dist/types/constant.d.ts +25 -0
  103. package/dist/types/interfaces/bundler.d.ts +18 -0
  104. package/dist/types/interfaces/global.d.ts +27 -0
  105. package/dist/types/logger.d.ts +2 -0
  106. package/dist/types/runtime/AwaitDataFetch.d.ts +19 -0
  107. package/dist/types/runtime/createRemoteComponent.d.ts +26 -0
  108. package/dist/types/runtime/index.d.ts +10 -0
  109. package/dist/types/runtime/wrapNoSSR.d.ts +9 -0
  110. package/dist/types/server/fileCache.d.ts +14 -0
  111. package/dist/types/server/fileCache.spec.d.ts +1 -0
  112. package/dist/types/server/index.d.ts +4 -0
  113. package/dist/types/server/staticMiddleware.d.ts +6 -0
  114. package/dist/types/server/staticMiddleware.spec.d.ts +1 -0
  115. package/dist/types/ssr-runtime/SSRLiveReload.d.ts +1 -0
  116. package/dist/types/ssr-runtime/devPlugin.d.ts +2 -0
  117. package/dist/types/ssr-runtime/downgrade.d.ts +4 -0
  118. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +7 -0
  119. package/dist/types/types/index.d.ts +24 -0
  120. package/dist/types/utils/dataFetch.d.ts +26 -0
  121. package/dist/types/utils/index.d.ts +15 -0
  122. package/package.json +37 -12
@@ -0,0 +1,291 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import React, { useEffect, useState } from "react";
3
+ import logger from "../logger";
4
+ import { getInstance } from "@module-federation/enhanced/runtime";
5
+ import { AwaitDataFetch, transformError } from "./AwaitDataFetch";
6
+ import { fetchData, getDataFetchItem, getDataFetchMapKey } from "../utils/dataFetch";
7
+ import { getDataFetchInfo, getLoadedRemoteInfos, setDataFetchItemLoadedStatus, wrapDataFetchId } from "../utils";
8
+ import { DATA_FETCH_ERROR_PREFIX, DATA_FETCH_FUNCTION, FS_HREF, LOAD_REMOTE_ERROR_PREFIX, MF_DATA_FETCH_TYPE } from "../constant";
9
+ function getTargetModuleInfo(id) {
10
+ const instance = getInstance();
11
+ if (!instance) {
12
+ return;
13
+ }
14
+ const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);
15
+ if (!loadedRemoteInfo) {
16
+ return;
17
+ }
18
+ const snapshot = loadedRemoteInfo.snapshot;
19
+ if (!snapshot) {
20
+ return;
21
+ }
22
+ const publicPath = "publicPath" in snapshot ? snapshot.publicPath : "getPublicPath" in snapshot ? new Function(snapshot.getPublicPath)() : "";
23
+ if (!publicPath) {
24
+ return;
25
+ }
26
+ const modules = "modules" in snapshot ? snapshot.modules : [];
27
+ const targetModule = modules.find((m) => m.modulePath === loadedRemoteInfo.expose);
28
+ if (!targetModule) {
29
+ return;
30
+ }
31
+ const remoteEntry = "remoteEntry" in snapshot ? snapshot.remoteEntry : "";
32
+ if (!remoteEntry) {
33
+ return;
34
+ }
35
+ return {
36
+ module: targetModule,
37
+ publicPath,
38
+ remoteEntry
39
+ };
40
+ }
41
+ function collectSSRAssets(options) {
42
+ const { id, injectLink = true, injectScript = false } = typeof options === "string" ? {
43
+ id: options
44
+ } : options;
45
+ const links = [];
46
+ const scripts = [];
47
+ const instance = getInstance();
48
+ if (!instance || !injectLink && !injectScript) {
49
+ return [
50
+ ...scripts,
51
+ ...links
52
+ ];
53
+ }
54
+ const moduleAndPublicPath = getTargetModuleInfo(id);
55
+ if (!moduleAndPublicPath) {
56
+ return [
57
+ ...scripts,
58
+ ...links
59
+ ];
60
+ }
61
+ const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
62
+ if (injectLink) {
63
+ [
64
+ ...targetModule.assets.css.sync,
65
+ ...targetModule.assets.css.async
66
+ ].sort().forEach((file, index) => {
67
+ links.push(/* @__PURE__ */ _jsx("link", {
68
+ href: `${publicPath}${file}`,
69
+ rel: "stylesheet",
70
+ type: "text/css"
71
+ }, `${file.split(".")[0]}_${index}`));
72
+ });
73
+ }
74
+ if (injectScript) {
75
+ scripts.push(/* @__PURE__ */ _jsx("script", {
76
+ async: true,
77
+ src: `${publicPath}${remoteEntry}`,
78
+ crossOrigin: "anonymous"
79
+ }, remoteEntry.split(".")[0]));
80
+ [
81
+ ...targetModule.assets.js.sync
82
+ ].sort().forEach((file, index) => {
83
+ scripts.push(/* @__PURE__ */ _jsx("script", {
84
+ async: true,
85
+ src: `${publicPath}${file}`,
86
+ crossOrigin: "anonymous"
87
+ }, `${file.split(".")[0]}_${index}`));
88
+ });
89
+ }
90
+ return [
91
+ ...scripts,
92
+ ...links
93
+ ];
94
+ }
95
+ function getServerNeedRemoteInfo(loadedRemoteInfo, id, noSSR) {
96
+ if (noSSR || typeof window !== "undefined" && window.location.href !== window[FS_HREF]) {
97
+ var _dataFetchItem_;
98
+ if (!(loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.version)) {
99
+ throw new Error(`${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} version is empty`);
100
+ }
101
+ const { snapshot } = loadedRemoteInfo;
102
+ if (!snapshot) {
103
+ throw new Error(`${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} snapshot is empty`);
104
+ }
105
+ const dataFetchItem = getDataFetchItem(id);
106
+ const isFetchServer = (dataFetchItem === null || dataFetchItem === void 0 ? void 0 : (_dataFetchItem_ = dataFetchItem[0]) === null || _dataFetchItem_ === void 0 ? void 0 : _dataFetchItem_[1]) === MF_DATA_FETCH_TYPE.FETCH_SERVER;
107
+ if (isFetchServer && (!("ssrPublicPath" in snapshot) || !snapshot.ssrPublicPath)) {
108
+ throw new Error(`ssrPublicPath is required while fetching ${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} data in SSR project!`);
109
+ }
110
+ if (isFetchServer && (!("ssrRemoteEntry" in snapshot) || !snapshot.ssrRemoteEntry)) {
111
+ throw new Error(`ssrRemoteEntry is required while loading ${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} data loader in SSR project!`);
112
+ }
113
+ return {
114
+ name: loadedRemoteInfo.name,
115
+ version: loadedRemoteInfo.version,
116
+ ssrPublicPath: "ssrPublicPath" in snapshot ? snapshot.ssrPublicPath || "" : "",
117
+ ssrRemoteEntry: "ssrRemoteEntry" in snapshot ? snapshot.ssrRemoteEntry || "" : "",
118
+ globalName: loadedRemoteInfo.entryGlobalName
119
+ };
120
+ }
121
+ return;
122
+ }
123
+ function createRemoteComponent(options) {
124
+ const exportName = (options === null || options === void 0 ? void 0 : options.export) || "default";
125
+ const callLoader = async () => {
126
+ logger.debug("callLoader start", Date.now());
127
+ const m = await options.loader();
128
+ logger.debug("callLoader end", Date.now());
129
+ if (!m) {
130
+ throw new Error("load remote failed");
131
+ }
132
+ return m;
133
+ };
134
+ const getData = async (noSSR) => {
135
+ let loadedRemoteInfo;
136
+ let moduleId;
137
+ const instance = getInstance();
138
+ try {
139
+ const m = await callLoader();
140
+ moduleId = m && m[Symbol.for("mf_module_id")];
141
+ if (!moduleId) {
142
+ throw new Error("moduleId is empty");
143
+ }
144
+ loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
145
+ if (!loadedRemoteInfo) {
146
+ throw new Error(`can not find loaded remote('${moduleId}') info!`);
147
+ }
148
+ } catch (e) {
149
+ const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;
150
+ logger.debug(e);
151
+ throw new Error(errMsg);
152
+ }
153
+ let dataFetchMapKey;
154
+ try {
155
+ dataFetchMapKey = getDataFetchMapKey(getDataFetchInfo({
156
+ name: loadedRemoteInfo.name,
157
+ alias: loadedRemoteInfo.alias,
158
+ id: moduleId,
159
+ remoteSnapshot: loadedRemoteInfo.snapshot
160
+ }), {
161
+ name: instance.name,
162
+ version: instance === null || instance === void 0 ? void 0 : instance.options.version
163
+ });
164
+ logger.debug("getData dataFetchMapKey: ", dataFetchMapKey);
165
+ if (!dataFetchMapKey) {
166
+ return;
167
+ }
168
+ const data = await fetchData(dataFetchMapKey, {
169
+ ...options.dataFetchParams,
170
+ isDowngrade: false
171
+ }, getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR));
172
+ setDataFetchItemLoadedStatus(dataFetchMapKey);
173
+ logger.debug("get data res: \n", data);
174
+ return data;
175
+ } catch (err) {
176
+ const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;
177
+ logger.debug(errMsg);
178
+ throw new Error(errMsg);
179
+ }
180
+ };
181
+ const LazyComponent = /* @__PURE__ */ React.lazy(async () => {
182
+ const m = await callLoader();
183
+ const moduleId = m && m[Symbol.for("mf_module_id")];
184
+ const instance = getInstance();
185
+ const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
186
+ loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.snapshot;
187
+ const dataFetchMapKey = loadedRemoteInfo ? getDataFetchMapKey(getDataFetchInfo({
188
+ name: loadedRemoteInfo.name,
189
+ alias: loadedRemoteInfo.alias,
190
+ id: moduleId,
191
+ remoteSnapshot: loadedRemoteInfo.snapshot
192
+ }), {
193
+ name: instance.name,
194
+ version: instance === null || instance === void 0 ? void 0 : instance.options.version
195
+ }) : void 0;
196
+ logger.debug("LazyComponent dataFetchMapKey: ", dataFetchMapKey);
197
+ const assets = collectSSRAssets({
198
+ id: moduleId
199
+ });
200
+ const Com = m[exportName];
201
+ if (exportName in m && typeof Com === "function") {
202
+ return {
203
+ default: (props) => /* @__PURE__ */ _jsxs(_Fragment, {
204
+ children: [
205
+ globalThis.FEDERATION_SSR && dataFetchMapKey && /* @__PURE__ */ _jsx("script", {
206
+ suppressHydrationWarning: true,
207
+ dangerouslySetInnerHTML: {
208
+ __html: String.raw`
209
+ globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || [];
210
+ globalThis['${DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
211
+ `
212
+ }
213
+ }),
214
+ globalThis.FEDERATION_SSR && assets,
215
+ /* @__PURE__ */ _jsx(Com, {
216
+ ...props
217
+ })
218
+ ]
219
+ })
220
+ };
221
+ } else {
222
+ throw Error(`Make sure that ${moduleId} has the correct export when export is ${String(exportName)}`);
223
+ }
224
+ });
225
+ return (props) => {
226
+ const { key, ...args } = props;
227
+ if (globalThis.FEDERATION_SSR && !options.noSSR) {
228
+ const { key: key2, ...args2 } = props;
229
+ return /* @__PURE__ */ _jsx(AwaitDataFetch, {
230
+ resolve: getData(options.noSSR),
231
+ loading: options.loading,
232
+ errorElement: options.fallback,
233
+ children: (data) => /* @__PURE__ */ _jsx(LazyComponent, {
234
+ ...args2,
235
+ mfData: data
236
+ })
237
+ });
238
+ } else {
239
+ const [data, setData] = useState(null);
240
+ const [loading, setLoading] = useState(true);
241
+ const [error, setError] = useState(null);
242
+ useEffect(() => {
243
+ let isMounted = true;
244
+ const fetchDataAsync = async () => {
245
+ try {
246
+ setLoading(true);
247
+ const result = await getData(options.noSSR);
248
+ if (isMounted) {
249
+ setData(result);
250
+ }
251
+ } catch (e) {
252
+ if (isMounted) {
253
+ setError(transformError(e));
254
+ }
255
+ } finally {
256
+ if (isMounted) {
257
+ setLoading(false);
258
+ }
259
+ }
260
+ };
261
+ fetchDataAsync();
262
+ return () => {
263
+ isMounted = false;
264
+ };
265
+ }, []);
266
+ if (loading) {
267
+ return /* @__PURE__ */ _jsx(_Fragment, {
268
+ children: options.loading
269
+ });
270
+ }
271
+ if (error) {
272
+ return /* @__PURE__ */ _jsx(_Fragment, {
273
+ children: typeof options.fallback === "function" ? options.fallback(error) : options.fallback
274
+ });
275
+ }
276
+ return /* @__PURE__ */ _jsx(LazyComponent, {
277
+ ...args,
278
+ mfData: data
279
+ });
280
+ }
281
+ };
282
+ }
283
+ function createRemoteSSRComponent(options) {
284
+ logger.warn("createRemoteSSRComponent is deprecated, please use createRemoteComponent instead!");
285
+ return createRemoteComponent(options);
286
+ }
287
+ export {
288
+ collectSSRAssets,
289
+ createRemoteComponent,
290
+ createRemoteSSRComponent
291
+ };
@@ -0,0 +1,22 @@
1
+ export * from "@module-federation/enhanced/runtime";
2
+ import { ERROR_TYPE } from "../constant";
3
+ const kit = {
4
+ get createRemoteSSRComponent() {
5
+ return require("./createRemoteComponent").createRemoteSSRComponent;
6
+ },
7
+ get createRemoteComponent() {
8
+ return require("./createRemoteComponent").createRemoteComponent;
9
+ },
10
+ get collectSSRAssets() {
11
+ return require("./createRemoteComponent").collectSSRAssets;
12
+ },
13
+ get wrapNoSSR() {
14
+ return require("./wrapNoSSR").wrapNoSSR;
15
+ }
16
+ };
17
+ import { setSSREnv } from "../ssr-runtime/injectDataFetchFunctionPlugin";
18
+ export {
19
+ ERROR_TYPE,
20
+ kit,
21
+ setSSREnv
22
+ };
@@ -0,0 +1,11 @@
1
+ function wrapNoSSR(createComponentFn) {
2
+ return (options) => {
3
+ return createComponentFn({
4
+ ...options,
5
+ noSSR: true
6
+ });
7
+ };
8
+ }
9
+ export {
10
+ wrapNoSSR
11
+ };
@@ -0,0 +1,49 @@
1
+ import fs from "fs-extra";
2
+ import { LRUCache } from "lru-cache";
3
+ class FileCache {
4
+ /**
5
+ * Check if file exists and return file info
6
+ * @param filepath Path to the file
7
+ * @returns FileResult or null if file doesn't exist
8
+ */
9
+ async getFile(filepath) {
10
+ if (!await fs.pathExists(filepath)) {
11
+ return null;
12
+ }
13
+ try {
14
+ const stat = await fs.lstat(filepath);
15
+ const currentModified = stat.mtimeMs;
16
+ const cachedEntry = this.cache.get(filepath);
17
+ if (cachedEntry && currentModified <= cachedEntry.lastModified) {
18
+ return {
19
+ content: cachedEntry.content,
20
+ lastModified: cachedEntry.lastModified
21
+ };
22
+ }
23
+ const content = await fs.readFile(filepath, "utf-8");
24
+ const newEntry = {
25
+ content,
26
+ lastModified: currentModified
27
+ };
28
+ this.cache.set(filepath, newEntry, {
29
+ size: stat.size || content.length
30
+ });
31
+ return {
32
+ content,
33
+ lastModified: currentModified
34
+ };
35
+ } catch (err) {
36
+ return null;
37
+ }
38
+ }
39
+ constructor() {
40
+ this.cache = new LRUCache({
41
+ maxSize: 200 * 1024 * 1024
42
+ });
43
+ }
44
+ }
45
+ const fileCache = new FileCache();
46
+ export {
47
+ FileCache,
48
+ fileCache
49
+ };
@@ -0,0 +1,27 @@
1
+ import { it, expect, describe, vi, beforeAll } from "vitest";
2
+ import { FileCache } from "./fileCache";
3
+ beforeAll(() => {
4
+ vi.mock("fs-extra", () => ({
5
+ default: {
6
+ pathExists: () => {
7
+ return true;
8
+ },
9
+ lstat: () => {
10
+ return {
11
+ mtimeMs: Date.now(),
12
+ size: 4
13
+ };
14
+ },
15
+ readFile: () => {
16
+ return "test";
17
+ }
18
+ }
19
+ }));
20
+ });
21
+ describe("modern serve static file cache", async () => {
22
+ it("should cache file", async () => {
23
+ const cache = new FileCache();
24
+ const result = await cache.getFile("test.txt");
25
+ expect(result === null || result === void 0 ? void 0 : result.content).toBe("test");
26
+ });
27
+ });
@@ -0,0 +1,34 @@
1
+ import { createStaticMiddleware } from "./staticMiddleware";
2
+ const staticServePlugin = () => ({
3
+ name: "@modern-js/module-federation/server",
4
+ setup: (api) => {
5
+ api.onPrepare(() => {
6
+ var _config_output, _config_server;
7
+ console.log(process.env.NODE_ENV);
8
+ if (process.env.NODE_ENV === "development") {
9
+ return;
10
+ }
11
+ const { middlewares } = api.getServerContext();
12
+ const config = api.getServerConfig();
13
+ const assetPrefix = ((_config_output = config.output) === null || _config_output === void 0 ? void 0 : _config_output.assetPrefix) || "";
14
+ if (!((_config_server = config.server) === null || _config_server === void 0 ? void 0 : _config_server.ssr)) {
15
+ return;
16
+ }
17
+ const context = api.getServerContext();
18
+ const pwd = context.distDirectory;
19
+ const serverStaticMiddleware = createStaticMiddleware({
20
+ assetPrefix,
21
+ pwd
22
+ });
23
+ middlewares.push({
24
+ name: "module-federation-serve-manifest",
25
+ handler: serverStaticMiddleware
26
+ });
27
+ });
28
+ }
29
+ });
30
+ var server_default = staticServePlugin;
31
+ export {
32
+ server_default as default,
33
+ staticServePlugin
34
+ };
@@ -0,0 +1,43 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { fileCache } from "./fileCache";
4
+ const bundlesAssetPrefix = "/bundles";
5
+ const removeHost = (url) => {
6
+ try {
7
+ const hasProtocol = url.includes("://");
8
+ const hasDomain = hasProtocol || url.startsWith("//");
9
+ const pathname = hasDomain ? new URL(hasProtocol ? url : `http:${url}`).pathname : url;
10
+ return pathname;
11
+ } catch (e) {
12
+ return url;
13
+ }
14
+ };
15
+ const createStaticMiddleware = (options) => {
16
+ const { assetPrefix, pwd } = options;
17
+ return async (c, next) => {
18
+ const pathname = c.req.path;
19
+ if (path.extname(pathname) !== ".js") {
20
+ return next();
21
+ }
22
+ const prefixWithoutHost = removeHost(assetPrefix);
23
+ const prefixWithBundle = path.join(prefixWithoutHost, bundlesAssetPrefix);
24
+ if (!pathname.startsWith(prefixWithBundle)) {
25
+ return next();
26
+ }
27
+ const pathnameWithoutPrefix = pathname.replace(prefixWithBundle, "");
28
+ const filepath = path.join(pwd, bundlesAssetPrefix, pathnameWithoutPrefix);
29
+ if (!await fs.pathExists(filepath)) {
30
+ return next();
31
+ }
32
+ const fileResult = await fileCache.getFile(filepath);
33
+ if (!fileResult) {
34
+ return next();
35
+ }
36
+ c.header("Content-Type", "application/javascript");
37
+ c.header("Content-Length", String(fileResult.content.length));
38
+ return c.body(fileResult.content, 200);
39
+ };
40
+ };
41
+ export {
42
+ createStaticMiddleware
43
+ };
@@ -0,0 +1,162 @@
1
+ import { it, expect, describe, vi, beforeEach } from "vitest";
2
+ import { createStaticMiddleware } from "./staticMiddleware";
3
+ vi.mock("fs-extra", () => ({
4
+ default: {
5
+ pathExists: vi.fn()
6
+ }
7
+ }));
8
+ vi.mock("./fileCache", () => ({
9
+ fileCache: {
10
+ getFile: vi.fn()
11
+ }
12
+ }));
13
+ import fs from "fs-extra";
14
+ import { fileCache } from "./fileCache";
15
+ describe("staticMiddleware", () => {
16
+ let middleware;
17
+ let mockContext;
18
+ let nextSpy;
19
+ beforeEach(() => {
20
+ vi.clearAllMocks();
21
+ middleware = createStaticMiddleware({
22
+ assetPrefix: "",
23
+ pwd: "/test/path"
24
+ });
25
+ nextSpy = vi.fn();
26
+ mockContext = {
27
+ req: {
28
+ path: ""
29
+ },
30
+ header: vi.fn(),
31
+ body: vi.fn()
32
+ };
33
+ });
34
+ describe("file extension filtering", () => {
35
+ it("should call next() for non-js files", async () => {
36
+ mockContext.req.path = "/bundles/test.css";
37
+ await middleware(mockContext, nextSpy);
38
+ expect(nextSpy).toHaveBeenCalledOnce();
39
+ expect(mockContext.header).not.toHaveBeenCalled();
40
+ expect(mockContext.body).not.toHaveBeenCalled();
41
+ });
42
+ it("should call next() for files without extension", async () => {
43
+ mockContext.req.path = "/bundles/test";
44
+ await middleware(mockContext, nextSpy);
45
+ expect(nextSpy).toHaveBeenCalledOnce();
46
+ expect(mockContext.header).not.toHaveBeenCalled();
47
+ expect(mockContext.body).not.toHaveBeenCalled();
48
+ });
49
+ it("should process .js files", async () => {
50
+ mockContext.req.path = "/bundles/test.js";
51
+ fs.pathExists.mockResolvedValue(false);
52
+ await middleware(mockContext, nextSpy);
53
+ expect(fs.pathExists).toHaveBeenCalled();
54
+ });
55
+ });
56
+ describe("asset prefix filtering", () => {
57
+ it("should call next() for paths not starting with /bundles", async () => {
58
+ mockContext.req.path = "/assets/test.js";
59
+ await middleware(mockContext, nextSpy);
60
+ expect(nextSpy).toHaveBeenCalledOnce();
61
+ expect(fs.pathExists).not.toHaveBeenCalled();
62
+ expect(mockContext.header).not.toHaveBeenCalled();
63
+ expect(mockContext.body).not.toHaveBeenCalled();
64
+ });
65
+ it("should call next() for root path", async () => {
66
+ mockContext.req.path = "/test.js";
67
+ await middleware(mockContext, nextSpy);
68
+ expect(nextSpy).toHaveBeenCalledOnce();
69
+ expect(fs.pathExists).not.toHaveBeenCalled();
70
+ });
71
+ it("should process paths starting with /bundles", async () => {
72
+ mockContext.req.path = "/bundles/test.js";
73
+ fs.pathExists.mockResolvedValue(false);
74
+ await middleware(mockContext, nextSpy);
75
+ expect(fs.pathExists).toHaveBeenCalledWith("/test/path/bundles/test.js");
76
+ });
77
+ });
78
+ describe("file existence check", () => {
79
+ it("should call next() when file does not exist", async () => {
80
+ mockContext.req.path = "/bundles/nonexistent.js";
81
+ fs.pathExists.mockResolvedValue(false);
82
+ await middleware(mockContext, nextSpy);
83
+ expect(fs.pathExists).toHaveBeenCalledWith("/test/path/bundles/nonexistent.js");
84
+ expect(nextSpy).toHaveBeenCalledOnce();
85
+ expect(fileCache.getFile).not.toHaveBeenCalled();
86
+ expect(mockContext.header).not.toHaveBeenCalled();
87
+ expect(mockContext.body).not.toHaveBeenCalled();
88
+ });
89
+ it("should proceed to file cache when file exists", async () => {
90
+ mockContext.req.path = "/bundles/existing.js";
91
+ fs.pathExists.mockResolvedValue(true);
92
+ fileCache.getFile.mockResolvedValue(null);
93
+ await middleware(mockContext, nextSpy);
94
+ expect(fs.pathExists).toHaveBeenCalledWith("/test/path/bundles/existing.js");
95
+ expect(fileCache.getFile).toHaveBeenCalledWith("/test/path/bundles/existing.js");
96
+ });
97
+ });
98
+ describe("successful file serving", () => {
99
+ it("should serve file content with correct headers", async () => {
100
+ const mockFileContent = 'console.log("test");';
101
+ const mockFileResult = {
102
+ content: mockFileContent,
103
+ lastModified: Date.now()
104
+ };
105
+ mockContext.req.path = "/bundles/app.js";
106
+ fs.pathExists.mockResolvedValue(true);
107
+ fileCache.getFile.mockResolvedValue(mockFileResult);
108
+ mockContext.body.mockReturnValue("response");
109
+ const result = await middleware(mockContext, nextSpy);
110
+ expect(fs.pathExists).toHaveBeenCalledWith("/test/path/bundles/app.js");
111
+ expect(fileCache.getFile).toHaveBeenCalledWith("/test/path/bundles/app.js");
112
+ expect(nextSpy).not.toHaveBeenCalled();
113
+ expect(mockContext.header).toHaveBeenCalledWith("Content-Type", "application/javascript");
114
+ expect(mockContext.header).toHaveBeenCalledWith("Content-Length", String(mockFileResult.content.length));
115
+ expect(mockContext.body).toHaveBeenCalledWith(mockFileResult.content, 200);
116
+ expect(result).toBe("response");
117
+ });
118
+ it("should handle empty file content", async () => {
119
+ const mockFileResult = {
120
+ content: "",
121
+ lastModified: Date.now()
122
+ };
123
+ mockContext.req.path = "/bundles/empty.js";
124
+ fs.pathExists.mockResolvedValue(true);
125
+ fileCache.getFile.mockResolvedValue(mockFileResult);
126
+ mockContext.body.mockReturnValue("empty-response");
127
+ const result = await middleware(mockContext, nextSpy);
128
+ expect(mockContext.header).toHaveBeenCalledWith("Content-Length", "0");
129
+ expect(mockContext.body).toHaveBeenCalledWith(mockFileResult.content, 200);
130
+ expect(result).toBe("empty-response");
131
+ expect(nextSpy).not.toHaveBeenCalled();
132
+ });
133
+ });
134
+ describe("asset prefix handling", () => {
135
+ it("should handle custom asset prefix correctly", async () => {
136
+ const customMiddleware = createStaticMiddleware({
137
+ assetPrefix: "/custom-prefix",
138
+ pwd: "/test/path"
139
+ });
140
+ mockContext.req.path = "/bundles/test.js";
141
+ await customMiddleware(mockContext, nextSpy);
142
+ expect(nextSpy).toHaveBeenCalledOnce();
143
+ expect(mockContext.header).not.toHaveBeenCalled();
144
+ expect(mockContext.body).not.toHaveBeenCalled();
145
+ });
146
+ it("should handle asset prefix removal correctly", async () => {
147
+ const customMiddleware = createStaticMiddleware({
148
+ assetPrefix: "/prefix",
149
+ pwd: "/test/path"
150
+ });
151
+ const mockFileResult = {
152
+ content: "test content",
153
+ lastModified: Date.now()
154
+ };
155
+ mockContext.req.path = "/prefix/bundles/test.js";
156
+ fs.pathExists.mockResolvedValue(true);
157
+ fileCache.getFile.mockResolvedValue(mockFileResult);
158
+ await customMiddleware(mockContext, nextSpy);
159
+ expect(fs.pathExists).toHaveBeenCalledWith("/test/path/bundles/test.js");
160
+ });
161
+ });
162
+ });
@@ -0,0 +1,19 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ function SSRLiveReload() {
3
+ if (process.env.NODE_ENV !== "development") {
4
+ return null;
5
+ }
6
+ return /* @__PURE__ */ _jsx("script", {
7
+ suppressHydrationWarning: true,
8
+ dangerouslySetInnerHTML: {
9
+ __html: String.raw`
10
+ if(${globalThis.shouldUpdate}){
11
+ location.reload();
12
+ }
13
+ `
14
+ }
15
+ });
16
+ }
17
+ export {
18
+ SSRLiveReload
19
+ };