@module-federation/vite 1.16.1 → 1.16.3
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 +304 -83
- package/lib/index.d.cts +1 -1
- package/lib/index.d.mts +1 -1
- package/lib/index.mjs +304 -83
- package/lib/{packageUtils-DOekOsFz.mjs → packageUtils-Bbc6r6__.mjs} +4 -1
- package/lib/{packageUtils-CbbnJvKu.cjs → packageUtils-se-UDhCa.cjs} +9 -0
- package/lib/{pluginDts-BEOKyKQ-.cjs → pluginDts-7EoFboCu.cjs} +1 -1
- package/lib/{pluginDts-B5pcUmam.mjs → pluginDts-DDx4TPN8.mjs} +1 -1
- package/package.json +16 -16
package/lib/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as getPackageName, c as
|
|
1
|
+
import { a as getPackageName, c as hasPackageDependency, d as packageNameEncode, f as setPackageDetectionCwd, g as __require, h as mfWarn, i as getPackageDetectionCwd, l as isNuxtProjectRoot, n as getInstalledPackageJson, o as getPackageNameFromNodeModulePath, p as createModuleFederationError, r as getIsRolldown, s as getSharedCacheKey, t as getInstalledPackageEntry, u as packageNameDecode } from "./packageUtils-Bbc6r6__.mjs";
|
|
2
2
|
import * as fs$1 from "fs";
|
|
3
3
|
import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
|
|
4
4
|
import { createRequire } from "module";
|
|
@@ -417,24 +417,51 @@ function getSuffix(name) {
|
|
|
417
417
|
}
|
|
418
418
|
const patternMap = {};
|
|
419
419
|
const cacheMap = {};
|
|
420
|
+
const VITE_ID_PREFIX = "/@id/";
|
|
421
|
+
const VITE_ENCODED_NULL_BYTE_PREFIX = `${VITE_ID_PREFIX}__x00__`;
|
|
422
|
+
function escapeRegExp$1(value) {
|
|
423
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
424
|
+
}
|
|
425
|
+
function createViteEncodedIdPrefixRegExp(sourcePrefix = "") {
|
|
426
|
+
return new RegExp(`^(?:${escapeRegExp$1(VITE_ENCODED_NULL_BYTE_PREFIX)})?${sourcePrefix}`);
|
|
427
|
+
}
|
|
428
|
+
function toViteEncodedId(id) {
|
|
429
|
+
return `${VITE_ENCODED_NULL_BYTE_PREFIX}${id}`;
|
|
430
|
+
}
|
|
431
|
+
function decodeViteId(id) {
|
|
432
|
+
if (!id.startsWith("/@id/")) return id;
|
|
433
|
+
const viteId = id.slice(5);
|
|
434
|
+
return viteId.startsWith("__x00__") ? `\0${viteId.slice(7)}` : viteId;
|
|
435
|
+
}
|
|
420
436
|
function assertModuleFound(tag, str = "") {
|
|
421
437
|
const module = VirtualModule.findModule(tag, str);
|
|
422
438
|
if (!module) throw createModuleFederationError(`Module Federation shared module '${str}' not found. Please ensure it's installed as a dependency in your package.json.`);
|
|
423
439
|
return module;
|
|
424
440
|
}
|
|
425
|
-
|
|
441
|
+
function normalizeVirtualModuleId(id) {
|
|
442
|
+
const decoded = decodeViteId(id).replace(/^\0+/, "");
|
|
443
|
+
const queryIndex = decoded.indexOf("?");
|
|
444
|
+
const hashIndex = decoded.indexOf("#");
|
|
445
|
+
const endIndex = queryIndex === -1 ? hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
|
|
446
|
+
return endIndex === -1 ? decoded : decoded.slice(0, endIndex);
|
|
447
|
+
}
|
|
448
|
+
var VirtualModule = class VirtualModule {
|
|
426
449
|
name;
|
|
427
450
|
tag;
|
|
428
451
|
suffix;
|
|
429
452
|
inited = false;
|
|
430
453
|
code;
|
|
431
|
-
static
|
|
454
|
+
static findName(tag, str = "") {
|
|
432
455
|
if (!patternMap[tag]) patternMap[tag] = new RegExp(`(.*${packageNameEncode(tag)}(.+?)${packageNameEncode(tag)}.*)`);
|
|
433
|
-
const moduleName = (str.match(patternMap[tag]) || [])[2];
|
|
434
|
-
|
|
456
|
+
const moduleName = (normalizeVirtualModuleId(str).match(patternMap[tag]) || [])[2];
|
|
457
|
+
return moduleName ? packageNameDecode(moduleName) : void 0;
|
|
458
|
+
}
|
|
459
|
+
static findModule(tag, str = "") {
|
|
460
|
+
const moduleName = VirtualModule.findName(tag, str);
|
|
461
|
+
return moduleName ? cacheMap[tag][moduleName] : void 0;
|
|
435
462
|
}
|
|
436
463
|
static findById(id) {
|
|
437
|
-
const normalized =
|
|
464
|
+
const normalized = normalizeVirtualModuleId(id);
|
|
438
465
|
for (const modules of Object.values(cacheMap)) for (const module of Object.values(modules)) if (module.getImportId() === normalized) return module;
|
|
439
466
|
}
|
|
440
467
|
constructor(name, tag = "__mf_v__", suffix = "") {
|
|
@@ -748,11 +775,9 @@ function getPackageEsmEntryPath(pkg) {
|
|
|
748
775
|
resolveSubpathWithRequire: false
|
|
749
776
|
}) || resolvePackageEntryFromProjectRoot(pkg);
|
|
750
777
|
}
|
|
751
|
-
function
|
|
778
|
+
function getEsmNamedExportsFromFile(entryPath) {
|
|
752
779
|
let source = "";
|
|
753
|
-
let entryPath;
|
|
754
780
|
try {
|
|
755
|
-
entryPath = getPackageEsmEntryPath(pkg);
|
|
756
781
|
if (!entryPath) return [];
|
|
757
782
|
const { initSync, parse } = localRequire("es-module-lexer");
|
|
758
783
|
initSync();
|
|
@@ -767,6 +792,48 @@ function getEsmNamedExports(pkg) {
|
|
|
767
792
|
return source ? getNamedExportsViaRegex(source, entryPath) : [];
|
|
768
793
|
}
|
|
769
794
|
}
|
|
795
|
+
function getEsmNamedExports(pkg) {
|
|
796
|
+
return getEsmNamedExportsFromFile(getPackageEsmEntryPath(pkg));
|
|
797
|
+
}
|
|
798
|
+
function resolveConfiguredImportPath(importSource) {
|
|
799
|
+
if (path.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
|
|
800
|
+
const projectRoot = getPackageDetectionCwd();
|
|
801
|
+
if (importSource.startsWith(".")) return resolveFileLikeModule(path.resolve(projectRoot, importSource));
|
|
802
|
+
const esmEntry = getInstalledPackageEntry(importSource, {
|
|
803
|
+
conditions: [
|
|
804
|
+
"browser",
|
|
805
|
+
"import",
|
|
806
|
+
"module",
|
|
807
|
+
"default"
|
|
808
|
+
],
|
|
809
|
+
resolveSubpathWithRequire: false
|
|
810
|
+
});
|
|
811
|
+
if (esmEntry) return esmEntry;
|
|
812
|
+
try {
|
|
813
|
+
return createRequire(new URL(`file://${path.join(projectRoot, "package.json")}`)).resolve(importSource);
|
|
814
|
+
} catch {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
function resolveFileLikeModule(filePath) {
|
|
819
|
+
if (existsSync(filePath) && !statSync(filePath).isDirectory()) return filePath;
|
|
820
|
+
const extensions = [
|
|
821
|
+
".ts",
|
|
822
|
+
".tsx",
|
|
823
|
+
".js",
|
|
824
|
+
".jsx",
|
|
825
|
+
".mjs",
|
|
826
|
+
".mts"
|
|
827
|
+
];
|
|
828
|
+
for (const ext of extensions) {
|
|
829
|
+
const candidate = filePath + ext;
|
|
830
|
+
if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
|
|
831
|
+
}
|
|
832
|
+
for (const ext of extensions) {
|
|
833
|
+
const candidate = path.join(filePath, "index" + ext);
|
|
834
|
+
if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
770
837
|
function resolveRelativeModule(filePath, specifier) {
|
|
771
838
|
const dir = path.dirname(filePath);
|
|
772
839
|
const exact = path.resolve(dir, specifier);
|
|
@@ -836,6 +903,14 @@ function getPackageNamedExports(pkg) {
|
|
|
836
903
|
return getEsmNamedExports(pkg);
|
|
837
904
|
}
|
|
838
905
|
}
|
|
906
|
+
function getSharedNamedExports(pkg, shareItem) {
|
|
907
|
+
const configuredImport = shareItem?.shareConfig.import;
|
|
908
|
+
if (typeof configuredImport === "string") {
|
|
909
|
+
const configuredNamedExports = getEsmNamedExportsFromFile(resolveConfiguredImportPath(configuredImport));
|
|
910
|
+
if (configuredNamedExports.length > 0) return configuredNamedExports;
|
|
911
|
+
}
|
|
912
|
+
return getPackageNamedExports(pkg);
|
|
913
|
+
}
|
|
839
914
|
function getLocalProviderImportPath(pkg) {
|
|
840
915
|
try {
|
|
841
916
|
const resolved = createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
|
|
@@ -906,6 +981,20 @@ function writePreBuildLibPath(pkg, shareItem) {
|
|
|
906
981
|
if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG, ".js");
|
|
907
982
|
preBuildShareItemMap[pkg] = shareItem;
|
|
908
983
|
const importSource = getConcreteSharedImportSource(pkg, shareItem) || pkg;
|
|
984
|
+
if (pkg === "react/compiler-runtime") {
|
|
985
|
+
preBuildCacheMap[pkg].writeSync(`
|
|
986
|
+
const __mfCacheGlobalKey = "__mf_module_cache__";
|
|
987
|
+
export const c = function(size) {
|
|
988
|
+
const cache = globalThis[__mfCacheGlobalKey]?.share;
|
|
989
|
+
const sharedReact = cache?.['react'];
|
|
990
|
+
const reactExports = sharedReact?.default ?? sharedReact;
|
|
991
|
+
const internals = reactExports?.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
|
|
992
|
+
return internals?.H?.useMemoCache(size);
|
|
993
|
+
};
|
|
994
|
+
export default { c };
|
|
995
|
+
`, true);
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
909
998
|
if (pkg === "react/jsx-dev-runtime") {
|
|
910
999
|
preBuildCacheMap[pkg].writeSync(`
|
|
911
1000
|
import __mfPrebuildDefault from ${escapeGeneratedStringLiteral(importSource)};
|
|
@@ -929,7 +1018,7 @@ function writePreBuildLibPath(pkg, shareItem) {
|
|
|
929
1018
|
`, true);
|
|
930
1019
|
return;
|
|
931
1020
|
}
|
|
932
|
-
const namedExports =
|
|
1021
|
+
const namedExports = getSharedNamedExports(pkg, shareItem);
|
|
933
1022
|
if (namedExports.length > 0) {
|
|
934
1023
|
const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
|
|
935
1024
|
const declarations = namedExports.map((name, i) => `const ${namedExportVars[i]} = __mfPrebuildExports[${escapeGeneratedStringLiteral(name)}];`).join("\n ");
|
|
@@ -969,7 +1058,28 @@ function getLoadShareModulePath(pkg, isRolldown) {
|
|
|
969
1058
|
if (!loadShareCacheMap[pkg]) getLoadShareImportId(pkg, isRolldown);
|
|
970
1059
|
return loadShareCacheMap[pkg].getImportId();
|
|
971
1060
|
}
|
|
972
|
-
function
|
|
1061
|
+
function toViteOptimizedDepVirtualId(id) {
|
|
1062
|
+
return toViteEncodedId(id);
|
|
1063
|
+
}
|
|
1064
|
+
function getCachedLoadSharePkg(id) {
|
|
1065
|
+
const normalized = normalizeVirtualModuleId(id);
|
|
1066
|
+
if (!normalized.startsWith("virtual:mf:")) return;
|
|
1067
|
+
const pkg = VirtualModule.findName(LOAD_SHARE_TAG, normalized);
|
|
1068
|
+
if (!pkg) return;
|
|
1069
|
+
return pkg;
|
|
1070
|
+
}
|
|
1071
|
+
function materializeCachedLoadShareModule(options) {
|
|
1072
|
+
const pkg = getCachedLoadSharePkg(options.id);
|
|
1073
|
+
if (!pkg) return;
|
|
1074
|
+
const key = options.findSharedKey(pkg, options.shared);
|
|
1075
|
+
if (!key) return;
|
|
1076
|
+
const shareItem = options.shared[key];
|
|
1077
|
+
writeLoadShareModule(pkg, shareItem, options.command, options.isRolldown);
|
|
1078
|
+
if (shareItem.shareConfig?.import !== false) writePreBuildLibPath(pkg, shareItem);
|
|
1079
|
+
options.addUsedShares(pkg);
|
|
1080
|
+
options.writeLocalSharedImportMap();
|
|
1081
|
+
}
|
|
1082
|
+
function generateDeferredHostProvidedExports(namedExports, pkg, cacheKey) {
|
|
973
1083
|
const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
|
|
974
1084
|
const declarations = ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ");
|
|
975
1085
|
const assignments = [...namedExports.map((name, i) => `${namedExportVars[i]} = exportModule[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = exportModule.default ?? exportModule;"].join("\n ");
|
|
@@ -978,10 +1088,10 @@ function generateDeferredHostProvidedExports(namedExports, pkg) {
|
|
|
978
1088
|
const __mfApplyHostProvidedExports = (exportModule) => {
|
|
979
1089
|
${assignments}
|
|
980
1090
|
};
|
|
981
|
-
let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(
|
|
1091
|
+
let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}];
|
|
982
1092
|
if (exportModule === undefined) {
|
|
983
1093
|
initPromise.then(() => {
|
|
984
|
-
exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(
|
|
1094
|
+
exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}];
|
|
985
1095
|
if (exportModule === undefined) {
|
|
986
1096
|
throw new Error("[Module Federation] Shared module ${pkg} was imported before federation bootstrap finished.");
|
|
987
1097
|
}
|
|
@@ -1012,13 +1122,14 @@ const normalizeLocalShareModuleCode = `const __mfNormalizeShareModule = (mod) =>
|
|
|
1012
1122
|
function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
1013
1123
|
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".mjs");
|
|
1014
1124
|
const importLine = getRuntimeModuleCacheBootstrapCode();
|
|
1125
|
+
const cacheKey = getSharedCacheKey(pkg, shareItem);
|
|
1015
1126
|
if (shareItem.shareConfig.import === false) {
|
|
1016
1127
|
const namedExports = getPackageNamedExports(pkg);
|
|
1017
1128
|
let exportLine;
|
|
1018
|
-
if (namedExports.length > 0) exportLine = generateDeferredHostProvidedExports(namedExports, pkg);
|
|
1129
|
+
if (namedExports.length > 0) exportLine = generateDeferredHostProvidedExports(namedExports, pkg, cacheKey);
|
|
1019
1130
|
else {
|
|
1020
1131
|
mfWarn(`Shared dependency "${pkg}" has import: false but is not installed locally.\n Named imports (e.g. import { ... } from '${pkg}') will not work in production builds.\n Install it as a devDependency to enable named export detection.`);
|
|
1021
|
-
exportLine = generateDeferredHostProvidedExports([], pkg);
|
|
1132
|
+
exportLine = generateDeferredHostProvidedExports([], pkg, cacheKey);
|
|
1022
1133
|
}
|
|
1023
1134
|
loadShareCacheMap[pkg].writeSync(`
|
|
1024
1135
|
${getRuntimeInitPromiseBootstrapCode()}
|
|
@@ -1035,7 +1146,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
|
1035
1146
|
const lazyLocalFallbackSource = concreteSharedImportSource || localProviderPath || sharedImportSource;
|
|
1036
1147
|
const skipServePrebuildWarmup = command !== "build" && (pkg === "lit" || pkg.startsWith("lit/"));
|
|
1037
1148
|
const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
|
|
1038
|
-
const namedExports =
|
|
1149
|
+
const namedExports = getSharedNamedExports(pkg, shareItem);
|
|
1039
1150
|
let exportLine;
|
|
1040
1151
|
if (namedExports.length > 0) {
|
|
1041
1152
|
const destructure = `const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`;
|
|
@@ -1059,11 +1170,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
|
1059
1170
|
${devDynamicImportLine}
|
|
1060
1171
|
${importLine}
|
|
1061
1172
|
${normalizeLocalShareModuleCode}
|
|
1062
|
-
let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(
|
|
1173
|
+
let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}]
|
|
1063
1174
|
if (exportModule === undefined) {
|
|
1064
1175
|
${usesLazyLocalFallback ? `exportModule = __mfNormalizeShareModule(await import(${escapeGeneratedStringLiteral(lazyLocalFallbackSource)}));
|
|
1065
|
-
__mfModuleCache.share[${escapeGeneratedStringLiteral(
|
|
1066
|
-
__mfModuleCache.share[${escapeGeneratedStringLiteral(
|
|
1176
|
+
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;` : `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
1177
|
+
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`}
|
|
1067
1178
|
}
|
|
1068
1179
|
${exportLine}
|
|
1069
1180
|
`, true);
|
|
@@ -1135,7 +1246,7 @@ function generateLocalSharedImportMap() {
|
|
|
1135
1246
|
version: ${JSON.stringify(shareItem.version)},
|
|
1136
1247
|
scope: [${JSON.stringify(shareItem.scope)}],
|
|
1137
1248
|
loaded: false,
|
|
1138
|
-
from: ${JSON.stringify(options.
|
|
1249
|
+
from: ${JSON.stringify(options.name)},
|
|
1139
1250
|
async get () {
|
|
1140
1251
|
if (${shareItem.shareConfig.import === false}) {
|
|
1141
1252
|
throw new Error(\`[Module Federation] Shared module '\${${JSON.stringify(key)}}' must be provided by host\`);
|
|
@@ -1217,8 +1328,9 @@ function getShareItemForPreload(pkg) {
|
|
|
1217
1328
|
if (isExplicitSharedKey(pkg)) return shared[pkg];
|
|
1218
1329
|
if (isExplicitSharedKey(wildcardKey)) return shared[wildcardKey];
|
|
1219
1330
|
}
|
|
1220
|
-
function generateSharedCacheSeedItem(pkg, importPath) {
|
|
1221
|
-
|
|
1331
|
+
function generateSharedCacheSeedItem(pkg, shareItem, importPath) {
|
|
1332
|
+
const cacheKey = getSharedCacheKey(pkg, shareItem);
|
|
1333
|
+
return `if (__mfModuleCache.share[${JSON.stringify(cacheKey)}] === undefined) {
|
|
1222
1334
|
const mod = await import(${JSON.stringify(importPath)});
|
|
1223
1335
|
${normalizeRuntimeShareCode}
|
|
1224
1336
|
const normalizedModule = __mfNormalizeRuntimeShare(mod);
|
|
@@ -1227,7 +1339,7 @@ function generateSharedCacheSeedItem(pkg, importPath) {
|
|
|
1227
1339
|
value: true,
|
|
1228
1340
|
enumerable: false
|
|
1229
1341
|
});
|
|
1230
|
-
__mfModuleCache.share[${JSON.stringify(
|
|
1342
|
+
__mfModuleCache.share[${JSON.stringify(cacheKey)}] = exportModule;
|
|
1231
1343
|
}`;
|
|
1232
1344
|
}
|
|
1233
1345
|
const normalizeRuntimeShareCode = `const __mfNormalizeRuntimeShare = (mod) => {
|
|
@@ -1245,7 +1357,7 @@ function generateDirectSharedCacheSeedCode(command = "build") {
|
|
|
1245
1357
|
return getOrderedUsedShares().map((pkg) => {
|
|
1246
1358
|
const shareItem = getShareItemForPreload(pkg);
|
|
1247
1359
|
if (!shareItem || shareItem.shareConfig.import === false) return null;
|
|
1248
|
-
return generateSharedCacheSeedItem(pkg, command === "serve" ? getLocalSharedPackagePath(pkg, shareItem) : getDirectSharedCacheSeedImportPath(pkg, shareItem));
|
|
1360
|
+
return generateSharedCacheSeedItem(pkg, shareItem, command === "serve" ? getLocalSharedPackagePath(pkg, shareItem) : getDirectSharedCacheSeedImportPath(pkg, shareItem));
|
|
1249
1361
|
}).filter((item) => item !== null).join("\n");
|
|
1250
1362
|
}
|
|
1251
1363
|
function getBrowserImportPath(importPath) {
|
|
@@ -1267,7 +1379,7 @@ function generateHostAutoInitSharedCacheSeedCode(command = "build") {
|
|
|
1267
1379
|
if (command === "build") return "";
|
|
1268
1380
|
return getHostAutoInitSharedSeedItems().map(({ pkg, shareItem }) => {
|
|
1269
1381
|
if (!shareItem) return null;
|
|
1270
|
-
return generateSharedCacheSeedItem(pkg, getBrowserImportPath(getDirectSharedCacheSeedImportPath(pkg, shareItem)));
|
|
1382
|
+
return generateSharedCacheSeedItem(pkg, shareItem, getBrowserImportPath(getDirectSharedCacheSeedImportPath(pkg, shareItem)));
|
|
1271
1383
|
}).filter((item) => item !== null).join("\n");
|
|
1272
1384
|
}
|
|
1273
1385
|
const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
|
|
@@ -1305,7 +1417,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
1305
1417
|
${getRuntimeModuleCacheBootstrapCode()}
|
|
1306
1418
|
const initTokens = {}
|
|
1307
1419
|
const shareScopeName = ${JSON.stringify(options.shareScope)}
|
|
1308
|
-
const mfName = ${JSON.stringify(options.
|
|
1420
|
+
const mfName = ${JSON.stringify(options.name)}
|
|
1309
1421
|
let localSharedImportMapPromise
|
|
1310
1422
|
let exposesMapPromise
|
|
1311
1423
|
const shouldRetrySharedInitError = ${command !== "build"} && ((error) => {
|
|
@@ -1347,6 +1459,28 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
1347
1459
|
|
|
1348
1460
|
async function init(shared = {}, initScope = []) {
|
|
1349
1461
|
const {usedShared, usedRemotes} = await getLocalSharedImportMap()
|
|
1462
|
+
try {
|
|
1463
|
+
const allInstances = globalThis.__FEDERATION__?.__SHARE__;
|
|
1464
|
+
if (allInstances) {
|
|
1465
|
+
${normalizeRuntimeShareCode}
|
|
1466
|
+
for (const [, scopes] of Object.entries(allInstances)) {
|
|
1467
|
+
const scopeShare = scopes?.['${options.shareScope}'];
|
|
1468
|
+
if (!scopeShare) continue;
|
|
1469
|
+
for (const [pkg, versionMap] of Object.entries(scopeShare)) {
|
|
1470
|
+
for (const [version, provider] of Object.entries(versionMap)) {
|
|
1471
|
+
if (!provider.lib) continue;
|
|
1472
|
+
const cacheKey = provider.shareConfig?.singleton ? pkg : \`\${pkg}@\${version}\`;
|
|
1473
|
+
if (__mfModuleCache.share[cacheKey] !== undefined) continue;
|
|
1474
|
+
const mod = typeof provider.lib === "function" ? provider.lib() : provider.lib;
|
|
1475
|
+
const resolved = await Promise.resolve(mod);
|
|
1476
|
+
__mfModuleCache.share[cacheKey] = __mfNormalizeRuntimeShare(resolved);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
} catch (e) {
|
|
1482
|
+
console.error('[Module Federation] Failed to bridge external shared modules', e)
|
|
1483
|
+
}
|
|
1350
1484
|
${generateDirectSharedCacheSeedCode(command)}
|
|
1351
1485
|
const __browserPlugins = [${pluginImportNames.filter((item) => !isSsrOnlyPlugin(item[1])).map((item) => `${item[0]}(${item[2]})`).join(", ")}];
|
|
1352
1486
|
const __ssrPlugins = typeof globalThis.window === 'undefined'
|
|
@@ -1383,7 +1517,8 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
1383
1517
|
console.error('[Module Federation]', e)
|
|
1384
1518
|
}
|
|
1385
1519
|
for (const [pkg, share] of Object.entries(usedShared)) {
|
|
1386
|
-
|
|
1520
|
+
const cacheKey = share.shareConfig?.singleton || !share.version ? pkg : \`\${pkg}@\${share.version}\`;
|
|
1521
|
+
if (share.shareConfig?.import !== false || __mfModuleCache.share[cacheKey] !== undefined) continue;
|
|
1387
1522
|
${normalizeRuntimeShareCode}
|
|
1388
1523
|
const versions = shared?.[pkg];
|
|
1389
1524
|
const provider = versions && versions[Object.keys(versions)[0]];
|
|
@@ -1391,7 +1526,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
1391
1526
|
const factory = provider.lib || (provider.loading ? await provider.loading : await provider.get?.());
|
|
1392
1527
|
const mod = typeof factory === "function" ? factory() : factory;
|
|
1393
1528
|
const resolved = await Promise.resolve(mod);
|
|
1394
|
-
__mfModuleCache.share[
|
|
1529
|
+
__mfModuleCache.share[cacheKey] = __mfNormalizeRuntimeShare(resolved);
|
|
1395
1530
|
}
|
|
1396
1531
|
return initRes
|
|
1397
1532
|
}
|
|
@@ -1425,7 +1560,8 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build") {
|
|
|
1425
1560
|
${normalizeRuntimeShareCode}
|
|
1426
1561
|
${shouldPreloadShares ? `
|
|
1427
1562
|
for (const [pkg, share] of Object.entries(usedShared)) {
|
|
1428
|
-
|
|
1563
|
+
const cacheKey = share.shareConfig?.singleton || !share.version ? pkg : \`\${pkg}@\${share.version}\`;
|
|
1564
|
+
if (__mfModuleCache.share[cacheKey] !== undefined) {
|
|
1429
1565
|
continue;
|
|
1430
1566
|
}
|
|
1431
1567
|
await runtime.loadShare(pkg, {
|
|
@@ -1433,7 +1569,7 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build") {
|
|
|
1433
1569
|
}).then((factory) => {
|
|
1434
1570
|
const mod = typeof factory === "function" ? factory() : factory;
|
|
1435
1571
|
return Promise.resolve(mod).then((resolved) => {
|
|
1436
|
-
__mfModuleCache.share[
|
|
1572
|
+
__mfModuleCache.share[cacheKey] = __mfNormalizeRuntimeShare(resolved);
|
|
1437
1573
|
});
|
|
1438
1574
|
});
|
|
1439
1575
|
}
|
|
@@ -1801,7 +1937,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1801
1937
|
return inject === "entry" || !htmlFilePath;
|
|
1802
1938
|
}
|
|
1803
1939
|
function normalizeDevHtmlProxyId(id) {
|
|
1804
|
-
return id.replace(/^\0/, "")
|
|
1940
|
+
return decodeViteId(id).replace(/^\0/, "");
|
|
1805
1941
|
}
|
|
1806
1942
|
function normalizeModuleId(id) {
|
|
1807
1943
|
return id.split("?")[0].replace(/\\/g, "/");
|
|
@@ -1835,7 +1971,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1835
1971
|
configResolved(config) {
|
|
1836
1972
|
viteConfig = config;
|
|
1837
1973
|
const resolvedEntryPath = getEntryPath();
|
|
1838
|
-
if (resolvedEntryPath.startsWith("virtual:mf")) devEntryPath = config.base +
|
|
1974
|
+
if (resolvedEntryPath.startsWith("virtual:mf")) devEntryPath = config.base + VITE_ID_PREFIX.slice(1) + resolvedEntryPath;
|
|
1839
1975
|
else {
|
|
1840
1976
|
const normalized = resolvedEntryPath.replace(/\\\\?/g, "/");
|
|
1841
1977
|
const root = config.root.replace(/\\\\?/g, "/").replace(/\/$/, "");
|
|
@@ -1876,10 +2012,10 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1876
2012
|
const base = viteConfig.base.replace(/\/$/, "");
|
|
1877
2013
|
const stripBase = (p) => base && p.startsWith(base + "/") ? p.slice(base.length) : p;
|
|
1878
2014
|
const html = rewriteEntryScripts(c, (originalSrc) => {
|
|
1879
|
-
return
|
|
2015
|
+
return toViteEncodedId(`${DEV_HTML_PROXY_PREFIX}${new URLSearchParams({
|
|
1880
2016
|
init: sanitizeDevEntryPath(stripBase(devEntryPath)),
|
|
1881
2017
|
entry: sanitizeDevEntryPath(stripBase(originalSrc))
|
|
1882
|
-
}).toString()}
|
|
2018
|
+
}).toString()}`);
|
|
1883
2019
|
});
|
|
1884
2020
|
return html === c ? injectEntryScript(c, stripBase(devEntryPath)) : html;
|
|
1885
2021
|
}
|
|
@@ -2825,9 +2961,19 @@ const processModuleAssets = (bundle, filesMap, moduleMatcher, options = {}) => {
|
|
|
2825
2961
|
foundCssViaMetadata = true;
|
|
2826
2962
|
}
|
|
2827
2963
|
if (!foundCssViaMetadata && chunkContainsCssModules(fileData.modules)) for (const cssAsset of Array.from(bundleCssAssets)) trackAsset(filesMap, matchKey, cssAsset, false, "css");
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2964
|
+
const visited = /* @__PURE__ */ new Set();
|
|
2965
|
+
const queue = [fileName];
|
|
2966
|
+
for (let queueIndex = 0; queueIndex < queue.length; queueIndex++) {
|
|
2967
|
+
const cur = queue[queueIndex];
|
|
2968
|
+
if (visited.has(cur)) continue;
|
|
2969
|
+
visited.add(cur);
|
|
2970
|
+
const chunk = bundle[cur];
|
|
2971
|
+
if (!chunk || chunk.type !== "chunk") continue;
|
|
2972
|
+
if (chunk.dynamicImports) for (const dynamicImport of chunk.dynamicImports) {
|
|
2973
|
+
if (!bundle[dynamicImport]) continue;
|
|
2974
|
+
trackAsset(filesMap, matchKey, dynamicImport, true, isCSSFile(dynamicImport) ? "css" : "js");
|
|
2975
|
+
}
|
|
2976
|
+
if (chunk.imports) for (const imp of chunk.imports) queue.push(imp);
|
|
2831
2977
|
}
|
|
2832
2978
|
}
|
|
2833
2979
|
}
|
|
@@ -2875,7 +3021,11 @@ const buildFileToShareKeyMap = async (shareKeys, resolveFn) => {
|
|
|
2875
3021
|
//#endregion
|
|
2876
3022
|
//#region src/utils/pathNormalization.ts
|
|
2877
3023
|
const COMMON_SHARED_SUBPATHS = {
|
|
2878
|
-
react: [
|
|
3024
|
+
react: [
|
|
3025
|
+
"react/jsx-runtime",
|
|
3026
|
+
"react/jsx-dev-runtime",
|
|
3027
|
+
"react/compiler-runtime"
|
|
3028
|
+
],
|
|
2879
3029
|
"react-dom": [
|
|
2880
3030
|
"react-dom/client",
|
|
2881
3031
|
"react-dom/server",
|
|
@@ -2928,7 +3078,7 @@ function getCommonSharedSubpathFromNodeModulePath(source, sharedKey) {
|
|
|
2928
3078
|
*/
|
|
2929
3079
|
function resolvePublicPath(options, viteBase, originalBase) {
|
|
2930
3080
|
if (options.publicPath && options.publicPath !== "auto") return options.publicPath;
|
|
2931
|
-
if (originalBase
|
|
3081
|
+
if (!originalBase) return "auto";
|
|
2932
3082
|
if (viteBase) return ensureTrailingSlash(viteBase);
|
|
2933
3083
|
return "auto";
|
|
2934
3084
|
}
|
|
@@ -3010,11 +3160,11 @@ function generateRemoteEntrySSR(options) {
|
|
|
3010
3160
|
*/
|
|
3011
3161
|
async function init(shared = {}, initScope = []) {
|
|
3012
3162
|
const initRes = runtimeInit({
|
|
3013
|
-
name: ${JSON.stringify(options.
|
|
3163
|
+
name: ${JSON.stringify(options.name)},
|
|
3014
3164
|
remotes: [],
|
|
3015
3165
|
shared: {},
|
|
3016
3166
|
});
|
|
3017
|
-
const initToken = { from: ${JSON.stringify(options.
|
|
3167
|
+
const initToken = { from: ${JSON.stringify(options.name)} };
|
|
3018
3168
|
if (initScope.indexOf(initToken) >= 0) return;
|
|
3019
3169
|
initScope.push(initToken);
|
|
3020
3170
|
initRes.initShareScopeMap(${JSON.stringify(options.shareScope)}, shared);
|
|
@@ -3430,7 +3580,8 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
3430
3580
|
if (id.includes(getHostAutoInitPath())) {
|
|
3431
3581
|
if (_command === "serve") {
|
|
3432
3582
|
const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
|
|
3433
|
-
const
|
|
3583
|
+
const resolvedPublicPath = resolvePublicPath(options, viteConfig.base);
|
|
3584
|
+
const publicPath = JSON.stringify((resolvedPublicPath === "auto" ? "/" : resolvedPublicPath) + options.filename);
|
|
3434
3585
|
const fallbackOrigin = `//${host}:${viteConfig.server?.port}`;
|
|
3435
3586
|
const ssrRemoteEntry = "data:text/javascript," + encodeURIComponent("export async function init(){return {loadRemote:async()=>({}),loadShare:async()=>({})}}");
|
|
3436
3587
|
return `
|
|
@@ -3594,6 +3745,7 @@ function isBuildConfigImporter(importer) {
|
|
|
3594
3745
|
}
|
|
3595
3746
|
function matchesSharedSource(source, key) {
|
|
3596
3747
|
const keyBase = key.endsWith("/") ? key.slice(0, -1) : key;
|
|
3748
|
+
if (keyBase === "vue" && (source === "vue/dist/vue.esm-bundler.js" || source === "vue/dist/vue.runtime.esm-bundler.js")) return true;
|
|
3597
3749
|
if (key.endsWith("/")) return source === keyBase || source.startsWith(`${keyBase}/`);
|
|
3598
3750
|
if (getCommonSharedSubpaths(keyBase).includes(source)) return true;
|
|
3599
3751
|
return source === keyBase;
|
|
@@ -3605,9 +3757,16 @@ function findSharedKey(source, shared) {
|
|
|
3605
3757
|
function findSharedKeyForSource(source, shared) {
|
|
3606
3758
|
const key = findSharedKey(source, shared);
|
|
3607
3759
|
if (key) return key;
|
|
3760
|
+
const explicitSharedSubpathKeys = Object.keys(shared || {}).filter((sharedKey) => getPackageName(sharedKey) !== sharedKey && !sharedKey.endsWith("/"));
|
|
3608
3761
|
if (isNodeModulePath(source)) {
|
|
3609
|
-
const explicitSubpathKey = getMatchingNodeModuleSubpath(source,
|
|
3762
|
+
const explicitSubpathKey = getMatchingNodeModuleSubpath(source, explicitSharedSubpathKeys);
|
|
3610
3763
|
if (explicitSubpathKey) return explicitSubpathKey;
|
|
3764
|
+
const normalizedSource = normalizeNodeModulePath(source);
|
|
3765
|
+
const explicitSubpathEntryKey = explicitSharedSubpathKeys.find((sharedKey) => {
|
|
3766
|
+
const entry = getInstalledPackageEntry(sharedKey, { cwd: getPackageDetectionCwd() });
|
|
3767
|
+
return entry ? normalizeNodeModulePath(entry) === normalizedSource : false;
|
|
3768
|
+
});
|
|
3769
|
+
if (explicitSubpathEntryKey) return explicitSubpathEntryKey;
|
|
3611
3770
|
}
|
|
3612
3771
|
const packageName = getPackageNameFromNodeModulePath(source);
|
|
3613
3772
|
return packageName ? findSharedKey(packageName, shared) : void 0;
|
|
@@ -3652,6 +3811,7 @@ function proxySharedModule(options) {
|
|
|
3652
3811
|
let useRolldown = false;
|
|
3653
3812
|
const savePrebuild = new PromiseStore();
|
|
3654
3813
|
let devServer;
|
|
3814
|
+
const materializedLoadShareSources = /* @__PURE__ */ new Set();
|
|
3655
3815
|
return [
|
|
3656
3816
|
{
|
|
3657
3817
|
name: "generateLocalSharedImportMap",
|
|
@@ -3708,6 +3868,12 @@ function proxySharedModule(options) {
|
|
|
3708
3868
|
name: "proxyPreBuildShared:resolve-shared-loadShare",
|
|
3709
3869
|
enforce: "pre",
|
|
3710
3870
|
async resolveId(source, importer) {
|
|
3871
|
+
function shouldSkipTaggedImporterProxy(sharedKey, tag) {
|
|
3872
|
+
if (!importer?.includes(tag)) return false;
|
|
3873
|
+
const taggedModule = VirtualModule.findModule(tag, importer);
|
|
3874
|
+
if (!taggedModule) return true;
|
|
3875
|
+
return taggedModule.name === sharedKey || matchesSharedSource(source, taggedModule.name);
|
|
3876
|
+
}
|
|
3711
3877
|
const key = findSharedKeyForSource(source, shared);
|
|
3712
3878
|
if (!key) return;
|
|
3713
3879
|
if (useDirectReactImport && key === "react") return;
|
|
@@ -3716,15 +3882,18 @@ function proxySharedModule(options) {
|
|
|
3716
3882
|
if (useDirectReactImport && source === "react") return;
|
|
3717
3883
|
if (importer && importer.includes("localSharedImportMap")) return;
|
|
3718
3884
|
if (importer && (importer.includes("hostAutoInit") || importer.includes("__H_A_I__"))) return;
|
|
3719
|
-
if (
|
|
3720
|
-
if (
|
|
3721
|
-
const shareSource = isNodeModulePath(source) ? getCommonSharedSubpathFromNodeModulePath(source, key) || key : source;
|
|
3885
|
+
if (shouldSkipTaggedImporterProxy(key, "__loadShare__")) return;
|
|
3886
|
+
if (shouldSkipTaggedImporterProxy(key, "__prebuild__")) return;
|
|
3887
|
+
const shareSource = key === "vue" && source.startsWith("vue/dist/") ? key : isNodeModulePath(source) ? getCommonSharedSubpathFromNodeModulePath(source, key) || key : source;
|
|
3722
3888
|
const loadSharePath = getLoadShareModulePath(shareSource, useRolldown);
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3889
|
+
if (!materializedLoadShareSources.has(shareSource)) {
|
|
3890
|
+
materializedLoadShareSources.add(shareSource);
|
|
3891
|
+
writeLoadShareModule(shareSource, shared[key], _command, useRolldown);
|
|
3892
|
+
if (shared[key].shareConfig.import !== false) writePreBuildLibPath(shareSource, shared[key]);
|
|
3893
|
+
addUsedShares(shareSource);
|
|
3894
|
+
writeLocalSharedImportMap();
|
|
3895
|
+
refreshHostAutoInit();
|
|
3896
|
+
}
|
|
3728
3897
|
return this.resolve(loadSharePath, importer, { skipSelf: true });
|
|
3729
3898
|
}
|
|
3730
3899
|
},
|
|
@@ -3805,19 +3974,8 @@ function applyRewrites(code, imports, id) {
|
|
|
3805
3974
|
const ms = new CodeRewriter(code);
|
|
3806
3975
|
let changed = false;
|
|
3807
3976
|
let counter = 0;
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
const src = JSON.stringify(imp.source);
|
|
3811
|
-
if (imp.namespaceLocal && !imp.defaultLocal && imp.named.length === 0) ms.overwrite(imp.start, imp.end, `import { __moduleExports as ${imp.namespaceLocal} } from ${src};`);
|
|
3812
|
-
else {
|
|
3813
|
-
const nsId = `__mf_ns_${counter++}`;
|
|
3814
|
-
const importParts = [];
|
|
3815
|
-
if (imp.defaultLocal) importParts.push(`default as ${imp.defaultLocal}`);
|
|
3816
|
-
importParts.push(`__moduleExports as ${nsId}`);
|
|
3817
|
-
let rewrite = `import { ${importParts.join(", ")} } from ${src};`;
|
|
3818
|
-
if (imp.named.length > 0) {
|
|
3819
|
-
const isProxyId = `__mf_is_proxy_${counter++}`;
|
|
3820
|
-
const namedProxyHelper = `function __mfCreateNamedRemoteProxy(ns, key) {
|
|
3977
|
+
let namedProxyHelperDeclared = false;
|
|
3978
|
+
const namedProxyHelper = `function __mfCreateNamedRemoteProxy(ns, key) {
|
|
3821
3979
|
const target = function (...args) {
|
|
3822
3980
|
const value = ns[key];
|
|
3823
3981
|
return typeof value === "function" ? value.apply(this, args) : value;
|
|
@@ -3835,13 +3993,29 @@ function applyRewrites(code, imports, id) {
|
|
|
3835
3993
|
}
|
|
3836
3994
|
});
|
|
3837
3995
|
}`;
|
|
3996
|
+
for (const imp of imports) switch (imp.kind) {
|
|
3997
|
+
case "static": {
|
|
3998
|
+
const src = JSON.stringify(imp.source);
|
|
3999
|
+
if (imp.namespaceLocal && !imp.defaultLocal && imp.named.length === 0) ms.overwrite(imp.start, imp.end, `import { __moduleExports as ${imp.namespaceLocal} } from ${src};`);
|
|
4000
|
+
else {
|
|
4001
|
+
const nsId = `__mf_ns_${counter++}`;
|
|
4002
|
+
const importParts = [];
|
|
4003
|
+
if (imp.defaultLocal) importParts.push(`default as ${imp.defaultLocal}`);
|
|
4004
|
+
importParts.push(`__moduleExports as ${nsId}`);
|
|
4005
|
+
let rewrite = `import { ${importParts.join(", ")} } from ${src};`;
|
|
4006
|
+
if (imp.named.length > 0) {
|
|
4007
|
+
const isProxyId = `__mf_is_proxy_${counter++}`;
|
|
3838
4008
|
const tempNames = imp.named.map((_s) => `__mf_named_${counter++}`);
|
|
3839
4009
|
const destructParts = imp.named.map((s, index) => `${s.imported}: ${tempNames[index]}`);
|
|
3840
4010
|
const bindingLines = imp.named.map((s, index) => {
|
|
3841
4011
|
const temp = tempNames[index];
|
|
3842
4012
|
return `const ${s.local} = ${isProxyId} ? __mfCreateNamedRemoteProxy(${nsId}, ${JSON.stringify(s.imported)}) : ${temp};`;
|
|
3843
4013
|
});
|
|
3844
|
-
|
|
4014
|
+
if (!namedProxyHelperDeclared) {
|
|
4015
|
+
rewrite += `\n${namedProxyHelper}`;
|
|
4016
|
+
namedProxyHelperDeclared = true;
|
|
4017
|
+
}
|
|
4018
|
+
rewrite += `\nconst ${isProxyId} = ${nsId} && ${nsId}.__mf_is_remote_proxy;`;
|
|
3845
4019
|
rewrite += `\nconst { ${destructParts.join(", ")} } = ${isProxyId} ? {} : ${nsId};`;
|
|
3846
4020
|
rewrite += `\n${bindingLines.join("\n")}`;
|
|
3847
4021
|
}
|
|
@@ -4243,7 +4417,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
4243
4417
|
try {
|
|
4244
4418
|
result = await fetchFn(id, importer, opts);
|
|
4245
4419
|
} catch (fetchErr) {
|
|
4246
|
-
const bareId =
|
|
4420
|
+
const bareId = decodeViteId(id);
|
|
4247
4421
|
try {
|
|
4248
4422
|
const { createRequire } = await import("module");
|
|
4249
4423
|
const resolved = createRequire(new URL(`file://${server.config.root}/package.json`)).resolve(bareId.replace(/^\0/, ""));
|
|
@@ -4498,6 +4672,8 @@ var normalizeOptimizeDeps_default = {
|
|
|
4498
4672
|
//#endregion
|
|
4499
4673
|
//#region src/index.ts
|
|
4500
4674
|
const patchedManualChunks = /* @__PURE__ */ new WeakSet();
|
|
4675
|
+
const PRELOAD_HELPER_CHUNK = "vite-preload-helper";
|
|
4676
|
+
const PRELOAD_HELPER_TEST = /\0?vite\/preload-helper/;
|
|
4501
4677
|
function normalizeVinextRscPreloadHints(code) {
|
|
4502
4678
|
return code.replace(/(:HL\[[^\]\n]*?,)"stylesheet"/g, "$1\"style\"").replace(/(:HL\[[^\]\n]*?,)\\"stylesheet\\"/g, "$1\\\"style\\\"");
|
|
4503
4679
|
}
|
|
@@ -4565,6 +4741,14 @@ function isFederationHtmlPreloadDependency(dep, includeSharedRuntime = false) {
|
|
|
4565
4741
|
if (file.includes("__mfe_internal__") || file.includes("virtual_mf-") || file.includes("virtualExposes") || file.includes("localSharedImportMap") || file.includes("hostInit")) return true;
|
|
4566
4742
|
return includeSharedRuntime && (file.includes("preload-helper") || file.includes("rolldown-runtime") || file.startsWith("dist-"));
|
|
4567
4743
|
}
|
|
4744
|
+
function canResolveSharedSubpath(subpath, projectRoot) {
|
|
4745
|
+
try {
|
|
4746
|
+
createRequire(new URL(`file://${projectRoot}/package.json`)).resolve(subpath);
|
|
4747
|
+
return true;
|
|
4748
|
+
} catch {
|
|
4749
|
+
return false;
|
|
4750
|
+
}
|
|
4751
|
+
}
|
|
4568
4752
|
/**
|
|
4569
4753
|
* Plugin that runs FIRST to register generated virtual modules in the config hook.
|
|
4570
4754
|
* This prevents 504 "Outdated Optimize Dep" errors by ensuring ids are known
|
|
@@ -4631,7 +4815,7 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
4631
4815
|
optimizeDeps.esbuildOptions.plugins.push({
|
|
4632
4816
|
name: "module-federation:optimize-shared-proxy",
|
|
4633
4817
|
setup(build) {
|
|
4634
|
-
build.onResolve({ filter:
|
|
4818
|
+
build.onResolve({ filter: createViteEncodedIdPrefixRegExp("virtual:mf:") }, (args) => ({
|
|
4635
4819
|
path: args.path,
|
|
4636
4820
|
external: true
|
|
4637
4821
|
}));
|
|
@@ -4651,15 +4835,15 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
4651
4835
|
const key = findSharedKey(args.path, shared);
|
|
4652
4836
|
if (!key) return;
|
|
4653
4837
|
const shareItem = shared[key];
|
|
4654
|
-
const
|
|
4838
|
+
const optimizedLoadSharePath = toViteOptimizedDepVirtualId(getLoadShareModulePath(args.path, isRolldown));
|
|
4655
4839
|
writeLoadShareModule(args.path, shareItem, _command, isRolldown);
|
|
4656
4840
|
if (shareItem.shareConfig?.import !== false) writePreBuildLibPath(args.path, shareItem);
|
|
4657
4841
|
addUsedShares(args.path);
|
|
4658
4842
|
return {
|
|
4659
4843
|
loader: "js",
|
|
4660
4844
|
resolveDir: root,
|
|
4661
|
-
contents: `import * as __mfShared from ${JSON.stringify(
|
|
4662
|
-
export * from ${JSON.stringify(
|
|
4845
|
+
contents: `import * as __mfShared from ${JSON.stringify(optimizedLoadSharePath)};
|
|
4846
|
+
export * from ${JSON.stringify(optimizedLoadSharePath)};
|
|
4663
4847
|
export default __mfShared.default ?? __mfShared;`
|
|
4664
4848
|
};
|
|
4665
4849
|
});
|
|
@@ -4673,9 +4857,11 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4673
4857
|
if (_command === "serve" && shareItem.shareConfig?.import !== false) {
|
|
4674
4858
|
const optimizeDeps = config.optimizeDeps ??= {};
|
|
4675
4859
|
optimizeDeps.include ??= [];
|
|
4860
|
+
optimizeDeps.exclude ??= [];
|
|
4676
4861
|
for (const subpath of getCommonSharedSubpaths(key)) {
|
|
4677
4862
|
writePreBuildLibPath(subpath, shareItem);
|
|
4678
|
-
optimizeDeps.include.push(subpath);
|
|
4863
|
+
if (canResolveSharedSubpath(subpath, root)) optimizeDeps.include.push(subpath);
|
|
4864
|
+
else optimizeDeps.exclude.push(subpath);
|
|
4679
4865
|
}
|
|
4680
4866
|
}
|
|
4681
4867
|
continue;
|
|
@@ -4699,7 +4885,8 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4699
4885
|
writeLoadShareModule(subpath, shareItem, _command, isRolldown);
|
|
4700
4886
|
writePreBuildLibPath(subpath, shareItem);
|
|
4701
4887
|
addUsedShares(subpath);
|
|
4702
|
-
optimizeDeps.include.push(subpath);
|
|
4888
|
+
if (canResolveSharedSubpath(subpath, root)) optimizeDeps.include.push(subpath);
|
|
4889
|
+
else optimizeDeps.exclude.push(subpath);
|
|
4703
4890
|
}
|
|
4704
4891
|
}
|
|
4705
4892
|
}
|
|
@@ -4720,6 +4907,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4720
4907
|
"react-dom",
|
|
4721
4908
|
"react/jsx-runtime",
|
|
4722
4909
|
"react/jsx-dev-runtime",
|
|
4910
|
+
"react/compiler-runtime",
|
|
4723
4911
|
"@module-federation/runtime",
|
|
4724
4912
|
"@module-federation/runtime-core",
|
|
4725
4913
|
"@module-federation/sdk"
|
|
@@ -4743,7 +4931,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4743
4931
|
const SSR_ONLY_PLUGINS = new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
4744
4932
|
function loadPluginDts(options) {
|
|
4745
4933
|
if (options.dts === false) return [];
|
|
4746
|
-
return [import("./pluginDts-
|
|
4934
|
+
return [import("./pluginDts-DDx4TPN8.mjs").then(({ default: pluginDts }) => pluginDts(options))];
|
|
4747
4935
|
}
|
|
4748
4936
|
function federation(mfUserOptions) {
|
|
4749
4937
|
if (isTestEnv()) return [];
|
|
@@ -4760,7 +4948,19 @@ function federation(mfUserOptions) {
|
|
|
4760
4948
|
name: "vite:module-federation-virtual-modules",
|
|
4761
4949
|
enforce: "pre",
|
|
4762
4950
|
resolveId(id) {
|
|
4763
|
-
|
|
4951
|
+
let virtualModule = VirtualModule.findById(id);
|
|
4952
|
+
if (!virtualModule) {
|
|
4953
|
+
materializeCachedLoadShareModule({
|
|
4954
|
+
id,
|
|
4955
|
+
shared: options.shared,
|
|
4956
|
+
command,
|
|
4957
|
+
isRolldown: getIsRolldown(this),
|
|
4958
|
+
findSharedKey,
|
|
4959
|
+
addUsedShares,
|
|
4960
|
+
writeLocalSharedImportMap
|
|
4961
|
+
});
|
|
4962
|
+
virtualModule = VirtualModule.findById(id);
|
|
4963
|
+
}
|
|
4764
4964
|
if (!virtualModule) return;
|
|
4765
4965
|
return virtualModule.getResolvedId();
|
|
4766
4966
|
},
|
|
@@ -4779,7 +4979,8 @@ function federation(mfUserOptions) {
|
|
|
4779
4979
|
resolveId(id) {
|
|
4780
4980
|
const reactServerEntryMap = {
|
|
4781
4981
|
"react/jsx-runtime": "react/cjs/react-jsx-runtime.production.js",
|
|
4782
|
-
"react/jsx-dev-runtime": "react/cjs/react-jsx-dev-runtime.production.js"
|
|
4982
|
+
"react/jsx-dev-runtime": "react/cjs/react-jsx-dev-runtime.production.js",
|
|
4983
|
+
"react/compiler-runtime": "react/cjs/react-compiler-runtime.production.js"
|
|
4783
4984
|
};
|
|
4784
4985
|
if (!(id in reactServerEntryMap)) return;
|
|
4785
4986
|
const environmentName = this.environment?.name;
|
|
@@ -4881,6 +5082,8 @@ function federation(mfUserOptions) {
|
|
|
4881
5082
|
}
|
|
4882
5083
|
if (!output?.codeSplitting || typeof output.codeSplitting !== "object") return;
|
|
4883
5084
|
if (!("groups" in output.codeSplitting)) return;
|
|
5085
|
+
const groups = output.codeSplitting.groups;
|
|
5086
|
+
if (Array.isArray(groups) && groups.some((group) => typeof group?.name === "function" && patchedManualChunks.has(group.name))) return;
|
|
4884
5087
|
delete output.codeSplitting.groups;
|
|
4885
5088
|
if (Object.keys(output.codeSplitting).length === 0) delete output.codeSplitting;
|
|
4886
5089
|
if (warnedAboutCodeSplittingGroups) return;
|
|
@@ -4888,27 +5091,45 @@ function federation(mfUserOptions) {
|
|
|
4888
5091
|
mfWarn("Ignoring `output.codeSplitting.groups` because it conflicts with module federation. Grouping shared dependency init wrappers with their dependent modules can break runtime init order and cause standalone remotes to fail before mount.");
|
|
4889
5092
|
};
|
|
4890
5093
|
let warnedAboutManualChunks = false;
|
|
4891
|
-
const applyManualChunks = (output) => {
|
|
5094
|
+
const applyManualChunks = (output, useCodeSplitting) => {
|
|
4892
5095
|
ensureCodeSplitting(output);
|
|
4893
5096
|
const isPatchedByPlugin = typeof output.manualChunks === "function" && patchedManualChunks.has(output.manualChunks);
|
|
4894
5097
|
if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
|
|
4895
5098
|
warnedAboutManualChunks = true;
|
|
4896
5099
|
mfWarn("Ignoring `output.manualChunks` because it conflicts with module federation. Module federation transforms shared dependency imports with async init wrappers, and grouping these transformed modules into a single chunk creates circular async dependencies that cause the application to silently hang.");
|
|
4897
5100
|
}
|
|
4898
|
-
const
|
|
5101
|
+
const mfChunkName = function(id) {
|
|
4899
5102
|
if (id.includes(runtimeInitId)) return "runtimeInit";
|
|
4900
5103
|
if (id.includes("__loadShare__")) {
|
|
4901
5104
|
const match = id.match(/([^/\\]+__loadShare__[^/\\]+)/);
|
|
4902
5105
|
return match ? match[1] : "loadShare";
|
|
4903
5106
|
}
|
|
5107
|
+
return null;
|
|
5108
|
+
};
|
|
5109
|
+
patchedManualChunks.add(mfChunkName);
|
|
5110
|
+
if (!useCodeSplitting) {
|
|
5111
|
+
const mfManualChunks = function(id) {
|
|
5112
|
+
return mfChunkName(id) ?? void 0;
|
|
5113
|
+
};
|
|
5114
|
+
patchedManualChunks.add(mfManualChunks);
|
|
5115
|
+
output.manualChunks = mfManualChunks;
|
|
5116
|
+
return;
|
|
5117
|
+
}
|
|
5118
|
+
const groups = [{
|
|
5119
|
+
name: PRELOAD_HELPER_CHUNK,
|
|
5120
|
+
test: PRELOAD_HELPER_TEST,
|
|
5121
|
+
priority: 100
|
|
5122
|
+
}, { name: mfChunkName }];
|
|
5123
|
+
output.codeSplitting = {
|
|
5124
|
+
...output.codeSplitting || {},
|
|
5125
|
+
groups
|
|
4904
5126
|
};
|
|
4905
|
-
|
|
4906
|
-
output.manualChunks = mfManualChunks;
|
|
5127
|
+
delete output.manualChunks;
|
|
4907
5128
|
};
|
|
4908
5129
|
config.build.rollupOptions = config.build.rollupOptions || {};
|
|
4909
5130
|
const rollupOutput = config.build.rollupOptions.output;
|
|
4910
|
-
if (Array.isArray(rollupOutput)) rollupOutput.forEach((output) => applyManualChunks(output));
|
|
4911
|
-
else applyManualChunks(config.build.rollupOptions.output ||= {});
|
|
5131
|
+
if (Array.isArray(rollupOutput)) rollupOutput.forEach((output) => applyManualChunks(output, false));
|
|
5132
|
+
else applyManualChunks(config.build.rollupOptions.output ||= {}, false);
|
|
4912
5133
|
const buildWithRolldown = config.build;
|
|
4913
5134
|
buildWithRolldown.rolldownOptions = buildWithRolldown.rolldownOptions || {};
|
|
4914
5135
|
const rolldownOutput = buildWithRolldown.rolldownOptions.output;
|
|
@@ -4918,10 +5139,10 @@ function federation(mfUserOptions) {
|
|
|
4918
5139
|
assetFileNames: output.assetFileNames
|
|
4919
5140
|
});
|
|
4920
5141
|
if (Array.isArray(rolldownOutput)) {
|
|
4921
|
-
rolldownOutput.forEach((output) => applyManualChunks(output));
|
|
5142
|
+
rolldownOutput.forEach((output) => applyManualChunks(output, true));
|
|
4922
5143
|
desiredRolldownOutput = rolldownOutput.map((output) => snapshotRolldownOutput(output));
|
|
4923
5144
|
} else {
|
|
4924
|
-
applyManualChunks(buildWithRolldown.rolldownOptions.output ||= {});
|
|
5145
|
+
applyManualChunks(buildWithRolldown.rolldownOptions.output ||= {}, true);
|
|
4925
5146
|
desiredRolldownOutput = [snapshotRolldownOutput(buildWithRolldown.rolldownOptions.output)];
|
|
4926
5147
|
}
|
|
4927
5148
|
},
|