@module-federation/vite 1.0.0-alpha-54ad191 → 1.0.0-alpha-4a73cd4

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.
package/lib/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@rollup/pluginutils'), require('path'), require('fs'), require('estree-walker'), require('magic-string')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@rollup/pluginutils', 'path', 'fs', 'estree-walker', 'magic-string'], factory) :
4
- (global = global || self, factory(global.vite = {}, global.pluginutils, global.path, global.fs, global.estreeWalker, global.magicString));
5
- })(this, (function (exports, pluginutils, path, fs, estreeWalker, MagicString) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('pathe'), require('@rollup/pluginutils'), require('estree-walker'), require('magic-string')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'fs', 'pathe', '@rollup/pluginutils', 'estree-walker', 'magic-string'], factory) :
4
+ (global = global || self, factory(global.vite = {}, global.fs, global.pathe, global.pluginutils, global.estreeWalker, global.magicString));
5
+ })(this, (function (exports, fs, path, pluginutils, estreeWalker, MagicString) {
6
6
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
7
 
8
8
  function _interopNamespace(e) {
@@ -23,62 +23,80 @@
23
23
  return n;
24
24
  }
25
25
 
26
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
27
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
28
26
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
27
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
29
28
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
30
29
 
31
- var aliasToArrayPlugin = {
32
- name: 'alias-transform-plugin',
33
- config: function config(_config, _ref) {
34
- if (!_config.resolve) _config.resolve = {};
35
- if (!_config.resolve.alias) _config.resolve.alias = [];
36
- var alias = _config.resolve.alias;
37
- if (typeof alias === 'object' && !Array.isArray(alias)) {
38
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
39
- var find = _ref2[0],
40
- replacement = _ref2[1];
41
- return {
42
- find: find,
43
- replacement: replacement
44
- };
30
+ var addEntry = function addEntry(_ref) {
31
+ var entryPath = _ref.entryPath,
32
+ fileName = _ref.fileName;
33
+ var entryFiles = [];
34
+ var htmlFilePath;
35
+ return [{
36
+ name: 'add-entry',
37
+ apply: "serve",
38
+ configureServer: function configureServer(server) {
39
+ var _server$httpServer;
40
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
41
+ var port = server.config.server.port;
42
+ fetch(path__namespace.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
45
43
  });
44
+ server.middlewares.use(function (req, res, next) {
45
+ if (!fileName) {
46
+ next();
47
+ return;
48
+ }
49
+ if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
50
+ req.url = entryPath;
51
+ }
52
+ next();
53
+ });
54
+ },
55
+ transformIndexHtml: function transformIndexHtml(c) {
56
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
46
57
  }
47
- }
48
- };
49
-
50
- var normalizeBuildPlugin = (function (singleChunkModules) {
51
- return {
52
- name: 'normalizeBuild',
53
- config: function config(_config, _ref) {
54
- if (!_config.build) _config.build = {};
55
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
56
- var rollupOptions = _config.build.rollupOptions;
57
- if (!rollupOptions.output) rollupOptions.output = {};
58
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
59
- }
60
- };
61
- });
62
- function normalizeManualChunks(output, singleChunkModules) {
63
- var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
64
- if (!output.manualChunks) output.manualChunks = {};
65
- var wrapManualChunks = function wrapManualChunks(original) {
66
- return function (id) {
67
- var _ref2 = id.match(pattern) || [],
68
- moduleName = _ref2[1];
69
- if (moduleName) {
70
- return moduleName;
58
+ }, {
59
+ name: "add-entry",
60
+ enforce: "post",
61
+ apply: "build",
62
+ configResolved: function configResolved(config) {
63
+ var inputOptions = config.build.rollupOptions.input;
64
+ if (!inputOptions) {
65
+ htmlFilePath = path__namespace.resolve(config.root, 'index.html');
66
+ } else if (typeof inputOptions === 'string') {
67
+ entryFiles = [inputOptions];
68
+ htmlFilePath = path__namespace.resolve(config.root, inputOptions);
69
+ } else if (Array.isArray(inputOptions)) {
70
+ entryFiles = inputOptions;
71
+ htmlFilePath = path__namespace.resolve(config.root, inputOptions[0]);
72
+ } else if (typeof inputOptions === 'object') {
73
+ entryFiles = Object.values(inputOptions);
74
+ htmlFilePath = path__namespace.resolve(config.root, Object.values(inputOptions)[0]);
71
75
  }
72
- if (typeof original === 'function') {
73
- return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
76
+ },
77
+ buildStart: function buildStart() {
78
+ var _this$emitFile;
79
+ var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
80
+ this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
81
+ if (htmlFilePath) {
82
+ var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
83
+ var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
84
+ var match;
85
+ while ((match = scriptRegex.exec(htmlContent)) !== null) {
86
+ entryFiles.push(match[1]);
87
+ }
74
88
  }
75
- if (typeof original === 'object' && original) {
76
- return original[id];
89
+ },
90
+ transform: function transform(code, id) {
91
+ if (entryFiles.some(function (file) {
92
+ return id.endsWith(file);
93
+ })) {
94
+ var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
95
+ return injection + code;
77
96
  }
78
- };
79
- };
80
- output.manualChunks = wrapManualChunks(output.manualChunks);
81
- }
97
+ }
98
+ }];
99
+ };
82
100
 
83
101
  function normalizeExposesItem(key, item) {
84
102
  var importPath = '';
@@ -96,7 +114,7 @@
96
114
  if (!exposes) return {};
97
115
  var res = {};
98
116
  Object.keys(exposes).forEach(function (key) {
99
- res[key.replace(/^\.?\/?/, './')] = normalizeExposesItem(key, exposes[key]);
117
+ res[key] = normalizeExposesItem(key, exposes[key]);
100
118
  });
101
119
  return res;
102
120
  }
@@ -133,7 +151,7 @@
133
151
  function normalizeShareItem(key, shareItem) {
134
152
  var version;
135
153
  try {
136
- version = require(path__default["default"].join(key, 'package.json')).version;
154
+ version = require(path__namespace.join(key, 'package.json')).version;
137
155
  } catch (e) {
138
156
  console.log(e);
139
157
  }
@@ -181,8 +199,12 @@
181
199
  if (!library) return undefined;
182
200
  return library;
183
201
  }
202
+ var config;
203
+ function getNormalizeModuleFederationOptions() {
204
+ return config;
205
+ }
184
206
  function normalizeModuleFederationOptions(options) {
185
- return {
207
+ return config = {
186
208
  exposes: normalizeExposes(options.exposes),
187
209
  filename: options.filename || 'remoteEntry-[hash]',
188
210
  library: normalizeLibrary(options.library),
@@ -201,216 +223,63 @@
201
223
  };
202
224
  }
203
225
 
204
- var normalizeOptimizeDepsPlugin = {
205
- name: 'normalizeOptimizeDeps',
206
- config: function config(_config, _ref) {
207
- var optimizeDeps = _config.optimizeDeps;
208
- if (!optimizeDeps) {
209
- _config.optimizeDeps = {};
210
- optimizeDeps = _config.optimizeDeps;
211
- }
212
- if (!optimizeDeps.include) optimizeDeps.include = [];
213
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
214
- }
215
- };
216
-
217
- var addEntry = function addEntry(_ref) {
218
- var entryPath = _ref.entryPath,
219
- fileName = _ref.fileName;
220
- var entryFiles = [];
221
- var htmlFilePath;
222
- return [{
223
- name: 'add-entry',
224
- apply: "serve",
225
- configureServer: function configureServer(server) {
226
- var _server$httpServer;
227
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
228
- var port = server.config.server.port;
229
- fetch("http://localhost:" + port + entryPath);
230
- });
231
- server.middlewares.use(function (req, res, next) {
232
- if (!fileName) {
233
- next();
234
- return;
235
- }
236
- if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
237
- req.url = entryPath;
238
- }
239
- next();
240
- });
241
- },
242
- transformIndexHtml: function transformIndexHtml(c) {
243
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\/g, '/')) + "></script>");
244
- }
245
- }, {
246
- name: "add-entry",
247
- enforce: "post",
248
- apply: "build",
249
- configResolved: function configResolved(config) {
250
- var inputOptions = config.build.rollupOptions.input;
251
- if (!inputOptions) {
252
- htmlFilePath = path__namespace.resolve(config.root, 'index.html');
253
- } else if (typeof inputOptions === 'string') {
254
- entryFiles = [inputOptions];
255
- htmlFilePath = path__namespace.resolve(config.root, inputOptions);
256
- } else if (Array.isArray(inputOptions)) {
257
- entryFiles = inputOptions;
258
- htmlFilePath = path__namespace.resolve(config.root, inputOptions[0]);
259
- } else if (typeof inputOptions === 'object') {
260
- entryFiles = Object.values(inputOptions);
261
- htmlFilePath = path__namespace.resolve(config.root, Object.values(inputOptions)[0]);
262
- }
263
- },
264
- buildStart: function buildStart() {
265
- var _this$emitFile;
266
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
267
- this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
268
- if (htmlFilePath) {
269
- var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
270
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
271
- var match;
272
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
273
- entryFiles.push(match[1]);
274
- }
275
- }
276
- },
277
- transform: function transform(code, id) {
278
- if (entryFiles.some(function (file) {
279
- return id.endsWith(file);
280
- })) {
281
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
282
- return injection + code;
283
- }
284
- }
285
- }];
286
- };
287
-
288
- function _arrayLikeToArray(r, a) {
289
- (null == a || a > r.length) && (a = r.length);
290
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
291
- return n;
226
+ /**
227
+ * Even the resolveId hook cannot interfere with vite pre-build,
228
+ * and adding query parameter virtual modules will also fail.
229
+ * You can only proxy to the real file through alias
230
+ */
231
+ var emptyNpmDir = path.resolve(require.resolve("an-empty-js-file"), "../");
232
+ /**
233
+ * The original shared module is proxied by getLoadShareModulePath, and the new shared module is prebuilt here
234
+ */
235
+ var cacheMap2 = {};
236
+ function getPreBuildLibPath(pkg) {
237
+ if (!cacheMap2[pkg]) cacheMap2[pkg] = "__mf__prebuildwrap_" + npmPackageNameToFileName(pkg) + ".js";
238
+ var filename = cacheMap2[pkg];
239
+ return filename;
292
240
  }
293
- function _createForOfIteratorHelperLoose(r, e) {
294
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
295
- if (t) return (t = t.call(r)).next.bind(t);
296
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
297
- t && (r = t);
298
- var o = 0;
299
- return function () {
300
- return o >= r.length ? {
301
- done: !0
302
- } : {
303
- done: !1,
304
- value: r[o++]
305
- };
306
- };
307
- }
308
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
241
+ function getLocalSharedImportMapFileName() {
242
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
243
+ name = _getNormalizeModuleFe.name;
244
+ return npmPackageNameToFileName(name) + "_" + "__mf__localSharedImportMap.js";
309
245
  }
310
- function _unsupportedIterableToArray(r, a) {
311
- if (r) {
312
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
313
- var t = {}.toString.call(r).slice(8, -1);
314
- 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;
315
- }
246
+ // Only npm package name import can trigger pre-build, absolute path cannot
247
+ function getLocalSharedImportMapId() {
248
+ return "an-empty-js-file/" + getLocalSharedImportMapFileName();
316
249
  }
317
-
318
- function overrideModule(options) {
319
- if (options === void 0) {
320
- options = {};
321
- }
322
- var _options = options,
323
- _options$override = _options.override,
324
- _override = _options$override === void 0 ? [] : _options$override,
325
- include = _options.include,
326
- exclude = _options.exclude;
327
- var override = new Set(_override);
328
- var filterFunction = pluginutils.createFilter(include, exclude);
329
- var alias = {};
330
- var keys = override.keys();
331
- for (var _iterator = _createForOfIteratorHelperLoose(keys), _step; !(_step = _iterator()).done;) {
332
- var key = _step.value;
333
- alias['__overrideModule__' + key] = require.resolve("an-empty-js-file") + ("?__overrideModule__=" + encodeURIComponent(key));
334
- }
335
- return {
336
- name: 'overrideModule',
337
- enforce: 'post',
338
- config: function config(_config) {
339
- var _config$resolve$alias;
340
- if (!_config.optimizeDeps) _config.optimizeDeps = {};
341
- if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
342
- Object.keys(alias).forEach(function (key) {
343
- var _config$optimizeDeps;
344
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(key);
345
- });
346
- _config.optimizeDeps.needsInterop.push('an-empty-js-file');
347
- (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(alias).map(function (key) {
348
- return {
349
- find: key,
350
- replacement: alias[key]
351
- };
352
- }));
353
- },
354
- resolveId: function resolveId(id) {
355
- return alias[id];
356
- },
357
- transform: {
358
- handler: function handler(code, id) {
359
- if (!filterFunction(id)) return null;
360
- var ast;
361
- try {
362
- ast = this.parse(code, {
363
- allowReturnOutsideFunction: true
364
- });
365
- } catch (e) {
366
- throw new Error(id + ": " + e);
367
- }
368
- var s = new MagicString__default["default"](code);
369
- estreeWalker.walk(ast, {
370
- enter: function enter(node) {
371
- var replaceIfMatch = function replaceIfMatch(sourceNode) {
372
- if (sourceNode && sourceNode.value) {
373
- if (override.has(sourceNode.value)) {
374
- var start = sourceNode.start + 1; // Skip the opening quote
375
- var end = sourceNode.end - 1; // Skip the closing quote
376
- s.overwrite(start, end, '__overrideModule__' + sourceNode.value);
377
- }
378
- }
379
- };
380
- if (node.type === 'ImportDeclaration') {
381
- replaceIfMatch(node.source);
382
- }
383
- if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {
384
- replaceIfMatch(node.source);
385
- }
386
- if (node.type === 'CallExpression' && node.callee.type === 'Import' && node.arguments.length && node.arguments[0].type === 'Literal') {
387
- replaceIfMatch(node.arguments[0]);
388
- }
389
- if (node.type === 'CallExpression' && node.callee.name === 'require' && node.arguments.length && node.arguments[0].type === 'Literal') {
390
- replaceIfMatch(node.arguments[0]);
391
- }
392
- }
393
- });
394
- return {
395
- code: s.toString(),
396
- map: s.generateMap({
397
- hires: true
398
- })
399
- };
400
- }
401
- }
402
- };
250
+ function getLocalSharedImportMapPath() {
251
+ return path.resolve(emptyNpmDir, getLocalSharedImportMapFileName());
403
252
  }
404
-
405
- var emptyPath = require.resolve('an-empty-js-file');
406
- var filter = pluginutils.createFilter();
407
- var command = '';
408
- function wrapRemoteEntry() {
409
- return "\n import {init, get} from \"__mf__cwdRemoteEntry\"\n export {init, get}\n ";
253
+ function writeLocalSharedImportMap(pkgList) {
254
+ fs.writeFileSync(getLocalSharedImportMapPath(), "\n export default {\n " + pkgList.map(function (pkg) {
255
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
256
+ }).join(",") + "\n }\n ");
257
+ }
258
+ /**
259
+ * generate loadShare virtual module
260
+ */
261
+ var cacheMap1 = {};
262
+ function getLoadShareModulePath(pkg) {
263
+ var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
264
+ name = _getNormalizeModuleFe2.name;
265
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("__mf__loadShare_" + npmPackageNameToFileName(pkg) + ".js");
266
+ var filename = cacheMap1[pkg];
267
+ return path.resolve(emptyNpmDir, filename);
410
268
  }
411
- function wrapHostInit() {
412
- return "\n import {init} from \"__mf__cwdRemoteEntry\"\n init()\n ";
269
+ function writeLoadShareModule(pkg, shareItem, command) {
270
+ fs.writeFileSync(getLoadShareModulePath(pkg), "\n const {loadShare} = require(\"@module-federation/runtime\")\n const res = 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 const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "res.then(factory => factory())\n module.exports = exportModule\n ");
413
271
  }
272
+ function npmPackageNameToFileName(packageName) {
273
+ // 1. 去掉包名前的 "@"
274
+ // 2. 将包名中的 "/" 替换为 "__" 以避免文件路径问题
275
+ // 3. 去掉不合法的文件名字符
276
+ return packageName.replace(/^@/, '') // 移除作用域前缀 "@"
277
+ .replace(/\//g, '__') // 将 "/" 替换为 "__"
278
+ .replace(/[^a-zA-Z0-9_.-]/g, '_'); // 替换其他非法字符为 "_"
279
+ }
280
+
281
+ var emptyPath = require.resolve('an-empty-js-file');
282
+ var REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
414
283
  function generateRemoteEntry(options) {
415
284
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
416
285
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -419,9 +288,9 @@
419
288
  return item[1];
420
289
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
421
290
  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 ";
422
- }).join(',') + "\n }\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
291
+ }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
423
292
  var shareItem = options.shared[key];
424
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const pkg = await import(" + JSON.stringify(key) + ")\n return function () {\n return pkg\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
293
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n return function () {\n return res\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
425
294
  }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
426
295
  var remote = options.remotes[key];
427
296
  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 }\n ";
@@ -429,124 +298,315 @@
429
298
  return item[0] + "()";
430
299
  }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
431
300
  }
432
- function wrapShare(id, shared) {
433
- var shareConfig = shared[id].shareConfig;
301
+ var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?__mf__wrapRemoteEntry__';
302
+ function generateWrapRemoteEntry() {
303
+ return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
304
+ }
305
+ /**
306
+ * Inject entry file, automatically init when used as host,
307
+ * and will not inject remoteEntry
308
+ */
309
+ var HOST_AUTO_INIT = emptyPath + '?__mf__isHostInit';
310
+ function generateWrapHostInit() {
311
+ return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
312
+ }
313
+
314
+ var filter$1 = pluginutils.createFilter();
315
+ function pluginProxyRemoteEntry () {
434
316
  return {
435
- code: "\n import {loadShare} from \"@module-federation/runtime\"\n const res = await loadShare(" + JSON.stringify(id) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareConfig.singleton + ",\n strictVersion: " + JSON.stringify(shareConfig.strictVersion) + ",\n requiredVersion: " + JSON.stringify(shareConfig.requiredVersion) + "\n }}})\n export default res()\n ",
436
- map: null,
437
- syntheticNamedExports: 'default'
317
+ name: 'proxyRemoteEntry',
318
+ enforce: 'post',
319
+ resolveId: function resolveId(id) {
320
+ if (id === REMOTE_ENTRY_ID) {
321
+ return REMOTE_ENTRY_ID;
322
+ }
323
+ },
324
+ load: function load(id) {
325
+ if (id === REMOTE_ENTRY_ID) {
326
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
327
+ }
328
+ },
329
+ transform: function transform(code, id) {
330
+ try {
331
+ if (!filter$1(id)) return Promise.resolve();
332
+ if (id === REMOTE_ENTRY_ID) {
333
+ return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
334
+ }
335
+ if (id.includes(WRAP_REMOTE_ENTRY_PATH)) {
336
+ return Promise.resolve(generateWrapRemoteEntry());
337
+ }
338
+ if (id.includes(HOST_AUTO_INIT)) {
339
+ return Promise.resolve(generateWrapHostInit());
340
+ }
341
+ return Promise.resolve();
342
+ } catch (e) {
343
+ return Promise.reject(e);
344
+ }
345
+ }
438
346
  };
439
347
  }
440
- var con;
441
- function wrapRemote(id) {
348
+
349
+ function generateRemotes(id, command) {
442
350
  return {
443
- code: "\n import {loadRemote} from \"@module-federation/runtime\"\n export " + (command !== 'build' ? 'default' : 'const dynamicExport = ') + " await loadRemote(" + JSON.stringify(id) + ")\n ",
351
+ code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
444
352
  map: null,
445
- syntheticNamedExports: 'dynamicExport'
353
+ // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
354
+ syntheticNamedExports: '__mf__dynamicExports'
446
355
  };
447
356
  }
448
- function federation(mfUserOptions) {
449
- var options = normalizeModuleFederationOptions(mfUserOptions);
450
- var remotes = options.remotes,
451
- shared = options.shared,
452
- filename = options.filename;
453
- var alias = [{
454
- find: '@module-federation/runtime',
455
- replacement: require.resolve('@module-federation/runtime')
456
- }];
457
- Object.keys(remotes).forEach(function (key) {
458
- var remote = remotes[key];
459
- alias.push({
460
- find: new RegExp("(" + remote.name + "(/.*|$)?)"),
461
- replacement: '$1',
462
- customResolver: function customResolver(source) {
463
- if (!con.optimizeDeps) con.optimizeDeps = {};
464
- if (!con.optimizeDeps.needsInterop) con.optimizeDeps.needsInterop = [];
465
- if (con.optimizeDeps.needsInterop.indexOf(source) === -1) con.optimizeDeps.needsInterop.push(source);
466
- return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
467
- }
468
- });
469
- });
470
- var remotePrefixList = Object.keys(remotes);
471
- // pkgname will be escaped, and matching path also needs to be processed in the same way:
472
- // @json2csv/plainjs --> .vite/deps/@json2csv_plainjs
473
- var sharedKeyMatchList = Object.keys(shared).map(function (item) {
474
- return "__overrideModule__" + item.replace('/', '_');
357
+
358
+ var filter = pluginutils.createFilter();
359
+ function pluginProxyRemotes (options) {
360
+ var command;
361
+ var remotes = options.remotes;
362
+ var matchRemotesList = Object.keys(remotes).map(function (item) {
363
+ return item.replace(/\//g, "_");
475
364
  });
476
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
477
- entryName: 'remoteEntry',
478
- entryPath: emptyPath + '?__mf__wrapRemoteEntry__',
479
- fileName: filename
480
- }), addEntry({
481
- entryName: 'hostInit',
482
- entryPath: emptyPath + '?__mf__isHostInit'
483
- }), [overrideModule({
484
- override: Object.keys(shared)
485
- }), {
486
- name: 'module-federation-vite',
487
- enforce: 'post',
365
+ return {
366
+ name: "proxyRemotes",
488
367
  config: function config(_config, _ref) {
489
- var _config$resolve$alias, _config$optimizeDeps;
490
368
  var _command = _ref.command;
491
- con = _config;
492
369
  command = _command;
493
- (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, alias);
494
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
495
- Object.keys(shared).forEach(function (key) {
496
- var _config$optimizeDeps2;
497
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(key);
370
+ Object.keys(remotes).forEach(function (key) {
371
+ var remote = remotes[key];
372
+ _config.resolve.alias.push({
373
+ find: new RegExp("(" + remote.name + "(/.*|$)?)"),
374
+ replacement: '$1',
375
+ customResolver: function customResolver(source) {
376
+ if (!_config.optimizeDeps) _config.optimizeDeps = {};
377
+ if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
378
+ if (_config.optimizeDeps.needsInterop.indexOf(source) === -1) _config.optimizeDeps.needsInterop.push(source);
379
+ return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
380
+ }
381
+ });
498
382
  });
499
383
  },
500
- resolveId: function resolveId(id) {
501
- if (id === '__mf__cwdRemoteEntry') {
502
- return '__mf__cwdRemoteEntry';
503
- }
504
- },
505
- load: function load(id) {
506
- if (id === '__mf__cwdRemoteEntry') {
507
- return generateRemoteEntry(options);
508
- }
509
- },
510
384
  transform: function transform(code, id) {
511
385
  try {
512
386
  if (!filter(id)) return Promise.resolve();
513
- if (id === '__mf__cwdRemoteEntry') {
514
- return Promise.resolve(generateRemoteEntry(options));
515
- }
516
- if (id.indexOf('__mf__wrapRemoteEntry__') > -1) {
517
- return Promise.resolve(wrapRemoteEntry());
518
- }
519
- if (id.indexOf('__mf__isHostInit') > -1) {
520
- return Promise.resolve(wrapHostInit());
521
- }
522
- if (id.indexOf('__mf__cwdRemoteEntry') > -1) {
523
- return Promise.resolve(generateRemoteEntry(options));
524
- }
525
- var _ref2 = sharedKeyMatchList.length && id.match(new RegExp("/(" + sharedKeyMatchList.join('|') + ")(_.*.js|.js)")) || [],
526
- devSharedModuleName = _ref2[0];
527
- if (devSharedModuleName) {
528
- return Promise.resolve(wrapShare(devSharedModuleName.replace('/__overrideModule__', '').replace(/_/g, '/').replace('.js', ''), shared));
529
- }
530
- var _ref3 = id.match(/\_\_overrideModule\_\_=[^&]+/) || [],
531
- prodSharedName = _ref3[0];
532
- if (prodSharedName) {
533
- return Promise.resolve(wrapShare(decodeURIComponent(prodSharedName.replace('__overrideModule__=', '')), shared));
534
- }
535
- var _ref4 = remotePrefixList.length && id.match(new RegExp("/(" + remotePrefixList.join('|') + ")(_.*.js|.js)")) || [],
536
- devRemoteModuleName = _ref4[0];
387
+ var _ref2 = matchRemotesList.length && id.match(new RegExp("/(" + matchRemotesList.join('|') + ")(_.*.js|.js)")) || [],
388
+ devRemoteModuleName = _ref2[0];
537
389
  if (devRemoteModuleName) {
538
- return Promise.resolve(wrapRemote(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', '')));
390
+ return Promise.resolve(generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command));
539
391
  }
540
- var _ref5 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
541
- prodRemoteName = _ref5[0];
392
+ var _ref3 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
393
+ prodRemoteName = _ref3[0];
542
394
  if (prodRemoteName) {
543
- return Promise.resolve(wrapRemote(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', ''))));
395
+ return Promise.resolve(generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command));
544
396
  }
545
397
  return Promise.resolve();
546
398
  } catch (e) {
547
399
  return Promise.reject(e);
548
400
  }
549
401
  }
402
+ };
403
+ }
404
+
405
+ function proxySharedModule(options) {
406
+ var _options$shared = options.shared,
407
+ shared = _options$shared === void 0 ? {} : _options$shared,
408
+ include = options.include,
409
+ exclude = options.exclude;
410
+ var filterFunction = pluginutils.createFilter(include, exclude);
411
+ writeLocalSharedImportMap(Object.keys(shared));
412
+ return [{
413
+ name: 'preBuildShared',
414
+ enforce: 'post',
415
+ config: function config(_config, _ref) {
416
+ var _config$resolve$alias, _config$resolve$alias2;
417
+ var command = _ref.command;
418
+ // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
419
+ // config.optimizeDeps.needsInterop.push('an-empty-js-file');
420
+ (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
421
+ var _config$optimizeDeps;
422
+ _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
423
+ // write proxyFile
424
+ writeLoadShareModule(key, shared[key], command);
425
+ var preBuildLibPath = getLoadShareModulePath(key);
426
+ return {
427
+ // Intercept all dependency requests to the proxy module
428
+ // Dependency requests issued by localSharedImportMap are allowed without proxying.
429
+ find: new RegExp("^" + key + "$"),
430
+ replacement: preBuildLibPath,
431
+ customResolver: function customResolver(source, importer) {
432
+ if (importer.includes("node_modules/" + key + "/")) {
433
+ return this.resolve(key);
434
+ }
435
+ return this.resolve(preBuildLibPath);
436
+ }
437
+ };
438
+ }));
439
+ (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
440
+ return {
441
+ find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
442
+ customResolver: function customResolver(source, importer) {
443
+ return this.resolve(key);
444
+ }
445
+ };
446
+ }));
447
+ }
448
+ }, {
449
+ name: "prebuild-top-level-await",
450
+ apply: "serve",
451
+ transform: function transform(code, id) {
452
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
453
+ return null;
454
+ }
455
+ if (!filterFunction(id)) return null;
456
+ var ast;
457
+ try {
458
+ ast = this.parse(code, {
459
+ allowReturnOutsideFunction: true
460
+ });
461
+ } catch (e) {
462
+ throw new Error(id + ": " + e);
463
+ }
464
+ var magicString = new MagicString__default["default"](code);
465
+ estreeWalker.walk(ast, {
466
+ enter: function enter(node) {
467
+ // 处理命名导出
468
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
469
+ var exportSpecifiers = node.specifiers.map(function (specifier) {
470
+ return specifier.exported.name;
471
+ });
472
+ var proxyStatements = exportSpecifiers.map(function (name) {
473
+ return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
474
+ }).join('\n');
475
+ var exportStatements = exportSpecifiers.map(function (name) {
476
+ return "__mfproxy__" + name + " as " + name;
477
+ }).join(', ');
478
+ var start = node.start;
479
+ var end = node.end;
480
+ var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
481
+ magicString.overwrite(start, end, replacement);
482
+ }
483
+ // 处理默认导出
484
+ if (node.type === 'ExportDefaultDeclaration') {
485
+ var declaration = node.declaration;
486
+ var _start = node.start;
487
+ var _end = node.end;
488
+ var proxyStatement;
489
+ var exportStatement = 'default';
490
+ if (declaration.type === 'Identifier') {
491
+ // 处理标识符 (如: export default foo;)
492
+ proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
493
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
494
+ // 处理调用表达式或函数声明 (如: export default someFunction();)
495
+ var declarationCode = code.slice(declaration.start, declaration.end);
496
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
497
+ } else {
498
+ // 其他类型 (可以根据需要添加更多处理逻辑)
499
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
500
+ }
501
+ var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
502
+ magicString.overwrite(_start, _end, _replacement);
503
+ }
504
+ }
505
+ });
506
+ return {
507
+ code: magicString.toString(),
508
+ map: magicString.generateMap({
509
+ hires: true
510
+ })
511
+ };
512
+ }
513
+ }];
514
+ }
515
+
516
+ var aliasToArrayPlugin = {
517
+ name: 'alias-transform-plugin',
518
+ config: function config(_config, _ref) {
519
+ if (!_config.resolve) _config.resolve = {};
520
+ if (!_config.resolve.alias) _config.resolve.alias = [];
521
+ var alias = _config.resolve.alias;
522
+ if (typeof alias === 'object' && !Array.isArray(alias)) {
523
+ _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
524
+ var find = _ref2[0],
525
+ replacement = _ref2[1];
526
+ return {
527
+ find: find,
528
+ replacement: replacement
529
+ };
530
+ });
531
+ }
532
+ }
533
+ };
534
+
535
+ var normalizeBuildPlugin = (function (singleChunkModules) {
536
+ return {
537
+ name: 'normalizeBuild',
538
+ config: function config(_config, _ref) {
539
+ if (!_config.build) _config.build = {};
540
+ if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
541
+ var rollupOptions = _config.build.rollupOptions;
542
+ if (!rollupOptions.output) rollupOptions.output = {};
543
+ normalizeManualChunks(rollupOptions.output, singleChunkModules);
544
+ }
545
+ };
546
+ });
547
+ function normalizeManualChunks(output, singleChunkModules) {
548
+ var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
549
+ if (!output.manualChunks) output.manualChunks = {};
550
+ var wrapManualChunks = function wrapManualChunks(original) {
551
+ return function (id) {
552
+ var _ref2 = id.match(pattern) || [],
553
+ moduleName = _ref2[1];
554
+ if (moduleName) {
555
+ return moduleName;
556
+ }
557
+ if (typeof original === 'function') {
558
+ return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
559
+ }
560
+ if (typeof original === 'object' && original) {
561
+ return original[id];
562
+ }
563
+ };
564
+ };
565
+ output.manualChunks = wrapManualChunks(output.manualChunks);
566
+ }
567
+
568
+ var normalizeOptimizeDepsPlugin = {
569
+ name: 'normalizeOptimizeDeps',
570
+ config: function config(_config, _ref) {
571
+ var optimizeDeps = _config.optimizeDeps;
572
+ if (!optimizeDeps) {
573
+ _config.optimizeDeps = {};
574
+ optimizeDeps = _config.optimizeDeps;
575
+ }
576
+ if (!optimizeDeps.include) optimizeDeps.include = [];
577
+ if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
578
+ }
579
+ };
580
+
581
+ function federation(mfUserOptions) {
582
+ var options = normalizeModuleFederationOptions(mfUserOptions);
583
+ var name = options.name,
584
+ shared = options.shared,
585
+ filename = options.filename;
586
+ if (!name) throw new Error("name is required");
587
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
588
+ entryName: 'remoteEntry',
589
+ entryPath: WRAP_REMOTE_ENTRY_PATH,
590
+ fileName: filename
591
+ }), addEntry({
592
+ entryName: 'hostInit',
593
+ entryPath: HOST_AUTO_INIT
594
+ }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], proxySharedModule({
595
+ shared: shared
596
+ }), [{
597
+ name: 'module-federation-vite',
598
+ enforce: 'post',
599
+ config: function config(_config, _ref) {
600
+ var _config$optimizeDeps;
601
+ _config.resolve.alias.push({
602
+ find: '@module-federation/runtime',
603
+ replacement: require.resolve('@module-federation/runtime')
604
+ });
605
+ (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
606
+ // Object.keys(shared).forEach((key) => {
607
+ // config.optimizeDeps?.include?.push(key);
608
+ // });
609
+ }
550
610
  }]);
551
611
  }
552
612