@module-federation/vite 1.0.0-alpha-2f53b4e → 1.0.0-alpha-b1bba84

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.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  var fs = require('fs');
2
2
  var path = require('pathe');
3
3
  var pluginutils = require('@rollup/pluginutils');
4
- var defu = require('defu');
5
4
  var estreeWalker = require('estree-walker');
6
5
  var MagicString = require('magic-string');
6
+ var defu = require('defu');
7
7
 
8
8
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
9
 
@@ -34,16 +34,22 @@ var addEntry = function addEntry(_ref) {
34
34
  var entryName = _ref.entryName,
35
35
  entryPath = _ref.entryPath,
36
36
  fileName = _ref.fileName;
37
+ var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
37
38
  var entryFiles = [];
38
39
  var htmlFilePath;
40
+ var _command;
39
41
  return [{
40
42
  name: 'add-entry',
41
43
  apply: "serve",
44
+ config: function config(_config, _ref2) {
45
+ var command = _ref2.command;
46
+ _command = command;
47
+ },
42
48
  configureServer: function configureServer(server) {
43
49
  var _server$httpServer;
44
50
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
45
51
  var port = server.config.server.port;
46
- fetch(path__namespace.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
52
+ fetch(path__namespace.join("http://localhost:" + port, "" + devEntryPath))["catch"](function (e) {});
47
53
  });
48
54
  server.middlewares.use(function (req, res, next) {
49
55
  if (!fileName) {
@@ -51,18 +57,17 @@ var addEntry = function addEntry(_ref) {
51
57
  return;
52
58
  }
53
59
  if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
54
- req.url = entryPath;
60
+ req.url = devEntryPath;
55
61
  }
56
62
  next();
57
63
  });
58
64
  },
59
65
  transformIndexHtml: function transformIndexHtml(c) {
60
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
66
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
61
67
  }
62
68
  }, {
63
69
  name: "add-entry",
64
70
  enforce: "post",
65
- apply: "build",
66
71
  configResolved: function configResolved(config) {
67
72
  var inputOptions = config.build.rollupOptions.input;
68
73
  if (!inputOptions) {
@@ -80,6 +85,7 @@ var addEntry = function addEntry(_ref) {
80
85
  },
81
86
  buildStart: function buildStart() {
82
87
  var _this$emitFile;
88
+ if (_command === "serve") return;
83
89
  var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
84
90
  this.emitFile((_this$emitFile = {
85
91
  name: entryName
@@ -104,46 +110,105 @@ var addEntry = function addEntry(_ref) {
104
110
  }];
105
111
  };
106
112
 
107
- var _resolve,
108
- promise = new Promise(function (resolve, reject) {
109
- _resolve = resolve;
110
- });
111
- var parsePromise = promise;
112
- var parseStartSet = new Set();
113
- var parseEndSet = new Set();
114
- function pluginModuleParseEnd (excludeFn) {
115
- return [{
116
- name: "_",
113
+ /**
114
+ * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
115
+ */
116
+ function PluginDevProxyModuleTopLevelAwait() {
117
+ var filterFunction = pluginutils.createFilter();
118
+ return {
119
+ name: "dev-proxy-module-top-level-await",
117
120
  apply: "serve",
118
- config: function config() {
119
- // No waiting in development mode
120
- _resolve(1);
121
- }
122
- }, {
123
- enforce: "pre",
124
- name: "parseStart",
125
- apply: "build",
126
- load: function load(id) {
127
- if (excludeFn(id)) {
128
- return;
129
- }
130
- parseStartSet.add(id);
131
- }
132
- }, {
133
- enforce: "post",
134
- name: "parseEnd",
135
- apply: "build",
136
- moduleParsed: function moduleParsed(module) {
137
- var id = module.id;
138
- if (excludeFn(id)) {
139
- return;
121
+ transform: function transform(code, id) {
122
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
123
+ return null;
140
124
  }
141
- parseEndSet.add(id);
142
- if (parseStartSet.size === parseEndSet.size) {
143
- _resolve(1);
125
+ if (!filterFunction(id)) return null;
126
+ var ast;
127
+ try {
128
+ ast = this.parse(code, {
129
+ allowReturnOutsideFunction: true
130
+ });
131
+ } catch (e) {
132
+ throw new Error(id + ": " + e);
144
133
  }
134
+ var magicString = new MagicString__default["default"](code);
135
+ estreeWalker.walk(ast, {
136
+ enter: function enter(node) {
137
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
138
+ var exportSpecifiers = node.specifiers.map(function (specifier) {
139
+ return specifier.exported.name;
140
+ });
141
+ var proxyStatements = exportSpecifiers.map(function (name) {
142
+ return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
143
+ }).join('\n');
144
+ var exportStatements = exportSpecifiers.map(function (name) {
145
+ return "__mfproxy__" + name + " as " + name;
146
+ }).join(', ');
147
+ var start = node.start;
148
+ var end = node.end;
149
+ var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
150
+ magicString.overwrite(start, end, replacement);
151
+ }
152
+ if (node.type === 'ExportDefaultDeclaration') {
153
+ var declaration = node.declaration;
154
+ var _start = node.start;
155
+ var _end = node.end;
156
+ var proxyStatement;
157
+ var exportStatement = 'default';
158
+ if (declaration.type === 'Identifier') {
159
+ // example: export default foo;
160
+ proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
161
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
162
+ // example: export default someFunction();
163
+ var declarationCode = code.slice(declaration.start, declaration.end);
164
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
165
+ } else {
166
+ // other
167
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
168
+ }
169
+ var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
170
+ magicString.overwrite(_start, _end, _replacement);
171
+ }
172
+ }
173
+ });
174
+ return {
175
+ code: magicString.toString(),
176
+ map: magicString.generateMap({
177
+ hires: true
178
+ })
179
+ };
145
180
  }
146
- }];
181
+ };
182
+ }
183
+
184
+ function _arrayLikeToArray(r, a) {
185
+ (null == a || a > r.length) && (a = r.length);
186
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
187
+ return n;
188
+ }
189
+ function _createForOfIteratorHelperLoose(r, e) {
190
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
191
+ if (t) return (t = t.call(r)).next.bind(t);
192
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
193
+ t && (r = t);
194
+ var o = 0;
195
+ return function () {
196
+ return o >= r.length ? {
197
+ done: !0
198
+ } : {
199
+ done: !1,
200
+ value: r[o++]
201
+ };
202
+ };
203
+ }
204
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
205
+ }
206
+ function _unsupportedIterableToArray(r, a) {
207
+ if (r) {
208
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
209
+ var t = {}.toString.call(r).slice(8, -1);
210
+ 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;
211
+ }
147
212
  }
148
213
 
149
214
  function normalizeExposesItem(key, item) {
@@ -196,7 +261,7 @@ function normalizeRemoteItem(key, remote) {
196
261
  entryGlobalName: key
197
262
  }, remote);
198
263
  }
199
- function removePathFromNpmPackage$1(packageString) {
264
+ function removePathFromNpmPackage(packageString) {
200
265
  // 匹配npm包名的正则表达式,忽略路径部分
201
266
  var regex = /^(?:@[^/]+\/)?[^/]+/;
202
267
  // 使用正则表达式匹配并提取包名
@@ -207,7 +272,7 @@ function removePathFromNpmPackage$1(packageString) {
207
272
  function normalizeShareItem(key, shareItem) {
208
273
  var version;
209
274
  try {
210
- version = require(path__namespace.join(removePathFromNpmPackage$1(key), 'package.json')).version;
275
+ version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
211
276
  } catch (e) {
212
277
  console.log(e);
213
278
  }
@@ -255,10 +320,28 @@ function normalizeLibrary(library) {
255
320
  if (!library) return undefined;
256
321
  return library;
257
322
  }
323
+ function normalizeManifest(manifest) {
324
+ if (manifest === void 0) {
325
+ manifest = false;
326
+ }
327
+ if (typeof manifest === "boolean") {
328
+ return manifest;
329
+ }
330
+ return Object.assign({
331
+ filePath: "",
332
+ disableAssetsAnalyze: false,
333
+ fileName: "mf-manifest.json"
334
+ }, manifest);
335
+ }
258
336
  var config;
259
337
  function getNormalizeModuleFederationOptions() {
260
338
  return config;
261
339
  }
340
+ function getNormalizeShareItem(key) {
341
+ var options = getNormalizeModuleFederationOptions();
342
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
343
+ return shareItem;
344
+ }
262
345
  function normalizeModuleFederationOptions(options) {
263
346
  return config = {
264
347
  exposes: normalizeExposes(options.exposes),
@@ -273,7 +356,7 @@ function normalizeModuleFederationOptions(options) {
273
356
  runtimePlugins: options.runtimePlugins || [],
274
357
  getPublicPath: options.getPublicPath,
275
358
  implementation: options.implementation,
276
- manifest: options.manifest,
359
+ manifest: normalizeManifest(options.manifest),
277
360
  dev: options.dev,
278
361
  dts: options.dts
279
362
  };
@@ -288,33 +371,42 @@ function normalizeModuleFederationOptions(options) {
288
371
  * . => 4
289
372
  */
290
373
  /**
291
- * @param {*} name "@scope/xx-xx.xx" => "__$1__scope__$2__xx__$3__xx$__4__xx"
374
+ * Encodes a package name into a valid file name.
375
+ * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
376
+ * @returns {string} - The encoded file name.
292
377
  */
293
378
  function packageNameEncode(name) {
294
379
  if (typeof name !== "string") throw new Error("A string package name is required");
295
- return name.replace(/\@/g, "__$1__").replace(/\//g, "__$2__").replace(/\-/g, "__$3__").replace(/\./g, "__$4__");
380
+ return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
296
381
  }
297
382
  /**
298
- * @param {*} global "__$1__scope__$2__xx__$3__xx$__4__xx" => "@scope/xx-xx.xx"
383
+ * Decodes an encoded file name back to the original package name.
384
+ * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
385
+ * @returns {string} - The decoded package name.
299
386
  */
300
- function packageNameDecode(global) {
301
- if (typeof global !== "string") throw new Error("A string global variable name is required");
302
- return global.replace(/\_\_\$1\_\_/g, "@").replace(/\_\_\$2\_\_/g, "/").replace(/\_\_\$3\_\_/g, "-").replace(/\_\_\$4\_\_/g, ".");
387
+ function packageNameDecode(encoded) {
388
+ if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
389
+ return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
303
390
  }
304
- function removePathFromNpmPackage(packageString) {
305
- // Regular expression to match npm package name, ignoring path parts
306
- var regex = /^(?:@[^/]+\/)?[^/]+/;
307
- // Use regular expression to match and extract the package name
308
- var match = packageString.match(regex);
309
- // Return the matched package name or the original string if no match is found
310
- return match ? match[0] : packageString;
391
+
392
+ /**
393
+ * https://github.com/module-federation/vite/issues/68
394
+ */
395
+ function getLocalSharedImportMapPath_windows() {
396
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
397
+ name = _getNormalizeModuleFe.name;
398
+ return path__default["default"].resolve(".__mf__win", packageNameEncode(name), "localSharedImportMap");
399
+ }
400
+ function writeLocalSharedImportMap_windows(content) {
401
+ var localSharedImportMapId = getLocalSharedImportMapPath_windows();
402
+ createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
311
403
  }
312
- function getExtFromNpmPackage(packageString) {
313
- var pkgName = removePathFromNpmPackage(packageString);
314
- var subpath = packageString.replace(pkgName, "");
315
- var parts = subpath.split('.');
316
- var ext = parts.length > 1 ? "." + parts.pop() : undefined;
317
- return ext;
404
+ function createFile(filePath, content) {
405
+ var dir = path__default["default"].dirname(filePath);
406
+ fs.mkdirSync(dir, {
407
+ recursive: true
408
+ });
409
+ fs.writeFileSync(filePath, content);
318
410
  }
319
411
 
320
412
  var nodeModulesDir = function findNodeModulesDir(startDir) {
@@ -340,28 +432,47 @@ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "package.json"
340
432
  name: virtualPackageName,
341
433
  main: "empty.js"
342
434
  }));
435
+ var patternMap = {};
436
+ var cacheMap = {};
343
437
  /**
344
438
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
345
439
  */
346
440
  var VirtualModule = /*#__PURE__*/function () {
347
- function VirtualModule(name, ext) {
348
- if (ext === void 0) {
349
- ext = ".js";
441
+ function VirtualModule(name, tag, suffix) {
442
+ var _name$split$slice$pop;
443
+ if (tag === void 0) {
444
+ tag = '__mf_v__';
445
+ }
446
+ if (suffix === void 0) {
447
+ suffix = "";
350
448
  }
351
- this.originName = void 0;
449
+ this.name = void 0;
450
+ this.tag = void 0;
451
+ this.suffix = void 0;
352
452
  this.inited = false;
353
- this.ext = void 0;
354
- this.originName = name;
355
- this.ext = ext;
453
+ this.name = name;
454
+ this.tag = tag;
455
+ this.suffix = suffix || ((_name$split$slice$pop = name.split(".").slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, ".$1")) || ".js";
456
+ if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
457
+ cacheMap[this.tag][this.name] = this;
356
458
  }
459
+ VirtualModule.findModule = function findModule(tag, str) {
460
+ if (str === void 0) {
461
+ str = "";
462
+ }
463
+ if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
464
+ var moduleName = (str.match(patternMap[tag]) || [])[2];
465
+ if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
466
+ return undefined;
467
+ };
357
468
  var _proto = VirtualModule.prototype;
358
469
  _proto.getPath = function getPath() {
359
470
  return path.resolve(nodeModulesDir, this.getImportId());
360
471
  };
361
472
  _proto.getImportId = function getImportId() {
362
473
  var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
363
- name = _getNormalizeModuleFe.name;
364
- return virtualPackageName + "/" + packageNameEncode(name) + "-" + packageNameEncode(this.originName) + this.ext;
474
+ mfName = _getNormalizeModuleFe.name;
475
+ return virtualPackageName + "/" + packageNameEncode("" + mfName + this.tag + this.name + this.tag) + this.suffix;
365
476
  };
366
477
  _proto.writeSync = function writeSync(code, force) {
367
478
  if (!force && this.inited) return;
@@ -376,24 +487,33 @@ var VirtualModule = /*#__PURE__*/function () {
376
487
  return VirtualModule;
377
488
  }();
378
489
 
379
- /**
380
- * https://github.com/module-federation/vite/issues/68
381
- */
382
- function getLocalSharedImportMapPath_windows() {
383
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
384
- name = _getNormalizeModuleFe.name;
385
- return path__default["default"].resolve(".__mf__win", packageNameEncode(name), "localSharedImportMap");
490
+ var virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
491
+ function writeRuntimeInitStatus() {
492
+ virtualRuntimeInitStatus.writeSync("\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n export {\n initPromise,\n initResolve,\n initReject\n }\n ");
386
493
  }
387
- function writeLocalSharedImportMap_windows(content) {
388
- var localSharedImportMapId = getLocalSharedImportMapPath_windows();
389
- createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
494
+
495
+ var cacheRemoteMap = {};
496
+ var LOAD_REMOTE_TAG = '__loadRemote__';
497
+ function getRemoteVirtualModule(remote, command) {
498
+ if (!cacheRemoteMap[remote]) {
499
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
500
+ cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
501
+ }
502
+ var virtual = cacheRemoteMap[remote];
503
+ return virtual;
390
504
  }
391
- function createFile(filePath, content) {
392
- var dir = path__default["default"].dirname(filePath);
393
- fs.mkdirSync(dir, {
394
- recursive: true
395
- });
396
- fs.writeFileSync(filePath, content);
505
+ var usedRemotesMap = {
506
+ // remote1: {remote1/App, remote1, remote1/Button}
507
+ };
508
+ function addUsedRemote(remoteKey, remoteModule) {
509
+ if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
510
+ usedRemotesMap[remoteKey].add(remoteModule);
511
+ }
512
+ function getUsedRemotesMap() {
513
+ return usedRemotesMap;
514
+ }
515
+ function generateRemotes(id, command) {
516
+ return "\n const {loadRemote} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => 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 ";
397
517
  }
398
518
 
399
519
  /**
@@ -402,63 +522,35 @@ function createFile(filePath, content) {
402
522
  * You can only proxy to the real file through alias
403
523
  */
404
524
  // *** __prebuild__
405
-
406
- var generateLocalSharedImportMap = function generateLocalSharedImportMap() {
407
- return Promise.resolve(parsePromise).then(function () {
408
- var options = getNormalizeModuleFederationOptions();
409
- return "\n const localSharedImportMap = {\n " + Array.from(shareds).map(function (pkg) {
410
- return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
411
- }).join(",") + "\n }\n const localShared = {\n " + Array.from(shareds).map(function (key) {
412
- var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
413
- 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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \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 }\n }\n ";
414
- }).join(',') + "\n }\n export default localShared\n ";
415
- });
416
- };
417
- // *** __loadShare__
418
- var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
419
- try {
420
- var _exit;
421
- var sharedCount = shareds.size;
422
- return Promise.resolve(function () {
423
- if (prevSharedCount !== sharedCount) {
424
- var _temp2 = function _temp2(_result) {
425
- if (_exit) return _result;
426
- var _writeSync = localSharedImportMapModule.writeSync;
427
- return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI2) {
428
- return _writeSync.call(localSharedImportMapModule, _generateLocalSharedI2, true);
429
- });
430
- };
431
- prevSharedCount = sharedCount;
432
- var _temp = function () {
433
- if (process.platform === "win32") {
434
- return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI) {
435
- var _writeLocalSharedImpo = writeLocalSharedImportMap_windows(_generateLocalSharedI);
436
- _exit = 1;
437
- return _writeLocalSharedImpo;
438
- });
439
- }
440
- }();
441
- return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
442
- }
443
- }());
444
- } catch (e) {
445
- return Promise.reject(e);
446
- }
447
- };
448
525
  var preBuildCacheMap = {};
449
526
  var PREBUILD_TAG = "__prebuild__";
450
527
  function writePreBuildLibPath(pkg) {
451
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
528
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
452
529
  preBuildCacheMap[pkg].writeSync("");
453
530
  }
454
531
  function getPreBuildLibImportId(pkg) {
455
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
532
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
456
533
  var importId = preBuildCacheMap[pkg].getImportId();
457
534
  return importId;
458
535
  }
459
- var shareds = new Set();
460
- function addShare(pkg) {
461
- shareds.add(pkg);
536
+ // *** __loadShare__
537
+ var LOAD_SHARE_TAG = "__loadShare__";
538
+ var loadShareCacheMap = {};
539
+ function getLoadShareModulePath(pkg) {
540
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
541
+ var filepath = loadShareCacheMap[pkg].getPath();
542
+ return filepath;
543
+ }
544
+ function writeLoadShareModule(pkg, shareItem, command) {
545
+ loadShareCacheMap[pkg].writeSync("\n \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 {loadShare} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => 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 ");
546
+ }
547
+
548
+ var usedShares = new Set();
549
+ function getUsedShares() {
550
+ return usedShares;
551
+ }
552
+ function addUsedShares(pkg) {
553
+ usedShares.add(pkg);
462
554
  }
463
555
  // *** Expose locally provided shared modules here
464
556
  var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
@@ -468,43 +560,42 @@ function getLocalSharedImportMapPath() {
468
560
  }
469
561
  return localSharedImportMapModule.getPath();
470
562
  }
471
- var prevSharedCount = 0;
472
- var LOAD_SHARE_TAG = "__loadShare__";
473
- var loadShareCacheMap = {};
474
- function getLoadShareModulePath(pkg) {
475
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(LOAD_SHARE_TAG + pkg);
476
- var filepath = loadShareCacheMap[pkg].getPath();
477
- return filepath;
563
+ var prevSharedCount;
564
+ function writeLocalSharedImportMap() {
565
+ var sharedCount = getUsedShares().size;
566
+ if (prevSharedCount !== sharedCount) {
567
+ prevSharedCount = sharedCount;
568
+ if (process.platform === "win32") {
569
+ writeLocalSharedImportMap_windows(generateLocalSharedImportMap());
570
+ } else {
571
+ localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true);
572
+ }
573
+ }
478
574
  }
479
- function writeLoadShareModule(pkg, shareItem, command) {
480
- 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 {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 ");
575
+ function generateLocalSharedImportMap() {
576
+ var options = getNormalizeModuleFederationOptions();
577
+ return "\n const importMap = {\n " + Array.from(getUsedShares()).map(function (pkg) {
578
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
579
+ }).join(",") + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
580
+ var shareItem = getNormalizeShareItem(key);
581
+ 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 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 }\n }\n ";
582
+ }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
583
+ var remote = options.remotes[key];
584
+ 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 ";
585
+ }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
481
586
  }
482
-
483
- var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
587
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
484
588
  function generateRemoteEntry(options) {
485
589
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
486
590
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
487
591
  });
488
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n \n " + pluginImportNames.map(function (item) {
592
+ return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
489
593
  return item[1];
490
594
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
491
595
  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 ";
492
- }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapPath() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
493
- var remote = options.remotes[key];
494
- 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 ";
495
- }).join(',') + "\n ],\n shared: localSharedImportMap,\n plugins: [" + pluginImportNames.map(function (item) {
596
+ }).join(',') + "\n }\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
496
597
  return item[0] + "()";
497
- }).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 ";
498
- }
499
- var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
500
- function writeWrapRemoteEntry() {
501
- wrapRemoteEntryModule.writeSync("\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ");
502
- }
503
- function getWrapRemoteEntryImportId() {
504
- return wrapRemoteEntryModule.getImportId();
505
- }
506
- function getWrapRemoteEntryPath() {
507
- return wrapRemoteEntryModule.getPath();
598
+ }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
508
599
  }
509
600
  /**
510
601
  * Inject entry file, automatically init when used as host,
@@ -521,27 +612,401 @@ function getHostAutoInitPath() {
521
612
  return hostAutoInitModule.getPath();
522
613
  }
523
614
 
524
- var remoteVirtualModule = new VirtualModule("remoteModule");
525
- function writeRemote() {
526
- remoteVirtualModule.writeSync("");
527
- }
528
- function generateRemotes(id, command) {
529
- return {
530
- 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 ",
531
- map: null,
532
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
533
- syntheticNamedExports: '__mf__dynamicExports'
534
- };
535
- }
536
-
537
615
  function initVirtualModules() {
538
616
  writeLocalSharedImportMap();
539
- writeWrapRemoteEntry();
540
617
  writeHostAutoInit();
541
- writeRemote();
618
+ writeRuntimeInitStatus();
542
619
  }
543
620
 
544
- var filter$1 = pluginutils.createFilter();
621
+ var Manifest = function Manifest() {
622
+ var mfOptions = getNormalizeModuleFederationOptions();
623
+ var name = mfOptions.name,
624
+ filename = mfOptions.filename,
625
+ manifestOptions = mfOptions.manifest;
626
+ var mfManifestName = "";
627
+ if (manifestOptions === true) {
628
+ mfManifestName = "mf-manifest.json";
629
+ }
630
+ if (typeof manifestOptions !== "boolean") {
631
+ mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || "", (manifestOptions == null ? void 0 : manifestOptions.fileName) || "");
632
+ }
633
+ var extensions;
634
+ var root;
635
+ var remoteEntryFile;
636
+ return [{
637
+ name: 'moddule-federation-manifest',
638
+ apply: 'serve',
639
+ configureServer: function configureServer(server) {
640
+ server.middlewares.use(function (req, res, next) {
641
+ if (!mfManifestName) {
642
+ next();
643
+ return;
644
+ }
645
+ if (req.url === mfManifestName.replace(/^\/?/, "/")) {
646
+ res.setHeader('Content-Type', 'application/json');
647
+ res.setHeader('Access-Control-Allow-Origin', '*');
648
+ res.end(JSON.stringify({
649
+ id: name,
650
+ name: name,
651
+ metaData: {
652
+ name: name,
653
+ type: 'app',
654
+ buildInfo: {
655
+ buildVersion: '1.0.0',
656
+ buildName: name
657
+ },
658
+ remoteEntry: {
659
+ name: filename,
660
+ path: '',
661
+ type: 'module'
662
+ },
663
+ ssrRemoteEntry: {
664
+ name: filename,
665
+ path: '',
666
+ type: 'module'
667
+ },
668
+ types: {
669
+ path: '',
670
+ name: ''
671
+ },
672
+ globalName: name,
673
+ pluginVersion: '0.2.5',
674
+ publicPath: 'auto'
675
+ },
676
+ shared: Array.from(getUsedShares()).map(function (shareKey) {
677
+ var shareItem = getNormalizeShareItem(shareKey);
678
+ return {
679
+ id: name + ":" + shareKey,
680
+ name: shareKey,
681
+ version: shareItem.version,
682
+ requiredVersion: shareItem.shareConfig.requiredVersion,
683
+ assets: {
684
+ js: {
685
+ async: [],
686
+ sync: []
687
+ },
688
+ css: {
689
+ async: [],
690
+ sync: []
691
+ }
692
+ }
693
+ };
694
+ }),
695
+ remotes: function () {
696
+ var remotes = [];
697
+ var usedRemotesMap = getUsedRemotesMap();
698
+ Object.keys(usedRemotesMap).forEach(function (remoteKey) {
699
+ var usedModules = Array.from(usedRemotesMap[remoteKey]);
700
+ usedModules.forEach(function (moduleKey) {
701
+ remotes.push({
702
+ federationContainerName: mfOptions.remotes[remoteKey].entry,
703
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
704
+ alias: remoteKey,
705
+ entry: '*'
706
+ });
707
+ });
708
+ });
709
+ return remotes;
710
+ }(),
711
+ exposes: Object.keys(mfOptions.exposes).map(function (key) {
712
+ var formatKey = key.replace('./', '');
713
+ return {
714
+ id: name + ':' + formatKey,
715
+ name: formatKey,
716
+ assets: {
717
+ js: {
718
+ async: [],
719
+ sync: []
720
+ },
721
+ css: {
722
+ sync: [],
723
+ async: []
724
+ }
725
+ },
726
+ path: key
727
+ };
728
+ })
729
+ }));
730
+ } else {
731
+ next();
732
+ }
733
+ });
734
+ }
735
+ }, {
736
+ name: 'moddule-federation-manifest',
737
+ enforce: 'post',
738
+ config: function config(_config) {
739
+ if (!_config.build) _config.build = {};
740
+ if (!_config.build.manifest) _config.build.manifest = _config.build.manifest || !!manifestOptions;
741
+ },
742
+ configResolved: function configResolved(config) {
743
+ root = config.root;
744
+ extensions = config.resolve.extensions || ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'];
745
+ },
746
+ generateBundle: function generateBundle(options, bundle) {
747
+ try {
748
+ var _this = this;
749
+ // 递归查找模块的同步导入文件
750
+ var _findSynchronousImports = function findSynchronousImports(fileName, array) {
751
+ var fileData = bundle[fileName];
752
+ if (fileData && fileData.type === 'chunk') {
753
+ array.push(fileName); // 将当前文件加入预加载列表
754
+ // 遍历该文件的同步导入文件
755
+ fileData.imports.forEach(function (importedFile) {
756
+ if (array.indexOf(importedFile) === -1) {
757
+ _findSynchronousImports(importedFile, array); // 递归查找同步导入的文件
758
+ }
759
+ });
760
+ }
761
+ };
762
+ if (!mfManifestName) return Promise.resolve();
763
+ var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
764
+ return mfOptions.exposes[item]["import"];
765
+ }); // 获取你提供的 moduleIds
766
+ var filesContainingModules = {};
767
+ // 帮助函数:检查模块路径是否匹配
768
+ var isModuleMatched = function isModuleMatched(relativeModulePath, preloadModule) {
769
+ // 先尝试直接匹配
770
+ if (relativeModulePath === preloadModule) return true;
771
+ // 如果 preloadModule 没有后缀,尝试添加可能的后缀进行匹配
772
+ for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
773
+ var ext = _step.value;
774
+ if (relativeModulePath === "" + preloadModule + ext) {
775
+ return true;
776
+ }
777
+ }
778
+ return false;
779
+ };
780
+ // 遍历打包生成的每个文件
781
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
782
+ var _Object$entries$_i = _Object$entries[_i],
783
+ fileName = _Object$entries$_i[0],
784
+ fileData = _Object$entries$_i[1];
785
+ if (mfOptions.filename.replace(/[\[\]]/g, "_") === fileData.name) {
786
+ remoteEntryFile = fileData.fileName;
787
+ }
788
+ if (fileData.type === 'chunk') {
789
+ // 遍历该文件的所有模块
790
+ for (var _i2 = 0, _Object$keys = Object.keys(fileData.modules); _i2 < _Object$keys.length; _i2++) {
791
+ var modulePath = _Object$keys[_i2];
792
+ // 将绝对路径转换为相对于 Vite root 的相对路径
793
+ var relativeModulePath = path.relative(root, modulePath);
794
+ // 检查模块是否在 preloadModules 列表中
795
+ for (var _iterator2 = _createForOfIteratorHelperLoose(exposesModules), _step2; !(_step2 = _iterator2()).done;) {
796
+ var preloadModule = _step2.value;
797
+ var formatPreloadModule = preloadModule.replace("./", "");
798
+ if (isModuleMatched(relativeModulePath, formatPreloadModule)) {
799
+ var _filesContainingModul;
800
+ if (!filesContainingModules[preloadModule]) {
801
+ filesContainingModules[preloadModule] = {
802
+ sync: [],
803
+ async: []
804
+ };
805
+ }
806
+ console.log(Object.keys(fileData.modules));
807
+ filesContainingModules[preloadModule].sync.push(fileName);
808
+ (_filesContainingModul = filesContainingModules[preloadModule].async).push.apply(_filesContainingModul, fileData.dynamicImports || []);
809
+ _findSynchronousImports(fileName, filesContainingModules[preloadModule].sync);
810
+ break; // 如果找到匹配,跳出循环
811
+ }
812
+ }
813
+ }
814
+ }
815
+ }
816
+ ;
817
+ var fileToShareKey = {};
818
+ return Promise.resolve(Promise.all(Array.from(getUsedShares()).map(function (shareKey) {
819
+ try {
820
+ return Promise.resolve(_this.resolve(getPreBuildLibImportId(shareKey))).then(function (_this$resolve) {
821
+ var file = _this$resolve.id.split("?")[0];
822
+ fileToShareKey[file] = shareKey;
823
+ });
824
+ } catch (e) {
825
+ return Promise.reject(e);
826
+ }
827
+ }))).then(function () {
828
+ // 遍历打包生成的每个文件
829
+ for (var _i3 = 0, _Object$entries2 = Object.entries(bundle); _i3 < _Object$entries2.length; _i3++) {
830
+ var _Object$entries2$_i = _Object$entries2[_i3],
831
+ _fileName = _Object$entries2$_i[0],
832
+ _fileData = _Object$entries2$_i[1];
833
+ if (_fileData.type === 'chunk') {
834
+ // 遍历该文件的所有模块
835
+ for (var _i4 = 0, _Object$keys2 = Object.keys(_fileData.modules); _i4 < _Object$keys2.length; _i4++) {
836
+ var _modulePath = _Object$keys2[_i4];
837
+ var sharedKey = fileToShareKey[_modulePath];
838
+ if (sharedKey) {
839
+ var _filesContainingModul2;
840
+ if (!filesContainingModules[sharedKey]) {
841
+ filesContainingModules[sharedKey] = {
842
+ sync: [],
843
+ async: []
844
+ };
845
+ }
846
+ filesContainingModules[sharedKey].sync.push(_fileName);
847
+ (_filesContainingModul2 = filesContainingModules[sharedKey].async).push.apply(_filesContainingModul2, _fileData.dynamicImports || []);
848
+ _findSynchronousImports(_fileName, filesContainingModules[sharedKey].sync);
849
+ break; // 如果找到匹配,跳出循环
850
+ }
851
+ }
852
+ }
853
+ }
854
+ Object.keys(filesContainingModules).forEach(function (key) {
855
+ filesContainingModules[key].sync = Array.from(new Set(filesContainingModules[key].sync));
856
+ filesContainingModules[key].async = Array.from(new Set(filesContainingModules[key].async));
857
+ });
858
+ _this.emitFile({
859
+ type: 'asset',
860
+ fileName: mfManifestName,
861
+ source: generateMFManifest(filesContainingModules)
862
+ });
863
+ });
864
+ } catch (e) {
865
+ return Promise.reject(e);
866
+ }
867
+ }
868
+ }];
869
+ function generateMFManifest(preloadMap) {
870
+ var options = getNormalizeModuleFederationOptions();
871
+ var name = options.name;
872
+ var remoteEntry = {
873
+ name: remoteEntryFile,
874
+ path: '',
875
+ type: 'module'
876
+ };
877
+ var remotes = [];
878
+ var usedRemotesMap = getUsedRemotesMap();
879
+ Object.keys(usedRemotesMap).forEach(function (remoteKey) {
880
+ var usedModules = Array.from(usedRemotesMap[remoteKey]);
881
+ usedModules.forEach(function (moduleKey) {
882
+ remotes.push({
883
+ federationContainerName: options.remotes[remoteKey].entry,
884
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
885
+ alias: remoteKey,
886
+ entry: '*'
887
+ });
888
+ });
889
+ });
890
+ // @ts-ignore
891
+ var shared = Array.from(getUsedShares()).map(function (shareKey) {
892
+ // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
893
+ if (!preloadMap[shareKey]) return;
894
+ var shareItem = getNormalizeShareItem(shareKey);
895
+ return {
896
+ id: name + ":" + shareKey,
897
+ name: shareKey,
898
+ version: shareItem.version,
899
+ requiredVersion: shareItem.shareConfig.requiredVersion,
900
+ assets: {
901
+ js: {
902
+ async: preloadMap[shareKey].async,
903
+ sync: preloadMap[shareKey].sync
904
+ },
905
+ css: {
906
+ async: [],
907
+ sync: []
908
+ }
909
+ }
910
+ };
911
+ }).filter(function (item) {
912
+ return item;
913
+ });
914
+ var exposes = Object.keys(options.exposes).map(function (key) {
915
+ // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
916
+ var formatKey = key.replace('./', '');
917
+ var sourceFile = options.exposes[key]["import"];
918
+ if (!preloadMap[sourceFile]) return;
919
+ return {
920
+ id: name + ':' + formatKey,
921
+ name: formatKey,
922
+ assets: {
923
+ js: {
924
+ async: preloadMap[sourceFile].async,
925
+ sync: preloadMap[sourceFile].sync
926
+ },
927
+ css: {
928
+ sync: [],
929
+ async: []
930
+ }
931
+ },
932
+ path: key
933
+ };
934
+ }).filter(function (item) {
935
+ return item;
936
+ }); // Filter out any null values
937
+ var result = {
938
+ id: name,
939
+ name: name,
940
+ metaData: {
941
+ name: name,
942
+ type: 'app',
943
+ buildInfo: {
944
+ buildVersion: '1.0.0',
945
+ buildName: name
946
+ },
947
+ remoteEntry: remoteEntry,
948
+ ssrRemoteEntry: remoteEntry,
949
+ types: {
950
+ path: '',
951
+ name: ''
952
+ // "zip": "@mf-types.zip",
953
+ // "api": "@mf-types.d.ts"
954
+ },
955
+ globalName: name,
956
+ pluginVersion: '0.2.5',
957
+ publicPath: 'auto'
958
+ },
959
+ shared: shared,
960
+ remotes: remotes,
961
+ exposes: exposes
962
+ };
963
+ return JSON.stringify(result);
964
+ }
965
+ };
966
+
967
+ var _resolve,
968
+ promise = new Promise(function (resolve, reject) {
969
+ _resolve = resolve;
970
+ });
971
+ var parsePromise = promise;
972
+ var parseStartSet = new Set();
973
+ var parseEndSet = new Set();
974
+ function pluginModuleParseEnd (excludeFn) {
975
+ return [{
976
+ name: "_",
977
+ apply: "serve",
978
+ config: function config() {
979
+ // No waiting in development mode
980
+ _resolve(1);
981
+ }
982
+ }, {
983
+ enforce: "pre",
984
+ name: "parseStart",
985
+ apply: "build",
986
+ load: function load(id) {
987
+ if (excludeFn(id)) {
988
+ return;
989
+ }
990
+ parseStartSet.add(id);
991
+ }
992
+ }, {
993
+ enforce: "post",
994
+ name: "parseEnd",
995
+ apply: "build",
996
+ moduleParsed: function moduleParsed(module) {
997
+ var id = module.id;
998
+ if (excludeFn(id)) {
999
+ return;
1000
+ }
1001
+ parseEndSet.add(id);
1002
+ if (parseStartSet.size === parseEndSet.size) {
1003
+ _resolve(1);
1004
+ }
1005
+ }
1006
+ }];
1007
+ }
1008
+
1009
+ var filter = pluginutils.createFilter();
545
1010
  function pluginProxyRemoteEntry () {
546
1011
  return {
547
1012
  name: 'proxyRemoteEntry',
@@ -553,14 +1018,18 @@ function pluginProxyRemoteEntry () {
553
1018
  },
554
1019
  load: function load(id) {
555
1020
  if (id === REMOTE_ENTRY_ID) {
556
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1021
+ return parsePromise.then(function (_) {
1022
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1023
+ });
557
1024
  }
558
1025
  },
559
1026
  transform: function transform(code, id) {
560
1027
  try {
561
- if (!filter$1(id)) return Promise.resolve();
1028
+ if (!filter(id)) return Promise.resolve();
562
1029
  if (id.includes(REMOTE_ENTRY_ID)) {
563
- return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
1030
+ return Promise.resolve(parsePromise.then(function (_) {
1031
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1032
+ }));
564
1033
  }
565
1034
  return Promise.resolve();
566
1035
  } catch (e) {
@@ -570,50 +1039,25 @@ function pluginProxyRemoteEntry () {
570
1039
  };
571
1040
  }
572
1041
 
573
- var filter = pluginutils.createFilter();
1042
+ pluginutils.createFilter();
574
1043
  function pluginProxyRemotes (options) {
575
- var command;
576
1044
  var remotes = options.remotes;
577
- var matchRemotesList = Object.keys(remotes).map(function (item) {
578
- return item.replace(/\//g, "_");
579
- });
580
1045
  return {
581
1046
  name: "proxyRemotes",
582
1047
  config: function config(_config, _ref) {
583
1048
  var _command = _ref.command;
584
- command = _command;
585
1049
  Object.keys(remotes).forEach(function (key) {
586
1050
  var remote = remotes[key];
587
1051
  _config.resolve.alias.push({
588
- find: new RegExp("(" + remote.name + "(/.*|$)?)"),
589
- replacement: '$1',
1052
+ find: new RegExp("^(" + remote.name + "(/.*|$))"),
1053
+ replacement: "$1",
590
1054
  customResolver: function customResolver(source) {
591
- var requestPath = remoteVirtualModule.getImportId() + '?__moduleRemote__=' + encodeURIComponent(source);
592
- if (!_config.optimizeDeps) _config.optimizeDeps = {};
593
- if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
594
- if (_config.optimizeDeps.needsInterop.indexOf(requestPath) === -1) _config.optimizeDeps.needsInterop.push(requestPath);
595
- return this.resolve(requestPath);
1055
+ var remoteModule = getRemoteVirtualModule(source, _command);
1056
+ addUsedRemote(remote.name, source);
1057
+ return remoteModule.getPath();
596
1058
  }
597
1059
  });
598
1060
  });
599
- },
600
- transform: function transform(code, id) {
601
- try {
602
- if (!filter(id)) return Promise.resolve();
603
- var _ref2 = matchRemotesList.length && id.match(new RegExp("/(" + matchRemotesList.join('|') + ")(_.*.js|.js)")) || [],
604
- devRemoteModuleName = _ref2[0];
605
- if (devRemoteModuleName) {
606
- return Promise.resolve(generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command));
607
- }
608
- var _ref3 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
609
- prodRemoteName = _ref3[0];
610
- if (prodRemoteName) {
611
- return Promise.resolve(generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command));
612
- }
613
- return Promise.resolve();
614
- } catch (e) {
615
- return Promise.reject(e);
616
- }
617
1061
  }
618
1062
  };
619
1063
  }
@@ -655,44 +1099,24 @@ var PromiseStore = /*#__PURE__*/function () {
655
1099
  return PromiseStore;
656
1100
  }();
657
1101
 
658
- function wrapManualChunks(output, manualChunksCb) {
659
- if (!output.manualChunks) output.manualChunks = {};
660
- var wrapManualChunks = function wrapManualChunks(original) {
661
- return function (id) {
662
- var args = [].slice.call(arguments, 1);
663
- var customRes = manualChunksCb == null ? void 0 : manualChunksCb.apply(void 0, [id].concat(args));
664
- if (customRes) return customRes;
665
- if (typeof original === 'function') {
666
- return original.apply(void 0, [id].concat(args));
667
- }
668
- if (typeof original === 'object' && original) {
669
- return original[id];
670
- }
671
- };
672
- };
673
- output.manualChunks = wrapManualChunks(output.manualChunks);
674
- }
675
-
676
1102
  function proxySharedModule(options) {
677
1103
  var _options$shared = options.shared,
678
- shared = _options$shared === void 0 ? {} : _options$shared,
679
- include = options.include,
680
- exclude = options.exclude;
681
- var filterFunction = pluginutils.createFilter(include, exclude);
1104
+ shared = _options$shared === void 0 ? {} : _options$shared;
682
1105
  return [{
683
1106
  name: "generateLocalSharedImportMap",
684
1107
  enforce: "post",
685
- resolveId: function resolveId(id) {
686
- if (id.includes(getLocalSharedImportMapPath())) return id;
687
- },
688
1108
  load: function load(id) {
689
1109
  if (id.includes(getLocalSharedImportMapPath())) {
690
- return generateLocalSharedImportMap();
1110
+ return parsePromise.then(function (_) {
1111
+ return generateLocalSharedImportMap();
1112
+ });
691
1113
  }
692
1114
  },
693
1115
  transform: function transform(code, id) {
694
1116
  if (id.includes(getLocalSharedImportMapPath())) {
695
- return generateLocalSharedImportMap();
1117
+ return parsePromise.then(function (_) {
1118
+ return generateLocalSharedImportMap();
1119
+ });
696
1120
  }
697
1121
  }
698
1122
  }, {
@@ -701,19 +1125,6 @@ function proxySharedModule(options) {
701
1125
  config: function config(_config, _ref) {
702
1126
  var _config$resolve$alias, _config$resolve$alias2;
703
1127
  var command = _ref.command;
704
- if (!_config.build) _config.build = {};
705
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
706
- var rollupOptions = _config.build.rollupOptions;
707
- if (!rollupOptions.output) rollupOptions.output = {};
708
- wrapManualChunks(_config.build.rollupOptions.output, function (id) {
709
- // https://github.com/module-federation/vite/issues/40#issuecomment-2311434503
710
- if (id.includes('/preload-helper.js')) {
711
- return "preload-helper";
712
- }
713
- if (id.includes("node_modules/@module-federation/runtime")) {
714
- return "@module-federation/runtime";
715
- }
716
- });
717
1128
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
718
1129
  var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
719
1130
  return {
@@ -721,12 +1132,10 @@ function proxySharedModule(options) {
721
1132
  find: new RegExp(pattern),
722
1133
  replacement: "$1",
723
1134
  customResolver: function customResolver(source, importer) {
724
- var _config$optimizeDeps;
725
1135
  var loadSharePath = getLoadShareModulePath(source);
726
- _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(loadSharePath);
727
1136
  writeLoadShareModule(source, shared[key], command);
728
1137
  writePreBuildLibPath(source);
729
- addShare(source);
1138
+ addUsedShares(source);
730
1139
  writeLocalSharedImportMap();
731
1140
  return this.resolve(loadSharePath);
732
1141
  }
@@ -735,20 +1144,18 @@ function proxySharedModule(options) {
735
1144
  var savePrebuild = new PromiseStore();
736
1145
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
737
1146
  return command === "build" ? {
738
- find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
1147
+ find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
739
1148
  replacement: function replacement($1) {
740
- $1 = $1.replace(/\.[^.]+$/, "");
741
- var pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
742
- return packageNameDecode(pkgName);
1149
+ var pkgName = VirtualModule.findModule(PREBUILD_TAG, $1).name;
1150
+ return pkgName;
743
1151
  }
744
1152
  } : {
745
- find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
1153
+ find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
746
1154
  replacement: "$1",
747
1155
  customResolver: function customResolver(source, importer) {
748
1156
  try {
749
1157
  var _this = this;
750
- source = source.replace(/\.[^.]+$/, "");
751
- var pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
1158
+ var pkgName = VirtualModule.findModule(PREBUILD_TAG, source).name;
752
1159
  if (importer.includes(LOAD_SHARE_TAG)) {
753
1160
  // save pre-bunding module id
754
1161
  savePrebuild.set(pkgName, _this.resolve(pkgName).then(function (item) {
@@ -783,69 +1190,6 @@ function proxySharedModule(options) {
783
1190
  watch.ignored = [].concat(watch.ignored);
784
1191
  watch.ignored.push("!**" + getLocalSharedImportMapPath() + "**");
785
1192
  }
786
- }, {
787
- name: "prebuild-top-level-await",
788
- apply: "serve",
789
- transform: function transform(code, id) {
790
- if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
791
- return null;
792
- }
793
- if (!filterFunction(id)) return null;
794
- var ast;
795
- try {
796
- ast = this.parse(code, {
797
- allowReturnOutsideFunction: true
798
- });
799
- } catch (e) {
800
- throw new Error(id + ": " + e);
801
- }
802
- var magicString = new MagicString__default["default"](code);
803
- estreeWalker.walk(ast, {
804
- enter: function enter(node) {
805
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
806
- var exportSpecifiers = node.specifiers.map(function (specifier) {
807
- return specifier.exported.name;
808
- });
809
- var proxyStatements = exportSpecifiers.map(function (name) {
810
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
811
- }).join('\n');
812
- var exportStatements = exportSpecifiers.map(function (name) {
813
- return "__mfproxy__" + name + " as " + name;
814
- }).join(', ');
815
- var start = node.start;
816
- var end = node.end;
817
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
818
- magicString.overwrite(start, end, replacement);
819
- }
820
- if (node.type === 'ExportDefaultDeclaration') {
821
- var declaration = node.declaration;
822
- var _start = node.start;
823
- var _end = node.end;
824
- var proxyStatement;
825
- var exportStatement = 'default';
826
- if (declaration.type === 'Identifier') {
827
- // example: export default foo;
828
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
829
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
830
- // example: export default someFunction();
831
- var declarationCode = code.slice(declaration.start, declaration.end);
832
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
833
- } else {
834
- // other
835
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
836
- }
837
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
838
- magicString.overwrite(_start, _end, _replacement);
839
- }
840
- }
841
- });
842
- return {
843
- code: magicString.toString(),
844
- map: magicString.generateMap({
845
- hires: true
846
- })
847
- };
848
- }
849
1193
  }];
850
1194
  }
851
1195
 
@@ -892,16 +1236,16 @@ function federation(mfUserOptions) {
892
1236
  if (!name) throw new Error("name is required");
893
1237
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
894
1238
  entryName: 'remoteEntry',
895
- entryPath: getWrapRemoteEntryPath(),
1239
+ entryPath: REMOTE_ENTRY_ID,
896
1240
  fileName: filename
897
1241
  }), addEntry({
898
1242
  entryName: 'hostInit',
899
1243
  entryPath: getHostAutoInitPath()
900
1244
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
901
- return id.includes(getHostAutoInitImportId()) || id.includes(getWrapRemoteEntryImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
1245
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
902
1246
  }), proxySharedModule({
903
1247
  shared: shared
904
- }), [{
1248
+ }), [PluginDevProxyModuleTopLevelAwait(), {
905
1249
  name: 'module-federation-vite',
906
1250
  enforce: 'post',
907
1251
  config: function config(_config, _ref) {
@@ -911,11 +1255,8 @@ function federation(mfUserOptions) {
911
1255
  replacement: require.resolve('@module-federation/runtime')
912
1256
  });
913
1257
  (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
914
- // Object.keys(shared).forEach((key) => {
915
- // config.optimizeDeps?.include?.push(key);
916
- // });
917
1258
  }
918
- }]);
1259
+ }], Manifest());
919
1260
  }
920
1261
 
921
1262
  exports.federation = federation;