@module-federation/vite 1.11.0 → 1.12.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 (47) hide show
  1. package/README.md +4 -1
  2. package/lib/index.cjs +2113 -2109
  3. package/lib/index.d.cts +131 -0
  4. package/lib/index.d.mts +131 -0
  5. package/lib/index.mjs +2239 -0
  6. package/package.json +40 -28
  7. package/lib/index.d.ts +0 -4
  8. package/lib/index.esm.js +0 -2236
  9. package/lib/index.modern.js +0 -2288
  10. package/lib/index.umd.js +0 -2257
  11. package/lib/plugins/__tests__/pluginCheckAliasConflicts.test.d.ts +0 -1
  12. package/lib/plugins/__tests__/pluginDts.test.d.ts +0 -1
  13. package/lib/plugins/pluginAddEntry.d.ts +0 -10
  14. package/lib/plugins/pluginCheckAliasConflicts.d.ts +0 -9
  15. package/lib/plugins/pluginDevProxyModuleTopLevelAwait.d.ts +0 -2
  16. package/lib/plugins/pluginDts.d.ts +0 -3
  17. package/lib/plugins/pluginMFManifest.d.ts +0 -3
  18. package/lib/plugins/pluginModuleParseEnd.d.ts +0 -10
  19. package/lib/plugins/pluginProxyRemoteEntry.d.ts +0 -2
  20. package/lib/plugins/pluginProxyRemotes.d.ts +0 -3
  21. package/lib/plugins/pluginProxySharedModule_preBuild.d.ts +0 -7
  22. package/lib/plugins/pluginVarRemoteEntry.d.ts +0 -3
  23. package/lib/utils/PromiseStore.d.ts +0 -16
  24. package/lib/utils/VirtualModule.d.ts +0 -26
  25. package/lib/utils/__tests__/VirtualModule.test.d.ts +0 -1
  26. package/lib/utils/__tests__/cssModuleHelpers.test.d.ts +0 -1
  27. package/lib/utils/__tests__/helpers.d.ts +0 -2
  28. package/lib/utils/__tests__/normalizeModuleFederationOption.test.d.ts +0 -1
  29. package/lib/utils/__tests__/publicPath.test.d.ts +0 -1
  30. package/lib/utils/__tests__/serializeRuntimeOptions.test.d.ts +0 -1
  31. package/lib/utils/aliasToArrayPlugin.d.ts +0 -10
  32. package/lib/utils/bundleHelpers.d.ts +0 -2
  33. package/lib/utils/cssModuleHelpers.d.ts +0 -75
  34. package/lib/utils/localSharedImportMap_temp.d.ts +0 -2
  35. package/lib/utils/mapCodeToCodeWithSourcemap.d.ts +0 -4
  36. package/lib/utils/normalizeModuleFederationOptions.d.ts +0 -164
  37. package/lib/utils/normalizeOptimizeDeps.d.ts +0 -9
  38. package/lib/utils/packageNameUtils.d.ts +0 -22
  39. package/lib/utils/publicPath.d.ts +0 -9
  40. package/lib/utils/serializeRuntimeOptions.d.ts +0 -10
  41. package/lib/utils/wrapManualChunks.d.ts +0 -1
  42. package/lib/virtualModules/index.d.ts +0 -6
  43. package/lib/virtualModules/virtualExposes.d.ts +0 -2
  44. package/lib/virtualModules/virtualRemoteEntry.d.ts +0 -16
  45. package/lib/virtualModules/virtualRemotes.d.ts +0 -6
  46. package/lib/virtualModules/virtualRuntimeInitStatus.d.ts +0 -3
  47. package/lib/virtualModules/virtualShared_preBuild.d.ts +0 -17
package/lib/index.cjs CHANGED
@@ -1,2260 +1,2264 @@
1
- var defu = require('defu');
2
- var fs = require('fs');
3
- var path = require('pathe');
4
- var MagicString = require('magic-string');
5
- var pluginutils = require('@rollup/pluginutils');
6
- var estreeWalker = require('estree-walker');
7
- var sdk = require('@module-federation/sdk');
8
- var dtsPlugin = require('@module-federation/dts-plugin');
9
- var core = require('@module-federation/dts-plugin/core');
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
10
27
 
11
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
28
+ //#endregion
29
+ let defu = require("defu");
30
+ defu = __toESM(defu);
31
+ let fs = require("fs");
32
+ fs = __toESM(fs);
33
+ let pathe = require("pathe");
34
+ pathe = __toESM(pathe);
35
+ let magic_string = require("magic-string");
36
+ magic_string = __toESM(magic_string);
37
+ let _rollup_pluginutils = require("@rollup/pluginutils");
38
+ let estree_walker = require("estree-walker");
39
+ let _module_federation_sdk = require("@module-federation/sdk");
40
+ let _module_federation_dts_plugin = require("@module-federation/dts-plugin");
41
+ let _module_federation_dts_plugin_core = require("@module-federation/dts-plugin/core");
42
+ let module$1 = require("module");
43
+ let url = require("url");
12
44
 
13
- function _interopNamespace(e) {
14
- if (e && e.__esModule) return e;
15
- var n = Object.create(null);
16
- if (e) {
17
- Object.keys(e).forEach(function (k) {
18
- if (k !== 'default') {
19
- var d = Object.getOwnPropertyDescriptor(e, k);
20
- Object.defineProperty(n, k, d.get ? d : {
21
- enumerable: true,
22
- get: function () { return e[k]; }
23
- });
24
- }
25
- });
26
- }
27
- n["default"] = e;
28
- return n;
45
+ //#region src/utils/mapCodeToCodeWithSourcemap.ts
46
+ async function mapCodeToCodeWithSourcemap(code) {
47
+ const resolvedCode = await code;
48
+ if (resolvedCode === void 0) return;
49
+ const s = new magic_string.default(resolvedCode);
50
+ return {
51
+ code: s.toString(),
52
+ map: s.generateMap({ hires: true })
53
+ };
29
54
  }
30
55
 
31
- var defu__default = /*#__PURE__*/_interopDefaultLegacy(defu);
32
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
33
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
34
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
35
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
36
-
37
- var mapCodeToCodeWithSourcemap = function mapCodeToCodeWithSourcemap(code) {
38
- return Promise.resolve(code).then(function (resolvedCode) {
39
- if (resolvedCode === undefined) {
40
- return;
41
- }
42
- var s = new MagicString__default["default"](resolvedCode);
43
- return {
44
- code: s.toString(),
45
- map: s.generateMap({
46
- hires: true
47
- })
48
- };
49
- });
50
- };
51
-
56
+ //#endregion
57
+ //#region src/plugins/pluginAddEntry.ts
52
58
  function getFirstHtmlEntryFile(entryFiles) {
53
- return entryFiles.find(function (file) {
54
- return file.endsWith('.html');
55
- });
59
+ return entryFiles.find((file) => file.endsWith(".html"));
56
60
  }
57
- var addEntry = function addEntry(_ref) {
58
- var entryName = _ref.entryName,
59
- entryPath = _ref.entryPath,
60
- fileName = _ref.fileName,
61
- _ref$inject = _ref.inject,
62
- inject = _ref$inject === void 0 ? 'entry' : _ref$inject;
63
- var devEntryPath = entryPath.startsWith('virtual:mf') ? '@id/' + entryPath : entryPath;
64
- var entryFiles = [];
65
- var htmlFilePath;
66
- var _command;
67
- var emitFileId;
68
- var viteConfig;
69
- function injectHtml() {
70
- return inject === 'html' && htmlFilePath;
71
- }
72
- function injectEntry() {
73
- return inject === 'entry' || !htmlFilePath;
74
- }
75
- return [{
76
- name: 'add-entry',
77
- apply: 'serve',
78
- config: function config(_config, _ref2) {
79
- var command = _ref2.command;
80
- _command = command;
81
- },
82
- configResolved: function configResolved(config) {
83
- viteConfig = config;
84
- devEntryPath = config.base + devEntryPath.replace(/\\\\?/g, '/').replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/^\//, '');
85
- },
86
- configureServer: function configureServer(server) {
87
- server.middlewares.use(function (req, res, next) {
88
- if (!fileName) {
89
- next();
90
- return;
91
- }
92
- if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, '/'))) {
93
- req.url = devEntryPath;
94
- }
95
- next();
96
- });
97
- },
98
- transformIndexHtml: function transformIndexHtml(c) {
99
- if (!injectHtml()) return;
100
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
101
- },
102
- transform: function transform(code, id) {
103
- if (id.includes('node_modules') || inject !== 'html' || htmlFilePath) {
104
- return;
105
- }
106
- if (id.includes('.svelte-kit') && id.includes('internal.js')) {
107
- var src = devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/');
108
- return code.replace(/<head>/g, '<head><script type=\\"module\\" src=\\"' + src + '\\"></script>');
109
- }
110
- }
111
- }, {
112
- name: 'add-entry',
113
- enforce: 'post',
114
- configResolved: function configResolved(config) {
115
- viteConfig = config;
116
- var inputOptions = config.build.rollupOptions.input;
117
- if (!inputOptions) {
118
- htmlFilePath = path__namespace.resolve(config.root, 'index.html');
119
- } else if (typeof inputOptions === 'string') {
120
- entryFiles = [inputOptions];
121
- } else if (Array.isArray(inputOptions)) {
122
- entryFiles = inputOptions;
123
- } else if (typeof inputOptions === 'object') {
124
- entryFiles = Object.values(inputOptions);
125
- }
126
- if (entryFiles && entryFiles.length > 0) {
127
- htmlFilePath = getFirstHtmlEntryFile(entryFiles);
128
- }
129
- },
130
- buildStart: function buildStart() {
131
- if (_command === 'serve') return;
132
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes('[hash');
133
- var emitFileOptions = {
134
- name: entryName,
135
- type: 'chunk',
136
- id: entryPath,
137
- preserveSignature: 'strict'
138
- };
139
- if (!hasHash) {
140
- emitFileOptions.fileName = fileName;
141
- }
142
- emitFileId = this.emitFile(emitFileOptions);
143
- if (htmlFilePath && fs__namespace.existsSync(htmlFilePath)) {
144
- var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
145
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
146
- var match;
147
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
148
- entryFiles.push(match[1]);
149
- }
150
- }
151
- },
152
- generateBundle: function generateBundle(options, bundle) {
153
- if (!injectHtml()) return;
154
- var file = this.getFileName(emitFileId);
155
- // Helper to resolve path with proper renderBuiltUrl handling
156
- var resolvePath = function resolvePath(htmlFileName) {
157
- var _viteConfig$experimen;
158
- if (!((_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl)) {
159
- return viteConfig.base + file;
160
- }
161
- var result = viteConfig.experimental.renderBuiltUrl(file, {
162
- hostId: htmlFileName,
163
- hostType: 'html',
164
- type: 'asset',
165
- ssr: false
166
- });
167
- // Handle return types
168
- if (typeof result === 'string') {
169
- return result;
170
- }
171
- if (result && typeof result === 'object') {
172
- if ('runtime' in result) {
173
- // Runtime code cannot be used in <script src="">
174
- console.warn('[vite-plugin-federation] renderBuiltUrl returned runtime code for HTML injection. ' + 'Runtime code cannot be used in <script src="">. Falling back to base path.');
175
- return viteConfig.base + file;
176
- }
177
- if (result.relative) {
178
- return file;
179
- }
180
- }
181
- // Fallback for undefined or unexpected values
182
- return viteConfig.base + file;
183
- };
184
- // Process each HTML file
185
- for (var _fileName in bundle) {
186
- if (_fileName.endsWith('.html')) {
187
- var htmlAsset = bundle[_fileName];
188
- if (htmlAsset.type === 'chunk') return;
189
- var _path = resolvePath(_fileName);
190
- var scriptContent = "\n <script type=\"module\" src=\"" + _path + "\"></script>\n ";
191
- var htmlContent = htmlAsset.source.toString() || '';
192
- htmlContent = htmlContent.replace('<head>', "<head>" + scriptContent);
193
- htmlAsset.source = htmlContent;
194
- }
195
- }
196
- },
197
- transform: function transform(code, id) {
198
- if (injectEntry() && entryFiles.some(function (file) {
199
- return id.endsWith(file);
200
- })) {
201
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
202
- return mapCodeToCodeWithSourcemap(injection + code);
203
- }
204
- }
205
- }];
61
+ const addEntry = ({ entryName, entryPath, fileName, inject = "entry" }) => {
62
+ let devEntryPath = entryPath.startsWith("virtual:mf") ? "@id/" + entryPath : entryPath;
63
+ let entryFiles = [];
64
+ let htmlFilePath;
65
+ let _command;
66
+ let emitFileId;
67
+ let viteConfig;
68
+ function injectHtml() {
69
+ return inject === "html" && htmlFilePath;
70
+ }
71
+ function injectEntry() {
72
+ return inject === "entry" || !htmlFilePath;
73
+ }
74
+ return [{
75
+ name: "add-entry",
76
+ apply: "serve",
77
+ config(config, { command }) {
78
+ _command = command;
79
+ },
80
+ configResolved(config) {
81
+ viteConfig = config;
82
+ devEntryPath = config.base + devEntryPath.replace(/\\\\?/g, "/").replace(/.+?\:([/\\])[/\\]?/, "$1").replace(/^\//, "");
83
+ },
84
+ configureServer(server) {
85
+ server.middlewares.use((req, res, next) => {
86
+ if (!fileName) {
87
+ next();
88
+ return;
89
+ }
90
+ if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, "/"))) req.url = devEntryPath;
91
+ next();
92
+ });
93
+ },
94
+ transformIndexHtml(c) {
95
+ if (!injectHtml()) return;
96
+ return c.replace("<head>", `<head><script type="module" src=${JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, "$1").replace(/\\\\?/g, "/"))}><\/script>`);
97
+ },
98
+ transform(code, id) {
99
+ if (id.includes("node_modules") || inject !== "html" || htmlFilePath) return;
100
+ if (id.includes(".svelte-kit") && id.includes("internal.js")) {
101
+ const src = devEntryPath.replace(/.+?\:([/\\])[/\\]?/, "$1").replace(/\\\\?/g, "/");
102
+ return code.replace(/<head>/g, "<head><script type=\\\"module\\\" src=\\\"" + src + "\\\"><\/script>");
103
+ }
104
+ }
105
+ }, {
106
+ name: "add-entry",
107
+ enforce: "post",
108
+ configResolved(config) {
109
+ viteConfig = config;
110
+ const inputOptions = config.build.rollupOptions.input;
111
+ if (!inputOptions) htmlFilePath = pathe.resolve(config.root, "index.html");
112
+ else if (typeof inputOptions === "string") entryFiles = [inputOptions];
113
+ else if (Array.isArray(inputOptions)) entryFiles = inputOptions;
114
+ else if (typeof inputOptions === "object") entryFiles = Object.values(inputOptions);
115
+ if (entryFiles && entryFiles.length > 0) htmlFilePath = getFirstHtmlEntryFile(entryFiles);
116
+ },
117
+ buildStart() {
118
+ if (_command === "serve") return;
119
+ const hasHash = fileName?.includes?.("[hash");
120
+ const emitFileOptions = {
121
+ name: entryName,
122
+ type: "chunk",
123
+ id: entryPath,
124
+ preserveSignature: "strict"
125
+ };
126
+ if (!hasHash) emitFileOptions.fileName = fileName;
127
+ emitFileId = this.emitFile(emitFileOptions);
128
+ if (htmlFilePath && fs.existsSync(htmlFilePath)) {
129
+ const htmlContent = fs.readFileSync(htmlFilePath, "utf-8");
130
+ const scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
131
+ let match;
132
+ while ((match = scriptRegex.exec(htmlContent)) !== null) entryFiles.push(match[1]);
133
+ }
134
+ },
135
+ generateBundle(options, bundle) {
136
+ if (!injectHtml()) return;
137
+ const file = this.getFileName(emitFileId);
138
+ const resolvePath = (htmlFileName) => {
139
+ if (!viteConfig.experimental?.renderBuiltUrl) return viteConfig.base + file;
140
+ const result = viteConfig.experimental.renderBuiltUrl(file, {
141
+ hostId: htmlFileName,
142
+ hostType: "html",
143
+ type: "asset",
144
+ ssr: false
145
+ });
146
+ if (typeof result === "string") return result;
147
+ if (result && typeof result === "object") {
148
+ if ("runtime" in result) {
149
+ console.warn("[vite-plugin-federation] renderBuiltUrl returned runtime code for HTML injection. Runtime code cannot be used in <script src=\"\">. Falling back to base path.");
150
+ return viteConfig.base + file;
151
+ }
152
+ if (result.relative) return file;
153
+ }
154
+ return viteConfig.base + file;
155
+ };
156
+ for (const fileName in bundle) if (fileName.endsWith(".html")) {
157
+ let htmlAsset = bundle[fileName];
158
+ if (htmlAsset.type === "chunk") return;
159
+ const scriptContent = `
160
+ <script type="module" src="${resolvePath(fileName)}"><\/script>
161
+ `;
162
+ let htmlContent = htmlAsset.source.toString() || "";
163
+ htmlContent = htmlContent.replace("<head>", `<head>${scriptContent}`);
164
+ htmlAsset.source = htmlContent;
165
+ }
166
+ },
167
+ transform(code, id) {
168
+ if (injectEntry() && entryFiles.some((file) => id.endsWith(file))) return mapCodeToCodeWithSourcemap(`
169
+ import ${JSON.stringify(entryPath)};
170
+ ` + code);
171
+ }
172
+ }];
206
173
  };
207
174
 
208
- function _arrayLikeToArray(r, a) {
209
- (null == a || a > r.length) && (a = r.length);
210
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
211
- return n;
212
- }
213
- function _createForOfIteratorHelperLoose(r, e) {
214
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
215
- if (t) return (t = t.call(r)).next.bind(t);
216
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
217
- t && (r = t);
218
- var o = 0;
219
- return function () {
220
- return o >= r.length ? {
221
- done: !0
222
- } : {
223
- done: !1,
224
- value: r[o++]
225
- };
226
- };
227
- }
228
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
229
- }
230
- function _extends() {
231
- return _extends = Object.assign ? Object.assign.bind() : function (n) {
232
- for (var e = 1; e < arguments.length; e++) {
233
- var t = arguments[e];
234
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
235
- }
236
- return n;
237
- }, _extends.apply(null, arguments);
238
- }
239
- function _unsupportedIterableToArray(r, a) {
240
- if (r) {
241
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
242
- var t = {}.toString.call(r).slice(8, -1);
243
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
244
- }
245
- }
246
-
247
- /**
248
- * Check if user-defined alias conflicts with shared modules
249
- * This should run after aliasToArrayPlugin to ensure alias is an array
250
- */
175
+ //#endregion
176
+ //#region src/plugins/pluginCheckAliasConflicts.ts
177
+ /**
178
+ * Check if user-defined alias conflicts with shared modules
179
+ * This should run after aliasToArrayPlugin to ensure alias is an array
180
+ */
251
181
  function checkAliasConflicts(options) {
252
- var _options$shared = options.shared,
253
- shared = _options$shared === void 0 ? {} : _options$shared;
254
- var sharedKeys = Object.keys(shared);
255
- return {
256
- name: 'check-alias-conflicts',
257
- configResolved: function configResolved(config) {
258
- var _config$resolve;
259
- if (sharedKeys.length === 0) return;
260
- var userAliases = ((_config$resolve = config.resolve) == null ? void 0 : _config$resolve.alias) || [];
261
- var conflicts = [];
262
- for (var _i = 0, _sharedKeys = sharedKeys; _i < _sharedKeys.length; _i++) {
263
- var sharedKey = _sharedKeys[_i];
264
- for (var _iterator = _createForOfIteratorHelperLoose(userAliases), _step; !(_step = _iterator()).done;) {
265
- var aliasEntry = _step.value;
266
- var findPattern = aliasEntry.find;
267
- var replacement = aliasEntry.replacement;
268
- // Skip if replacement is not a string (e.g., customResolver)
269
- if (typeof replacement !== 'string') continue;
270
- // Skip Module Federation internal aliases (used for proxying shared modules)
271
- // These are generated with replacement '$1' and should not trigger warnings
272
- if (replacement === '$1') continue;
273
- // Check if alias pattern matches the shared module
274
- var isMatch = false;
275
- if (typeof findPattern === 'string') {
276
- isMatch = findPattern === sharedKey || sharedKey.startsWith(findPattern + '/');
277
- } else if (findPattern instanceof RegExp) {
278
- isMatch = findPattern.test(sharedKey);
279
- }
280
- if (isMatch) {
281
- conflicts.push({
282
- sharedModule: sharedKey,
283
- alias: String(findPattern),
284
- target: replacement
285
- });
286
- }
287
- }
288
- }
289
- if (conflicts.length > 0) {
290
- config.logger.warn('\n[Module Federation] Detected alias conflicts with shared modules:');
291
- conflicts.forEach(function (_ref) {
292
- var sharedModule = _ref.sharedModule,
293
- alias = _ref.alias,
294
- target = _ref.target;
295
- config.logger.warn(" - Shared module \"" + sharedModule + "\" is aliased by \"" + alias + "\" to \"" + target + "\"");
296
- });
297
- config.logger.warn(" This may cause runtime errors as the shared module will bypass Module Federation's sharing mechanism.");
298
- }
299
- }
300
- };
182
+ const { shared = {} } = options;
183
+ const sharedKeys = Object.keys(shared);
184
+ return {
185
+ name: "check-alias-conflicts",
186
+ configResolved(config) {
187
+ if (sharedKeys.length === 0) return;
188
+ const userAliases = config.resolve?.alias || [];
189
+ const conflicts = [];
190
+ for (const sharedKey of sharedKeys) for (const aliasEntry of userAliases) {
191
+ const findPattern = aliasEntry.find;
192
+ const replacement = aliasEntry.replacement;
193
+ if (typeof replacement !== "string") continue;
194
+ if (replacement === "$1") continue;
195
+ let isMatch = false;
196
+ if (typeof findPattern === "string") isMatch = findPattern === sharedKey || sharedKey.startsWith(findPattern + "/");
197
+ else if (findPattern instanceof RegExp) isMatch = findPattern.test(sharedKey);
198
+ if (isMatch) conflicts.push({
199
+ sharedModule: sharedKey,
200
+ alias: String(findPattern),
201
+ target: replacement
202
+ });
203
+ }
204
+ if (conflicts.length > 0) {
205
+ config.logger.warn("\n[Module Federation] Detected alias conflicts with shared modules:");
206
+ conflicts.forEach(({ sharedModule, alias, target }) => {
207
+ config.logger.warn(` - Shared module "${sharedModule}" is aliased by "${alias}" to "${target}"`);
208
+ });
209
+ config.logger.warn(" This may cause runtime errors as the shared module will bypass Module Federation's sharing mechanism.");
210
+ }
211
+ }
212
+ };
301
213
  }
302
214
 
303
- /**
304
- * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
305
- */
215
+ //#endregion
216
+ //#region src/plugins/pluginDevProxyModuleTopLevelAwait.ts
217
+ /**
218
+ * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
219
+ */
306
220
  function PluginDevProxyModuleTopLevelAwait() {
307
- var filterFunction = pluginutils.createFilter();
308
- var processedFlag = '/* already-processed-by-dev-proxy-module-top-level-await */';
309
- return {
310
- name: 'dev-proxy-module-top-level-await',
311
- apply: 'serve',
312
- transform: function transform(code, id) {
313
- if (code.includes(processedFlag)) {
314
- return null;
315
- }
316
- if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
317
- return null;
318
- }
319
- if (!filterFunction(id)) return null;
320
- var ast;
321
- try {
322
- ast = this.parse(code, {
323
- allowReturnOutsideFunction: true
324
- });
325
- } catch (e) {
326
- throw new Error(id + ": " + e);
327
- }
328
- var magicString = new MagicString__default["default"](code);
329
- estreeWalker.walk(ast, {
330
- enter: function enter(node) {
331
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
332
- var exportSpecifiers = node.specifiers.map(function (specifier) {
333
- return specifier.exported.name;
334
- });
335
- var proxyStatements = exportSpecifiers.map(function (name) {
336
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
337
- }).join('\n');
338
- var exportStatements = exportSpecifiers.map(function (name) {
339
- return "__mfproxy__" + name + " as " + name;
340
- }).join(', ');
341
- var start = node.start;
342
- var end = node.end;
343
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
344
- magicString.overwrite(start, end, replacement);
345
- }
346
- if (node.type === 'ExportDefaultDeclaration') {
347
- var declaration = node.declaration;
348
- var _start = node.start;
349
- var _end = node.end;
350
- var proxyStatement;
351
- var exportStatement = 'default';
352
- if (declaration.type === 'Identifier') {
353
- // example: export default foo;
354
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
355
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
356
- // example: export default someFunction();
357
- var declarationCode = code.slice(declaration.start, declaration.end);
358
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
359
- } else {
360
- // other
361
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
362
- }
363
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
364
- magicString.overwrite(_start, _end, _replacement);
365
- }
366
- }
367
- });
368
- var transformedCode = magicString.toString();
369
- return {
370
- code: processedFlag + "\n" + transformedCode,
371
- map: magicString.generateMap({
372
- hires: true
373
- })
374
- };
375
- }
376
- };
221
+ const filterFunction = (0, _rollup_pluginutils.createFilter)();
222
+ const processedFlag = "/* already-processed-by-dev-proxy-module-top-level-await */";
223
+ return {
224
+ name: "dev-proxy-module-top-level-await",
225
+ apply: "serve",
226
+ transform(code, id) {
227
+ if (code.includes(processedFlag)) return null;
228
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) return null;
229
+ if (!filterFunction(id)) return null;
230
+ let ast;
231
+ try {
232
+ ast = this.parse(code, { allowReturnOutsideFunction: true });
233
+ } catch (e) {
234
+ throw new Error(`${id}: ${e}`);
235
+ }
236
+ const magicString = new magic_string.default(code);
237
+ (0, estree_walker.walk)(ast, { enter(node) {
238
+ if (node.type === "ExportNamedDeclaration" && node.specifiers) {
239
+ const exportSpecifiers = node.specifiers.map((specifier) => specifier.exported.name);
240
+ const proxyStatements = exportSpecifiers.map((name) => `
241
+ const __mfproxy__await${name} = await ${name}();
242
+ const __mfproxy__${name} = () => __mfproxy__await${name};
243
+ `).join("\n");
244
+ const exportStatements = exportSpecifiers.map((name) => `__mfproxy__${name} as ${name}`).join(", ");
245
+ const start = node.start;
246
+ const end = node.end;
247
+ const replacement = `${proxyStatements}\nexport { ${exportStatements} };`;
248
+ magicString.overwrite(start, end, replacement);
249
+ }
250
+ if (node.type === "ExportDefaultDeclaration") {
251
+ const declaration = node.declaration;
252
+ const start = node.start;
253
+ const end = node.end;
254
+ let proxyStatement;
255
+ let exportStatement = "default";
256
+ if (declaration.type === "Identifier") proxyStatement = `
257
+ const __mfproxy__awaitdefault = await ${declaration.name}();
258
+ const __mfproxy__default = __mfproxy__awaitdefault;
259
+ `;
260
+ else if (declaration.type === "CallExpression" || declaration.type === "FunctionDeclaration") proxyStatement = `
261
+ const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
262
+ const __mfproxy__default = __mfproxy__awaitdefault;
263
+ `;
264
+ else proxyStatement = `
265
+ const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
266
+ const __mfproxy__default = __mfproxy__awaitdefault;
267
+ `;
268
+ const replacement = `${proxyStatement}\nexport { __mfproxy__default as ${exportStatement} };`;
269
+ magicString.overwrite(start, end, replacement);
270
+ }
271
+ } });
272
+ return {
273
+ code: `${processedFlag}\n${magicString.toString()}`,
274
+ map: magicString.generateMap({ hires: true })
275
+ };
276
+ }
277
+ };
377
278
  }
378
279
 
379
- function _catch(body, recover) {
380
- try {
381
- var result = body();
382
- } catch (e) {
383
- return recover(e);
384
- }
385
- if (result && result.then) {
386
- return result.then(void 0, recover);
387
- }
388
- return result;
389
- }
390
- var DEFAULT_DEV_OPTIONS = {
391
- disableLiveReload: true,
392
- disableHotTypesReload: false,
393
- disableDynamicRemoteTypeHints: false
280
+ //#endregion
281
+ //#region src/plugins/pluginDts.ts
282
+ const DEFAULT_DEV_OPTIONS = {
283
+ disableLiveReload: true,
284
+ disableHotTypesReload: false,
285
+ disableDynamicRemoteTypeHints: false
394
286
  };
395
- var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
396
- var getIPv4 = function getIPv4() {
397
- return process.env['FEDERATION_IPV4'] || '127.0.0.1';
287
+ const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
288
+ const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
289
+ const forkDevWorkerPath = require.resolve("@module-federation/dts-plugin/dist/fork-dev-worker.js");
290
+ var DevWorker = class {
291
+ constructor(options) {
292
+ this.worker = _module_federation_dts_plugin_core.rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
293
+ this.worker.connect(options);
294
+ }
295
+ update() {
296
+ this.worker.process?.send?.({
297
+ type: _module_federation_dts_plugin_core.rpc.RpcGMCallTypes.CALL,
298
+ id: this.worker.id,
299
+ args: [void 0, "update"]
300
+ });
301
+ }
302
+ exit() {
303
+ this.worker.terminate();
304
+ }
398
305
  };
399
- var forkDevWorkerPath = function () {
400
- // eslint-disable-next-line @typescript-eslint/no-var-requires
401
- return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
402
- }();
403
- var DevWorker = /*#__PURE__*/function () {
404
- function DevWorker(options) {
405
- this.worker = core.rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
406
- this.worker.connect(options);
407
- }
408
- var _proto = DevWorker.prototype;
409
- _proto.update = function update() {
410
- var _this$worker$process;
411
- (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
412
- type: core.rpc.RpcGMCallTypes.CALL,
413
- id: this.worker.id,
414
- args: [undefined, 'update']
415
- });
416
- };
417
- _proto.exit = function exit() {
418
- this.worker.terminate();
419
- };
420
- return DevWorker;
421
- }();
422
- var normalizeDevOptions = function normalizeDevOptions(dev) {
423
- if (dev === false) {
424
- return false;
425
- }
426
- if (dev === true || typeof dev === 'undefined') {
427
- return _extends({}, DEFAULT_DEV_OPTIONS);
428
- }
429
- return _extends({}, DEFAULT_DEV_OPTIONS, dev);
306
+ const normalizeDevOptions = (dev) => {
307
+ if (dev === false) return false;
308
+ if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
309
+ return {
310
+ ...DEFAULT_DEV_OPTIONS,
311
+ ...dev
312
+ };
430
313
  };
431
- var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
432
- var exposes = {};
433
- Object.entries(options.exposes).forEach(function (_ref) {
434
- var key = _ref[0],
435
- value = _ref[1];
436
- if (typeof value === 'string') {
437
- exposes[key] = value;
438
- return;
439
- }
440
- var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
441
- if (importValue) {
442
- exposes[key] = importValue;
443
- }
444
- });
445
- var remotes = {};
446
- Object.entries(options.remotes).forEach(function (_ref2) {
447
- var _remote$entryGlobalNa, _remote$entryGlobalNa2;
448
- var key = _ref2[0],
449
- remote = _ref2[1];
450
- if (typeof remote === 'string') {
451
- remotes[key] = remote;
452
- return;
453
- }
454
- if (!remote.entry) {
455
- return;
456
- }
457
- var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
458
- var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
459
- remotes[key] = entryGlobalName + "@" + remote.entry;
460
- });
461
- return _extends({}, options, {
462
- exposes: exposes,
463
- remotes: remotes
464
- });
314
+ const buildDtsModuleFederationConfig = (options) => {
315
+ const exposes = {};
316
+ Object.entries(options.exposes).forEach(([key, value]) => {
317
+ if (typeof value === "string") {
318
+ exposes[key] = value;
319
+ return;
320
+ }
321
+ const importValue = Array.isArray(value.import) ? value.import[0] : value.import;
322
+ if (importValue) exposes[key] = importValue;
323
+ });
324
+ const remotes = {};
325
+ Object.entries(options.remotes).forEach(([key, remote]) => {
326
+ if (typeof remote === "string") {
327
+ remotes[key] = remote;
328
+ return;
329
+ }
330
+ if (!remote.entry) return;
331
+ remotes[key] = `${remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key}@${remote.entry}`;
332
+ });
333
+ return {
334
+ ...options,
335
+ exposes,
336
+ remotes
337
+ };
465
338
  };
466
- var resolveOutputDir = function resolveOutputDir(config) {
467
- var outDir = config.build.outDir;
468
- if (path__namespace.isAbsolute(outDir)) {
469
- return path__namespace.relative(config.root, outDir);
470
- }
471
- return outDir;
339
+ const resolveOutputDir = (config) => {
340
+ const { outDir } = config.build;
341
+ if (pathe.isAbsolute(outDir)) return pathe.relative(config.root, outDir);
342
+ return outDir;
472
343
  };
473
- var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
474
- var hasPlugin = options.runtimePlugins.some(function (plugin) {
475
- if (typeof plugin === 'string') {
476
- return plugin === pluginId;
477
- }
478
- return plugin[0] === pluginId;
479
- });
480
- if (!hasPlugin) {
481
- options.runtimePlugins.push(pluginId);
482
- }
344
+ const ensureRuntimePlugin = (options, pluginId) => {
345
+ if (!options.runtimePlugins.some((plugin) => {
346
+ if (typeof plugin === "string") return plugin === pluginId;
347
+ return plugin[0] === pluginId;
348
+ })) options.runtimePlugins.push(pluginId);
483
349
  };
484
- var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
485
- var defaultGenerateTypes = {
486
- compileInChildProcess: true
487
- };
488
- var defaultConsumeTypes = {
489
- consumeAPITypes: true
490
- };
491
- return sdk.normalizeOptions(dtsPlugin.isTSProject(dts, context), {
492
- generateTypes: defaultGenerateTypes,
493
- consumeTypes: defaultConsumeTypes,
494
- extraOptions: {},
495
- displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
496
- }, 'mfOptions.dts')(dts);
350
+ const normalizeDevDtsOptions = (dts, context) => {
351
+ return (0, _module_federation_sdk.normalizeOptions)((0, _module_federation_dts_plugin.isTSProject)(dts, context), {
352
+ generateTypes: { compileInChildProcess: true },
353
+ consumeTypes: { consumeAPITypes: true },
354
+ extraOptions: {},
355
+ displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
356
+ }, "mfOptions.dts")(dts);
497
357
  };
498
- var logDtsError = function logDtsError(error, dtsOptions) {
499
- if (dtsOptions === false) {
500
- return;
501
- }
502
- if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
503
- return;
504
- }
505
- console.error(error);
358
+ const logDtsError = (error, dtsOptions) => {
359
+ if (dtsOptions === false) return;
360
+ if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
361
+ console.error(error);
506
362
  };
507
363
  function pluginDts(options) {
508
- if (options.dts === false) {
509
- return [];
510
- }
511
- var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
512
- var resolvedConfig;
513
- var devWorker;
514
- var normalizedDevOptions;
515
- var hasGeneratedBundle = false;
516
- var devPlugin = {
517
- name: 'module-federation-dts-dev',
518
- apply: 'serve',
519
- config: function config(_config) {
520
- normalizedDevOptions = normalizeDevOptions(options.dev);
521
- if (!normalizedDevOptions) {
522
- return;
523
- }
524
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
525
- return;
526
- }
527
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
528
- var define = _config.define ? _extends({}, _config.define) : {};
529
- if (!('FEDERATION_IPV4' in define)) {
530
- define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
531
- }
532
- _config.define = define;
533
- },
534
- configResolved: function configResolved(config) {
535
- resolvedConfig = config;
536
- },
537
- configureServer: function configureServer(server) {
538
- if (!normalizedDevOptions || !resolvedConfig) {
539
- return;
540
- }
541
- var devOptions = normalizedDevOptions;
542
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
543
- return;
544
- }
545
- if (!options.name) {
546
- throw new Error('name is required if you want to enable dev server!');
547
- }
548
- var outputDir = resolveOutputDir(resolvedConfig);
549
- var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
550
- if (typeof normalizedDtsOptions !== 'object') {
551
- return;
552
- }
553
- var normalizedGenerateTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
554
- compileInChildProcess: true
555
- }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
556
- var remote = normalizedGenerateTypes === false ? undefined : _extends({
557
- implementation: normalizedDtsOptions.implementation,
558
- context: resolvedConfig.root,
559
- outputDir: outputDir,
560
- moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
561
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
562
- }, normalizedGenerateTypes, {
563
- typesFolder: '.dev-server'
564
- });
565
- if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
566
- remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
567
- }
568
- var normalizedConsumeTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
569
- consumeAPITypes: true
570
- }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
571
- var host = normalizedConsumeTypes === false ? undefined : _extends({
572
- implementation: normalizedDtsOptions.implementation,
573
- context: resolvedConfig.root,
574
- moduleFederationConfig: dtsModuleFederationConfig,
575
- typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
576
- abortOnError: false
577
- }, normalizedConsumeTypes);
578
- var extraOptions = normalizedDtsOptions.extraOptions || {};
579
- if (!remote && !host && devOptions.disableLiveReload) {
580
- return;
581
- }
582
- var startDevWorker = function startDevWorker() {
583
- try {
584
- var _temp2 = function _temp2() {
585
- var _server$httpServer;
586
- devWorker = new DevWorker({
587
- name: options.name,
588
- remote: remote,
589
- host: host ? _extends({}, host, {
590
- remoteTypeUrls: remoteTypeUrls
591
- }) : undefined,
592
- extraOptions: extraOptions,
593
- disableLiveReload: devOptions.disableLiveReload,
594
- disableHotTypesReload: devOptions.disableHotTypesReload
595
- });
596
- var update = function update() {
597
- var _devWorker;
598
- return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
599
- };
600
- server.watcher.on('change', update);
601
- server.watcher.on('add', update);
602
- server.watcher.on('unlink', update);
603
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
604
- var _devWorker2;
605
- (_devWorker2 = devWorker) == null || _devWorker2.exit();
606
- server.watcher.off('change', update);
607
- server.watcher.off('add', update);
608
- server.watcher.off('unlink', update);
609
- });
610
- };
611
- var remoteTypeUrls;
612
- var _temp = function () {
613
- if (host) {
614
- return Promise.resolve(new Promise(function (resolve) {
615
- dtsPlugin.consumeTypesAPI({
616
- host: host,
617
- extraOptions: extraOptions,
618
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
619
- }, resolve);
620
- })).then(function (_Promise) {
621
- remoteTypeUrls = _Promise;
622
- });
623
- }
624
- }();
625
- return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
626
- } catch (e) {
627
- return Promise.reject(e);
628
- }
629
- };
630
- startDevWorker()["catch"](function (error) {
631
- logDtsError(error, normalizedDtsOptions);
632
- });
633
- }
634
- };
635
- var buildPlugin = {
636
- name: 'module-federation-dts-build',
637
- apply: 'build',
638
- configResolved: function configResolved(config) {
639
- resolvedConfig = config;
640
- },
641
- generateBundle: function generateBundle() {
642
- try {
643
- var _temp6 = function _temp6() {
644
- var generateOptions;
645
- try {
646
- generateOptions = dtsPlugin.normalizeGenerateTypesOptions({
647
- context: context,
648
- outputDir: outputDir,
649
- dtsOptions: normalizedDtsOptions,
650
- pluginOptions: dtsModuleFederationConfig
651
- });
652
- } catch (error) {
653
- logDtsError(error, normalizedDtsOptions);
654
- return;
655
- }
656
- if (!generateOptions) {
657
- return;
658
- }
659
- var _temp4 = _catch(function () {
660
- return Promise.resolve(dtsPlugin.generateTypesAPI({
661
- dtsManagerOptions: generateOptions
662
- })).then(function () {});
663
- }, function (error) {
664
- logDtsError(error, normalizedDtsOptions);
665
- });
666
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
667
- };
668
- if (hasGeneratedBundle) {
669
- return Promise.resolve();
670
- }
671
- hasGeneratedBundle = true;
672
- if (!resolvedConfig) {
673
- return Promise.resolve();
674
- }
675
- var normalizedDtsOptions;
676
- try {
677
- normalizedDtsOptions = dtsPlugin.normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
678
- } catch (error) {
679
- logDtsError(error, options.dts);
680
- return Promise.resolve();
681
- }
682
- if (typeof normalizedDtsOptions !== 'object') {
683
- return Promise.resolve();
684
- }
685
- var context = resolvedConfig.root;
686
- var outputDir = resolveOutputDir(resolvedConfig);
687
- var consumeOptions;
688
- try {
689
- consumeOptions = dtsPlugin.normalizeConsumeTypesOptions({
690
- context: context,
691
- dtsOptions: normalizedDtsOptions,
692
- pluginOptions: dtsModuleFederationConfig
693
- });
694
- } catch (error) {
695
- logDtsError(error, normalizedDtsOptions);
696
- return Promise.resolve();
697
- }
698
- var _temp5 = function (_consumeOptions) {
699
- if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
700
- var _temp3 = _catch(function () {
701
- return Promise.resolve(dtsPlugin.consumeTypesAPI(consumeOptions)).then(function () {});
702
- }, function (error) {
703
- logDtsError(error, normalizedDtsOptions);
704
- });
705
- if (_temp3 && _temp3.then) return _temp3.then(function () {});
706
- }
707
- }();
708
- return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
709
- } catch (e) {
710
- return Promise.reject(e);
711
- }
712
- }
713
- };
714
- return [devPlugin, buildPlugin];
364
+ if (options.dts === false) return [];
365
+ const dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
366
+ let resolvedConfig;
367
+ let devWorker;
368
+ let normalizedDevOptions;
369
+ let hasGeneratedBundle = false;
370
+ return [{
371
+ name: "module-federation-dts-dev",
372
+ apply: "serve",
373
+ config(config) {
374
+ normalizedDevOptions = normalizeDevOptions(options.dev);
375
+ if (!normalizedDevOptions) return;
376
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
377
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
378
+ const define = config.define ? { ...config.define } : {};
379
+ if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
380
+ config.define = define;
381
+ },
382
+ configResolved(config) {
383
+ resolvedConfig = config;
384
+ },
385
+ configureServer(server) {
386
+ if (!normalizedDevOptions || !resolvedConfig) return;
387
+ const devOptions = normalizedDevOptions;
388
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
389
+ if (!options.name) throw new Error("name is required if you want to enable dev server!");
390
+ const outputDir = resolveOutputDir(resolvedConfig);
391
+ const normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
392
+ if (typeof normalizedDtsOptions !== "object") return;
393
+ const normalizedGenerateTypes = (0, _module_federation_sdk.normalizeOptions)(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
394
+ const remote = normalizedGenerateTypes === false ? void 0 : {
395
+ implementation: normalizedDtsOptions.implementation,
396
+ context: resolvedConfig.root,
397
+ outputDir,
398
+ moduleFederationConfig: { ...dtsModuleFederationConfig },
399
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
400
+ ...normalizedGenerateTypes,
401
+ typesFolder: ".dev-server"
402
+ };
403
+ if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === "object" && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
404
+ const normalizedConsumeTypes = (0, _module_federation_sdk.normalizeOptions)(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
405
+ const host = normalizedConsumeTypes === false ? void 0 : {
406
+ implementation: normalizedDtsOptions.implementation,
407
+ context: resolvedConfig.root,
408
+ moduleFederationConfig: dtsModuleFederationConfig,
409
+ typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
410
+ abortOnError: false,
411
+ ...normalizedConsumeTypes
412
+ };
413
+ const extraOptions = normalizedDtsOptions.extraOptions || {};
414
+ if (!remote && !host && devOptions.disableLiveReload) return;
415
+ const startDevWorker = async () => {
416
+ let remoteTypeUrls;
417
+ if (host) remoteTypeUrls = await new Promise((resolve) => {
418
+ (0, _module_federation_dts_plugin.consumeTypesAPI)({
419
+ host,
420
+ extraOptions,
421
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
422
+ }, resolve);
423
+ });
424
+ devWorker = new DevWorker({
425
+ name: options.name,
426
+ remote,
427
+ host: host ? {
428
+ ...host,
429
+ remoteTypeUrls
430
+ } : void 0,
431
+ extraOptions,
432
+ disableLiveReload: devOptions.disableLiveReload,
433
+ disableHotTypesReload: devOptions.disableHotTypesReload
434
+ });
435
+ const update = () => devWorker?.update();
436
+ server.watcher.on("change", update);
437
+ server.watcher.on("add", update);
438
+ server.watcher.on("unlink", update);
439
+ server.httpServer?.once("close", () => {
440
+ devWorker?.exit();
441
+ server.watcher.off("change", update);
442
+ server.watcher.off("add", update);
443
+ server.watcher.off("unlink", update);
444
+ });
445
+ };
446
+ startDevWorker().catch((error) => {
447
+ logDtsError(error, normalizedDtsOptions);
448
+ });
449
+ }
450
+ }, {
451
+ name: "module-federation-dts-build",
452
+ apply: "build",
453
+ configResolved(config) {
454
+ resolvedConfig = config;
455
+ },
456
+ async generateBundle() {
457
+ if (hasGeneratedBundle) return;
458
+ hasGeneratedBundle = true;
459
+ if (!resolvedConfig) return;
460
+ let normalizedDtsOptions;
461
+ try {
462
+ normalizedDtsOptions = (0, _module_federation_dts_plugin.normalizeDtsOptions)(dtsModuleFederationConfig, resolvedConfig.root);
463
+ } catch (error) {
464
+ logDtsError(error, options.dts);
465
+ return;
466
+ }
467
+ if (typeof normalizedDtsOptions !== "object") return;
468
+ const context = resolvedConfig.root;
469
+ const outputDir = resolveOutputDir(resolvedConfig);
470
+ let consumeOptions;
471
+ try {
472
+ consumeOptions = (0, _module_federation_dts_plugin.normalizeConsumeTypesOptions)({
473
+ context,
474
+ dtsOptions: normalizedDtsOptions,
475
+ pluginOptions: dtsModuleFederationConfig
476
+ });
477
+ } catch (error) {
478
+ logDtsError(error, normalizedDtsOptions);
479
+ return;
480
+ }
481
+ if (consumeOptions?.host?.typesOnBuild) try {
482
+ await (0, _module_federation_dts_plugin.consumeTypesAPI)(consumeOptions);
483
+ } catch (error) {
484
+ logDtsError(error, normalizedDtsOptions);
485
+ }
486
+ let generateOptions;
487
+ try {
488
+ generateOptions = (0, _module_federation_dts_plugin.normalizeGenerateTypesOptions)({
489
+ context,
490
+ outputDir,
491
+ dtsOptions: normalizedDtsOptions,
492
+ pluginOptions: dtsModuleFederationConfig
493
+ });
494
+ } catch (error) {
495
+ logDtsError(error, normalizedDtsOptions);
496
+ return;
497
+ }
498
+ if (!generateOptions) return;
499
+ try {
500
+ await (0, _module_federation_dts_plugin.generateTypesAPI)({ dtsManagerOptions: generateOptions });
501
+ } catch (error) {
502
+ logDtsError(error, normalizedDtsOptions);
503
+ }
504
+ }
505
+ }];
715
506
  }
716
507
 
508
+ //#endregion
509
+ //#region src/utils/normalizeModuleFederationOptions.ts
717
510
  function normalizeExposesItem(key, item) {
718
- var importPath = '';
719
- if (typeof item === 'string') {
720
- importPath = item;
721
- }
722
- if (typeof item === 'object') {
723
- importPath = item["import"];
724
- }
725
- return {
726
- "import": importPath
727
- };
511
+ let importPath = "";
512
+ if (typeof item === "string") importPath = item;
513
+ if (typeof item === "object") importPath = item.import;
514
+ return { import: importPath };
728
515
  }
729
516
  function normalizeExposes(exposes) {
730
- if (!exposes) return {};
731
- var res = {};
732
- Object.keys(exposes).forEach(function (key) {
733
- res[key] = normalizeExposesItem(key, exposes[key]);
734
- });
735
- return res;
517
+ if (!exposes) return {};
518
+ const res = {};
519
+ Object.keys(exposes).forEach((key) => {
520
+ res[key] = normalizeExposesItem(key, exposes[key]);
521
+ });
522
+ return res;
736
523
  }
737
524
  function normalizeRemotes(remotes) {
738
- if (!remotes) return {};
739
- var result = {};
740
- if (typeof remotes === 'object') {
741
- Object.keys(remotes).forEach(function (key) {
742
- result[key] = normalizeRemoteItem(key, remotes[key]);
743
- });
744
- }
745
- return result;
525
+ if (!remotes) return {};
526
+ const result = {};
527
+ if (typeof remotes === "object") Object.keys(remotes).forEach((key) => {
528
+ result[key] = normalizeRemoteItem(key, remotes[key]);
529
+ });
530
+ return result;
746
531
  }
747
532
  function normalizeRemoteItem(key, remote) {
748
- if (typeof remote === 'string') {
749
- var _remote$split = remote.split('@'),
750
- entryGlobalName = _remote$split[0];
751
- var entry = remote.replace(entryGlobalName + '@', '');
752
- return {
753
- type: 'var',
754
- name: key,
755
- entry: entry,
756
- entryGlobalName: entryGlobalName,
757
- shareScope: 'default'
758
- };
759
- }
760
- return Object.assign({
761
- type: 'var',
762
- name: key,
763
- shareScope: 'default',
764
- entryGlobalName: key
765
- }, remote);
533
+ if (typeof remote === "string") {
534
+ const [entryGlobalName] = remote.split("@");
535
+ return {
536
+ type: "var",
537
+ name: key,
538
+ entry: remote.replace(entryGlobalName + "@", ""),
539
+ entryGlobalName,
540
+ shareScope: "default"
541
+ };
542
+ }
543
+ return Object.assign({
544
+ type: "var",
545
+ name: key,
546
+ shareScope: "default",
547
+ entryGlobalName: key
548
+ }, remote);
766
549
  }
767
550
  function removePathFromNpmPackage(packageString) {
768
- // 匹配npm包名的正则表达式,忽略路径部分
769
- var regex = /^(?:@[^/]+\/)?[^/]+/;
770
- // 使用正则表达式匹配并提取包名
771
- var match = packageString.match(regex);
772
- // 返回匹配到的包名,如果没有匹配到则返回原字符串
773
- return match ? match[0] : packageString;
551
+ const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
552
+ return match ? match[0] : packageString;
774
553
  }
775
- /**
776
- * Tries to find the package.json's version of a shared package
777
- * if `package.json` is not declared in `exports`
778
- * @param {string} sharedName
779
- * @returns {string | undefined}
780
- */
554
+ /**
555
+ * Tries to find the package.json's version of a shared package
556
+ * if `package.json` is not declared in `exports`
557
+ * @param {string} sharedName
558
+ * @returns {string | undefined}
559
+ */
781
560
  function searchPackageVersion(sharedName) {
782
- try {
783
- var sharedPath = require.resolve(sharedName);
784
- var potentialPackageJsonDir = path__namespace.dirname(sharedPath);
785
- var rootDir = path__namespace.parse(potentialPackageJsonDir).root;
786
- while (path__namespace.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
787
- var potentialPackageJsonPath = path__namespace.join(potentialPackageJsonDir, 'package.json');
788
- if (fs__namespace.existsSync(potentialPackageJsonPath)) {
789
- var potentialPackageJson = require(potentialPackageJsonPath);
790
- if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
791
- return potentialPackageJson.version;
792
- }
793
- }
794
- potentialPackageJsonDir = path__namespace.dirname(potentialPackageJsonDir);
795
- }
796
- } catch (_) {}
797
- return undefined;
561
+ try {
562
+ const sharedPath = require.resolve(sharedName);
563
+ let potentialPackageJsonDir = pathe.dirname(sharedPath);
564
+ const rootDir = pathe.parse(potentialPackageJsonDir).root;
565
+ while (pathe.parse(potentialPackageJsonDir).base !== "node_modules" && potentialPackageJsonDir !== rootDir) {
566
+ const potentialPackageJsonPath = pathe.join(potentialPackageJsonDir, "package.json");
567
+ if (fs.existsSync(potentialPackageJsonPath)) {
568
+ const potentialPackageJson = require(potentialPackageJsonPath);
569
+ if (typeof potentialPackageJson == "object" && potentialPackageJson !== null && typeof potentialPackageJson.version === "string" && potentialPackageJson.name === sharedName) return potentialPackageJson.version;
570
+ }
571
+ potentialPackageJsonDir = pathe.dirname(potentialPackageJsonDir);
572
+ }
573
+ } catch (_) {}
798
574
  }
799
575
  function normalizeShareItem(key, shareItem) {
800
- var version;
801
- try {
802
- try {
803
- version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
804
- } catch (e1) {
805
- try {
806
- var localPath = path__namespace.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
807
- version = require(localPath).version;
808
- } catch (e2) {
809
- version = searchPackageVersion(key);
810
- if (!version) console.error(e1);
811
- }
812
- }
813
- } catch (e) {
814
- console.error("Unexpected error resolving version for " + key + ":", e);
815
- }
816
- if (typeof shareItem === 'string') {
817
- return {
818
- name: shareItem,
819
- version: version,
820
- scope: 'default',
821
- from: '',
822
- shareConfig: {
823
- "import": undefined,
824
- singleton: false,
825
- requiredVersion: version ? "^" + version : '*'
826
- }
827
- };
828
- }
829
- return {
830
- name: key,
831
- from: '',
832
- version: shareItem.version || version,
833
- scope: shareItem.shareScope || 'default',
834
- shareConfig: {
835
- "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
836
- singleton: shareItem.singleton || false,
837
- requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
838
- strictVersion: !!shareItem.strictVersion
839
- }
840
- };
576
+ let version;
577
+ try {
578
+ try {
579
+ version = require(pathe.join(removePathFromNpmPackage(key), "package.json")).version;
580
+ } catch (e1) {
581
+ try {
582
+ const localPath = pathe.join(process.cwd(), "node_modules", removePathFromNpmPackage(key), "package.json");
583
+ version = require(localPath).version;
584
+ } catch (e2) {
585
+ version = searchPackageVersion(key);
586
+ if (!version) console.error(e1);
587
+ }
588
+ }
589
+ } catch (e) {
590
+ console.error(`Unexpected error resolving version for ${key}:`, e);
591
+ }
592
+ if (typeof shareItem === "string") return {
593
+ name: shareItem,
594
+ version,
595
+ scope: "default",
596
+ from: "",
597
+ shareConfig: {
598
+ import: void 0,
599
+ singleton: false,
600
+ requiredVersion: version ? `^${version}` : "*"
601
+ }
602
+ };
603
+ return {
604
+ name: key,
605
+ from: "",
606
+ version: shareItem.version || version,
607
+ scope: shareItem.shareScope || "default",
608
+ shareConfig: {
609
+ import: typeof shareItem === "object" ? shareItem.import : void 0,
610
+ singleton: shareItem.singleton || false,
611
+ requiredVersion: shareItem.requiredVersion || (version ? `^${version}` : "*"),
612
+ strictVersion: !!shareItem.strictVersion
613
+ }
614
+ };
841
615
  }
842
616
  function normalizeShared(shared) {
843
- if (!shared) return {};
844
- var result = {};
845
- if (Array.isArray(shared)) {
846
- shared.forEach(function (key) {
847
- result[key] = normalizeShareItem(key, key);
848
- });
849
- return result;
850
- }
851
- if (typeof shared === 'object') {
852
- Object.keys(shared).forEach(function (key) {
853
- result[key] = normalizeShareItem(key, shared[key]);
854
- });
855
- }
856
- return result;
617
+ if (!shared) return {};
618
+ const result = {};
619
+ if (Array.isArray(shared)) {
620
+ shared.forEach((key) => {
621
+ result[key] = normalizeShareItem(key, key);
622
+ });
623
+ return result;
624
+ }
625
+ if (typeof shared === "object") Object.keys(shared).forEach((key) => {
626
+ result[key] = normalizeShareItem(key, shared[key]);
627
+ });
628
+ return result;
857
629
  }
858
630
  function normalizeLibrary(library) {
859
- if (!library) return undefined;
860
- return library;
631
+ if (!library) return void 0;
632
+ return library;
861
633
  }
862
- function normalizeManifest(manifest) {
863
- if (manifest === void 0) {
864
- manifest = false;
865
- }
866
- if (typeof manifest === 'boolean') {
867
- return manifest;
868
- }
869
- return Object.assign({
870
- filePath: '',
871
- disableAssetsAnalyze: false,
872
- fileName: 'mf-manifest.json'
873
- }, manifest);
634
+ function normalizeManifest(manifest = false) {
635
+ if (typeof manifest === "boolean") return manifest;
636
+ return Object.assign({
637
+ filePath: "",
638
+ disableAssetsAnalyze: false,
639
+ fileName: "mf-manifest.json"
640
+ }, manifest);
874
641
  }
875
- var config;
642
+ let config;
876
643
  function getNormalizeModuleFederationOptions() {
877
- return config;
644
+ return config;
878
645
  }
879
646
  function getNormalizeShareItem(key) {
880
- var options = getNormalizeModuleFederationOptions();
881
- var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
882
- return shareItem;
647
+ const options = getNormalizeModuleFederationOptions();
648
+ return options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
883
649
  }
884
650
  function normalizeModuleFederationOptions(options) {
885
- if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
886
- throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
887
- }
888
- return config = {
889
- exposes: normalizeExposes(options.exposes),
890
- filename: options.filename || 'remoteEntry-[hash]',
891
- library: normalizeLibrary(options.library),
892
- name: options.name,
893
- // remoteType: options.remoteType,
894
- remotes: normalizeRemotes(options.remotes),
895
- runtime: options.runtime,
896
- shareScope: options.shareScope || 'default',
897
- shared: normalizeShared(options.shared),
898
- runtimePlugins: options.runtimePlugins || [],
899
- implementation: options.implementation || require.resolve('@module-federation/runtime'),
900
- manifest: normalizeManifest(options.manifest),
901
- dev: options.dev,
902
- dts: options.dts,
903
- getPublicPath: options.getPublicPath,
904
- publicPath: options.publicPath,
905
- shareStrategy: options.shareStrategy || 'version-first',
906
- ignoreOrigin: options.ignoreOrigin || false,
907
- virtualModuleDir: options.virtualModuleDir || '__mf__virtual',
908
- hostInitInjectLocation: options.hostInitInjectLocation || 'html',
909
- bundleAllCSS: options.bundleAllCSS || false,
910
- moduleParseTimeout: options.moduleParseTimeout || 10,
911
- varFilename: options.varFilename
912
- };
651
+ if (options.virtualModuleDir && options.virtualModuleDir.includes("/")) throw new Error(`Invalid virtualModuleDir: "${options.virtualModuleDir}". The virtualModuleDir option cannot contain slashes (/). Please use a single directory name like '__mf__virtual__your_app_name'.`);
652
+ return config = {
653
+ exposes: normalizeExposes(options.exposes),
654
+ filename: options.filename || "remoteEntry-[hash]",
655
+ library: normalizeLibrary(options.library),
656
+ name: options.name,
657
+ remotes: normalizeRemotes(options.remotes),
658
+ runtime: options.runtime,
659
+ shareScope: options.shareScope || "default",
660
+ shared: normalizeShared(options.shared),
661
+ runtimePlugins: options.runtimePlugins || [],
662
+ implementation: options.implementation || require.resolve("@module-federation/runtime"),
663
+ manifest: normalizeManifest(options.manifest),
664
+ dev: options.dev,
665
+ dts: options.dts,
666
+ getPublicPath: options.getPublicPath,
667
+ publicPath: options.publicPath,
668
+ shareStrategy: options.shareStrategy || "version-first",
669
+ ignoreOrigin: options.ignoreOrigin || false,
670
+ virtualModuleDir: options.virtualModuleDir || "__mf__virtual",
671
+ hostInitInjectLocation: options.hostInitInjectLocation || "html",
672
+ bundleAllCSS: options.bundleAllCSS || false,
673
+ moduleParseTimeout: options.moduleParseTimeout || 10,
674
+ varFilename: options.varFilename,
675
+ target: options.target
676
+ };
913
677
  }
914
678
 
915
- /**
916
- * Escaping rules:
917
- * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
918
- * @ => 1
919
- * / => 2
920
- * - => 3
921
- * . => 4
922
- */
923
- /**
924
- * Encodes a package name into a valid file name.
925
- * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
926
- * @returns {string} - The encoded file name.
927
- */
679
+ //#endregion
680
+ //#region src/utils/packageNameUtils.ts
681
+ /**
682
+ * Escaping rules:
683
+ * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
684
+ * @ => 1
685
+ * / => 2
686
+ * - => 3
687
+ * . => 4
688
+ */
689
+ /**
690
+ * Encodes a package name into a valid file name.
691
+ * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
692
+ * @returns {string} - The encoded file name.
693
+ */
928
694
  function packageNameEncode(name) {
929
- if (typeof name !== 'string') throw new Error('A string package name is required');
930
- return name.replace(/@/g, '_mf_0_').replace(/\//g, '_mf_1_').replace(/-/g, '_mf_2_').replace(/\./g, '_mf_3_');
695
+ if (typeof name !== "string") throw new Error("A string package name is required");
696
+ return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
931
697
  }
932
- /**
933
- * Decodes an encoded file name back to the original package name.
934
- * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
935
- * @returns {string} - The decoded package name.
936
- */
698
+ /**
699
+ * Decodes an encoded file name back to the original package name.
700
+ * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
701
+ * @returns {string} - The decoded package name.
702
+ */
937
703
  function packageNameDecode(encoded) {
938
- if (typeof encoded !== 'string') throw new Error('A string encoded file name is required');
939
- return encoded.replace(/_mf_0_/g, '@').replace(/_mf_1_/g, '/').replace(/_mf_2_/g, '-').replace(/_mf_3_/g, '.');
704
+ if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
705
+ return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
940
706
  }
941
707
 
942
- /**
943
- * https://github.com/module-federation/vite/issues/68
944
- */
708
+ //#endregion
709
+ //#region src/utils/localSharedImportMap_temp.ts
710
+ /**
711
+ * https://github.com/module-federation/vite/issues/68
712
+ */
945
713
  function getLocalSharedImportMapPath_temp() {
946
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
947
- name = _getNormalizeModuleFe.name;
948
- return path__default["default"].resolve('.__mf__temp', packageNameEncode(name), 'localSharedImportMap');
714
+ const { name } = getNormalizeModuleFederationOptions();
715
+ return pathe.default.resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
949
716
  }
950
717
  function writeLocalSharedImportMap_temp(content) {
951
- var localSharedImportMapId = getLocalSharedImportMapPath_temp();
952
- createFile(localSharedImportMapId + '.js', '\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n' + content);
718
+ createFile(getLocalSharedImportMapPath_temp() + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
953
719
  }
954
720
  function createFile(filePath, content) {
955
- var dir = path__default["default"].dirname(filePath);
956
- fs.mkdirSync(dir, {
957
- recursive: true
958
- });
959
- fs.writeFileSync(filePath, content);
721
+ (0, fs.mkdirSync)(pathe.default.dirname(filePath), { recursive: true });
722
+ (0, fs.writeFileSync)(filePath, content);
960
723
  }
961
724
 
962
- /**
963
- * Serializes a JavaScript object into a string of source code that can be evaluated.
964
- * This function is used to create runtime plugin options without relying solely on JSON.stringify,
965
- * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
966
- * It also safely handles circular references.
967
- *
968
- * @param {Record<string, unknown>} options - The options object to serialize.
969
- * @returns {string} The resulting JavaScript source code string.
970
- */
725
+ //#endregion
726
+ //#region src/utils/serializeRuntimeOptions.ts
727
+ /**
728
+ * Serializes a JavaScript object into a string of source code that can be evaluated.
729
+ * This function is used to create runtime plugin options without relying solely on JSON.stringify,
730
+ * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
731
+ * It also safely handles circular references.
732
+ *
733
+ * @param {Record<string, unknown>} options - The options object to serialize.
734
+ * @returns {string} The resulting JavaScript source code string.
735
+ */
971
736
  function serializeRuntimeOptions(options) {
972
- // Use a WeakSet to track objects already encountered, which helps in detecting circular references.
973
- var seenObjects = new WeakSet();
974
- /**
975
- * Recursive inner function to serialize any value into a source code string.
976
- */
977
- function valueToCode(val) {
978
- // 1. Handle primitive values
979
- if (val === null) return 'null';
980
- var type = typeof val;
981
- if (type === 'string') return JSON.stringify(val);
982
- if (type === 'number' || type === 'boolean') return String(val);
983
- if (type === 'undefined') return 'undefined';
984
- // Handle Symbol
985
- if (type === 'symbol') {
986
- var _val$description;
987
- var desc = (_val$description = val.description) != null ? _val$description : '';
988
- return "Symbol(" + JSON.stringify(desc) + ")";
989
- }
990
- // Handle Function (returns the function's source code)
991
- if (type === 'function') return val.toString();
992
- // 2. Handle special built-in objects
993
- if (val instanceof Date) return "new Date(" + JSON.stringify(val.toISOString()) + ")";
994
- if (val instanceof RegExp) {
995
- return "new RegExp(" + JSON.stringify(val.source) + ", " + JSON.stringify(val.flags) + ")";
996
- }
997
- // 3. Check for circular references and mark object as seen
998
- // This applies to objects, arrays, maps, and sets.
999
- if (type === 'object') {
1000
- if (seenObjects.has(val)) {
1001
- // This object has been seen previously in the recursion path
1002
- return "\"__circular__\"";
1003
- }
1004
- seenObjects.add(val);
1005
- }
1006
- // 4. Handle Array, Map, Set
1007
- if (Array.isArray(val)) {
1008
- // Recursively serialize each element
1009
- return "[" + val.map(valueToCode).join(', ') + "]";
1010
- }
1011
- if (val instanceof Map) {
1012
- // Serialize Map entries into an array of [key, value] pairs
1013
- var entries = Array.from(val.entries()).map(function (_ref) {
1014
- var k = _ref[0],
1015
- v = _ref[1];
1016
- return "[" + valueToCode(k) + ", " + valueToCode(v) + "]";
1017
- });
1018
- return "new Map([" + entries.join(', ') + "])";
1019
- }
1020
- if (val instanceof Set) {
1021
- // Serialize Set values into an array
1022
- var items = Array.from(val.values()).map(valueToCode);
1023
- return "new Set([" + items.join(', ') + "])";
1024
- }
1025
- // 5. Handle plain objects (the default object type)
1026
- if (type === 'object') {
1027
- var properties = [];
1028
- // Iterate over the object's own enumerable properties
1029
- for (var key in val) {
1030
- if (Object.prototype.hasOwnProperty.call(val, key)) {
1031
- // Wrap the key in JSON.stringify to handle non-identifier keys
1032
- properties.push(JSON.stringify(key) + ": " + valueToCode(val[key]));
1033
- }
1034
- }
1035
- return "{" + properties.join(', ') + "}";
1036
- }
1037
- // 6. Fallback case (e.g., BigInt, other object types)
1038
- // Coerce to string and then JSON.stringify that string for safety
1039
- return JSON.stringify(String(val));
1040
- }
1041
- // Start serialization for the top-level object
1042
- var topLevelProps = [];
1043
- // Iterate over the properties of the root 'options' object
1044
- for (var key in options) {
1045
- if (Object.prototype.hasOwnProperty.call(options, key)) {
1046
- topLevelProps.push(JSON.stringify(key) + ": " + valueToCode(options[key]));
1047
- }
1048
- }
1049
- return "{" + topLevelProps.join(', ') + "}";
737
+ const seenObjects = /* @__PURE__ */ new WeakSet();
738
+ /**
739
+ * Recursive inner function to serialize any value into a source code string.
740
+ */
741
+ function valueToCode(val) {
742
+ if (val === null) return "null";
743
+ const type = typeof val;
744
+ if (type === "string") return JSON.stringify(val);
745
+ if (type === "number" || type === "boolean") return String(val);
746
+ if (type === "undefined") return "undefined";
747
+ if (type === "symbol") {
748
+ const desc = val.description ?? "";
749
+ return `Symbol(${JSON.stringify(desc)})`;
750
+ }
751
+ if (type === "function") return val.toString();
752
+ if (val instanceof Date) return `new Date(${JSON.stringify(val.toISOString())})`;
753
+ if (val instanceof RegExp) return `new RegExp(${JSON.stringify(val.source)}, ${JSON.stringify(val.flags)})`;
754
+ if (type === "object") {
755
+ if (seenObjects.has(val)) return `"__circular__"`;
756
+ seenObjects.add(val);
757
+ }
758
+ if (Array.isArray(val)) return `[${val.map(valueToCode).join(", ")}]`;
759
+ if (val instanceof Map) return `new Map([${Array.from(val.entries()).map(([k, v]) => `[${valueToCode(k)}, ${valueToCode(v)}]`).join(", ")}])`;
760
+ if (val instanceof Set) return `new Set([${Array.from(val.values()).map(valueToCode).join(", ")}])`;
761
+ if (type === "object") {
762
+ const properties = [];
763
+ for (const key in val) if (Object.prototype.hasOwnProperty.call(val, key)) properties.push(`${JSON.stringify(key)}: ${valueToCode(val[key])}`);
764
+ return `{${properties.join(", ")}}`;
765
+ }
766
+ return JSON.stringify(String(val));
767
+ }
768
+ const topLevelProps = [];
769
+ for (const key in options) if (Object.prototype.hasOwnProperty.call(options, key)) topLevelProps.push(`${JSON.stringify(key)}: ${valueToCode(options[key])}`);
770
+ return `{${topLevelProps.join(", ")}}`;
1050
771
  }
1051
772
 
1052
- // Cache root path
1053
- var rootDir;
1054
- function findNodeModulesDir(root) {
1055
- if (root === void 0) {
1056
- root = process.cwd();
1057
- }
1058
- var currentDir = root;
1059
- while (currentDir !== path.parse(currentDir).root) {
1060
- var nodeModulesPath = path.join(currentDir, 'node_modules');
1061
- if (fs.existsSync(nodeModulesPath)) {
1062
- return nodeModulesPath;
1063
- }
1064
- currentDir = path.dirname(currentDir);
1065
- }
1066
- return '';
773
+ //#endregion
774
+ //#region src/utils/VirtualModule.ts
775
+ /**
776
+ * Initialize virtual module infrastructure BEFORE VirtualModule class is used.
777
+ * This must be called in the config hook to ensure the directory exists
778
+ * before Vite's optimization phase.
779
+ */
780
+ function initVirtualModuleInfrastructure(root, virtualModuleDir = "__mf__virtual") {
781
+ const virtualPackagePath = (0, pathe.join)((0, pathe.join)(root, "node_modules"), virtualModuleDir);
782
+ if (!(0, fs.existsSync)(virtualPackagePath)) {
783
+ (0, fs.mkdirSync)(virtualPackagePath, { recursive: true });
784
+ (0, fs.writeFileSync)((0, pathe.join)(virtualPackagePath, "empty.js"), "");
785
+ (0, fs.writeFileSync)((0, pathe.join)(virtualPackagePath, "package.json"), JSON.stringify({
786
+ name: virtualModuleDir,
787
+ main: "empty.js"
788
+ }));
789
+ }
790
+ }
791
+ let rootDir;
792
+ function findNodeModulesDir(root = process.cwd()) {
793
+ let currentDir = root;
794
+ while (currentDir !== (0, pathe.parse)(currentDir).root) {
795
+ const nodeModulesPath = (0, pathe.join)(currentDir, "node_modules");
796
+ if ((0, fs.existsSync)(nodeModulesPath)) return nodeModulesPath;
797
+ currentDir = (0, pathe.dirname)(currentDir);
798
+ }
799
+ return "";
1067
800
  }
1068
- // Cache nodeModulesDir result to avoid repeated calculations
1069
- var cachedNodeModulesDir;
801
+ let cachedNodeModulesDir;
1070
802
  function getNodeModulesDir() {
1071
- if (!cachedNodeModulesDir) {
1072
- cachedNodeModulesDir = findNodeModulesDir(rootDir);
1073
- }
1074
- return cachedNodeModulesDir;
803
+ if (!cachedNodeModulesDir) cachedNodeModulesDir = findNodeModulesDir(rootDir);
804
+ return cachedNodeModulesDir;
1075
805
  }
1076
806
  function getSuffix(name) {
1077
- var base = path.basename(name);
1078
- var dotIndex = base.lastIndexOf('.');
1079
- if (dotIndex > 0 && dotIndex < base.length - 1) {
1080
- return base.slice(dotIndex);
1081
- }
1082
- return '.js';
807
+ const base = (0, pathe.basename)(name);
808
+ const dotIndex = base.lastIndexOf(".");
809
+ if (dotIndex > 0 && dotIndex < base.length - 1) return base.slice(dotIndex);
810
+ return ".js";
1083
811
  }
1084
- var patternMap = {};
1085
- var cacheMap = {};
1086
- /**
1087
- * Physically generate files as virtual modules under node_modules/__mf__virtual/*
1088
- */
1089
- function assertModuleFound(tag, str) {
1090
- if (str === void 0) {
1091
- str = '';
1092
- }
1093
- var module = VirtualModule.findModule(tag, str);
1094
- if (!module) {
1095
- throw new Error("Module Federation shared module '" + str + "' not found. Please ensure it's installed as a dependency in your package.json.");
1096
- }
1097
- return module;
812
+ const patternMap = {};
813
+ const cacheMap = {};
814
+ /**
815
+ * Physically generate files as virtual modules under node_modules/__mf__virtual/*
816
+ */
817
+ function assertModuleFound(tag, str = "") {
818
+ const module = VirtualModule.findModule(tag, str);
819
+ if (!module) throw new Error(`Module Federation shared module '${str}' not found. Please ensure it's installed as a dependency in your package.json.`);
820
+ return module;
1098
821
  }
1099
- var VirtualModule = /*#__PURE__*/function () {
1100
- function VirtualModule(name, tag, suffix) {
1101
- if (tag === void 0) {
1102
- tag = '__mf_v__';
1103
- }
1104
- if (suffix === void 0) {
1105
- suffix = '';
1106
- }
1107
- this.name = void 0;
1108
- this.tag = void 0;
1109
- this.suffix = void 0;
1110
- this.inited = false;
1111
- this.name = name;
1112
- this.tag = tag;
1113
- this.suffix = suffix || getSuffix(name);
1114
- if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
1115
- cacheMap[this.tag][this.name] = this;
1116
- }
1117
- /**
1118
- * Set the root path for finding node_modules
1119
- * @param root - Root path
1120
- */
1121
- VirtualModule.setRoot = function setRoot(root) {
1122
- rootDir = root;
1123
- // Reset cache to ensure using the new root path
1124
- cachedNodeModulesDir = undefined;
1125
- }
1126
- /**
1127
- * Ensure virtual package directory exists
1128
- */;
1129
- VirtualModule.ensureVirtualPackageExists = function ensureVirtualPackageExists() {
1130
- var nodeModulesDir = getNodeModulesDir();
1131
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
1132
- virtualModuleDir = _getNormalizeModuleFe.virtualModuleDir;
1133
- var virtualPackagePath = path.resolve(nodeModulesDir, virtualModuleDir);
1134
- if (!fs.existsSync(virtualPackagePath)) {
1135
- fs.mkdirSync(virtualPackagePath);
1136
- fs.writeFileSync(path.resolve(virtualPackagePath, 'empty.js'), '');
1137
- fs.writeFileSync(path.resolve(virtualPackagePath, 'package.json'), JSON.stringify({
1138
- name: virtualModuleDir,
1139
- main: 'empty.js'
1140
- }));
1141
- }
1142
- };
1143
- VirtualModule.findModule = function findModule(tag, str) {
1144
- if (str === void 0) {
1145
- str = '';
1146
- }
1147
- if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
1148
- var moduleName = (str.match(patternMap[tag]) || [])[2];
1149
- if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
1150
- return undefined;
1151
- };
1152
- var _proto = VirtualModule.prototype;
1153
- _proto.getPath = function getPath() {
1154
- return path.resolve(getNodeModulesDir(), this.getImportId());
1155
- };
1156
- _proto.getImportId = function getImportId() {
1157
- var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
1158
- mfName = _getNormalizeModuleFe2.name,
1159
- virtualModuleDir = _getNormalizeModuleFe2.virtualModuleDir;
1160
- return virtualModuleDir + "/" + packageNameEncode("" + mfName + this.tag + this.name + this.tag) + this.suffix;
1161
- };
1162
- _proto.writeSync = function writeSync(code, force) {
1163
- if (!force && this.inited) return;
1164
- if (!this.inited) {
1165
- this.inited = true;
1166
- }
1167
- fs.writeFileSync(this.getPath(), code);
1168
- };
1169
- _proto.write = function write(code) {
1170
- fs.writeFile(this.getPath(), code, function () {});
1171
- };
1172
- return VirtualModule;
1173
- }();
822
+ var VirtualModule = class {
823
+ /**
824
+ * Set the root path for finding node_modules
825
+ * @param root - Root path
826
+ */
827
+ static setRoot(root) {
828
+ rootDir = root;
829
+ cachedNodeModulesDir = void 0;
830
+ }
831
+ /**
832
+ * Ensure virtual package directory exists
833
+ */
834
+ static ensureVirtualPackageExists() {
835
+ const nodeModulesDir = getNodeModulesDir();
836
+ const { virtualModuleDir } = getNormalizeModuleFederationOptions();
837
+ const virtualPackagePath = (0, pathe.resolve)(nodeModulesDir, virtualModuleDir);
838
+ if (!(0, fs.existsSync)(virtualPackagePath)) {
839
+ (0, fs.mkdirSync)(virtualPackagePath);
840
+ (0, fs.writeFileSync)((0, pathe.resolve)(virtualPackagePath, "empty.js"), "");
841
+ (0, fs.writeFileSync)((0, pathe.resolve)(virtualPackagePath, "package.json"), JSON.stringify({
842
+ name: virtualModuleDir,
843
+ main: "empty.js"
844
+ }));
845
+ }
846
+ }
847
+ static findModule(tag, str = "") {
848
+ if (!patternMap[tag]) patternMap[tag] = new RegExp(`(.*${packageNameEncode(tag)}(.+?)${packageNameEncode(tag)}.*)`);
849
+ const moduleName = (str.match(patternMap[tag]) || [])[2];
850
+ if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
851
+ }
852
+ constructor(name, tag = "__mf_v__", suffix = "") {
853
+ this.inited = false;
854
+ this.name = name;
855
+ this.tag = tag;
856
+ this.suffix = suffix || getSuffix(name);
857
+ if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
858
+ cacheMap[this.tag][this.name] = this;
859
+ }
860
+ getPath() {
861
+ return (0, pathe.resolve)(getNodeModulesDir(), this.getImportId());
862
+ }
863
+ getImportId() {
864
+ const { name: mfName, virtualModuleDir } = getNormalizeModuleFederationOptions();
865
+ return `${virtualModuleDir}/${packageNameEncode(`${mfName}${this.tag}${this.name}${this.tag}`)}${this.suffix}`;
866
+ }
867
+ writeSync(code, force) {
868
+ if (!force && this.inited) return;
869
+ if (!this.inited) this.inited = true;
870
+ (0, fs.writeFileSync)(this.getPath(), code);
871
+ }
872
+ write(code) {
873
+ (0, fs.writeFile)(this.getPath(), code, function() {});
874
+ }
875
+ };
1174
876
 
1175
- var VIRTUAL_EXPOSES = 'virtual:mf-exposes';
1176
- function generateExposes() {
1177
- var options = getNormalizeModuleFederationOptions();
1178
- return "\n export default {\n " + Object.keys(options.exposes).map(function (key) {
1179
- return "\n " + JSON.stringify(key) + ": async () => {\n const importModule = await import(" + JSON.stringify(options.exposes[key]["import"]) + ")\n const exportModule = {}\n Object.assign(exportModule, importModule)\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return exportModule\n }\n ";
1180
- }).join(',') + "\n }\n ";
877
+ //#endregion
878
+ //#region src/virtualModules/virtualExposes.ts
879
+ function getVirtualExposesId(options) {
880
+ return `virtual:mf-exposes:${`${options.name}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
881
+ }
882
+ function generateExposes(options) {
883
+ return `
884
+ export default {
885
+ ${Object.keys(options.exposes).map((key) => {
886
+ return `
887
+ ${JSON.stringify(key)}: async () => {
888
+ const importModule = await import(${JSON.stringify(options.exposes[key].import)})
889
+ const exportModule = {}
890
+ Object.assign(exportModule, importModule)
891
+ Object.defineProperty(exportModule, "__esModule", {
892
+ value: true,
893
+ enumerable: false
894
+ })
895
+ return exportModule
896
+ }
897
+ `;
898
+ }).join(",")}
899
+ }
900
+ `;
1181
901
  }
1182
902
 
1183
- var virtualRuntimeInitStatus = new VirtualModule('runtimeInit');
1184
- function writeRuntimeInitStatus() {
1185
- // Use globalThis singleton to ensure only one initPromise exists
1186
- var globalKey = "__mf_init__" + virtualRuntimeInitStatus.getImportId() + "__";
1187
- virtualRuntimeInitStatus.writeSync("\n const globalKey = " + JSON.stringify(globalKey) + "\n if (!globalThis[globalKey]) {\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n globalThis[globalKey] = {\n initPromise,\n initResolve,\n initReject\n }\n }\n module.exports = globalThis[globalKey]\n ");
903
+ //#endregion
904
+ //#region src/virtualModules/virtualRuntimeInitStatus.ts
905
+ const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
906
+ function writeRuntimeInitStatus(command) {
907
+ const globalKey = `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
908
+ const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject } = globalThis[globalKey];
909
+ export { initPromise, initResolve, initReject };` : `module.exports = globalThis[globalKey];`;
910
+ virtualRuntimeInitStatus.writeSync(`
911
+ const globalKey = ${JSON.stringify(globalKey)};
912
+ if (!globalThis[globalKey]) {
913
+ let initResolve, initReject;
914
+ const initPromise = new Promise((re, rj) => {
915
+ initResolve = re;
916
+ initReject = rj;
917
+ });
918
+ globalThis[globalKey] = {
919
+ initPromise,
920
+ initResolve,
921
+ initReject,
922
+ };
923
+ }
924
+ ${exportStatement}
925
+ `);
1188
926
  }
1189
927
 
1190
- var cacheRemoteMap = {};
1191
- var LOAD_REMOTE_TAG = '__loadRemote__';
1192
- function getRemoteVirtualModule(remote, command) {
1193
- if (!cacheRemoteMap[remote]) {
1194
- cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
1195
- cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
1196
- }
1197
- var virtual = cacheRemoteMap[remote];
1198
- return virtual;
928
+ //#endregion
929
+ //#region src/virtualModules/virtualRemotes.ts
930
+ const cacheRemoteMap = {};
931
+ const LOAD_REMOTE_TAG = "__loadRemote__";
932
+ function getRemoteVirtualModule(remote, command, isRolldown) {
933
+ if (!cacheRemoteMap[remote]) {
934
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, isRolldown ? ".mjs" : ".js");
935
+ cacheRemoteMap[remote].writeSync(generateRemotes(remote, command, isRolldown));
936
+ }
937
+ return cacheRemoteMap[remote];
1199
938
  }
1200
- var usedRemotesMap = {
1201
- // remote1: {remote1/App, remote1, remote1/Button}
1202
- };
939
+ const usedRemotesMap = {};
1203
940
  function addUsedRemote(remoteKey, remoteModule) {
1204
- if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
1205
- usedRemotesMap[remoteKey].add(remoteModule);
941
+ if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = /* @__PURE__ */ new Set();
942
+ usedRemotesMap[remoteKey].add(remoteModule);
1206
943
  }
1207
944
  function getUsedRemotesMap() {
1208
- return usedRemotesMap;
945
+ return usedRemotesMap;
1209
946
  }
1210
- function generateRemotes(id, command) {
1211
- return "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
947
+ function generateRemotes(id, command, isRolldown) {
948
+ const useESM = command === "build" || isRolldown;
949
+ const importLine = useESM ? `import { initPromise } from "${virtualRuntimeInitStatus.getImportId()}"` : `const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")`;
950
+ const awaitOrPlaceholder = useESM ? "await " : "/*mf top-level-await placeholder replacement mf*/";
951
+ const exportLine = command === "serve" && useESM ? "export default exportModule.default ?? exportModule" : useESM ? "export default exportModule" : "module.exports = exportModule";
952
+ return `
953
+ ${importLine}
954
+ const res = initPromise.then(runtime => runtime.loadRemote(${JSON.stringify(id)}))
955
+ const exportModule = ${awaitOrPlaceholder}initPromise.then(_ => res)
956
+ ${exportLine}
957
+ `;
1212
958
  }
1213
959
 
1214
- /**
1215
- * Even the resolveId hook cannot interfere with vite pre-build,
1216
- * and adding query parameter virtual modules will also fail.
1217
- * You can only proxy to the real file through alias
1218
- */
1219
- // *** __prebuild__
1220
- var preBuildCacheMap = {};
1221
- var PREBUILD_TAG = '__prebuild__';
960
+ //#endregion
961
+ //#region src/virtualModules/virtualShared_preBuild.ts
962
+ /**
963
+ * Even the resolveId hook cannot interfere with vite pre-build,
964
+ * and adding query parameter virtual modules will also fail.
965
+ * You can only proxy to the real file through alias
966
+ */
967
+ /**
968
+ * shared will be proxied:
969
+ * 1. __prebuild__: export shareModule (pre-built source code of modules such as vue, react, etc.)
970
+ * 2. __loadShare__: load shareModule (mfRuntime.loadShare('vue'))
971
+ */
972
+ function getPackageNamedExports(pkg) {
973
+ try {
974
+ const mod = (0, module$1.createRequire)(new URL("file://" + process.cwd() + "/package.json"))(pkg);
975
+ return Object.keys(mod).filter((k) => k !== "default" && k !== "__esModule");
976
+ } catch {
977
+ return [];
978
+ }
979
+ }
980
+ const preBuildCacheMap = {};
981
+ const PREBUILD_TAG = "__prebuild__";
1222
982
  function writePreBuildLibPath(pkg) {
1223
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1224
- preBuildCacheMap[pkg].writeSync('');
983
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
984
+ preBuildCacheMap[pkg].writeSync("");
1225
985
  }
1226
986
  function getPreBuildLibImportId(pkg) {
1227
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1228
- var importId = preBuildCacheMap[pkg].getImportId();
1229
- return importId;
987
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
988
+ return preBuildCacheMap[pkg].getImportId();
1230
989
  }
1231
- // *** __loadShare__
1232
- var LOAD_SHARE_TAG = '__loadShare__';
1233
- var loadShareCacheMap = {};
1234
- function getLoadShareModulePath(pkg) {
1235
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, '.js');
1236
- var filepath = loadShareCacheMap[pkg].getPath();
1237
- return filepath;
990
+ const LOAD_SHARE_TAG = "__loadShare__";
991
+ const loadShareCacheMap = {};
992
+ function getLoadShareModulePath(pkg, isRolldown, command) {
993
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, isRolldown || command === "build" ? ".mjs" : ".js");
994
+ return loadShareCacheMap[pkg].getPath();
1238
995
  }
1239
- function writeLoadShareModule(pkg, shareItem, command) {
1240
- loadShareCacheMap[pkg].writeSync("\n ;() => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== 'build' ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}\n }))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "res.then(factory => factory())\n module.exports = exportModule\n ");
996
+ function writeLoadShareModule(pkg, shareItem, command, isRolldown) {
997
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, isRolldown || command === "build" ? ".mjs" : ".js");
998
+ const useESM = command === "build" || isRolldown;
999
+ const importLine = useESM ? `import { initPromise } from "${virtualRuntimeInitStatus.getImportId()}"` : `const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")`;
1000
+ const awaitOrPlaceholder = useESM ? "await " : "/*mf top-level-await placeholder replacement mf*/";
1001
+ const namedExports = getPackageNamedExports(pkg);
1002
+ let exportLine;
1003
+ if (namedExports.length > 0) {
1004
+ const destructure = `const { ${namedExports.join(", ")} } = exportModule;`;
1005
+ const namedExportLine = `export { ${namedExports.join(", ")} };`;
1006
+ exportLine = useESM ? `export default exportModule;\n ${destructure}\n ${namedExportLine}` : `module.exports = exportModule;\n ${destructure}\n Object.assign(module.exports, { ${namedExports.join(", ")} });`;
1007
+ } else exportLine = useESM ? `export default exportModule\n export * from ${JSON.stringify(getPreBuildLibImportId(pkg))}` : "module.exports = exportModule";
1008
+ loadShareCacheMap[pkg].writeSync(`
1009
+ import ${JSON.stringify(getPreBuildLibImportId(pkg))};
1010
+ ${command !== "build" ? `;() => import(${JSON.stringify(pkg)}).catch(() => {});` : ""}
1011
+ ${importLine}
1012
+ const res = initPromise.then(runtime => runtime.loadShare(${JSON.stringify(pkg)}, {
1013
+ customShareInfo: {shareConfig:{
1014
+ singleton: ${shareItem.shareConfig.singleton},
1015
+ strictVersion: ${shareItem.shareConfig.strictVersion},
1016
+ requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)}
1017
+ }}
1018
+ }))
1019
+ const exportModule = ${awaitOrPlaceholder}res.then((factory) => (typeof factory === "function" ? factory() : factory))
1020
+ ${exportLine}
1021
+ `);
1241
1022
  }
1242
1023
 
1243
- var usedShares = new Set();
1024
+ //#endregion
1025
+ //#region src/virtualModules/virtualRemoteEntry.ts
1026
+ let usedShares = /* @__PURE__ */ new Set();
1244
1027
  function getUsedShares() {
1245
- return usedShares;
1028
+ return usedShares;
1246
1029
  }
1247
1030
  function addUsedShares(pkg) {
1248
- usedShares.add(pkg);
1031
+ usedShares.add(pkg);
1249
1032
  }
1250
- // *** Expose locally provided shared modules here
1251
- new VirtualModule('localSharedImportMap');
1033
+ new VirtualModule("localSharedImportMap");
1252
1034
  function getLocalSharedImportMapPath() {
1253
- return getLocalSharedImportMapPath_temp();
1254
- // return localSharedImportMapModule.getPath()
1035
+ return getLocalSharedImportMapPath_temp();
1255
1036
  }
1256
- var prevSharedCount;
1037
+ let prevSharedCount;
1257
1038
  function writeLocalSharedImportMap() {
1258
- var sharedCount = getUsedShares().size;
1259
- if (prevSharedCount !== sharedCount) {
1260
- prevSharedCount = sharedCount;
1261
- writeLocalSharedImportMap_temp(generateLocalSharedImportMap());
1262
- // localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true)
1263
- }
1039
+ const sharedCount = getUsedShares().size;
1040
+ if (prevSharedCount !== sharedCount) {
1041
+ prevSharedCount = sharedCount;
1042
+ writeLocalSharedImportMap_temp(generateLocalSharedImportMap());
1043
+ }
1264
1044
  }
1265
1045
  function generateLocalSharedImportMap() {
1266
- var options = getNormalizeModuleFederationOptions();
1267
- return "\n import {loadShare} from \"@module-federation/runtime\";\n const importMap = {\n " + Array.from(getUsedShares()).sort().map(function (pkg) {
1268
- var shareItem = getNormalizeShareItem(pkg);
1269
- return "\n " + JSON.stringify(pkg) + ": async () => {\n " + ((shareItem == null ? void 0 : shareItem.shareConfig["import"]) === false ? "throw new Error(`Shared module '${" + JSON.stringify(pkg) + "}' must be provided by host`);" : "let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\");\n return pkg;") + "\n }\n ";
1270
- }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).sort().map(function (key) {
1271
- var shareItem = getNormalizeShareItem(key);
1272
- if (!shareItem) return null;
1273
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n if (" + (shareItem.shareConfig["import"] === false) + ") {\n throw new Error(`Shared module '${" + JSON.stringify(key) + "}' must be provided by host`);\n }\n usedShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = importMap\n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + ",\n " + (shareItem.shareConfig["import"] === false ? 'import: false,' : '') + "\n }\n }\n ";
1274
- }).filter(function (x) {
1275
- return x !== null;
1276
- }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
1277
- var _JSON$stringify;
1278
- var remote = options.remotes[key];
1279
- if (!remote) return null;
1280
- return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n shareScope: " + ((_JSON$stringify = JSON.stringify(remote.shareScope)) != null ? _JSON$stringify : 'default') + ",\n }\n ";
1281
- }).filter(function (x) {
1282
- return x !== null;
1283
- }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
1046
+ const options = getNormalizeModuleFederationOptions();
1047
+ return `
1048
+ import {loadShare} from "@module-federation/runtime";
1049
+ const importMap = {
1050
+ ${Array.from(getUsedShares()).sort().map((pkg) => {
1051
+ const shareItem = getNormalizeShareItem(pkg);
1052
+ return `
1053
+ ${JSON.stringify(pkg)}: async () => {
1054
+ ${shareItem?.shareConfig.import === false ? `throw new Error(\`Shared module '\${${JSON.stringify(pkg)}}' must be provided by host\`);` : `let pkg = await import("${getPreBuildLibImportId(pkg)}");
1055
+ return pkg;`}
1056
+ }
1057
+ `;
1058
+ }).join(",")}
1059
+ }
1060
+ const usedShared = {
1061
+ ${Array.from(getUsedShares()).sort().map((key) => {
1062
+ const shareItem = getNormalizeShareItem(key);
1063
+ if (!shareItem) return null;
1064
+ return `
1065
+ ${JSON.stringify(key)}: {
1066
+ name: ${JSON.stringify(key)},
1067
+ version: ${JSON.stringify(shareItem.version)},
1068
+ scope: [${JSON.stringify(shareItem.scope)}],
1069
+ loaded: false,
1070
+ from: ${JSON.stringify(options.name)},
1071
+ async get () {
1072
+ if (${shareItem.shareConfig.import === false}) {
1073
+ throw new Error(\`Shared module '\${${JSON.stringify(key)}}' must be provided by host\`);
1074
+ }
1075
+ usedShared[${JSON.stringify(key)}].loaded = true
1076
+ const {${JSON.stringify(key)}: pkgDynamicImport} = importMap
1077
+ const res = await pkgDynamicImport()
1078
+ const exportModule = {...res}
1079
+ // All npm packages pre-built by vite will be converted to esm
1080
+ Object.defineProperty(exportModule, "__esModule", {
1081
+ value: true,
1082
+ enumerable: false
1083
+ })
1084
+ return function () {
1085
+ return exportModule
1086
+ }
1087
+ },
1088
+ shareConfig: {
1089
+ singleton: ${shareItem.shareConfig.singleton},
1090
+ requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)},
1091
+ ${shareItem.shareConfig.import === false ? "import: false," : ""}
1092
+ }
1093
+ }
1094
+ `;
1095
+ }).filter((x) => x !== null).join(",")}
1096
+ }
1097
+ const usedRemotes = [${Object.keys(getUsedRemotesMap()).map((key) => {
1098
+ const remote = options.remotes[key];
1099
+ if (!remote) return null;
1100
+ return `
1101
+ {
1102
+ entryGlobalName: ${JSON.stringify(remote.entryGlobalName)},
1103
+ name: ${JSON.stringify(remote.name)},
1104
+ type: ${JSON.stringify(remote.type)},
1105
+ entry: ${JSON.stringify(remote.entry)},
1106
+ shareScope: ${JSON.stringify(remote.shareScope) ?? "default"},
1107
+ }
1108
+ `;
1109
+ }).filter((x) => x !== null).join(",")}
1110
+ ]
1111
+ export {
1112
+ usedShared,
1113
+ usedRemotes
1114
+ }
1115
+ `;
1116
+ }
1117
+ const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
1118
+ function getRemoteEntryId(options) {
1119
+ return `${REMOTE_ENTRY_ID}:${`${options.name}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
1284
1120
  }
1285
- var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
1286
- function generateRemoteEntry(options) {
1287
- var pluginImportNames = options.runtimePlugins.map(function (p, i) {
1288
- if (typeof p === 'string') {
1289
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
1290
- } else {
1291
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
1121
+ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options)) {
1122
+ const pluginImportNames = options.runtimePlugins.map((p, i) => {
1123
+ if (typeof p === "string") return [
1124
+ `$runtimePlugin_${i}`,
1125
+ `import $runtimePlugin_${i} from "${p}";`,
1126
+ `undefined`
1127
+ ];
1128
+ else return [
1129
+ `$runtimePlugin_${i}`,
1130
+ `import $runtimePlugin_${i} from "${p[0]}";`,
1131
+ serializeRuntimeOptions(p[1])
1132
+ ];
1133
+ });
1134
+ return `
1135
+ import {init as runtimeInit, loadRemote} from "@module-federation/runtime";
1136
+ ${pluginImportNames.map((item) => item[1]).join("\n")}
1137
+ import exposesMap from "${virtualExposesId}"
1138
+ import {usedShared, usedRemotes} from "${getLocalSharedImportMapPath()}"
1139
+ import {
1140
+ initResolve
1141
+ } from "${virtualRuntimeInitStatus.getImportId()}"
1142
+ const initTokens = {}
1143
+ const shareScopeName = ${JSON.stringify(options.shareScope)}
1144
+ const mfName = ${JSON.stringify(options.name)}
1145
+ async function init(shared = {}, initScope = []) {
1146
+ const initRes = runtimeInit({
1147
+ name: mfName,
1148
+ remotes: usedRemotes,
1149
+ shared: usedShared,
1150
+ plugins: [${pluginImportNames.map((item) => `${item[0]}(${item[2]})`).join(", ")}],
1151
+ ${options.shareStrategy ? `shareStrategy: '${options.shareStrategy}'` : ""}
1152
+ });
1153
+ // handling circular init calls
1154
+ var initToken = initTokens[shareScopeName];
1155
+ if (!initToken)
1156
+ initToken = initTokens[shareScopeName] = { from: mfName };
1157
+ if (initScope.indexOf(initToken) >= 0) return;
1158
+ initScope.push(initToken);
1159
+ initRes.initShareScopeMap('${options.shareScope}', shared);
1160
+ try {
1161
+ await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1162
+ strategy: '${options.shareStrategy}',
1163
+ from: "build",
1164
+ initScope
1165
+ }));
1166
+ } catch (e) {
1167
+ console.error(e)
1292
1168
  }
1293
- });
1294
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
1295
- return item[1];
1296
- }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n const initTokens = {}\n const shareScopeName = " + JSON.stringify(options.shareScope) + "\n const mfName = " + JSON.stringify(options.name) + "\n async function init(shared = {}, initScope = []) {\n const initRes = runtimeInit({\n name: mfName,\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
1297
- return item[0] + "(" + item[2] + ")";
1298
- }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: '" + options.shareStrategy + "'" : '') + "\n });\n // handling circular init calls\n var initToken = initTokens[shareScopeName];\n if (!initToken)\n initToken = initTokens[shareScopeName] = { from: mfName };\n if (initScope.indexOf(initToken) >= 0) return;\n initScope.push(initToken);\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n try {\n await Promise.all(await initRes.initializeSharing('" + options.shareScope + "', {\n strategy: '" + options.shareStrategy + "',\n from: \"build\",\n initScope\n }));\n } catch (e) {\n console.error(e)\n }\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
1169
+ initResolve(initRes)
1170
+ return initRes
1171
+ }
1172
+
1173
+ function getExposes(moduleName) {
1174
+ if (!(moduleName in exposesMap)) throw new Error(\`Module \${moduleName} does not exist in container.\`)
1175
+ return (exposesMap[moduleName])().then(res => () => res)
1176
+ }
1177
+ export {
1178
+ init,
1179
+ getExposes as get
1180
+ }
1181
+ `;
1299
1182
  }
1300
- /**
1301
- * Inject entry file, automatically init when used as host,
1302
- * and will not inject remoteEntry
1303
- */
1304
- var HOST_AUTO_INIT_TAG = '__H_A_I__';
1305
- var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
1306
- function writeHostAutoInit() {
1307
- hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1183
+ /**
1184
+ * Inject entry file, automatically init when used as host,
1185
+ * and will not inject remoteEntry
1186
+ */
1187
+ const HOST_AUTO_INIT_TAG = "__H_A_I__";
1188
+ const hostAutoInitModule = new VirtualModule("hostAutoInit", HOST_AUTO_INIT_TAG);
1189
+ function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID) {
1190
+ hostAutoInitModule.writeSync(`
1191
+ const remoteEntryPromise = import("${remoteEntryId}")
1192
+ // __tla only serves as a hack for vite-plugin-top-level-await.
1193
+ Promise.resolve(remoteEntryPromise)
1194
+ .then(remoteEntry => {
1195
+ return Promise.resolve(remoteEntry.__tla)
1196
+ .then(remoteEntry.init).catch(remoteEntry.init)
1197
+ })
1198
+ `);
1308
1199
  }
1309
1200
  function getHostAutoInitImportId() {
1310
- return hostAutoInitModule.getImportId();
1201
+ return hostAutoInitModule.getImportId();
1311
1202
  }
1312
1203
  function getHostAutoInitPath() {
1313
- return hostAutoInitModule.getPath();
1204
+ return hostAutoInitModule.getPath();
1314
1205
  }
1315
1206
 
1316
- function initVirtualModules() {
1317
- writeLocalSharedImportMap();
1318
- writeHostAutoInit();
1319
- writeRuntimeInitStatus();
1207
+ //#endregion
1208
+ //#region src/virtualModules/index.ts
1209
+ function initVirtualModules(command, remoteEntryId) {
1210
+ writeLocalSharedImportMap();
1211
+ writeHostAutoInit(remoteEntryId);
1212
+ writeRuntimeInitStatus(command);
1320
1213
  }
1321
1214
 
1215
+ //#endregion
1216
+ //#region src/utils/bundleHelpers.ts
1322
1217
  function findRemoteEntryFile(filename, bundle) {
1323
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1324
- var _Object$entries$_i = _Object$entries[_i],
1325
- fileData = _Object$entries$_i[1];
1326
- if (filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1327
- return fileData.fileName; // We can return early since we only need to find remoteEntry once
1328
- }
1329
- }
1218
+ for (const [_, fileData] of Object.entries(bundle)) if (filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "") === fileData.name || fileData.name === "remoteEntry") return fileData.fileName;
1330
1219
  }
1331
1220
 
1332
- var ASSET_TYPES = ['js', 'css'];
1333
- var LOAD_TIMINGS = ['sync', 'async'];
1334
- var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
1335
- /**
1336
- * Creates an empty asset map structure for tracking JS and CSS assets
1337
- * @returns Initialized asset map with sync/async arrays for JS and CSS
1338
- */
1339
- var createEmptyAssetMap = function createEmptyAssetMap() {
1340
- return {
1341
- js: {
1342
- sync: [],
1343
- async: []
1344
- },
1345
- css: {
1346
- sync: [],
1347
- async: []
1348
- }
1349
- };
1221
+ //#endregion
1222
+ //#region src/utils/cssModuleHelpers.ts
1223
+ const ASSET_TYPES = ["js", "css"];
1224
+ const LOAD_TIMINGS = ["sync", "async"];
1225
+ const JS_EXTENSIONS = [
1226
+ ".ts",
1227
+ ".tsx",
1228
+ ".jsx",
1229
+ ".mjs",
1230
+ ".cjs"
1231
+ ];
1232
+ /**
1233
+ * Creates an empty asset map structure for tracking JS and CSS assets
1234
+ * @returns Initialized asset map with sync/async arrays for JS and CSS
1235
+ */
1236
+ const createEmptyAssetMap = () => ({
1237
+ js: {
1238
+ sync: [],
1239
+ async: []
1240
+ },
1241
+ css: {
1242
+ sync: [],
1243
+ async: []
1244
+ }
1245
+ });
1246
+ /**
1247
+ * Tracks an asset in the preload map with deduplication
1248
+ * @param map - The preload map to update
1249
+ * @param key - The module key to track under
1250
+ * @param fileName - The asset filename to track
1251
+ * @param isAsync - Whether the asset is loaded async
1252
+ * @param type - The asset type ('js' or 'css')
1253
+ */
1254
+ const trackAsset = (map, key, fileName, isAsync, type) => {
1255
+ if (!map[key]) map[key] = createEmptyAssetMap();
1256
+ const target = isAsync ? map[key][type].async : map[key][type].sync;
1257
+ if (!target.includes(fileName)) target.push(fileName);
1350
1258
  };
1351
- /**
1352
- * Tracks an asset in the preload map with deduplication
1353
- * @param map - The preload map to update
1354
- * @param key - The module key to track under
1355
- * @param fileName - The asset filename to track
1356
- * @param isAsync - Whether the asset is loaded async
1357
- * @param type - The asset type ('js' or 'css')
1358
- */
1359
- var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
1360
- if (!map[key]) {
1361
- map[key] = createEmptyAssetMap();
1362
- }
1363
- var target = isAsync ? map[key][type].async : map[key][type].sync;
1364
- if (!target.includes(fileName)) {
1365
- target.push(fileName);
1366
- }
1259
+ /**
1260
+ * Checks if a file is a CSS file by extension
1261
+ * @param fileName - The filename to check
1262
+ * @returns True if file has a CSS extension (.css, .scss, .less)
1263
+ */
1264
+ const isCSSFile = (fileName) => {
1265
+ return fileName.endsWith(".css") || fileName.endsWith(".scss") || fileName.endsWith(".less");
1367
1266
  };
1368
- /**
1369
- * Checks if a file is a CSS file by extension
1370
- * @param fileName - The filename to check
1371
- * @returns True if file has a CSS extension (.css, .scss, .less)
1372
- */
1373
- var isCSSFile = function isCSSFile(fileName) {
1374
- return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
1267
+ /**
1268
+ * Collects all CSS assets from the bundle
1269
+ * @param bundle - The Rollup output bundle
1270
+ * @returns Set of CSS asset filenames
1271
+ */
1272
+ const collectCssAssets = (bundle) => {
1273
+ const cssAssets = /* @__PURE__ */ new Set();
1274
+ for (const [fileName, fileData] of Object.entries(bundle)) if (fileData.type === "asset" && isCSSFile(fileName)) cssAssets.add(fileName);
1275
+ return cssAssets;
1375
1276
  };
1376
- /**
1377
- * Collects all CSS assets from the bundle
1378
- * @param bundle - The Rollup output bundle
1379
- * @returns Set of CSS asset filenames
1380
- */
1381
- var collectCssAssets = function collectCssAssets(bundle) {
1382
- var cssAssets = new Set();
1383
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1384
- var _Object$entries$_i = _Object$entries[_i],
1385
- fileName = _Object$entries$_i[0],
1386
- fileData = _Object$entries$_i[1];
1387
- if (fileData.type === 'asset' && isCSSFile(fileName)) {
1388
- cssAssets.add(fileName);
1389
- }
1390
- }
1391
- return cssAssets;
1277
+ /**
1278
+ * Checks if a chunk contains CSS modules (e.g. .css, .vanilla.css, .scss, .less)
1279
+ * by scanning its module list
1280
+ */
1281
+ const chunkContainsCssModules = (modules) => {
1282
+ for (const modulePath of Object.keys(modules)) if (isCSSFile(modulePath)) return true;
1283
+ return false;
1392
1284
  };
1393
- /**
1394
- * Processes module assets and tracks them in the files map
1395
- * @param bundle - The Rollup output bundle
1396
- * @param filesMap - The preload map to populate
1397
- * @param moduleMatcher - Function that matches module paths to keys
1398
- */
1399
- var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1400
- for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1401
- var _Object$entries2$_i = _Object$entries2[_i2],
1402
- fileName = _Object$entries2$_i[0],
1403
- fileData = _Object$entries2$_i[1];
1404
- if (fileData.type !== 'chunk') continue;
1405
- if (!fileData.modules) continue;
1406
- for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1407
- var modulePath = _Object$keys[_i3];
1408
- var matchKey = moduleMatcher(modulePath);
1409
- if (!matchKey) continue;
1410
- // Track main JS chunk
1411
- trackAsset(filesMap, matchKey, fileName, false, 'js');
1412
- // Handle dynamic imports
1413
- if (fileData.dynamicImports) {
1414
- for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1415
- var dynamicImport = _step.value;
1416
- var importData = bundle[dynamicImport];
1417
- if (!importData) continue;
1418
- var isCss = isCSSFile(dynamicImport);
1419
- trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1420
- }
1421
- }
1422
- }
1423
- }
1285
+ /**
1286
+ * Processes module assets and tracks them in the files map
1287
+ * @param bundle - The Rollup output bundle
1288
+ * @param filesMap - The preload map to populate
1289
+ * @param moduleMatcher - Function that matches module paths to keys
1290
+ */
1291
+ const processModuleAssets = (bundle, filesMap, moduleMatcher) => {
1292
+ const bundleCssAssets = collectCssAssets(bundle);
1293
+ for (const [fileName, fileData] of Object.entries(bundle)) {
1294
+ if (fileData.type !== "chunk") continue;
1295
+ if (!fileData.modules) continue;
1296
+ for (const modulePath of Object.keys(fileData.modules)) {
1297
+ const matchKey = moduleMatcher(modulePath);
1298
+ if (!matchKey) continue;
1299
+ trackAsset(filesMap, matchKey, fileName, false, "js");
1300
+ let foundCssViaMetadata = false;
1301
+ if (fileData.viteMetadata?.importedCss?.size) for (const cssFile of fileData.viteMetadata.importedCss) {
1302
+ trackAsset(filesMap, matchKey, cssFile, false, "css");
1303
+ foundCssViaMetadata = true;
1304
+ }
1305
+ if (!foundCssViaMetadata && chunkContainsCssModules(fileData.modules)) for (const cssAsset of bundleCssAssets) trackAsset(filesMap, matchKey, cssAsset, false, "css");
1306
+ if (fileData.dynamicImports) for (const dynamicImport of fileData.dynamicImports) {
1307
+ if (!bundle[dynamicImport]) continue;
1308
+ trackAsset(filesMap, matchKey, dynamicImport, true, isCSSFile(dynamicImport) ? "css" : "js");
1309
+ }
1310
+ }
1311
+ }
1424
1312
  };
1425
- /**
1426
- * Deduplicates assets in the files map
1427
- * @param filesMap - The preload map to deduplicate
1428
- * @returns New deduplicated preload map
1429
- */
1430
- var deduplicateAssets = function deduplicateAssets(filesMap) {
1431
- var result = {};
1432
- for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1433
- var _Object$entries3$_i = _Object$entries3[_i4],
1434
- key = _Object$entries3$_i[0],
1435
- assetMaps = _Object$entries3$_i[1];
1436
- result[key] = createEmptyAssetMap();
1437
- for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1438
- var type = _ASSET_TYPES[_i5];
1439
- for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1440
- var timing = _LOAD_TIMINGS[_i6];
1441
- result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1442
- }
1443
- }
1444
- }
1445
- return result;
1313
+ /**
1314
+ * Deduplicates assets in the files map
1315
+ * @param filesMap - The preload map to deduplicate
1316
+ * @returns New deduplicated preload map
1317
+ */
1318
+ const deduplicateAssets = (filesMap) => {
1319
+ const result = {};
1320
+ for (const [key, assetMaps] of Object.entries(filesMap)) {
1321
+ result[key] = createEmptyAssetMap();
1322
+ for (const type of ASSET_TYPES) for (const timing of LOAD_TIMINGS) result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1323
+ }
1324
+ return result;
1446
1325
  };
1447
- /**
1448
- * Builds a mapping between module files and their share keys
1449
- * @param shareKeys - Set of share keys to map
1450
- * @param resolveFn - Function to resolve module paths
1451
- * @returns Map of file paths to their corresponding share keys
1452
- */
1453
- var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1454
- try {
1455
- var fileToShareKey = new Map();
1456
- return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1457
- return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1458
- var _resolution$id;
1459
- return {
1460
- shareKey: shareKey,
1461
- file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1462
- };
1463
- })["catch"](function () {
1464
- return null;
1465
- });
1466
- }))).then(function (resolutions) {
1467
- for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1468
- var resolution = _step2.value;
1469
- if (resolution != null && resolution.file) {
1470
- fileToShareKey.set(resolution.file, resolution.shareKey);
1471
- }
1472
- }
1473
- return fileToShareKey;
1474
- });
1475
- } catch (e) {
1476
- return Promise.reject(e);
1477
- }
1326
+ /**
1327
+ * Builds a mapping between module files and their share keys
1328
+ * @param shareKeys - Set of share keys to map
1329
+ * @param resolveFn - Function to resolve module paths
1330
+ * @returns Map of file paths to their corresponding share keys
1331
+ */
1332
+ const buildFileToShareKeyMap = async (shareKeys, resolveFn) => {
1333
+ const fileToShareKey = /* @__PURE__ */ new Map();
1334
+ const resolutions = await Promise.all(Array.from(shareKeys).map((shareKey) => resolveFn(getPreBuildLibImportId(shareKey)).then((resolution) => ({
1335
+ shareKey,
1336
+ file: resolution?.id?.split("?")[0]
1337
+ })).catch(() => null)));
1338
+ for (const resolution of resolutions) if (resolution?.file) fileToShareKey.set(resolution.file, resolution.shareKey);
1339
+ return fileToShareKey;
1478
1340
  };
1479
1341
 
1480
- /**
1481
- * Resolves the public path for remote entries
1482
- * @param options - Module Federation options
1483
- * @param viteBase - Vite's base config value
1484
- * @param originalBase - Original base config before any transformations
1485
- * @returns The resolved public path
1486
- */
1342
+ //#endregion
1343
+ //#region src/utils/publicPath.ts
1344
+ /**
1345
+ * Resolves the public path for remote entries
1346
+ * @param options - Module Federation options
1347
+ * @param viteBase - Vite's base config value
1348
+ * @param originalBase - Original base config before any transformations
1349
+ * @returns The resolved public path
1350
+ */
1487
1351
  function resolvePublicPath(options, viteBase, originalBase) {
1488
- // Use explicitly set publicPath if provided
1489
- if (options.publicPath) {
1490
- return options.publicPath;
1491
- }
1492
- // Handle empty original base case
1493
- if (originalBase === '') {
1494
- return 'auto';
1495
- }
1496
- // Use viteBase if available, ensuring it ends with a slash
1497
- if (viteBase) {
1498
- return viteBase.replace(/\/?$/, '/');
1499
- }
1500
- // Fallback to auto if no base is specified
1501
- return 'auto';
1352
+ if (options.publicPath) return options.publicPath;
1353
+ if (originalBase === "") return "auto";
1354
+ if (viteBase) return viteBase.replace(/\/?$/, "/");
1355
+ return "auto";
1502
1356
  }
1503
1357
 
1504
- var Manifest = function Manifest() {
1505
- var mfOptions = getNormalizeModuleFederationOptions();
1506
- var name = mfOptions.name,
1507
- filename = mfOptions.filename,
1508
- getPublicPath = mfOptions.getPublicPath,
1509
- manifestOptions = mfOptions.manifest,
1510
- varFilename = mfOptions.varFilename;
1511
- var mfManifestName = '';
1512
- if (manifestOptions === true) {
1513
- mfManifestName = 'mf-manifest.json';
1514
- }
1515
- if (typeof manifestOptions !== 'boolean') {
1516
- mfManifestName = path__namespace.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1517
- }
1518
- var root;
1519
- var remoteEntryFile;
1520
- var publicPath;
1521
- var _command;
1522
- var _originalConfigBase;
1523
- var viteConfig;
1524
- /**
1525
- * Adds global CSS assets to all module exports
1526
- * @param filesMap - The preload map to update
1527
- * @param cssAssets - Set of CSS asset filenames to add
1528
- */
1529
- var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1530
- Object.keys(filesMap).forEach(function (key) {
1531
- cssAssets.forEach(function (cssAsset) {
1532
- trackAsset(filesMap, key, cssAsset, false, 'css');
1533
- });
1534
- });
1535
- };
1536
- return [{
1537
- name: 'module-federation-manifest',
1538
- apply: 'serve',
1539
- /**
1540
- * Stores resolved Vite config for later use
1541
- */
1542
- /**
1543
- * Finalizes configuration after all plugins are resolved
1544
- * @param config - Fully resolved Vite config
1545
- */
1546
- configResolved: function configResolved(config) {
1547
- viteConfig = config;
1548
- },
1549
- /**
1550
- * Configures dev server middleware to handle manifest requests
1551
- * @param server - Vite dev server instance
1552
- */
1553
- configureServer: function configureServer(server) {
1554
- server.middlewares.use(function (req, res, next) {
1555
- var _req$url;
1556
- if (!mfManifestName) {
1557
- next();
1558
- return;
1559
- }
1560
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1561
- res.setHeader('Content-Type', 'application/json');
1562
- res.setHeader('Access-Control-Allow-Origin', '*');
1563
- res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1564
- id: name,
1565
- name: name,
1566
- metaData: {
1567
- name: name,
1568
- type: 'app',
1569
- buildInfo: {
1570
- buildVersion: '1.0.0',
1571
- buildName: name
1572
- },
1573
- remoteEntry: {
1574
- name: filename,
1575
- path: '',
1576
- type: 'module'
1577
- },
1578
- ssrRemoteEntry: {
1579
- name: filename,
1580
- path: '',
1581
- type: 'module'
1582
- },
1583
- varRemoteEntry: varFilename ? {
1584
- name: varFilename,
1585
- path: '',
1586
- type: 'var'
1587
- } : undefined,
1588
- types: {
1589
- path: '',
1590
- name: ''
1591
- },
1592
- globalName: name,
1593
- pluginVersion: '0.2.5',
1594
- publicPath: publicPath
1595
- }
1596
- })));
1597
- } else {
1598
- next();
1599
- }
1600
- });
1601
- }
1602
- }, {
1603
- name: 'module-federation-manifest',
1604
- enforce: 'post',
1605
- /**
1606
- * Initial plugin configuration
1607
- * @param config - Vite config object
1608
- * @param command - Current Vite command (serve/build)
1609
- */
1610
- config: function config(_config, _ref) {
1611
- var command = _ref.command;
1612
- if (!_config.build) _config.build = {};
1613
- if (!_config.build.manifest) {
1614
- _config.build.manifest = _config.build.manifest || !!manifestOptions;
1615
- }
1616
- _command = command;
1617
- _originalConfigBase = _config.base;
1618
- },
1619
- configResolved: function configResolved(config) {
1620
- root = config.root;
1621
- var base = config.base;
1622
- if (_command === 'serve') {
1623
- base = (config.server.origin || '') + config.base;
1624
- }
1625
- publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1626
- },
1627
- /**
1628
- * Generates the module federation manifest file
1629
- * @param options - Rollup output options
1630
- * @param bundle - Generated bundle assets
1631
- */
1632
- generateBundle: function generateBundle(options, bundle) {
1633
- try {
1634
- var _this = this;
1635
- if (!mfManifestName) return Promise.resolve();
1636
- var filesMap = {};
1637
- var foundRemoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1638
- // First pass: Find remoteEntry file
1639
- if (foundRemoteEntryFile) {
1640
- remoteEntryFile = foundRemoteEntryFile;
1641
- }
1642
- // Second pass: Collect all CSS assets
1643
- var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1644
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1645
- return mfOptions.exposes[item]["import"];
1646
- });
1647
- // Process exposed modules
1648
- processModuleAssets(bundle, filesMap, function (modulePath) {
1649
- var absoluteModulePath = path__namespace.resolve(root, modulePath);
1650
- return exposesModules.find(function (exposeModule) {
1651
- var exposePath = path__namespace.resolve(root, exposeModule);
1652
- // First try exact path match
1653
- if (absoluteModulePath === exposePath) {
1654
- return true;
1655
- }
1656
- // Then try path match without known extensions
1657
- var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1658
- var ext = path__namespace.extname(filePath);
1659
- return JS_EXTENSIONS.includes(ext) ? path__namespace.join(path__namespace.dirname(filePath), path__namespace.basename(filePath, ext)) : filePath;
1660
- };
1661
- var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1662
- var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1663
- return modulePathNoExt === exposePathNoExt;
1664
- });
1665
- });
1666
- // Process shared modules
1667
- return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1668
- processModuleAssets(bundle, filesMap, function (modulePath) {
1669
- return fileToShareKey.get(modulePath);
1670
- });
1671
- // Add all CSS assets to every export if bundleAllCSS is enabled
1672
- if (mfOptions.bundleAllCSS) {
1673
- addCssAssetsToAllExports(filesMap, allCssAssets);
1674
- }
1675
- // Final deduplication of all assets
1676
- filesMap = deduplicateAssets(filesMap);
1677
- _this.emitFile({
1678
- type: 'asset',
1679
- fileName: mfManifestName,
1680
- source: JSON.stringify(generateMFManifest(filesMap))
1681
- });
1682
- });
1683
- } catch (e) {
1684
- return Promise.reject(e);
1685
- }
1686
- }
1687
- }];
1688
- /**
1689
- * Generates the final manifest JSON structure
1690
- * @param preloadMap - Map of module assets to include
1691
- * @returns Complete manifest object
1692
- */
1693
- function generateMFManifest(preloadMap) {
1694
- var options = getNormalizeModuleFederationOptions();
1695
- var name = options.name,
1696
- varFilename = options.varFilename;
1697
- var remoteEntry = {
1698
- name: remoteEntryFile,
1699
- path: '',
1700
- type: 'module'
1701
- };
1702
- var varRemoteEntry = varFilename ? {
1703
- name: varFilename,
1704
- path: '',
1705
- type: 'module'
1706
- } : undefined;
1707
- // Process remotes
1708
- var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1709
- var remoteKey = _ref2[0],
1710
- modules = _ref2[1];
1711
- return Array.from(modules).map(function (moduleKey) {
1712
- return {
1713
- federationContainerName: options.remotes[remoteKey].entry,
1714
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1715
- alias: remoteKey,
1716
- entry: '*'
1717
- };
1718
- });
1719
- });
1720
- // Process shared dependencies
1721
- var shared = Array.from(getUsedShares()).map(function (shareKey) {
1722
- var shareItem = getNormalizeShareItem(shareKey);
1723
- var assets = preloadMap[shareKey] || createEmptyAssetMap();
1724
- return {
1725
- id: name + ":" + shareKey,
1726
- name: shareKey,
1727
- version: shareItem.version,
1728
- requiredVersion: shareItem.shareConfig.requiredVersion,
1729
- assets: {
1730
- js: {
1731
- async: assets.js.async,
1732
- sync: assets.js.sync
1733
- },
1734
- css: {
1735
- async: assets.css.async,
1736
- sync: assets.css.sync
1737
- }
1738
- }
1739
- };
1740
- }).filter(Boolean);
1741
- // Process exposed modules
1742
- var exposes = Object.entries(options.exposes).map(function (_ref3) {
1743
- var key = _ref3[0],
1744
- value = _ref3[1];
1745
- var formatKey = key.replace('./', '');
1746
- var sourceFile = value["import"];
1747
- var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1748
- return {
1749
- id: name + ":" + formatKey,
1750
- name: formatKey,
1751
- assets: {
1752
- js: {
1753
- async: assets.js.async,
1754
- sync: assets.js.sync
1755
- },
1756
- css: {
1757
- async: assets.css.async,
1758
- sync: assets.css.sync
1759
- }
1760
- },
1761
- path: key
1762
- };
1763
- }).filter(Boolean);
1764
- return {
1765
- id: name,
1766
- name: name,
1767
- metaData: _extends({
1768
- name: name,
1769
- type: 'app',
1770
- buildInfo: {
1771
- buildVersion: '1.0.0',
1772
- buildName: name
1773
- },
1774
- remoteEntry: remoteEntry,
1775
- ssrRemoteEntry: remoteEntry,
1776
- varRemoteEntry: varRemoteEntry,
1777
- types: {
1778
- path: '',
1779
- name: ''
1780
- },
1781
- globalName: name,
1782
- pluginVersion: '0.2.5'
1783
- }, !!getPublicPath ? {
1784
- getPublicPath: getPublicPath
1785
- } : {
1786
- publicPath: publicPath
1787
- }),
1788
- shared: shared,
1789
- remotes: remotes,
1790
- exposes: exposes
1791
- };
1792
- }
1358
+ //#endregion
1359
+ //#region src/plugins/pluginMFManifest.ts
1360
+ const Manifest = () => {
1361
+ const mfOptions = getNormalizeModuleFederationOptions();
1362
+ const { name, filename, getPublicPath, manifest: manifestOptions, varFilename } = mfOptions;
1363
+ let mfManifestName = "";
1364
+ if (manifestOptions === true) mfManifestName = "mf-manifest.json";
1365
+ if (typeof manifestOptions !== "boolean") mfManifestName = pathe.join(manifestOptions?.filePath || "", manifestOptions?.fileName || "");
1366
+ let root;
1367
+ let remoteEntryFile;
1368
+ let publicPath;
1369
+ let _command;
1370
+ let _originalConfigBase;
1371
+ let viteConfig;
1372
+ /**
1373
+ * Adds global CSS assets to all module exports
1374
+ * @param filesMap - The preload map to update
1375
+ * @param cssAssets - Set of CSS asset filenames to add
1376
+ */
1377
+ const addCssAssetsToAllExports = (filesMap, cssAssets) => {
1378
+ Object.keys(filesMap).forEach((key) => {
1379
+ cssAssets.forEach((cssAsset) => {
1380
+ trackAsset(filesMap, key, cssAsset, false, "css");
1381
+ });
1382
+ });
1383
+ };
1384
+ return [{
1385
+ name: "module-federation-manifest",
1386
+ apply: "serve",
1387
+ configResolved(config) {
1388
+ viteConfig = config;
1389
+ },
1390
+ configureServer(server) {
1391
+ server.middlewares.use((req, res, next) => {
1392
+ if (!mfManifestName) {
1393
+ next();
1394
+ return;
1395
+ }
1396
+ if (req.url?.replace(/\?.*/, "") === (viteConfig.base + mfManifestName).replace(/^\/?/, "/")) {
1397
+ res.setHeader("Content-Type", "application/json");
1398
+ res.setHeader("Access-Control-Allow-Origin", "*");
1399
+ res.end(JSON.stringify({
1400
+ ...generateMFManifest({}),
1401
+ id: name,
1402
+ name,
1403
+ metaData: {
1404
+ name,
1405
+ type: "app",
1406
+ buildInfo: {
1407
+ buildVersion: "1.0.0",
1408
+ buildName: name
1409
+ },
1410
+ remoteEntry: {
1411
+ name: filename,
1412
+ path: "",
1413
+ type: "module"
1414
+ },
1415
+ ssrRemoteEntry: {
1416
+ name: filename,
1417
+ path: "",
1418
+ type: "module"
1419
+ },
1420
+ varRemoteEntry: varFilename ? {
1421
+ name: varFilename,
1422
+ path: "",
1423
+ type: "var"
1424
+ } : void 0,
1425
+ types: {
1426
+ path: "",
1427
+ name: ""
1428
+ },
1429
+ globalName: name,
1430
+ pluginVersion: "0.2.5",
1431
+ publicPath
1432
+ }
1433
+ }));
1434
+ } else next();
1435
+ });
1436
+ }
1437
+ }, {
1438
+ name: "module-federation-manifest",
1439
+ enforce: "post",
1440
+ config(config, { command }) {
1441
+ if (!config.build) config.build = {};
1442
+ if (!config.build.manifest) config.build.manifest = config.build.manifest || !!manifestOptions;
1443
+ _command = command;
1444
+ _originalConfigBase = config.base;
1445
+ },
1446
+ configResolved(config) {
1447
+ root = config.root;
1448
+ let base = config.base;
1449
+ if (_command === "serve") base = (config.server.origin || "") + config.base;
1450
+ publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1451
+ },
1452
+ async generateBundle(options, bundle) {
1453
+ if (!mfManifestName) return;
1454
+ let filesMap = {};
1455
+ const foundRemoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1456
+ if (foundRemoteEntryFile) remoteEntryFile = foundRemoteEntryFile;
1457
+ const allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : /* @__PURE__ */ new Set();
1458
+ const exposesModules = Object.keys(mfOptions.exposes).map((item) => mfOptions.exposes[item].import);
1459
+ processModuleAssets(bundle, filesMap, (modulePath) => {
1460
+ const absoluteModulePath = pathe.resolve(root, modulePath);
1461
+ return exposesModules.find((exposeModule) => {
1462
+ const exposePath = pathe.resolve(root, exposeModule);
1463
+ if (absoluteModulePath === exposePath) return true;
1464
+ const getPathWithoutKnownExt = (filePath) => {
1465
+ const ext = pathe.extname(filePath);
1466
+ return JS_EXTENSIONS.includes(ext) ? pathe.join(pathe.dirname(filePath), pathe.basename(filePath, ext)) : filePath;
1467
+ };
1468
+ return getPathWithoutKnownExt(absoluteModulePath) === getPathWithoutKnownExt(exposePath);
1469
+ });
1470
+ });
1471
+ const fileToShareKey = await buildFileToShareKeyMap(getUsedShares(), this.resolve.bind(this));
1472
+ processModuleAssets(bundle, filesMap, (modulePath) => fileToShareKey.get(modulePath));
1473
+ if (mfOptions.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
1474
+ filesMap = deduplicateAssets(filesMap);
1475
+ this.emitFile({
1476
+ type: "asset",
1477
+ fileName: mfManifestName,
1478
+ source: JSON.stringify(generateMFManifest(filesMap))
1479
+ });
1480
+ }
1481
+ }];
1482
+ /**
1483
+ * Generates the final manifest JSON structure
1484
+ * @param preloadMap - Map of module assets to include
1485
+ * @returns Complete manifest object
1486
+ */
1487
+ function generateMFManifest(preloadMap) {
1488
+ const options = getNormalizeModuleFederationOptions();
1489
+ const { name, varFilename } = options;
1490
+ const remoteEntry = {
1491
+ name: remoteEntryFile,
1492
+ path: "",
1493
+ type: "module"
1494
+ };
1495
+ const varRemoteEntry = varFilename ? {
1496
+ name: varFilename,
1497
+ path: "",
1498
+ type: "module"
1499
+ } : void 0;
1500
+ const remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(([remoteKey, modules]) => Array.from(modules).map((moduleKey) => ({
1501
+ federationContainerName: options.remotes[remoteKey].entry,
1502
+ moduleName: moduleKey.replace(remoteKey, "").replace("/", ""),
1503
+ alias: remoteKey,
1504
+ entry: "*"
1505
+ })));
1506
+ const shared = Array.from(getUsedShares()).map((shareKey) => {
1507
+ const shareItem = getNormalizeShareItem(shareKey);
1508
+ const assets = preloadMap[shareKey] || createEmptyAssetMap();
1509
+ return {
1510
+ id: `${name}:${shareKey}`,
1511
+ name: shareKey,
1512
+ version: shareItem.version,
1513
+ requiredVersion: shareItem.shareConfig.requiredVersion,
1514
+ assets: {
1515
+ js: {
1516
+ async: assets.js.async,
1517
+ sync: assets.js.sync
1518
+ },
1519
+ css: {
1520
+ async: assets.css.async,
1521
+ sync: assets.css.sync
1522
+ }
1523
+ }
1524
+ };
1525
+ }).filter(Boolean);
1526
+ const exposes = Object.entries(options.exposes).map(([key, value]) => {
1527
+ const formatKey = key.replace("./", "");
1528
+ const assets = preloadMap[value.import] || createEmptyAssetMap();
1529
+ return {
1530
+ id: `${name}:${formatKey}`,
1531
+ name: formatKey,
1532
+ assets: {
1533
+ js: {
1534
+ async: assets.js.async,
1535
+ sync: assets.js.sync
1536
+ },
1537
+ css: {
1538
+ async: assets.css.async,
1539
+ sync: assets.css.sync
1540
+ }
1541
+ },
1542
+ path: key
1543
+ };
1544
+ }).filter(Boolean);
1545
+ return {
1546
+ id: name,
1547
+ name,
1548
+ metaData: {
1549
+ name,
1550
+ type: "app",
1551
+ buildInfo: {
1552
+ buildVersion: "1.0.0",
1553
+ buildName: name
1554
+ },
1555
+ remoteEntry,
1556
+ ssrRemoteEntry: remoteEntry,
1557
+ varRemoteEntry,
1558
+ types: {
1559
+ path: "",
1560
+ name: ""
1561
+ },
1562
+ globalName: name,
1563
+ pluginVersion: "0.2.5",
1564
+ ...!!getPublicPath ? { getPublicPath } : { publicPath }
1565
+ },
1566
+ shared,
1567
+ remotes,
1568
+ exposes
1569
+ };
1570
+ }
1793
1571
  };
1794
1572
 
1795
- var _resolve, _parseTimeout;
1796
- var promise = new Promise(function (resolve, reject) {
1797
- _resolve = function _resolve(v) {
1798
- clearTimeout(_parseTimeout);
1799
- _parseTimeout = null;
1800
- resolve(v);
1801
- };
1573
+ //#endregion
1574
+ //#region src/plugins/pluginModuleParseEnd.ts
1575
+ let _resolve, _parseTimeout;
1576
+ const promise = new Promise((resolve, reject) => {
1577
+ _resolve = (v) => {
1578
+ clearTimeout(_parseTimeout);
1579
+ _parseTimeout = null;
1580
+ resolve(v);
1581
+ };
1802
1582
  });
1803
1583
  function setParseTimeout(timeout) {
1804
- if (!_parseTimeout) {
1805
- _parseTimeout = setTimeout(function () {
1806
- console.warn("Parse timeout (" + timeout + "s) - forcing resolve");
1807
- _resolve(1);
1808
- }, timeout * 1000);
1809
- }
1584
+ if (!_parseTimeout) _parseTimeout = setTimeout(() => {
1585
+ console.warn(`Parse timeout (${timeout}s) - forcing resolve`);
1586
+ _resolve(1);
1587
+ }, timeout * 1e3);
1810
1588
  }
1811
- var parsePromise = promise;
1812
- var exposesParseEnd = false;
1813
- var parseStartSet = new Set();
1814
- var parseEndSet = new Set();
1815
- function pluginModuleParseEnd (excludeFn, options) {
1816
- setParseTimeout(options.moduleParseTimeout);
1817
- return [{
1818
- name: '_',
1819
- apply: 'serve',
1820
- config: function config() {
1821
- // No waiting in development mode
1822
- _resolve(1);
1823
- }
1824
- }, {
1825
- enforce: 'pre',
1826
- name: 'parseStart',
1827
- apply: 'build',
1828
- load: function load(id) {
1829
- if (excludeFn(id)) {
1830
- return;
1831
- }
1832
- parseStartSet.add(id);
1833
- }
1834
- }, {
1835
- enforce: 'post',
1836
- name: 'parseEnd',
1837
- apply: 'build',
1838
- moduleParsed: function moduleParsed(module) {
1839
- var id = module.id;
1840
- if (id === VIRTUAL_EXPOSES) {
1841
- // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1842
- exposesParseEnd = true;
1843
- }
1844
- if (excludeFn(id)) {
1845
- return;
1846
- }
1847
- parseEndSet.add(id);
1848
- if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1849
- _resolve(1);
1850
- }
1851
- }
1852
- }];
1589
+ let parsePromise = promise;
1590
+ let exposesParseEnd = false;
1591
+ const parseStartSet = /* @__PURE__ */ new Set();
1592
+ const parseEndSet = /* @__PURE__ */ new Set();
1593
+ function pluginModuleParseEnd_default(excludeFn, options) {
1594
+ setParseTimeout(options.moduleParseTimeout);
1595
+ return [
1596
+ {
1597
+ name: "_",
1598
+ apply: "serve",
1599
+ config() {
1600
+ _resolve(1);
1601
+ }
1602
+ },
1603
+ {
1604
+ enforce: "pre",
1605
+ name: "parseStart",
1606
+ apply: "build",
1607
+ load(id) {
1608
+ if (excludeFn(id)) return;
1609
+ parseStartSet.add(id);
1610
+ }
1611
+ },
1612
+ {
1613
+ enforce: "post",
1614
+ name: "parseEnd",
1615
+ apply: "build",
1616
+ moduleParsed(module) {
1617
+ const id = module.id;
1618
+ if (id === options.virtualExposesId) exposesParseEnd = true;
1619
+ if (excludeFn(id)) return;
1620
+ parseEndSet.add(id);
1621
+ if (exposesParseEnd && parseStartSet.size === parseEndSet.size) _resolve(1);
1622
+ }
1623
+ }
1624
+ ];
1853
1625
  }
1854
1626
 
1855
- var filter = pluginutils.createFilter();
1856
- function pluginProxyRemoteEntry () {
1857
- var viteConfig, _command;
1858
- return {
1859
- name: 'proxyRemoteEntry',
1860
- enforce: 'post',
1861
- configResolved: function configResolved(config) {
1862
- viteConfig = config;
1863
- },
1864
- config: function config(_config, _ref) {
1865
- var command = _ref.command;
1866
- _command = command;
1867
- },
1868
- resolveId: function resolveId(id) {
1869
- if (id === REMOTE_ENTRY_ID) {
1870
- return REMOTE_ENTRY_ID;
1871
- }
1872
- if (id === VIRTUAL_EXPOSES) {
1873
- return VIRTUAL_EXPOSES;
1874
- }
1875
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1876
- return id;
1877
- }
1878
- },
1879
- load: function load(id) {
1880
- if (id === REMOTE_ENTRY_ID) {
1881
- return parsePromise.then(function (_) {
1882
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1883
- });
1884
- }
1885
- if (id === VIRTUAL_EXPOSES) {
1886
- return generateExposes();
1887
- }
1888
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1889
- return id;
1890
- }
1891
- },
1892
- transform: function transform(code, id) {
1893
- var transformedCode = function () {
1894
- if (!filter(id)) return;
1895
- if (id.includes(REMOTE_ENTRY_ID)) {
1896
- return parsePromise.then(function (_) {
1897
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1898
- });
1899
- }
1900
- if (id === VIRTUAL_EXPOSES) {
1901
- return generateExposes();
1902
- }
1903
- if (id.includes(getHostAutoInitPath())) {
1904
- var options = getNormalizeModuleFederationOptions();
1905
- if (_command === 'serve') {
1906
- var _viteConfig$server, _viteConfig$server2;
1907
- var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1908
- var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1909
- return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1910
- }
1911
- return code;
1912
- }
1913
- }();
1914
- return mapCodeToCodeWithSourcemap(transformedCode);
1915
- }
1916
- };
1627
+ //#endregion
1628
+ //#region src/plugins/pluginProxyRemoteEntry.ts
1629
+ const filter = (0, _rollup_pluginutils.createFilter)();
1630
+ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId }) {
1631
+ let viteConfig, _command;
1632
+ return {
1633
+ name: "proxyRemoteEntry",
1634
+ enforce: "post",
1635
+ configResolved(config) {
1636
+ viteConfig = config;
1637
+ },
1638
+ config(config, { command }) {
1639
+ _command = command;
1640
+ },
1641
+ async buildStart() {
1642
+ if (_command !== "build") return;
1643
+ for (const expose of Object.values(options.exposes)) {
1644
+ const resolved = await this.resolve(expose.import);
1645
+ if (resolved) this.emitFile({
1646
+ type: "chunk",
1647
+ id: resolved.id
1648
+ });
1649
+ }
1650
+ },
1651
+ async resolveId(id, importer) {
1652
+ if (id === remoteEntryId) return remoteEntryId;
1653
+ if (id === virtualExposesId) return virtualExposesId;
1654
+ if (_command === "serve" && id.includes(getHostAutoInitPath())) return id;
1655
+ if (importer === remoteEntryId && !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !id.startsWith("virtual:")) {
1656
+ const importPath = typeof __filename === "string" ? __filename : (0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
1657
+ const resolved = await this.resolve(id, importPath, { skipSelf: true });
1658
+ if (resolved) return resolved;
1659
+ }
1660
+ },
1661
+ load(id) {
1662
+ if (id === remoteEntryId) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId));
1663
+ if (id === virtualExposesId) return generateExposes(options);
1664
+ if (_command === "serve" && id.includes(getHostAutoInitPath())) return id;
1665
+ },
1666
+ transform(code, id) {
1667
+ return mapCodeToCodeWithSourcemap((() => {
1668
+ if (!filter(id)) return;
1669
+ if (id.includes(remoteEntryId)) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId));
1670
+ if (id === virtualExposesId) return generateExposes(options);
1671
+ if (id.includes(getHostAutoInitPath())) {
1672
+ if (_command === "serve") {
1673
+ const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
1674
+ const publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1675
+ return `
1676
+ const origin = (window && ${!options.ignoreOrigin}) ? window.origin : "//${host}:${viteConfig.server?.port}"
1677
+ const remoteEntryPromise = await import(origin + ${publicPath})
1678
+ // __tla only serves as a hack for vite-plugin-top-level-await.
1679
+ Promise.resolve(remoteEntryPromise)
1680
+ .then(remoteEntry => {
1681
+ return Promise.resolve(remoteEntry.__tla)
1682
+ .then(remoteEntry.init).catch(remoteEntry.init)
1683
+ })
1684
+ `;
1685
+ }
1686
+ return code;
1687
+ }
1688
+ })());
1689
+ }
1690
+ };
1917
1691
  }
1918
1692
 
1919
- pluginutils.createFilter();
1920
- function pluginProxyRemotes (options) {
1921
- var remotes = options.remotes;
1922
- return {
1923
- name: 'proxyRemotes',
1924
- config: function config(_config, _ref) {
1925
- var _command = _ref.command;
1926
- Object.keys(remotes).forEach(function (key) {
1927
- var remote = remotes[key];
1928
- _config.resolve.alias.push({
1929
- find: new RegExp("^(" + remote.name + "(/.*|$))"),
1930
- replacement: '$1',
1931
- customResolver: function customResolver(source) {
1932
- var remoteModule = getRemoteVirtualModule(source, _command);
1933
- addUsedRemote(remote.name, source);
1934
- return remoteModule.getPath();
1935
- }
1936
- });
1937
- });
1938
- }
1939
- };
1693
+ //#endregion
1694
+ //#region src/plugins/pluginProxyRemotes.ts
1695
+ (0, _rollup_pluginutils.createFilter)();
1696
+ function pluginProxyRemotes_default(options) {
1697
+ const { remotes } = options;
1698
+ return {
1699
+ name: "proxyRemotes",
1700
+ config(config, { command: _command }) {
1701
+ const isRolldown = !!this?.meta?.rolldownVersion;
1702
+ Object.keys(remotes).forEach((key) => {
1703
+ const remote = remotes[key];
1704
+ config.resolve.alias.push({
1705
+ find: new RegExp(`^(${remote.name}(\/.*|$))`),
1706
+ replacement: "$1",
1707
+ customResolver(source) {
1708
+ const remoteModule = getRemoteVirtualModule(source, _command, isRolldown);
1709
+ addUsedRemote(remote.name, source);
1710
+ return remoteModule.getPath();
1711
+ }
1712
+ });
1713
+ });
1714
+ }
1715
+ };
1940
1716
  }
1941
1717
 
1942
- /**
1943
- * example:
1944
- * const store = new PromiseStore<number>();
1945
- * store.get("example").then((result) => {
1946
- * console.log("Result from example:", result); // 42
1947
- * });
1948
- * setTimeout(() => {
1949
- * store.set("example", Promise.resolve(42));
1950
- * }, 2000);
1951
- */
1952
- var PromiseStore = /*#__PURE__*/function () {
1953
- function PromiseStore() {
1954
- this.promiseMap = new Map();
1955
- this.resolveMap = new Map();
1956
- }
1957
- var _proto = PromiseStore.prototype;
1958
- _proto.set = function set(id, promise) {
1959
- if (this.resolveMap.has(id)) {
1960
- promise.then(this.resolveMap.get(id));
1961
- this.resolveMap["delete"](id);
1962
- }
1963
- this.promiseMap.set(id, promise);
1964
- };
1965
- _proto.get = function get(id) {
1966
- var _this = this;
1967
- if (this.promiseMap.has(id)) {
1968
- return this.promiseMap.get(id);
1969
- }
1970
- var pendingPromise = new Promise(function (resolve) {
1971
- _this.resolveMap.set(id, resolve);
1972
- });
1973
- this.promiseMap.set(id, pendingPromise);
1974
- return pendingPromise;
1975
- };
1976
- return PromiseStore;
1977
- }();
1718
+ //#endregion
1719
+ //#region src/utils/PromiseStore.ts
1720
+ /**
1721
+ * example:
1722
+ * const store = new PromiseStore<number>();
1723
+ * store.get("example").then((result) => {
1724
+ * console.log("Result from example:", result); // 42
1725
+ * });
1726
+ * setTimeout(() => {
1727
+ * store.set("example", Promise.resolve(42));
1728
+ * }, 2000);
1729
+ */
1730
+ var PromiseStore = class {
1731
+ constructor() {
1732
+ this.promiseMap = /* @__PURE__ */ new Map();
1733
+ this.resolveMap = /* @__PURE__ */ new Map();
1734
+ }
1735
+ set(id, promise) {
1736
+ if (this.resolveMap.has(id)) {
1737
+ promise.then(this.resolveMap.get(id));
1738
+ this.resolveMap.delete(id);
1739
+ }
1740
+ this.promiseMap.set(id, promise);
1741
+ }
1742
+ get(id) {
1743
+ if (this.promiseMap.has(id)) return this.promiseMap.get(id);
1744
+ const pendingPromise = new Promise((resolve) => {
1745
+ this.resolveMap.set(id, resolve);
1746
+ });
1747
+ this.promiseMap.set(id, pendingPromise);
1748
+ return pendingPromise;
1749
+ }
1750
+ };
1978
1751
 
1752
+ //#endregion
1753
+ //#region src/plugins/pluginProxySharedModule_preBuild.ts
1979
1754
  function proxySharedModule(options) {
1980
- var _options$shared = options.shared,
1981
- shared = _options$shared === void 0 ? {} : _options$shared;
1982
- var _config;
1983
- return [{
1984
- name: 'generateLocalSharedImportMap',
1985
- enforce: 'post',
1986
- load: function load(id) {
1987
- if (id.includes(getLocalSharedImportMapPath())) {
1988
- return parsePromise.then(function (_) {
1989
- return generateLocalSharedImportMap();
1990
- });
1991
- }
1992
- },
1993
- transform: function transform(_, id) {
1994
- if (id.includes(getLocalSharedImportMapPath())) {
1995
- return mapCodeToCodeWithSourcemap(parsePromise.then(function (_) {
1996
- return generateLocalSharedImportMap();
1997
- }));
1998
- }
1999
- }
2000
- }, {
2001
- name: 'proxyPreBuildShared',
2002
- enforce: 'post',
2003
- configResolved: function configResolved(config) {
2004
- _config = config;
2005
- },
2006
- config: function config(_config2, _ref) {
2007
- var _config2$resolve$alia, _config2$resolve$alia2;
2008
- var command = _ref.command;
2009
- (_config2$resolve$alia = _config2.resolve.alias).push.apply(_config2$resolve$alia, Object.keys(shared).map(function (key) {
2010
- var pattern = key.endsWith('/') ? "(^" + key.replace(/\/$/, '') + "(/.+)?$)" : "(^" + key + "$)";
2011
- return {
2012
- // Intercept all shared requests and proxy them to loadShare
2013
- find: new RegExp(pattern),
2014
- replacement: '$1',
2015
- customResolver: function customResolver(source, importer) {
2016
- if (/\.css$/.test(source)) return;
2017
- var loadSharePath = getLoadShareModulePath(source);
2018
- writeLoadShareModule(source, shared[key], command);
2019
- writePreBuildLibPath(source);
2020
- addUsedShares(source);
2021
- writeLocalSharedImportMap();
2022
- return this.resolve(loadSharePath, importer);
2023
- }
2024
- };
2025
- }));
2026
- var savePrebuild = new PromiseStore();
2027
- (_config2$resolve$alia2 = _config2.resolve.alias).push.apply(_config2$resolve$alia2, Object.keys(shared).map(function (key) {
2028
- return command === 'build' ? {
2029
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
2030
- replacement: function replacement($1) {
2031
- var module = assertModuleFound(PREBUILD_TAG, $1);
2032
- var pkgName = module.name;
2033
- return pkgName;
2034
- }
2035
- } : {
2036
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
2037
- replacement: '$1',
2038
- customResolver: function customResolver(source, importer) {
2039
- try {
2040
- var _this = this;
2041
- var module = assertModuleFound(PREBUILD_TAG, source);
2042
- var pkgName = module.name;
2043
- return Promise.resolve(_this.resolve(pkgName, importer).then(function (item) {
2044
- return item.id;
2045
- })).then(function (result) {
2046
- if (!result.includes(_config.cacheDir)) {
2047
- // save pre-bunding module id
2048
- savePrebuild.set(pkgName, Promise.resolve(result));
2049
- }
2050
- // Fix localSharedImportMap import id
2051
- var _resolve = _this.resolve;
2052
- return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
2053
- return Promise.resolve(_resolve.call(_this, _savePrebuild$get, importer));
2054
- });
2055
- });
2056
- } catch (e) {
2057
- return Promise.reject(e);
2058
- }
2059
- }
2060
- };
2061
- }));
2062
- }
2063
- }];
1755
+ const { shared = {} } = options;
1756
+ let _config;
1757
+ let _command = "serve";
1758
+ const savePrebuild = new PromiseStore();
1759
+ return [{
1760
+ name: "generateLocalSharedImportMap",
1761
+ enforce: "post",
1762
+ load(id) {
1763
+ if (id.includes(getLocalSharedImportMapPath())) return parsePromise.then((_) => generateLocalSharedImportMap());
1764
+ },
1765
+ transform(_, id) {
1766
+ if (id.includes(getLocalSharedImportMapPath())) return mapCodeToCodeWithSourcemap(parsePromise.then((_) => generateLocalSharedImportMap()));
1767
+ }
1768
+ }, {
1769
+ name: "proxyPreBuildShared",
1770
+ enforce: "post",
1771
+ config(config, { command }) {
1772
+ const isRolldown = !!this?.meta?.rolldownVersion;
1773
+ _command = command;
1774
+ config.resolve.alias.push(...Object.keys(shared).map((key) => {
1775
+ const keyBase = key.endsWith("/") ? key.slice(0, -1) : key;
1776
+ const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1777
+ const escapedKeyBase = escapeRegex(keyBase);
1778
+ const pattern = key.endsWith("/") ? `^(${escapedKeyBase}(?:\\/.*)?)$` : `^(${escapedKeyBase})$`;
1779
+ return {
1780
+ find: new RegExp(pattern),
1781
+ replacement: "$1",
1782
+ customResolver(source, importer) {
1783
+ if (/\.css$/.test(source)) return;
1784
+ if (importer && importer.includes("localSharedImportMap")) return;
1785
+ if (key.endsWith("/") && source !== key.slice(0, -1)) return;
1786
+ const loadSharePath = getLoadShareModulePath(source, isRolldown, command);
1787
+ writeLoadShareModule(source, shared[key], command, isRolldown);
1788
+ writePreBuildLibPath(source);
1789
+ addUsedShares(source);
1790
+ writeLocalSharedImportMap();
1791
+ return this.resolve(loadSharePath, importer);
1792
+ }
1793
+ };
1794
+ }));
1795
+ config.resolve.alias.push(...Object.keys(shared).map((key) => {
1796
+ return command === "build" ? {
1797
+ find: new RegExp(`(.*${PREBUILD_TAG}.*)`),
1798
+ replacement: function($1) {
1799
+ return assertModuleFound(PREBUILD_TAG, $1).name;
1800
+ }
1801
+ } : {
1802
+ find: new RegExp(`(.*${PREBUILD_TAG}.*)`),
1803
+ replacement: "$1",
1804
+ async customResolver(source, importer) {
1805
+ const pkgName = assertModuleFound(PREBUILD_TAG, source).name;
1806
+ const result = await this.resolve(pkgName, importer).then((item) => item.id);
1807
+ if (_config && !result.includes(_config.cacheDir)) savePrebuild.set(pkgName, Promise.resolve(result));
1808
+ return await this.resolve(await savePrebuild.get(pkgName), importer);
1809
+ }
1810
+ };
1811
+ }));
1812
+ },
1813
+ configResolved(config) {
1814
+ _config = config;
1815
+ const isRolldown = !!config.experimental?.rolldownDev;
1816
+ Object.keys(shared).forEach((key) => {
1817
+ if (key.endsWith("/")) return;
1818
+ writeLoadShareModule(key, shared[key], _command, isRolldown);
1819
+ writePreBuildLibPath(key);
1820
+ addUsedShares(key);
1821
+ });
1822
+ writeLocalSharedImportMap();
1823
+ }
1824
+ }];
2064
1825
  }
2065
1826
 
2066
- var VarRemoteEntry = function VarRemoteEntry() {
2067
- var mfOptions = getNormalizeModuleFederationOptions();
2068
- var name = mfOptions.name,
2069
- varFilename = mfOptions.varFilename,
2070
- filename = mfOptions.filename;
2071
- var viteConfig;
2072
- return [{
2073
- name: 'module-federation-var-remote-entry',
2074
- apply: 'serve',
2075
- /**
2076
- * Stores resolved Vite config for later use
2077
- */
2078
- /**
2079
- * Finalizes configuration after all plugins are resolved
2080
- * @param config - Fully resolved Vite config
2081
- */
2082
- configResolved: function configResolved(config) {
2083
- viteConfig = config;
2084
- },
2085
- /**
2086
- * Configures dev server middleware to handle varRemoteEntry requests
2087
- * @param server - Vite dev server instance
2088
- */
2089
- configureServer: function configureServer(server) {
2090
- server.middlewares.use(function (req, res, next) {
2091
- var _req$url;
2092
- if (!varFilename) {
2093
- next();
2094
- return;
2095
- }
2096
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + varFilename).replace(/^\/?/, '/')) {
2097
- res.setHeader('Content-Type', 'text/javascript');
2098
- res.setHeader('Access-Control-Allow-Origin', '*');
2099
- console.log({
2100
- filename: filename
2101
- });
2102
- res.end(generateVarRemoteEntry(filename));
2103
- } else {
2104
- next();
2105
- }
2106
- });
2107
- }
2108
- }, {
2109
- name: 'module-federation-var-remote-entry',
2110
- enforce: 'post',
2111
- /**
2112
- * Initial plugin configuration
2113
- * @param config - Vite config object
2114
- * @param command - Current Vite command (serve/build)
2115
- */
2116
- config: function config(_config, _ref) {
2117
- if (!_config.build) _config.build = {};
2118
- },
2119
- /**
2120
- * Generates the module federation "var" remote entry file
2121
- * @param options - Rollup output options
2122
- * @param bundle - Generated bundle assets
2123
- */
2124
- generateBundle: function generateBundle(options, bundle) {
2125
- try {
2126
- var _this = this;
2127
- if (!varFilename) return Promise.resolve();
2128
- var isValidName = isValidVarName(name);
2129
- if (!isValidName) {
2130
- viteConfig.logger.warn("Provided remote name \"" + name + "\" is not valid for \"var\" remoteEntry type, thus it's placed in globalThis['" + name + "'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).");
2131
- }
2132
- var remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
2133
- if (!remoteEntryFile) throw new Error("Couldn't find a remoteEntry chunk file for " + mfOptions.filename + ", can't generate varRemoteEntry file");
2134
- _this.emitFile({
2135
- type: 'asset',
2136
- fileName: varFilename,
2137
- source: generateVarRemoteEntry(remoteEntryFile)
2138
- });
2139
- return Promise.resolve();
2140
- } catch (e) {
2141
- return Promise.reject(e);
1827
+ //#endregion
1828
+ //#region src/plugins/pluginVarRemoteEntry.ts
1829
+ const VarRemoteEntry = () => {
1830
+ const mfOptions = getNormalizeModuleFederationOptions();
1831
+ const { name, varFilename, filename } = mfOptions;
1832
+ let viteConfig;
1833
+ return [{
1834
+ name: "module-federation-var-remote-entry",
1835
+ apply: "serve",
1836
+ configResolved(config) {
1837
+ viteConfig = config;
1838
+ },
1839
+ configureServer(server) {
1840
+ server.middlewares.use((req, res, next) => {
1841
+ if (!varFilename) {
1842
+ next();
1843
+ return;
1844
+ }
1845
+ if (req.url?.replace(/\?.*/, "") === (viteConfig.base + varFilename).replace(/^\/?/, "/")) {
1846
+ res.setHeader("Content-Type", "text/javascript");
1847
+ res.setHeader("Access-Control-Allow-Origin", "*");
1848
+ console.log({ filename });
1849
+ res.end(generateVarRemoteEntry(filename));
1850
+ } else next();
1851
+ });
1852
+ }
1853
+ }, {
1854
+ name: "module-federation-var-remote-entry",
1855
+ enforce: "post",
1856
+ config(config, { command }) {
1857
+ if (!config.build) config.build = {};
1858
+ },
1859
+ configResolved(config) {
1860
+ viteConfig = config;
1861
+ },
1862
+ async generateBundle(options, bundle) {
1863
+ if (!varFilename) return;
1864
+ if (!isValidVarName(name)) viteConfig.logger.warn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);
1865
+ const remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1866
+ if (!remoteEntryFile) throw new Error(`Couldn't find a remoteEntry chunk file for ${mfOptions.filename}, can't generate varRemoteEntry file`);
1867
+ this.emitFile({
1868
+ type: "asset",
1869
+ fileName: varFilename,
1870
+ source: generateVarRemoteEntry(remoteEntryFile)
1871
+ });
1872
+ }
1873
+ }];
1874
+ function isValidVarName(name) {
1875
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
1876
+ }
1877
+ /**
1878
+ * Generates the final "var" remote entry file
1879
+ * @param remoteEntryFile - Path to esm remote entry file
1880
+ * @returns Complete "var" remoteEntry.js file source
1881
+ */
1882
+ function generateVarRemoteEntry(remoteEntryFile) {
1883
+ const { name, varFilename } = getNormalizeModuleFederationOptions();
1884
+ const isValidName = isValidVarName(name);
1885
+ return `
1886
+ ${isValidName ? `var ${name};` : ""}
1887
+ ${isValidName ? name : `globalThis['${name}']`} = (function () {
1888
+ function getScriptUrl() {
1889
+ const currentScript = document.currentScript;
1890
+ if (!currentScript) {
1891
+ console.error("[VarRemoteEntry] ${varFilename} script should be called from sync <script> tag (document.currentScript is undefined)")
1892
+ return '/';
2142
1893
  }
1894
+ return document.currentScript.src.replace(/\\/[^/]*$/, '/');
2143
1895
  }
2144
- }];
2145
- function isValidVarName(name) {
2146
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
2147
- }
2148
- /**
2149
- * Generates the final "var" remote entry file
2150
- * @param remoteEntryFile - Path to esm remote entry file
2151
- * @returns Complete "var" remoteEntry.js file source
2152
- */
2153
- function generateVarRemoteEntry(remoteEntryFile) {
2154
- var options = getNormalizeModuleFederationOptions();
2155
- var name = options.name,
2156
- varFilename = options.varFilename;
2157
- var isValidName = isValidVarName(name);
2158
- // todo: implement publicPath/getPublicPath support
2159
- return "\n " + (isValidName ? "var " + name + ";" : '') + "\n " + (isValidName ? name : "globalThis['" + name + "']") + " = (function () {\n function getScriptUrl() {\n const currentScript = document.currentScript;\n if (!currentScript) {\n console.error(\"[VarRemoteEntry] " + varFilename + " script should be called from sync <script> tag (document.currentScript is undefined)\")\n return '/';\n }\n return document.currentScript.src.replace(/\\/[^/]*$/, '/');\n }\n\n const entry = getScriptUrl() + '" + remoteEntryFile + "';\n\n return {\n get: (...args) => import(entry).then(m => m.get(...args)),\n init: (...args) => import(entry).then(m => m.init(...args)),\n };\n })();\n ";
2160
- }
1896
+
1897
+ const entry = getScriptUrl() + '${remoteEntryFile}';
1898
+
1899
+ return {
1900
+ get: (...args) => import(entry).then(m => m.get(...args)),
1901
+ init: (...args) => import(entry).then(m => m.init(...args)),
1902
+ };
1903
+ })();
1904
+ `;
1905
+ }
2161
1906
  };
2162
1907
 
2163
- var aliasToArrayPlugin = {
2164
- name: 'alias-transform-plugin',
2165
- config: function config(_config, _ref) {
2166
- if (!_config.resolve) _config.resolve = {};
2167
- if (!_config.resolve.alias) _config.resolve.alias = [];
2168
- var alias = _config.resolve.alias;
2169
- if (typeof alias === 'object' && !Array.isArray(alias)) {
2170
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
2171
- var find = _ref2[0],
2172
- replacement = _ref2[1];
2173
- return {
2174
- find: find,
2175
- replacement: replacement
2176
- };
2177
- });
2178
- }
2179
- }
1908
+ //#endregion
1909
+ //#region src/utils/aliasToArrayPlugin.ts
1910
+ var aliasToArrayPlugin_default = {
1911
+ name: "alias-transform-plugin",
1912
+ config: (config, { command }) => {
1913
+ if (!config.resolve) config.resolve = {};
1914
+ if (!config.resolve.alias) config.resolve.alias = [];
1915
+ const { alias } = config.resolve;
1916
+ if (typeof alias === "object" && !Array.isArray(alias)) config.resolve.alias = Object.entries(alias).map(([find, replacement]) => ({
1917
+ find,
1918
+ replacement
1919
+ }));
1920
+ }
2180
1921
  };
2181
1922
 
2182
- var normalizeOptimizeDepsPlugin = {
2183
- name: 'normalizeOptimizeDeps',
2184
- config: function config(_config, _ref) {
2185
- var optimizeDeps = _config.optimizeDeps;
2186
- if (!optimizeDeps) {
2187
- _config.optimizeDeps = {};
2188
- optimizeDeps = _config.optimizeDeps;
2189
- }
2190
- // todo: fix this workaround
2191
- optimizeDeps.force = true;
2192
- if (!optimizeDeps.include) optimizeDeps.include = [];
2193
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
2194
- }
1923
+ //#endregion
1924
+ //#region src/utils/normalizeOptimizeDeps.ts
1925
+ var normalizeOptimizeDeps_default = {
1926
+ name: "normalizeOptimizeDeps",
1927
+ config: (config, { command }) => {
1928
+ let { optimizeDeps } = config;
1929
+ if (!optimizeDeps) {
1930
+ config.optimizeDeps = {};
1931
+ optimizeDeps = config.optimizeDeps;
1932
+ }
1933
+ if (!optimizeDeps.include) optimizeDeps.include = [];
1934
+ if (!optimizeDeps.exclude) optimizeDeps.exclude = [];
1935
+ if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
1936
+ }
2195
1937
  };
2196
1938
 
1939
+ //#endregion
1940
+ //#region src/index.ts
1941
+ /**
1942
+ * Plugin that runs FIRST to create virtual module files in the config hook.
1943
+ * This prevents 504 "Outdated Optimize Dep" errors by ensuring files exist
1944
+ * before Vite's optimization phase.
1945
+ */
1946
+ function createEarlyVirtualModulesPlugin(options) {
1947
+ const { shared, remotes, virtualModuleDir } = options;
1948
+ return {
1949
+ name: "vite:module-federation-early-init",
1950
+ enforce: "pre",
1951
+ config(config, { command: _command }) {
1952
+ if (_command !== "serve") return;
1953
+ const isRolldown = !!this?.meta?.rolldownVersion;
1954
+ const root = config.root || process.cwd();
1955
+ initVirtualModuleInfrastructure(root, virtualModuleDir);
1956
+ VirtualModule.setRoot(root);
1957
+ VirtualModule.ensureVirtualPackageExists();
1958
+ initVirtualModules(_command, getRemoteEntryId(options));
1959
+ if (remotes && Object.keys(remotes).length > 0) for (const key of Object.keys(remotes)) addUsedRemote(key, key);
1960
+ if (shared && Object.keys(shared).length > 0) {
1961
+ config.optimizeDeps = config.optimizeDeps || {};
1962
+ config.optimizeDeps.include = config.optimizeDeps.include || [];
1963
+ config.optimizeDeps.include.push(virtualRuntimeInitStatus.getImportId());
1964
+ for (const key of Object.keys(shared)) {
1965
+ if (key.endsWith("/")) continue;
1966
+ const shareItem = shared[key];
1967
+ getLoadShareModulePath(key, isRolldown);
1968
+ writeLoadShareModule(key, shareItem, _command, isRolldown);
1969
+ writePreBuildLibPath(key);
1970
+ addUsedShares(key);
1971
+ config.optimizeDeps.include.push(getPreBuildLibImportId(key));
1972
+ }
1973
+ writeLocalSharedImportMap();
1974
+ }
1975
+ }
1976
+ };
1977
+ }
2197
1978
  function federation(mfUserOptions) {
2198
- var options = normalizeModuleFederationOptions(mfUserOptions);
2199
- var name = options.name,
2200
- shared = options.shared,
2201
- filename = options.filename,
2202
- hostInitInjectLocation = options.hostInitInjectLocation;
2203
- if (!name) throw new Error('name is required');
2204
- return [{
2205
- name: 'vite:module-federation-config',
2206
- enforce: 'pre',
2207
- configResolved: function configResolved(config) {
2208
- // Set root path
2209
- VirtualModule.setRoot(config.root);
2210
- // Ensure virtual package directory exists
2211
- VirtualModule.ensureVirtualPackageExists();
2212
- initVirtualModules();
2213
- }
2214
- }, aliasToArrayPlugin, checkAliasConflicts({
2215
- shared: shared
2216
- }), normalizeOptimizeDepsPlugin].concat(pluginDts(options), addEntry({
2217
- entryName: 'remoteEntry',
2218
- entryPath: REMOTE_ENTRY_ID,
2219
- fileName: filename
2220
- }), addEntry({
2221
- entryName: 'hostInit',
2222
- entryPath: getHostAutoInitPath(),
2223
- inject: hostInitInjectLocation
2224
- }), addEntry({
2225
- entryName: 'virtualExposes',
2226
- entryPath: VIRTUAL_EXPOSES
2227
- }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
2228
- return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
2229
- }, {
2230
- moduleParseTimeout: options.moduleParseTimeout
2231
- }), proxySharedModule({
2232
- shared: shared
2233
- }), [PluginDevProxyModuleTopLevelAwait(), {
2234
- name: 'module-federation-vite',
2235
- enforce: 'post',
2236
- // @ts-expect-error
2237
- // used to expose plugin options: https://github.com/rolldown/rolldown/discussions/2577#discussioncomment-11137593
2238
- _options: options,
2239
- config: function config(_config, _ref) {
2240
- var _config$optimizeDeps, _config$optimizeDeps2, _config$optimizeDeps3, _config$optimizeDeps4;
2241
- // TODO: singleton
2242
- _config.resolve.alias.push({
2243
- find: '@module-federation/runtime',
2244
- replacement: options.implementation
2245
- });
2246
- _config.build = defu__default["default"](_config.build || {}, {
2247
- commonjsOptions: {
2248
- strictRequires: 'auto'
2249
- }
2250
- });
2251
- var virtualDir = options.virtualModuleDir || '__mf__virtual';
2252
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
2253
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(virtualDir);
2254
- (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(virtualDir);
2255
- (_config$optimizeDeps4 = _config.optimizeDeps) == null || (_config$optimizeDeps4 = _config$optimizeDeps4.needsInterop) == null || _config$optimizeDeps4.push(getLocalSharedImportMapPath());
2256
- }
2257
- }], Manifest(), VarRemoteEntry());
1979
+ const options = normalizeModuleFederationOptions(mfUserOptions);
1980
+ const { name, remotes, shared, filename, hostInitInjectLocation } = options;
1981
+ if (!name) throw new Error("name is required");
1982
+ const remoteEntryId = getRemoteEntryId(options);
1983
+ const virtualExposesId = getVirtualExposesId(options);
1984
+ let command;
1985
+ return [
1986
+ createEarlyVirtualModulesPlugin(options),
1987
+ {
1988
+ name: "vite:module-federation-config",
1989
+ enforce: "pre",
1990
+ config(_config, env) {
1991
+ command = env.command;
1992
+ },
1993
+ configResolved(config) {
1994
+ VirtualModule.setRoot(config.root);
1995
+ VirtualModule.ensureVirtualPackageExists();
1996
+ initVirtualModules(command, remoteEntryId);
1997
+ }
1998
+ },
1999
+ aliasToArrayPlugin_default,
2000
+ checkAliasConflicts({ shared }),
2001
+ normalizeOptimizeDeps_default,
2002
+ ...pluginDts(options),
2003
+ ...addEntry({
2004
+ entryName: "remoteEntry",
2005
+ entryPath: remoteEntryId,
2006
+ fileName: filename
2007
+ }),
2008
+ ...addEntry({
2009
+ entryName: "hostInit",
2010
+ entryPath: getHostAutoInitPath(),
2011
+ inject: hostInitInjectLocation
2012
+ }),
2013
+ ...addEntry({
2014
+ entryName: "virtualExposes",
2015
+ entryPath: virtualExposesId
2016
+ }),
2017
+ pluginProxyRemoteEntry_default({
2018
+ options,
2019
+ remoteEntryId,
2020
+ virtualExposesId
2021
+ }),
2022
+ pluginProxyRemotes_default(options),
2023
+ ...pluginModuleParseEnd_default((id) => {
2024
+ return id.includes(getHostAutoInitImportId()) || id.includes(remoteEntryId) || id.includes(virtualExposesId) || id.includes(getLocalSharedImportMapPath());
2025
+ }, {
2026
+ moduleParseTimeout: options.moduleParseTimeout,
2027
+ virtualExposesId
2028
+ }),
2029
+ ...proxySharedModule({ shared }),
2030
+ {
2031
+ name: "module-federation-esm-shims",
2032
+ enforce: "pre",
2033
+ apply: "build",
2034
+ config(config) {
2035
+ const runtimeInitId = virtualRuntimeInitStatus.getImportId();
2036
+ config.build = config.build || {};
2037
+ config.build.rollupOptions = config.build.rollupOptions || {};
2038
+ if (!Array.isArray(config.build.rollupOptions.output)) {
2039
+ const output = config.build.rollupOptions.output ||= {};
2040
+ const existingManualChunks = output.manualChunks;
2041
+ output.manualChunks = function(id) {
2042
+ if (id.includes(runtimeInitId)) return "runtimeInit";
2043
+ if (id.includes(LOAD_SHARE_TAG)) {
2044
+ const match = id.match(/([^/\\]+__loadShare__[^/\\]+)/);
2045
+ return match ? match[1] : "loadShare";
2046
+ }
2047
+ if (typeof existingManualChunks === "function") return existingManualChunks.apply(this, arguments);
2048
+ if (existingManualChunks && typeof existingManualChunks === "object") {
2049
+ for (const [key, ids] of Object.entries(existingManualChunks)) if (Array.isArray(ids) && ids.some((v) => id.includes(v))) return key;
2050
+ }
2051
+ };
2052
+ }
2053
+ },
2054
+ load(id) {
2055
+ if (id.startsWith("\0")) return;
2056
+ if (id.includes(LOAD_SHARE_TAG) || id.includes(LOAD_REMOTE_TAG)) {
2057
+ let code = (0, fs.readFileSync)(id, "utf-8");
2058
+ code = code.replace(/import\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
2059
+ code = code.replace(/export\s+\*\s+from\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
2060
+ /**
2061
+ * Shared/remote shims only have `export default exportModule`.
2062
+ *
2063
+ * We add a second named export (__moduleExports) that holds the full
2064
+ * module namespace and point syntheticNamedExports at it. This lets
2065
+ * Rollup resolve named imports (e.g. `import { useState } from 'react'`)
2066
+ * from the namespace while still applying its normal default-export
2067
+ * interop — which is needed for libraries like @emotion/styled where
2068
+ * `import styled from '@emotion/styled'` must receive the .default
2069
+ * function, not the raw namespace object.
2070
+ *
2071
+ * Using 'default' as the syntheticNamedExports key would skip the
2072
+ * interop and break default imports.
2073
+ *
2074
+ * @see https://rollupjs.org/plugin-development/#synthetic-named-exports
2075
+ */
2076
+ code = code.replace("export default exportModule", "export const __moduleExports = exportModule;\nexport default exportModule.__esModule ? exportModule.default : exportModule");
2077
+ return {
2078
+ code,
2079
+ syntheticNamedExports: "__moduleExports"
2080
+ };
2081
+ }
2082
+ },
2083
+ generateBundle(_, bundle) {
2084
+ for (const [fileName, chunk] of Object.entries(bundle)) {
2085
+ if (chunk.type !== "chunk") continue;
2086
+ if (fileName.includes(LOAD_SHARE_TAG)) continue;
2087
+ let code = chunk.code;
2088
+ let m;
2089
+ const importedFromLoadShare = /* @__PURE__ */ new Set();
2090
+ const importRegex = /import\s*\{([^}]+)\}\s*from\s*["'][^"']*__loadShare__[^"']*["']/g;
2091
+ while ((m = importRegex.exec(code)) !== null) for (const spec of m[1].split(",")) {
2092
+ const parts = spec.trim().split(/\s+as\s+/);
2093
+ const local = (parts[1] || parts[0]).trim();
2094
+ if (local) importedFromLoadShare.add(local);
2095
+ }
2096
+ const allInits = [];
2097
+ for (const v of importedFromLoadShare) if (new RegExp("\\(" + v + "\\(\\)\\s*,\\s*\\w+\\(\\w+\\)\\)").test(code)) allInits.push(v);
2098
+ if (allInits.length === 0) continue;
2099
+ const awaits = allInits.map((v) => `await ${v}();`).join("");
2100
+ const lastFromRegex = /\bfrom\s*["'][^"']*["']\s*;?/g;
2101
+ let lastFromEnd = -1;
2102
+ while ((m = lastFromRegex.exec(code)) !== null) lastFromEnd = m.index + m[0].length;
2103
+ if (lastFromEnd !== -1) {
2104
+ chunk.code = code.slice(0, lastFromEnd) + awaits + code.slice(lastFromEnd);
2105
+ continue;
2106
+ }
2107
+ const exportIdx = code.search(/\bexport\s*[{d]/);
2108
+ if (exportIdx !== -1) {
2109
+ chunk.code = code.slice(0, exportIdx) + awaits + code.slice(exportIdx);
2110
+ continue;
2111
+ }
2112
+ }
2113
+ const proxyChunks = /* @__PURE__ */ new Map();
2114
+ for (const [fileName, chunk] of Object.entries(bundle)) {
2115
+ if (chunk.type !== "chunk") continue;
2116
+ if (fileName.includes(LOAD_SHARE_TAG) && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
2117
+ code: chunk.code,
2118
+ fileName
2119
+ });
2120
+ }
2121
+ if (proxyChunks.size === 0) return;
2122
+ for (const [fileName, chunk] of Object.entries(bundle)) {
2123
+ if (chunk.type !== "chunk") continue;
2124
+ if (fileName.includes(LOAD_SHARE_TAG)) continue;
2125
+ let code = chunk.code;
2126
+ let modified = false;
2127
+ for (const [proxyFileName, proxyInfo] of proxyChunks) {
2128
+ const proxyBaseName = proxyFileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
2129
+ const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${proxyBaseName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^"']*)["']\\s*;?`).exec(code);
2130
+ if (!importMatch) continue;
2131
+ const fullImport = importMatch[0];
2132
+ const bindings = importMatch[1].split(",").map((s) => {
2133
+ const parts = s.trim().split(/\s+as\s+/);
2134
+ return {
2135
+ imported: parts[0].trim(),
2136
+ local: (parts[1] || parts[0]).trim()
2137
+ };
2138
+ });
2139
+ const proxyCode = proxyInfo.code;
2140
+ const exportMapMatch = proxyCode.match(/export\s*\{([^}]+)\}/);
2141
+ if (!exportMapMatch) continue;
2142
+ const exportMap = {};
2143
+ for (const entry of exportMapMatch[1].split(",")) {
2144
+ const parts = entry.trim().split(/\s+as\s+/);
2145
+ if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
2146
+ }
2147
+ const inlineable = [];
2148
+ const nonInlineable = [];
2149
+ for (const b of bindings) {
2150
+ const proxyLocal = exportMap[b.imported];
2151
+ if (!proxyLocal) {
2152
+ nonInlineable.push(b);
2153
+ continue;
2154
+ }
2155
+ const funcRe = new RegExp(`function\\s+${proxyLocal}\\s*\\([^)]*\\)\\s*\\{`);
2156
+ if (funcRe.test(proxyCode)) {
2157
+ const funcStart = proxyCode.search(funcRe);
2158
+ let depth = 0;
2159
+ let funcEnd = funcStart;
2160
+ for (let i = proxyCode.indexOf("{", funcStart); i < proxyCode.length; i++) if (proxyCode[i] === "{") depth++;
2161
+ else if (proxyCode[i] === "}") {
2162
+ depth--;
2163
+ if (depth === 0) {
2164
+ funcEnd = i + 1;
2165
+ break;
2166
+ }
2167
+ }
2168
+ const renamedFunc = proxyCode.slice(funcStart, funcEnd).replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`);
2169
+ inlineable.push({
2170
+ local: b.local,
2171
+ funcBody: renamedFunc
2172
+ });
2173
+ } else nonInlineable.push(b);
2174
+ }
2175
+ if (inlineable.length === 0) continue;
2176
+ let replacement = "";
2177
+ if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
2178
+ replacement += inlineable.map((f) => f.funcBody).join("");
2179
+ code = code.replace(fullImport, replacement);
2180
+ modified = true;
2181
+ }
2182
+ if (modified) chunk.code = code;
2183
+ }
2184
+ }
2185
+ },
2186
+ {
2187
+ name: "module-federation-dev-await-shared-init",
2188
+ apply: "serve",
2189
+ enforce: "post",
2190
+ transform(code, id) {
2191
+ if (!id.includes(".vite/deps/")) return;
2192
+ const initPattern = /\b(init_\w+__loadShare__\w+)\b/g;
2193
+ const initFns = /* @__PURE__ */ new Set();
2194
+ let match;
2195
+ while ((match = initPattern.exec(code)) !== null) initFns.add(match[1]);
2196
+ if (initFns.size === 0) return;
2197
+ if (![...initFns].some((fn) => {
2198
+ return code.includes(`${fn}(),`) || code.includes(`${fn}()`);
2199
+ })) return;
2200
+ if (/await\s+init_\w+__loadShare__/.test(code)) return;
2201
+ if (code.includes("__esmMin")) return;
2202
+ const awaits = [...initFns].map((fn) => `await ${fn}();`).join("\n");
2203
+ const topLevelImportRe = /^import\s/gm;
2204
+ let lastImportIdx = -1;
2205
+ let importMatch;
2206
+ while ((importMatch = topLevelImportRe.exec(code)) !== null) lastImportIdx = importMatch.index;
2207
+ if (lastImportIdx === -1) return;
2208
+ const lineEnd = code.indexOf("\n", lastImportIdx);
2209
+ return code.slice(0, lineEnd + 1) + awaits + "\n" + code.slice(lineEnd + 1);
2210
+ }
2211
+ },
2212
+ PluginDevProxyModuleTopLevelAwait(),
2213
+ {
2214
+ name: "module-federation-vite",
2215
+ enforce: "post",
2216
+ _options: options,
2217
+ config(config, { command: _command }) {
2218
+ const isRolldown = !!this?.meta?.rolldownVersion;
2219
+ let implementation = options.implementation;
2220
+ if (isRolldown) implementation = implementation.replace(/\.cjs\.cjs$/, ".esm.js");
2221
+ config.resolve.alias.push({
2222
+ find: "@module-federation/runtime",
2223
+ replacement: implementation
2224
+ });
2225
+ config.build = (0, defu.default)(config.build || {}, { commonjsOptions: { strictRequires: "auto" } });
2226
+ const virtualDir = options.virtualModuleDir || "__mf__virtual";
2227
+ config.optimizeDeps?.include?.push("@module-federation/runtime");
2228
+ config.optimizeDeps?.include?.push(virtualDir);
2229
+ if (isRolldown) config.build = (0, defu.default)(config.build || {}, { target: "esnext" });
2230
+ else {
2231
+ config.optimizeDeps?.needsInterop?.push(virtualDir);
2232
+ config.optimizeDeps?.needsInterop?.push(getLocalSharedImportMapPath());
2233
+ }
2234
+ const resolvedTarget = options.target ?? (config.build?.ssr ? "node" : "web");
2235
+ if (!config.define) config.define = {};
2236
+ if (!("ENV_TARGET" in config.define)) config.define["ENV_TARGET"] = JSON.stringify(resolvedTarget);
2237
+ if (options.target && "ENV_TARGET" in config.define && config.define["ENV_TARGET"] !== JSON.stringify(options.target)) console.warn(`[module-federation] ENV_TARGET define (${config.define["ENV_TARGET"]}) differs from target option ("${options.target}"). ENV_TARGET will not be overridden.`);
2238
+ }
2239
+ },
2240
+ ...Manifest(),
2241
+ ...VarRemoteEntry(),
2242
+ ...Object.keys(options.exposes).length > 0 ? [{
2243
+ name: "module-federation-fix-preload",
2244
+ enforce: "post",
2245
+ apply: "build",
2246
+ generateBundle(_, bundle) {
2247
+ for (const chunk of Object.values(bundle)) {
2248
+ if (chunk.type !== "chunk") continue;
2249
+ if (!chunk.code.includes("modulepreload")) continue;
2250
+ const replacement = "=function($1){return new URL(\"../\"+$1,import.meta.url).href}";
2251
+ const replaced = chunk.code.replace(/=\(?(\w+)(?:,\w+)?\)?\s*=>\s*["'`][^"'`]*["'`]\s*\+\s*\1/, replacement);
2252
+ if (replaced !== chunk.code) {
2253
+ chunk.code = replaced;
2254
+ continue;
2255
+ }
2256
+ chunk.code = chunk.code.replace(/=function\((\w+)(?:,\w+)?\)\{return\s*["'`][^"'`]*["'`]\s*\+\s*\1\s*\}/, replacement);
2257
+ }
2258
+ }
2259
+ }] : []
2260
+ ];
2258
2261
  }
2259
2262
 
2260
- exports.federation = federation;
2263
+ //#endregion
2264
+ exports.federation = federation;