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