@module-federation/vite 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.umd.js CHANGED
@@ -32,13 +32,13 @@
32
32
  var entryName = _ref.entryName,
33
33
  entryPath = _ref.entryPath,
34
34
  fileName = _ref.fileName;
35
- var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
35
+ var devEntryPath = entryPath.startsWith('virtual:mf') ? '/@id/' + entryPath : entryPath;
36
36
  var entryFiles = [];
37
37
  var htmlFilePath;
38
38
  var _command;
39
39
  return [{
40
40
  name: 'add-entry',
41
- apply: "serve",
41
+ apply: 'serve',
42
42
  config: function config(_config, _ref2) {
43
43
  var command = _ref2.command;
44
44
  _command = command;
@@ -64,8 +64,8 @@
64
64
  return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
65
65
  }
66
66
  }, {
67
- name: "add-entry",
68
- enforce: "post",
67
+ name: 'add-entry',
68
+ enforce: 'post',
69
69
  configResolved: function configResolved(config) {
70
70
  var inputOptions = config.build.rollupOptions.input;
71
71
  if (!inputOptions) {
@@ -82,8 +82,8 @@
82
82
  }
83
83
  },
84
84
  buildStart: function buildStart() {
85
- if (_command === "serve") return;
86
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
85
+ if (_command === 'serve') return;
86
+ var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes('[hash');
87
87
  var emitFileOptions = {
88
88
  name: entryName,
89
89
  type: 'chunk',
@@ -120,10 +120,10 @@
120
120
  function PluginDevProxyModuleTopLevelAwait() {
121
121
  var filterFunction = pluginutils.createFilter();
122
122
  return {
123
- name: "dev-proxy-module-top-level-await",
124
- apply: "serve",
123
+ name: 'dev-proxy-module-top-level-await',
124
+ apply: 'serve',
125
125
  transform: function transform(code, id) {
126
- if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
126
+ if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
127
127
  return null;
128
128
  }
129
129
  if (!filterFunction(id)) return null;
@@ -207,6 +207,15 @@
207
207
  }
208
208
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
209
209
  }
210
+ function _extends() {
211
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
212
+ for (var e = 1; e < arguments.length; e++) {
213
+ var t = arguments[e];
214
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
215
+ }
216
+ return n;
217
+ }, _extends.apply(null, arguments);
218
+ }
210
219
  function _unsupportedIterableToArray(r, a) {
211
220
  if (r) {
212
221
  if ("string" == typeof r) return _arrayLikeToArray(r, a);
@@ -215,6 +224,12 @@
215
224
  }
216
225
  }
217
226
 
227
+ var warn = function warn(message) {
228
+ return message.split('\n').forEach(function (msg) {
229
+ return console.warn('\x1b[33m%s\x1b[0m', msg);
230
+ });
231
+ };
232
+
218
233
  function normalizeExposesItem(key, item) {
219
234
  var importPath = '';
220
235
  if (typeof item === 'string') {
@@ -288,7 +303,7 @@
288
303
  from: '',
289
304
  shareConfig: {
290
305
  singleton: false,
291
- requiredVersion: "^" + version || '*'
306
+ requiredVersion: version ? "^" + version : '*'
292
307
  }
293
308
  };
294
309
  }
@@ -299,7 +314,7 @@
299
314
  scope: shareItem.shareScope || 'default',
300
315
  shareConfig: {
301
316
  singleton: shareItem.singleton || false,
302
- requiredVersion: shareItem.requiredVersion || "^" + version || '*',
317
+ requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
303
318
  strictVersion: !!shareItem.strictVersion
304
319
  }
305
320
  };
@@ -328,13 +343,13 @@
328
343
  if (manifest === void 0) {
329
344
  manifest = false;
330
345
  }
331
- if (typeof manifest === "boolean") {
346
+ if (typeof manifest === 'boolean') {
332
347
  return manifest;
333
348
  }
334
349
  return Object.assign({
335
- filePath: "",
350
+ filePath: '',
336
351
  disableAssetsAnalyze: false,
337
- fileName: "mf-manifest.json"
352
+ fileName: 'mf-manifest.json'
338
353
  }, manifest);
339
354
  }
340
355
  var config;
@@ -343,10 +358,13 @@
343
358
  }
344
359
  function getNormalizeShareItem(key) {
345
360
  var options = getNormalizeModuleFederationOptions();
346
- var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
361
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
347
362
  return shareItem;
348
363
  }
349
364
  function normalizeModuleFederationOptions(options) {
365
+ if (options.getPublicPath) {
366
+ warn("We are ignoring the getPublicPath options because they are natively supported by Vite\nwith the \"experimental.renderBuiltUrl\" configuration https://vitejs.dev/guide/build#advanced-base-options");
367
+ }
350
368
  return config = {
351
369
  exposes: normalizeExposes(options.exposes),
352
370
  filename: options.filename || 'remoteEntry-[hash]',
@@ -358,11 +376,12 @@
358
376
  shareScope: options.shareScope || 'default',
359
377
  shared: normalizeShared(options.shared),
360
378
  runtimePlugins: options.runtimePlugins || [],
361
- getPublicPath: options.getPublicPath,
362
379
  implementation: options.implementation,
363
380
  manifest: normalizeManifest(options.manifest),
364
381
  dev: options.dev,
365
- dts: options.dts
382
+ dts: options.dts,
383
+ getPublicPath: options.getPublicPath,
384
+ shareStrategy: options.shareStrategy
366
385
  };
367
386
  }
368
387
 
@@ -380,8 +399,8 @@
380
399
  * @returns {string} - The encoded file name.
381
400
  */
382
401
  function packageNameEncode(name) {
383
- if (typeof name !== "string") throw new Error("A string package name is required");
384
- return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
402
+ if (typeof name !== 'string') throw new Error('A string package name is required');
403
+ return name.replace(/@/g, '_mf_0_').replace(/\//g, '_mf_1_').replace(/-/g, '_mf_2_').replace(/\./g, '_mf_3_');
385
404
  }
386
405
  /**
387
406
  * Decodes an encoded file name back to the original package name.
@@ -389,8 +408,8 @@
389
408
  * @returns {string} - The decoded package name.
390
409
  */
391
410
  function packageNameDecode(encoded) {
392
- if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
393
- return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
411
+ if (typeof encoded !== 'string') throw new Error('A string encoded file name is required');
412
+ return encoded.replace(/_mf_0_/g, '@').replace(/_mf_1_/g, '/').replace(/_mf_2_/g, '-').replace(/_mf_3_/g, '.');
394
413
  }
395
414
 
396
415
  /**
@@ -399,11 +418,11 @@
399
418
  function getLocalSharedImportMapPath_temp() {
400
419
  var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
401
420
  name = _getNormalizeModuleFe.name;
402
- return path__default["default"].resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
421
+ return path__default["default"].resolve('.__mf__temp', packageNameEncode(name), 'localSharedImportMap');
403
422
  }
404
423
  function writeLocalSharedImportMap_temp(content) {
405
424
  var localSharedImportMapId = getLocalSharedImportMapPath_temp();
406
- createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
425
+ createFile(localSharedImportMapId + '.js', '\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n' + content);
407
426
  }
408
427
  function createFile(filePath, content) {
409
428
  var dir = path__default["default"].dirname(filePath);
@@ -425,16 +444,16 @@
425
444
  }
426
445
  currentDir = path.dirname(currentDir);
427
446
  }
428
- return "";
447
+ return '';
429
448
  }();
430
- var virtualPackageName = "__mf__virtual";
449
+ var virtualPackageName = '__mf__virtual';
431
450
  if (!fs.existsSync(path.resolve(nodeModulesDir, virtualPackageName))) {
432
451
  fs.mkdirSync(path.resolve(nodeModulesDir, virtualPackageName));
433
452
  }
434
- fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "empty.js"), "");
435
- fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.stringify({
453
+ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, 'empty.js'), '');
454
+ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, 'package.json'), JSON.stringify({
436
455
  name: virtualPackageName,
437
- main: "empty.js"
456
+ main: 'empty.js'
438
457
  }));
439
458
  var patternMap = {};
440
459
  var cacheMap = {};
@@ -448,7 +467,7 @@
448
467
  tag = '__mf_v__';
449
468
  }
450
469
  if (suffix === void 0) {
451
- suffix = "";
470
+ suffix = '';
452
471
  }
453
472
  this.name = void 0;
454
473
  this.tag = void 0;
@@ -456,13 +475,13 @@
456
475
  this.inited = false;
457
476
  this.name = name;
458
477
  this.tag = tag;
459
- this.suffix = suffix || ((_name$split$slice$pop = name.split(".").slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, ".$1")) || ".js";
478
+ this.suffix = suffix || ((_name$split$slice$pop = name.split('.').slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, '.$1')) || '.js';
460
479
  if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
461
480
  cacheMap[this.tag][this.name] = this;
462
481
  }
463
482
  VirtualModule.findModule = function findModule(tag, str) {
464
483
  if (str === void 0) {
465
- str = "";
484
+ str = '';
466
485
  }
467
486
  if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
468
487
  var moduleName = (str.match(patternMap[tag]) || [])[2];
@@ -491,16 +510,24 @@
491
510
  return VirtualModule;
492
511
  }();
493
512
 
494
- var virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
513
+ var VIRTUAL_EXPOSES = 'virtual:mf-exposes';
514
+ function generateExposes() {
515
+ var options = getNormalizeModuleFederationOptions();
516
+ return "\n export default {\n " + Object.keys(options.exposes).map(function (key) {
517
+ 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 ";
518
+ }).join(',') + "\n }\n ";
519
+ }
520
+
521
+ var virtualRuntimeInitStatus = new VirtualModule('runtimeInit');
495
522
  function writeRuntimeInitStatus() {
496
- 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 ");
523
+ virtualRuntimeInitStatus.writeSync("\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n module.exports = {\n initPromise,\n initResolve,\n initReject\n }\n ");
497
524
  }
498
525
 
499
526
  var cacheRemoteMap = {};
500
527
  var LOAD_REMOTE_TAG = '__loadRemote__';
501
528
  function getRemoteVirtualModule(remote, command) {
502
529
  if (!cacheRemoteMap[remote]) {
503
- cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
530
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
504
531
  cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
505
532
  }
506
533
  var virtual = cacheRemoteMap[remote];
@@ -517,7 +544,7 @@
517
544
  return usedRemotesMap;
518
545
  }
519
546
  function generateRemotes(id, command) {
520
- 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 ";
547
+ 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 ";
521
548
  }
522
549
 
523
550
  /**
@@ -527,10 +554,10 @@
527
554
  */
528
555
  // *** __prebuild__
529
556
  var preBuildCacheMap = {};
530
- var PREBUILD_TAG = "__prebuild__";
557
+ var PREBUILD_TAG = '__prebuild__';
531
558
  function writePreBuildLibPath(pkg) {
532
559
  if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
533
- preBuildCacheMap[pkg].writeSync("");
560
+ preBuildCacheMap[pkg].writeSync('');
534
561
  }
535
562
  function getPreBuildLibImportId(pkg) {
536
563
  if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
@@ -538,15 +565,15 @@
538
565
  return importId;
539
566
  }
540
567
  // *** __loadShare__
541
- var LOAD_SHARE_TAG = "__loadShare__";
568
+ var LOAD_SHARE_TAG = '__loadShare__';
542
569
  var loadShareCacheMap = {};
543
570
  function getLoadShareModulePath(pkg) {
544
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
571
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, '.js');
545
572
  var filepath = loadShareCacheMap[pkg].getPath();
546
573
  return filepath;
547
574
  }
548
575
  function writeLoadShareModule(pkg, shareItem, command) {
549
- 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 ");
576
+ 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 ");
550
577
  }
551
578
 
552
579
  var usedShares = new Set();
@@ -557,7 +584,7 @@
557
584
  usedShares.add(pkg);
558
585
  }
559
586
  // *** Expose locally provided shared modules here
560
- new VirtualModule("localSharedImportMap");
587
+ new VirtualModule('localSharedImportMap');
561
588
  function getLocalSharedImportMapPath() {
562
589
  return getLocalSharedImportMapPath_temp();
563
590
  // return localSharedImportMapModule.getPath()
@@ -575,7 +602,7 @@
575
602
  var options = getNormalizeModuleFederationOptions();
576
603
  return "\n const importMap = {\n " + Array.from(getUsedShares()).map(function (pkg) {
577
604
  return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
578
- }).join(",") + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
605
+ }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
579
606
  var shareItem = getNormalizeShareItem(key);
580
607
  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 ";
581
608
  }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
@@ -590,17 +617,15 @@
590
617
  });
591
618
  return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
592
619
  return item[1];
593
- }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
594
- 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 ";
595
- }).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) {
620
+ }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\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) {
596
621
  return item[0] + "()";
597
- }).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 ";
622
+ }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: " + options.shareStrategy : '') + "\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 ";
598
623
  }
599
624
  /**
600
625
  * Inject entry file, automatically init when used as host,
601
626
  * and will not inject remoteEntry
602
627
  */
603
- var hostAutoInitModule = new VirtualModule("hostAutoInit");
628
+ var hostAutoInitModule = new VirtualModule('hostAutoInit');
604
629
  function writeHostAutoInit() {
605
630
  hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
606
631
  }
@@ -621,13 +646,14 @@
621
646
  var mfOptions = getNormalizeModuleFederationOptions();
622
647
  var name = mfOptions.name,
623
648
  filename = mfOptions.filename,
649
+ getPublicPath = mfOptions.getPublicPath,
624
650
  manifestOptions = mfOptions.manifest;
625
- var mfManifestName = "";
651
+ var mfManifestName = '';
626
652
  if (manifestOptions === true) {
627
- mfManifestName = "mf-manifest.json";
653
+ mfManifestName = 'mf-manifest.json';
628
654
  }
629
- if (typeof manifestOptions !== "boolean") {
630
- mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || "", (manifestOptions == null ? void 0 : manifestOptions.fileName) || "");
655
+ if (typeof manifestOptions !== 'boolean') {
656
+ mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
631
657
  }
632
658
  var extensions;
633
659
  var root;
@@ -635,7 +661,7 @@
635
661
  var publicPath;
636
662
  var _command;
637
663
  return [{
638
- name: 'moddule-federation-manifest',
664
+ name: 'module-federation-manifest',
639
665
  apply: 'serve',
640
666
  configureServer: function configureServer(server) {
641
667
  server.middlewares.use(function (req, res, next) {
@@ -643,10 +669,10 @@
643
669
  next();
644
670
  return;
645
671
  }
646
- if (req.url === mfManifestName.replace(/^\/?/, "/")) {
672
+ if (req.url === mfManifestName.replace(/^\/?/, '/')) {
647
673
  res.setHeader('Content-Type', 'application/json');
648
674
  res.setHeader('Access-Control-Allow-Origin', '*');
649
- res.end(JSON.stringify({
675
+ res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
650
676
  id: name,
651
677
  name: name,
652
678
  metaData: {
@@ -673,68 +699,15 @@
673
699
  globalName: name,
674
700
  pluginVersion: '0.2.5',
675
701
  publicPath: publicPath
676
- },
677
- shared: Array.from(getUsedShares()).map(function (shareKey) {
678
- var shareItem = getNormalizeShareItem(shareKey);
679
- return {
680
- id: name + ":" + shareKey,
681
- name: shareKey,
682
- version: shareItem.version,
683
- requiredVersion: shareItem.shareConfig.requiredVersion,
684
- assets: {
685
- js: {
686
- async: [],
687
- sync: []
688
- },
689
- css: {
690
- async: [],
691
- sync: []
692
- }
693
- }
694
- };
695
- }),
696
- remotes: function () {
697
- var remotes = [];
698
- var usedRemotesMap = getUsedRemotesMap();
699
- Object.keys(usedRemotesMap).forEach(function (remoteKey) {
700
- var usedModules = Array.from(usedRemotesMap[remoteKey]);
701
- usedModules.forEach(function (moduleKey) {
702
- remotes.push({
703
- federationContainerName: mfOptions.remotes[remoteKey].entry,
704
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
705
- alias: remoteKey,
706
- entry: '*'
707
- });
708
- });
709
- });
710
- return remotes;
711
- }(),
712
- exposes: Object.keys(mfOptions.exposes).map(function (key) {
713
- var formatKey = key.replace('./', '');
714
- return {
715
- id: name + ':' + formatKey,
716
- name: formatKey,
717
- assets: {
718
- js: {
719
- async: [],
720
- sync: []
721
- },
722
- css: {
723
- sync: [],
724
- async: []
725
- }
726
- },
727
- path: key
728
- };
729
- })
730
- }));
702
+ }
703
+ })));
731
704
  } else {
732
705
  next();
733
706
  }
734
707
  });
735
708
  }
736
709
  }, {
737
- name: 'moddule-federation-manifest',
710
+ name: 'module-federation-manifest',
738
711
  enforce: 'post',
739
712
  config: function config(_config, _ref) {
740
713
  var command = _ref.command;
@@ -745,10 +718,10 @@
745
718
  configResolved: function configResolved(config) {
746
719
  root = config.root;
747
720
  extensions = config.resolve.extensions || ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'];
748
- publicPath = config.base ? config.base.replace(/\/?$/, "/") : "auto";
749
- if (_command === "serve") {
721
+ publicPath = config.base ? config.base.replace(/\/?$/, '/') : 'auto';
722
+ if (_command === 'serve') {
750
723
  var origin = config.server.origin;
751
- publicPath = origin ? origin.replace(/\/?$/, "/") : "auto";
724
+ publicPath = origin ? origin.replace(/\/?$/, '/') : 'auto';
752
725
  }
753
726
  },
754
727
  generateBundle: function generateBundle(options, bundle) {
@@ -790,7 +763,7 @@
790
763
  var _Object$entries$_i = _Object$entries[_i],
791
764
  fileName = _Object$entries$_i[0],
792
765
  fileData = _Object$entries$_i[1];
793
- if (mfOptions.filename.replace(/[\[\]]/g, "_") === fileData.name || fileData.name === "remoteEntry") {
766
+ if (mfOptions.filename.replace(/[\[\]]/g, '_') === fileData.name || fileData.name === 'remoteEntry') {
794
767
  remoteEntryFile = fileData.fileName;
795
768
  }
796
769
  if (fileData.type === 'chunk') {
@@ -802,7 +775,7 @@
802
775
  // 检查模块是否在 preloadModules 列表中
803
776
  for (var _iterator2 = _createForOfIteratorHelperLoose(exposesModules), _step2; !(_step2 = _iterator2()).done;) {
804
777
  var preloadModule = _step2.value;
805
- var formatPreloadModule = preloadModule.replace("./", "");
778
+ var formatPreloadModule = preloadModule.replace('./', '');
806
779
  if (isModuleMatched(relativeModulePath, formatPreloadModule)) {
807
780
  var _filesContainingModul;
808
781
  if (!filesContainingModules[preloadModule]) {
@@ -821,12 +794,11 @@
821
794
  }
822
795
  }
823
796
  }
824
- ;
825
797
  var fileToShareKey = {};
826
798
  return Promise.resolve(Promise.all(Array.from(getUsedShares()).map(function (shareKey) {
827
799
  try {
828
800
  return Promise.resolve(_this.resolve(getPreBuildLibImportId(shareKey))).then(function (_this$resolve) {
829
- var file = _this$resolve.id.split("?")[0];
801
+ var file = _this$resolve.id.split('?')[0];
830
802
  fileToShareKey[file] = shareKey;
831
803
  });
832
804
  } catch (e) {
@@ -866,7 +838,7 @@
866
838
  _this.emitFile({
867
839
  type: 'asset',
868
840
  fileName: mfManifestName,
869
- source: generateMFManifest(filesContainingModules)
841
+ source: JSON.stringify(generateMFManifest(filesContainingModules))
870
842
  });
871
843
  });
872
844
  } catch (e) {
@@ -897,8 +869,7 @@
897
869
  });
898
870
  // @ts-ignore
899
871
  var shared = Array.from(getUsedShares()).map(function (shareKey) {
900
- // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
901
- if (!preloadMap[shareKey]) return;
872
+ var _preloadMap$shareKey, _preloadMap$shareKey2;
902
873
  var shareItem = getNormalizeShareItem(shareKey);
903
874
  return {
904
875
  id: name + ":" + shareKey,
@@ -907,8 +878,8 @@
907
878
  requiredVersion: shareItem.shareConfig.requiredVersion,
908
879
  assets: {
909
880
  js: {
910
- async: preloadMap[shareKey].async,
911
- sync: preloadMap[shareKey].sync
881
+ async: (preloadMap == null || (_preloadMap$shareKey = preloadMap[shareKey]) == null ? void 0 : _preloadMap$shareKey.async) || [],
882
+ sync: (preloadMap == null || (_preloadMap$shareKey2 = preloadMap[shareKey]) == null ? void 0 : _preloadMap$shareKey2.sync) || []
912
883
  },
913
884
  css: {
914
885
  async: [],
@@ -920,17 +891,17 @@
920
891
  return item;
921
892
  });
922
893
  var exposes = Object.keys(options.exposes).map(function (key) {
894
+ var _preloadMap$sourceFil, _preloadMap$sourceFil2;
923
895
  // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
924
896
  var formatKey = key.replace('./', '');
925
897
  var sourceFile = options.exposes[key]["import"];
926
- if (!preloadMap[sourceFile]) return;
927
898
  return {
928
899
  id: name + ':' + formatKey,
929
900
  name: formatKey,
930
901
  assets: {
931
902
  js: {
932
- async: preloadMap[sourceFile].async,
933
- sync: preloadMap[sourceFile].sync
903
+ async: (preloadMap == null || (_preloadMap$sourceFil = preloadMap[sourceFile]) == null ? void 0 : _preloadMap$sourceFil.async) || [],
904
+ sync: (preloadMap == null || (_preloadMap$sourceFil2 = preloadMap[sourceFile]) == null ? void 0 : _preloadMap$sourceFil2.sync) || []
934
905
  },
935
906
  css: {
936
907
  sync: [],
@@ -945,7 +916,7 @@
945
916
  var result = {
946
917
  id: name,
947
918
  name: name,
948
- metaData: {
919
+ metaData: _extends({
949
920
  name: name,
950
921
  type: 'app',
951
922
  buildInfo: {
@@ -961,14 +932,17 @@
961
932
  // "api": "@mf-types.d.ts"
962
933
  },
963
934
  globalName: name,
964
- pluginVersion: '0.2.5',
935
+ pluginVersion: '0.2.5'
936
+ }, !!getPublicPath ? {
937
+ getPublicPath: getPublicPath
938
+ } : {
965
939
  publicPath: publicPath
966
- },
940
+ }),
967
941
  shared: shared,
968
942
  remotes: remotes,
969
943
  exposes: exposes
970
944
  };
971
- return JSON.stringify(result);
945
+ return result;
972
946
  }
973
947
  };
974
948
 
@@ -977,20 +951,21 @@
977
951
  _resolve = resolve;
978
952
  });
979
953
  var parsePromise = promise;
954
+ var exposesParseEnd = false;
980
955
  var parseStartSet = new Set();
981
956
  var parseEndSet = new Set();
982
957
  function pluginModuleParseEnd (excludeFn) {
983
958
  return [{
984
- name: "_",
985
- apply: "serve",
959
+ name: '_',
960
+ apply: 'serve',
986
961
  config: function config() {
987
962
  // No waiting in development mode
988
963
  _resolve(1);
989
964
  }
990
965
  }, {
991
- enforce: "pre",
992
- name: "parseStart",
993
- apply: "build",
966
+ enforce: 'pre',
967
+ name: 'parseStart',
968
+ apply: 'build',
994
969
  load: function load(id) {
995
970
  if (excludeFn(id)) {
996
971
  return;
@@ -998,16 +973,20 @@
998
973
  parseStartSet.add(id);
999
974
  }
1000
975
  }, {
1001
- enforce: "post",
1002
- name: "parseEnd",
1003
- apply: "build",
976
+ enforce: 'post',
977
+ name: 'parseEnd',
978
+ apply: 'build',
1004
979
  moduleParsed: function moduleParsed(module) {
1005
980
  var id = module.id;
1006
981
  if (excludeFn(id)) {
1007
982
  return;
1008
983
  }
984
+ if (id === VIRTUAL_EXPOSES) {
985
+ // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
986
+ exposesParseEnd = true;
987
+ }
1009
988
  parseEndSet.add(id);
1010
- if (parseStartSet.size === parseEndSet.size) {
989
+ if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1011
990
  _resolve(1);
1012
991
  }
1013
992
  }
@@ -1023,6 +1002,9 @@
1023
1002
  if (id === REMOTE_ENTRY_ID) {
1024
1003
  return REMOTE_ENTRY_ID;
1025
1004
  }
1005
+ if (id === VIRTUAL_EXPOSES) {
1006
+ return VIRTUAL_EXPOSES;
1007
+ }
1026
1008
  },
1027
1009
  load: function load(id) {
1028
1010
  if (id === REMOTE_ENTRY_ID) {
@@ -1030,6 +1012,9 @@
1030
1012
  return generateRemoteEntry(getNormalizeModuleFederationOptions());
1031
1013
  });
1032
1014
  }
1015
+ if (id === VIRTUAL_EXPOSES) {
1016
+ return generateExposes();
1017
+ }
1033
1018
  },
1034
1019
  transform: function transform(code, id) {
1035
1020
  try {
@@ -1039,6 +1024,9 @@
1039
1024
  return generateRemoteEntry(getNormalizeModuleFederationOptions());
1040
1025
  }));
1041
1026
  }
1027
+ if (id === VIRTUAL_EXPOSES) {
1028
+ return Promise.resolve(generateExposes());
1029
+ }
1042
1030
  return Promise.resolve();
1043
1031
  } catch (e) {
1044
1032
  return Promise.reject(e);
@@ -1051,14 +1039,14 @@
1051
1039
  function pluginProxyRemotes (options) {
1052
1040
  var remotes = options.remotes;
1053
1041
  return {
1054
- name: "proxyRemotes",
1042
+ name: 'proxyRemotes',
1055
1043
  config: function config(_config, _ref) {
1056
1044
  var _command = _ref.command;
1057
1045
  Object.keys(remotes).forEach(function (key) {
1058
1046
  var remote = remotes[key];
1059
1047
  _config.resolve.alias.push({
1060
1048
  find: new RegExp("^(" + remote.name + "(/.*|$))"),
1061
- replacement: "$1",
1049
+ replacement: '$1',
1062
1050
  customResolver: function customResolver(source) {
1063
1051
  var remoteModule = getRemoteVirtualModule(source, _command);
1064
1052
  addUsedRemote(remote.name, source);
@@ -1112,8 +1100,8 @@
1112
1100
  shared = _options$shared === void 0 ? {} : _options$shared;
1113
1101
  var _config;
1114
1102
  return [{
1115
- name: "generateLocalSharedImportMap",
1116
- enforce: "post",
1103
+ name: 'generateLocalSharedImportMap',
1104
+ enforce: 'post',
1117
1105
  load: function load(id) {
1118
1106
  if (id.includes(getLocalSharedImportMapPath())) {
1119
1107
  return parsePromise.then(function (_) {
@@ -1138,11 +1126,11 @@
1138
1126
  var _config2$resolve$alia, _config2$resolve$alia2;
1139
1127
  var command = _ref.command;
1140
1128
  (_config2$resolve$alia = _config2.resolve.alias).push.apply(_config2$resolve$alia, Object.keys(shared).map(function (key) {
1141
- var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
1129
+ var pattern = key.endsWith('/') ? "(^" + key.replace(/\/$/, '') + "(/.+)?$)" : "(^" + key + "$)";
1142
1130
  return {
1143
1131
  // Intercept all shared requests and proxy them to loadShare
1144
1132
  find: new RegExp(pattern),
1145
- replacement: "$1",
1133
+ replacement: '$1',
1146
1134
  customResolver: function customResolver(source, importer) {
1147
1135
  if (/\.css$/.test(source)) return;
1148
1136
  var loadSharePath = getLoadShareModulePath(source);
@@ -1156,7 +1144,7 @@
1156
1144
  }));
1157
1145
  var savePrebuild = new PromiseStore();
1158
1146
  (_config2$resolve$alia2 = _config2.resolve.alias).push.apply(_config2$resolve$alia2, Object.keys(shared).map(function (key) {
1159
- return command === "build" ? {
1147
+ return command === 'build' ? {
1160
1148
  find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1161
1149
  replacement: function replacement($1) {
1162
1150
  var pkgName = VirtualModule.findModule(PREBUILD_TAG, $1).name;
@@ -1164,7 +1152,7 @@
1164
1152
  }
1165
1153
  } : {
1166
1154
  find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1167
- replacement: "$1",
1155
+ replacement: '$1',
1168
1156
  customResolver: function customResolver(source, importer) {
1169
1157
  try {
1170
1158
  var _this = this;
@@ -1190,8 +1178,8 @@
1190
1178
  }));
1191
1179
  }
1192
1180
  }, {
1193
- name: "watchLocalSharedImportMap",
1194
- apply: "serve",
1181
+ name: 'watchLocalSharedImportMap',
1182
+ apply: 'serve',
1195
1183
  config: function config(_config3) {
1196
1184
  _config3.optimizeDeps = defu.defu(_config3.optimizeDeps, {
1197
1185
  exclude: [getLocalSharedImportMapPath()]
@@ -1248,7 +1236,7 @@
1248
1236
  var name = options.name,
1249
1237
  shared = options.shared,
1250
1238
  filename = options.filename;
1251
- if (!name) throw new Error("name is required");
1239
+ if (!name) throw new Error('name is required');
1252
1240
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
1253
1241
  entryName: 'remoteEntry',
1254
1242
  entryPath: REMOTE_ENTRY_ID,
@@ -1256,6 +1244,9 @@
1256
1244
  }), addEntry({
1257
1245
  entryName: 'hostInit',
1258
1246
  entryPath: getHostAutoInitPath()
1247
+ }), addEntry({
1248
+ entryName: 'virtualExposes',
1249
+ entryPath: VIRTUAL_EXPOSES
1259
1250
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
1260
1251
  return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
1261
1252
  }), proxySharedModule({
@@ -1264,12 +1255,15 @@
1264
1255
  name: 'module-federation-vite',
1265
1256
  enforce: 'post',
1266
1257
  config: function config(_config, _ref) {
1267
- var _config$optimizeDeps;
1258
+ var _config$optimizeDeps, _config$optimizeDeps2, _config$optimizeDeps3;
1259
+ // TODO: singleton
1268
1260
  _config.resolve.alias.push({
1269
1261
  find: '@module-federation/runtime',
1270
1262
  replacement: require.resolve('@module-federation/runtime')
1271
1263
  });
1272
1264
  (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
1265
+ (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push('__mf__virtual');
1266
+ (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push('__mf__virtual');
1273
1267
  }
1274
1268
  }], Manifest());
1275
1269
  }