@module-federation/vite 1.7.1 → 1.8.0

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.esm.js CHANGED
@@ -2,7 +2,7 @@ import defu from 'defu';
2
2
  import * as fs from 'fs';
3
3
  import { mkdirSync, writeFileSync, existsSync, writeFile } from 'fs';
4
4
  import * as path from 'pathe';
5
- import path__default, { resolve, basename, parse, join, dirname, relative } from 'pathe';
5
+ import path__default, { resolve, basename, parse, join, dirname } from 'pathe';
6
6
  import { createFilter } from '@rollup/pluginutils';
7
7
  import { walk } from 'estree-walker';
8
8
  import MagicString from 'magic-string';
@@ -98,7 +98,7 @@ var addEntry = function addEntry(_ref) {
98
98
  emitFileOptions.fileName = fileName;
99
99
  }
100
100
  emitFileId = this.emitFile(emitFileOptions);
101
- if (htmlFilePath) {
101
+ if (htmlFilePath && fs.existsSync(htmlFilePath)) {
102
102
  var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
103
103
  var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
104
104
  var match;
@@ -137,10 +137,14 @@ var addEntry = function addEntry(_ref) {
137
137
  */
138
138
  function PluginDevProxyModuleTopLevelAwait() {
139
139
  var filterFunction = createFilter();
140
+ var processedFlag = '/* already-processed-by-dev-proxy-module-top-level-await */';
140
141
  return {
141
142
  name: 'dev-proxy-module-top-level-await',
142
143
  apply: 'serve',
143
144
  transform: function transform(code, id) {
145
+ if (code.includes(processedFlag)) {
146
+ return null;
147
+ }
144
148
  if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
145
149
  return null;
146
150
  }
@@ -193,8 +197,9 @@ function PluginDevProxyModuleTopLevelAwait() {
193
197
  }
194
198
  }
195
199
  });
200
+ var transformedCode = magicString.toString();
196
201
  return {
197
- code: magicString.toString(),
202
+ code: processedFlag + "\n" + transformedCode,
198
203
  map: magicString.generateMap({
199
204
  hires: true
200
205
  })
@@ -436,6 +441,7 @@ function normalizeModuleFederationOptions(options) {
436
441
  dev: options.dev,
437
442
  dts: options.dts,
438
443
  getPublicPath: options.getPublicPath,
444
+ publicPath: options.publicPath,
439
445
  shareStrategy: options.shareStrategy || 'version-first',
440
446
  ignoreOrigin: options.ignoreOrigin || false,
441
447
  virtualModuleDir: options.virtualModuleDir || '__mf__virtual'
@@ -692,9 +698,9 @@ function writeLocalSharedImportMap() {
692
698
  }
693
699
  function generateLocalSharedImportMap() {
694
700
  var options = getNormalizeModuleFederationOptions();
695
- return "\n const importMap = {\n " + Array.from(getUsedShares()).map(function (pkg) {
701
+ return "\n const importMap = {\n " + Array.from(getUsedShares()).sort().map(function (pkg) {
696
702
  return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
697
- }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
703
+ }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).sort().map(function (key) {
698
704
  var shareItem = getNormalizeShareItem(key);
699
705
  if (!shareItem) return null;
700
706
  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 ";
@@ -742,6 +748,178 @@ function initVirtualModules() {
742
748
  writeRuntimeInitStatus();
743
749
  }
744
750
 
751
+ var ASSET_TYPES = ['js', 'css'];
752
+ var LOAD_TIMINGS = ['sync', 'async'];
753
+ var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
754
+ /**
755
+ * Creates an empty asset map structure for tracking JS and CSS assets
756
+ * @returns Initialized asset map with sync/async arrays for JS and CSS
757
+ */
758
+ var createEmptyAssetMap = function createEmptyAssetMap() {
759
+ return {
760
+ js: {
761
+ sync: [],
762
+ async: []
763
+ },
764
+ css: {
765
+ sync: [],
766
+ async: []
767
+ }
768
+ };
769
+ };
770
+ /**
771
+ * Tracks an asset in the preload map with deduplication
772
+ * @param map - The preload map to update
773
+ * @param key - The module key to track under
774
+ * @param fileName - The asset filename to track
775
+ * @param isAsync - Whether the asset is loaded async
776
+ * @param type - The asset type ('js' or 'css')
777
+ */
778
+ var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
779
+ if (!map[key]) {
780
+ map[key] = createEmptyAssetMap();
781
+ }
782
+ var target = isAsync ? map[key][type].async : map[key][type].sync;
783
+ if (!target.includes(fileName)) {
784
+ target.push(fileName);
785
+ }
786
+ };
787
+ /**
788
+ * Checks if a file is a CSS file by extension
789
+ * @param fileName - The filename to check
790
+ * @returns True if file has a CSS extension (.css, .scss, .less)
791
+ */
792
+ var isCSSFile = function isCSSFile(fileName) {
793
+ return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
794
+ };
795
+ /**
796
+ * Collects all CSS assets from the bundle
797
+ * @param bundle - The Rollup output bundle
798
+ * @returns Set of CSS asset filenames
799
+ */
800
+ var collectCssAssets = function collectCssAssets(bundle) {
801
+ var cssAssets = new Set();
802
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
803
+ var _Object$entries$_i = _Object$entries[_i],
804
+ fileName = _Object$entries$_i[0],
805
+ fileData = _Object$entries$_i[1];
806
+ if (fileData.type === 'asset' && isCSSFile(fileName)) {
807
+ cssAssets.add(fileName);
808
+ }
809
+ }
810
+ return cssAssets;
811
+ };
812
+ /**
813
+ * Processes module assets and tracks them in the files map
814
+ * @param bundle - The Rollup output bundle
815
+ * @param filesMap - The preload map to populate
816
+ * @param moduleMatcher - Function that matches module paths to keys
817
+ */
818
+ var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
819
+ for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
820
+ var _Object$entries2$_i = _Object$entries2[_i2],
821
+ fileName = _Object$entries2$_i[0],
822
+ fileData = _Object$entries2$_i[1];
823
+ if (fileData.type !== 'chunk') continue;
824
+ if (!fileData.modules) continue;
825
+ for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
826
+ var modulePath = _Object$keys[_i3];
827
+ var matchKey = moduleMatcher(modulePath);
828
+ if (!matchKey) continue;
829
+ // Track main JS chunk
830
+ trackAsset(filesMap, matchKey, fileName, false, 'js');
831
+ // Handle dynamic imports
832
+ if (fileData.dynamicImports) {
833
+ for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
834
+ var dynamicImport = _step.value;
835
+ var importData = bundle[dynamicImport];
836
+ if (!importData) continue;
837
+ var isCss = isCSSFile(dynamicImport);
838
+ trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
839
+ }
840
+ }
841
+ }
842
+ }
843
+ };
844
+ /**
845
+ * Deduplicates assets in the files map
846
+ * @param filesMap - The preload map to deduplicate
847
+ * @returns New deduplicated preload map
848
+ */
849
+ var deduplicateAssets = function deduplicateAssets(filesMap) {
850
+ var result = {};
851
+ for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
852
+ var _Object$entries3$_i = _Object$entries3[_i4],
853
+ key = _Object$entries3$_i[0],
854
+ assetMaps = _Object$entries3$_i[1];
855
+ result[key] = createEmptyAssetMap();
856
+ for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
857
+ var type = _ASSET_TYPES[_i5];
858
+ for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
859
+ var timing = _LOAD_TIMINGS[_i6];
860
+ result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
861
+ }
862
+ }
863
+ }
864
+ return result;
865
+ };
866
+ /**
867
+ * Builds a mapping between module files and their share keys
868
+ * @param shareKeys - Set of share keys to map
869
+ * @param resolveFn - Function to resolve module paths
870
+ * @returns Map of file paths to their corresponding share keys
871
+ */
872
+ var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
873
+ try {
874
+ var fileToShareKey = new Map();
875
+ return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
876
+ return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
877
+ var _resolution$id;
878
+ return {
879
+ shareKey: shareKey,
880
+ file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
881
+ };
882
+ })["catch"](function () {
883
+ return null;
884
+ });
885
+ }))).then(function (resolutions) {
886
+ for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
887
+ var resolution = _step2.value;
888
+ if (resolution != null && resolution.file) {
889
+ fileToShareKey.set(resolution.file, resolution.shareKey);
890
+ }
891
+ }
892
+ return fileToShareKey;
893
+ });
894
+ } catch (e) {
895
+ return Promise.reject(e);
896
+ }
897
+ };
898
+
899
+ /**
900
+ * Resolves the public path for remote entries
901
+ * @param options - Module Federation options
902
+ * @param viteBase - Vite's base config value
903
+ * @param originalBase - Original base config before any transformations
904
+ * @returns The resolved public path
905
+ */
906
+ function resolvePublicPath(options, viteBase, originalBase) {
907
+ // Use explicitly set publicPath if provided
908
+ if (options.publicPath) {
909
+ return options.publicPath;
910
+ }
911
+ // Handle empty original base case
912
+ if (originalBase === '') {
913
+ return 'auto';
914
+ }
915
+ // Use viteBase if available, ensuring it ends with a slash
916
+ if (viteBase) {
917
+ return viteBase.replace(/\/?$/, '/');
918
+ }
919
+ // Fallback to auto if no base is specified
920
+ return 'auto';
921
+ }
922
+
745
923
  var Manifest = function Manifest() {
746
924
  var mfOptions = getNormalizeModuleFederationOptions();
747
925
  var name = mfOptions.name,
@@ -753,21 +931,43 @@ var Manifest = function Manifest() {
753
931
  mfManifestName = 'mf-manifest.json';
754
932
  }
755
933
  if (typeof manifestOptions !== 'boolean') {
756
- mfManifestName = join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
934
+ mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
757
935
  }
758
- var extensions;
759
936
  var root;
760
937
  var remoteEntryFile;
761
938
  var publicPath;
762
939
  var _command;
763
940
  var _originalConfigBase;
764
941
  var viteConfig;
942
+ /**
943
+ * Adds global CSS assets to all module exports
944
+ * @param filesMap - The preload map to update
945
+ * @param cssAssets - Set of CSS asset filenames to add
946
+ */
947
+ var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
948
+ Object.keys(filesMap).forEach(function (key) {
949
+ cssAssets.forEach(function (cssAsset) {
950
+ trackAsset(filesMap, key, cssAsset, false, 'css');
951
+ });
952
+ });
953
+ };
765
954
  return [{
766
955
  name: 'module-federation-manifest',
767
956
  apply: 'serve',
957
+ /**
958
+ * Stores resolved Vite config for later use
959
+ */
960
+ /**
961
+ * Finalizes configuration after all plugins are resolved
962
+ * @param config - Fully resolved Vite config
963
+ */
768
964
  configResolved: function configResolved(config) {
769
965
  viteConfig = config;
770
966
  },
967
+ /**
968
+ * Configures dev server middleware to handle manifest requests
969
+ * @param server - Vite dev server instance
970
+ */
771
971
  configureServer: function configureServer(server) {
772
972
  server.middlewares.use(function (req, res, next) {
773
973
  var _req$url;
@@ -815,137 +1015,85 @@ var Manifest = function Manifest() {
815
1015
  }, {
816
1016
  name: 'module-federation-manifest',
817
1017
  enforce: 'post',
1018
+ /**
1019
+ * Initial plugin configuration
1020
+ * @param config - Vite config object
1021
+ * @param command - Current Vite command (serve/build)
1022
+ */
818
1023
  config: function config(_config, _ref) {
819
1024
  var command = _ref.command;
820
1025
  if (!_config.build) _config.build = {};
821
- if (!_config.build.manifest) _config.build.manifest = _config.build.manifest || !!manifestOptions;
1026
+ if (!_config.build.manifest) {
1027
+ _config.build.manifest = _config.build.manifest || !!manifestOptions;
1028
+ }
822
1029
  _command = command;
823
1030
  _originalConfigBase = _config.base;
824
1031
  },
825
1032
  configResolved: function configResolved(config) {
826
1033
  root = config.root;
827
- extensions = config.resolve.extensions || ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'];
828
1034
  var base = config.base;
829
1035
  if (_command === 'serve') {
830
1036
  base = (config.server.origin || '') + config.base;
831
1037
  }
832
- publicPath = _originalConfigBase === '' ? 'auto' : base ? base.replace(/\/?$/, '/') : 'auto';
1038
+ publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
833
1039
  },
1040
+ /**
1041
+ * Generates the module federation manifest file
1042
+ * @param options - Rollup output options
1043
+ * @param bundle - Generated bundle assets
1044
+ */
834
1045
  generateBundle: function generateBundle(options, bundle) {
835
1046
  try {
836
1047
  var _this = this;
837
- // 递归查找模块的同步导入文件
838
- var _findSynchronousImports = function findSynchronousImports(fileName, array) {
839
- var fileData = bundle[fileName];
840
- if (fileData && fileData.type === 'chunk') {
841
- array.push(fileName); // 将当前文件加入预加载列表
842
- // 遍历该文件的同步导入文件
843
- fileData.imports.forEach(function (importedFile) {
844
- if (array.indexOf(importedFile) === -1) {
845
- _findSynchronousImports(importedFile, array); // 递归查找同步导入的文件
846
- }
847
- });
848
- }
849
- };
850
1048
  if (!mfManifestName) return Promise.resolve();
851
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
852
- return mfOptions.exposes[item]["import"];
853
- }); // 获取你提供的 moduleIds
854
- var filesContainingModules = {};
855
- // 帮助函数:检查模块路径是否匹配
856
- var isModuleMatched = function isModuleMatched(relativeModulePath, preloadModule) {
857
- // 先尝试直接匹配
858
- if (relativeModulePath === preloadModule) return true;
859
- // 如果 preloadModule 没有后缀,尝试添加可能的后缀进行匹配
860
- for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
861
- var ext = _step.value;
862
- if (relativeModulePath === "" + preloadModule + ext) {
863
- return true;
864
- }
865
- }
866
- return false;
867
- };
868
- // 遍历打包生成的每个文件
1049
+ var filesMap = {};
1050
+ // First pass: Find remoteEntry file
869
1051
  for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
870
1052
  var _Object$entries$_i = _Object$entries[_i],
871
- fileName = _Object$entries$_i[0],
1053
+ _ = _Object$entries$_i[0],
872
1054
  fileData = _Object$entries$_i[1];
873
1055
  if (mfOptions.filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
874
1056
  remoteEntryFile = fileData.fileName;
875
- }
876
- if (fileData.type === 'chunk') {
877
- // 遍历该文件的所有模块
878
- for (var _i2 = 0, _Object$keys = Object.keys(fileData.modules); _i2 < _Object$keys.length; _i2++) {
879
- var modulePath = _Object$keys[_i2];
880
- // 将绝对路径转换为相对于 Vite root 的相对路径
881
- var relativeModulePath = relative(root, modulePath);
882
- // 检查模块是否在 preloadModules 列表中
883
- for (var _iterator2 = _createForOfIteratorHelperLoose(exposesModules), _step2; !(_step2 = _iterator2()).done;) {
884
- var preloadModule = _step2.value;
885
- var formatPreloadModule = preloadModule.replace('./', '');
886
- if (isModuleMatched(relativeModulePath, formatPreloadModule)) {
887
- var _filesContainingModul;
888
- if (!filesContainingModules[preloadModule]) {
889
- filesContainingModules[preloadModule] = {
890
- sync: [],
891
- async: []
892
- };
893
- }
894
- console.log(Object.keys(fileData.modules));
895
- filesContainingModules[preloadModule].sync.push(fileName);
896
- (_filesContainingModul = filesContainingModules[preloadModule].async).push.apply(_filesContainingModul, fileData.dynamicImports || []);
897
- _findSynchronousImports(fileName, filesContainingModules[preloadModule].sync);
898
- break; // 如果找到匹配,跳出循环
899
- }
900
- }
901
- }
1057
+ break; // We can break early since we only need to find remoteEntry once
902
1058
  }
903
1059
  }
904
- var fileToShareKey = {};
905
- return Promise.resolve(Promise.all(Array.from(getUsedShares()).map(function (shareKey) {
906
- try {
907
- return Promise.resolve(_this.resolve(getPreBuildLibImportId(shareKey))).then(function (_this$resolve) {
908
- var file = _this$resolve.id.split('?')[0];
909
- fileToShareKey[file] = shareKey;
910
- });
911
- } catch (e) {
912
- return Promise.reject(e);
913
- }
914
- }))).then(function () {
915
- // 遍历打包生成的每个文件
916
- for (var _i3 = 0, _Object$entries2 = Object.entries(bundle); _i3 < _Object$entries2.length; _i3++) {
917
- var _Object$entries2$_i = _Object$entries2[_i3],
918
- _fileName = _Object$entries2$_i[0],
919
- _fileData = _Object$entries2$_i[1];
920
- if (_fileData.type === 'chunk') {
921
- // 遍历该文件的所有模块
922
- for (var _i4 = 0, _Object$keys2 = Object.keys(_fileData.modules); _i4 < _Object$keys2.length; _i4++) {
923
- var _modulePath = _Object$keys2[_i4];
924
- var sharedKey = fileToShareKey[_modulePath];
925
- if (sharedKey) {
926
- var _filesContainingModul2;
927
- if (!filesContainingModules[sharedKey]) {
928
- filesContainingModules[sharedKey] = {
929
- sync: [],
930
- async: []
931
- };
932
- }
933
- filesContainingModules[sharedKey].sync.push(_fileName);
934
- (_filesContainingModul2 = filesContainingModules[sharedKey].async).push.apply(_filesContainingModul2, _fileData.dynamicImports || []);
935
- _findSynchronousImports(_fileName, filesContainingModules[sharedKey].sync);
936
- break; // 如果找到匹配,跳出循环
937
- }
938
- }
1060
+ // Second pass: Collect all CSS assets
1061
+ var allCssAssets = collectCssAssets(bundle);
1062
+ var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1063
+ return mfOptions.exposes[item]["import"];
1064
+ });
1065
+ // Process exposed modules
1066
+ processModuleAssets(bundle, filesMap, function (modulePath) {
1067
+ var absoluteModulePath = path.resolve(root, modulePath);
1068
+ return exposesModules.find(function (exposeModule) {
1069
+ var exposePath = path.resolve(root, exposeModule);
1070
+ // First try exact path match
1071
+ if (absoluteModulePath === exposePath) {
1072
+ return true;
939
1073
  }
940
- }
941
- Object.keys(filesContainingModules).forEach(function (key) {
942
- filesContainingModules[key].sync = Array.from(new Set(filesContainingModules[key].sync));
943
- filesContainingModules[key].async = Array.from(new Set(filesContainingModules[key].async));
1074
+ // Then try path match without known extensions
1075
+ var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1076
+ var ext = path.extname(filePath);
1077
+ return JS_EXTENSIONS.includes(ext) ? path.join(path.dirname(filePath), path.basename(filePath, ext)) : filePath;
1078
+ };
1079
+ var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1080
+ var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1081
+ return modulePathNoExt === exposePathNoExt;
1082
+ });
1083
+ });
1084
+ // Process shared modules
1085
+ return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1086
+ processModuleAssets(bundle, filesMap, function (modulePath) {
1087
+ return fileToShareKey.get(modulePath);
944
1088
  });
1089
+ // Add all CSS assets to every export
1090
+ addCssAssetsToAllExports(filesMap, allCssAssets);
1091
+ // Final deduplication of all assets
1092
+ filesMap = deduplicateAssets(filesMap);
945
1093
  _this.emitFile({
946
1094
  type: 'asset',
947
1095
  fileName: mfManifestName,
948
- source: JSON.stringify(generateMFManifest(filesContainingModules))
1096
+ source: JSON.stringify(generateMFManifest(filesMap))
949
1097
  });
950
1098
  });
951
1099
  } catch (e) {
@@ -953,6 +1101,11 @@ var Manifest = function Manifest() {
953
1101
  }
954
1102
  }
955
1103
  }];
1104
+ /**
1105
+ * Generates the final manifest JSON structure
1106
+ * @param preloadMap - Map of module assets to include
1107
+ * @returns Complete manifest object
1108
+ */
956
1109
  function generateMFManifest(preloadMap) {
957
1110
  var options = getNormalizeModuleFederationOptions();
958
1111
  var name = options.name;
@@ -961,23 +1114,23 @@ var Manifest = function Manifest() {
961
1114
  path: '',
962
1115
  type: 'module'
963
1116
  };
964
- var remotes = [];
965
- var usedRemotesMap = getUsedRemotesMap();
966
- Object.keys(usedRemotesMap).forEach(function (remoteKey) {
967
- var usedModules = Array.from(usedRemotesMap[remoteKey]);
968
- usedModules.forEach(function (moduleKey) {
969
- remotes.push({
1117
+ // Process remotes
1118
+ var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1119
+ var remoteKey = _ref2[0],
1120
+ modules = _ref2[1];
1121
+ return Array.from(modules).map(function (moduleKey) {
1122
+ return {
970
1123
  federationContainerName: options.remotes[remoteKey].entry,
971
1124
  moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
972
1125
  alias: remoteKey,
973
1126
  entry: '*'
974
- });
1127
+ };
975
1128
  });
976
1129
  });
977
- // @ts-ignore
1130
+ // Process shared dependencies
978
1131
  var shared = Array.from(getUsedShares()).map(function (shareKey) {
979
- var _preloadMap$shareKey, _preloadMap$shareKey2;
980
1132
  var shareItem = getNormalizeShareItem(shareKey);
1133
+ var assets = preloadMap[shareKey] || createEmptyAssetMap();
981
1134
  return {
982
1135
  id: name + ":" + shareKey,
983
1136
  name: shareKey,
@@ -985,42 +1138,40 @@ var Manifest = function Manifest() {
985
1138
  requiredVersion: shareItem.shareConfig.requiredVersion,
986
1139
  assets: {
987
1140
  js: {
988
- async: (preloadMap == null || (_preloadMap$shareKey = preloadMap[shareKey]) == null ? void 0 : _preloadMap$shareKey.async) || [],
989
- sync: (preloadMap == null || (_preloadMap$shareKey2 = preloadMap[shareKey]) == null ? void 0 : _preloadMap$shareKey2.sync) || []
1141
+ async: assets.js.async,
1142
+ sync: assets.js.sync
990
1143
  },
991
1144
  css: {
992
- async: [],
993
- sync: []
1145
+ async: assets.css.async,
1146
+ sync: assets.css.sync
994
1147
  }
995
1148
  }
996
1149
  };
997
- }).filter(function (item) {
998
- return item;
999
- });
1000
- var exposes = Object.keys(options.exposes).map(function (key) {
1001
- var _preloadMap$sourceFil, _preloadMap$sourceFil2;
1002
- // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
1150
+ }).filter(Boolean);
1151
+ // Process exposed modules
1152
+ var exposes = Object.entries(options.exposes).map(function (_ref3) {
1153
+ var key = _ref3[0],
1154
+ value = _ref3[1];
1003
1155
  var formatKey = key.replace('./', '');
1004
- var sourceFile = options.exposes[key]["import"];
1156
+ var sourceFile = value["import"];
1157
+ var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1005
1158
  return {
1006
- id: name + ':' + formatKey,
1159
+ id: name + ":" + formatKey,
1007
1160
  name: formatKey,
1008
1161
  assets: {
1009
1162
  js: {
1010
- async: (preloadMap == null || (_preloadMap$sourceFil = preloadMap[sourceFile]) == null ? void 0 : _preloadMap$sourceFil.async) || [],
1011
- sync: (preloadMap == null || (_preloadMap$sourceFil2 = preloadMap[sourceFile]) == null ? void 0 : _preloadMap$sourceFil2.sync) || []
1163
+ async: assets.js.async,
1164
+ sync: assets.js.sync
1012
1165
  },
1013
1166
  css: {
1014
- sync: [],
1015
- async: []
1167
+ async: assets.css.async,
1168
+ sync: assets.css.sync
1016
1169
  }
1017
1170
  },
1018
1171
  path: key
1019
1172
  };
1020
- }).filter(function (item) {
1021
- return item;
1022
- }); // Filter out any null values
1023
- var result = {
1173
+ }).filter(Boolean);
1174
+ return {
1024
1175
  id: name,
1025
1176
  name: name,
1026
1177
  metaData: _extends({
@@ -1035,8 +1186,6 @@ var Manifest = function Manifest() {
1035
1186
  types: {
1036
1187
  path: '',
1037
1188
  name: ''
1038
- // "zip": "@mf-types.zip",
1039
- // "api": "@mf-types.d.ts"
1040
1189
  },
1041
1190
  globalName: name,
1042
1191
  pluginVersion: '0.2.5'
@@ -1049,7 +1198,6 @@ var Manifest = function Manifest() {
1049
1198
  remotes: remotes,
1050
1199
  exposes: exposes
1051
1200
  };
1052
- return result;
1053
1201
  }
1054
1202
  };
1055
1203
 
@@ -1153,7 +1301,8 @@ function pluginProxyRemoteEntry () {
1153
1301
  if (_command === 'serve') {
1154
1302
  var _viteConfig$server, _viteConfig$server2;
1155
1303
  var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1156
- return Promise.resolve("\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + \"" + (viteConfig.base + options.filename) + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await. \n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1304
+ var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1305
+ return Promise.resolve("\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1157
1306
  }
1158
1307
  return Promise.resolve(code);
1159
1308
  }