@module-federation/vite 1.11.0 → 1.11.1

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