@module-federation/vite 1.16.5 → 1.16.6

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.js CHANGED
@@ -1,48 +1,15 @@
1
- import { a as getPackageName, c as hasPackageDependency, d as packageNameEncode, f as resolveImportPath, g as mfWarn, i as getPackageDetectionCwd, l as isNuxtProjectRoot, m as createModuleFederationError, n as getInstalledPackageJson, o as getPackageNameFromNodeModulePath, p as setPackageDetectionCwd, r as getIsRolldown, s as getSharedCacheKey, t as getInstalledPackageEntry, u as packageNameDecode } from "./packageUtils-CxYRnFwy.js";
1
+ import { _ as normalizePathForImport, a as getPackageName, c as hasPackageDependency, d as packageNameEncode, f as resolveImportPath, g as mfWarn, i as getPackageDetectionCwd, l as isNuxtProjectRoot, m as createModuleFederationError, n as getInstalledPackageJson, o as getPackageNameFromNodeModulePath, p as setPackageDetectionCwd, r as getIsRolldown, s as getSharedCacheKey, t as getInstalledPackageEntry, u as packageNameDecode, v as rebaseImport } from "./packageUtils-CYnJFfPP.js";
2
+ import { createRequire } from "node:module";
2
3
  import * as fs$1 from "fs";
3
4
  import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
4
- import { createRequire } from "module";
5
- import * as path$1 from "pathe";
6
- import path, { basename } from "pathe";
5
+ import { createRequire as createRequire$1 } from "module";
6
+ import * as path$1 from "node:path";
7
+ import path, { basename } from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "url";
7
9
  import { version } from "vite";
8
10
  import { createHash } from "node:crypto";
9
- import { fileURLToPath } from "url";
10
- import { init, parse } from "es-module-lexer";
11
- //#region src/utils/buildPaths.ts
12
- /**
13
- * Rebase an import path for a bootstrap file that moved from root into `dir`.
14
- *
15
- * When entryFileNames places entries in a subdirectory (e.g. `static/js/`),
16
- * the bootstrap file moves there too. Paths that resolved from the HTML root
17
- * must resolve from the new directory instead.
18
- *
19
- * Cases: `/static/js/hostInit.js` → `./hostInit.js` (strip dir prefix)
20
- * `./src/main.tsx` → `../../src/main.tsx` (climb back up for each dir level)
21
- * `https://cdn.example.com` → unchanged (absolute URL)
22
- */
23
- function rebaseImport(importSrc, dir) {
24
- if (!dir) return importSrc;
25
- if (isAbsoluteUrl(importSrc)) return importSrc;
26
- const absPrefix = "/" + dir;
27
- if (importSrc.startsWith(absPrefix)) {
28
- const remainder = importSrc.slice(absPrefix.length);
29
- return remainder ? "./" + remainder : "./";
30
- }
31
- if (importSrc.startsWith(dir)) {
32
- const remainder = importSrc.slice(dir.length);
33
- return remainder ? "./" + remainder : "./";
34
- }
35
- const upLevels = dir.split("/").filter(Boolean).length;
36
- const prefix = upLevels > 0 ? "../".repeat(upLevels) : "./";
37
- if (importSrc.startsWith("./")) return prefix + importSrc.slice(2);
38
- if (importSrc.startsWith("/")) return prefix + importSrc.slice(1);
39
- return prefix + importSrc;
40
- }
41
- const EXTERNAL_URL_RE = /^(?:[a-z]+:|\/\/)/i;
42
- function isAbsoluteUrl(src) {
43
- return EXTERNAL_URL_RE.test(src);
44
- }
45
- //#endregion
11
+ import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
12
+ import { pathToFileURL as pathToFileURL$1 } from "node:url";
46
13
  //#region src/utils/codeRewriter.ts
47
14
  const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
48
15
  var CodeRewriter = class {
@@ -670,20 +637,31 @@ let _ssrRemotes = [];
670
637
  function setSsrRemotes(remotes) {
671
638
  _ssrRemotes = remotes;
672
639
  }
673
- function getSsrNoopResolveCode(enableSsrInit) {
640
+ function getSsrNoopResolveCode(enableSsrInit, hostInitImportId, initResolveExpression = "initResolve") {
674
641
  if (!enableSsrInit) return "";
675
642
  return `if (typeof window === 'undefined') {
676
643
  var _noop = { loadRemote: function() { return Promise.resolve(undefined); }, loadShare: function() { return Promise.resolve(undefined); } };
677
- import(/* @vite-ignore */ '@module-federation/runtime').then(function(runtimeMod) {
678
- return import(/* @vite-ignore */ '@module-federation/vite/ssrEntryLoader').then(
679
- function(loaderMod) { return [runtimeMod, [loaderMod.default()]]; },
680
- function() { return [runtimeMod, []]; }
681
- );
682
- }).then(function(pair) {
683
- var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${JSON.stringify(_ssrRemotes)}, shared: {}, plugins: pair[1] });
684
- initResolve(runtime);
685
- }, function() {
686
- initResolve(_noop);
644
+ ${hostInitImportId ? `import(${JSON.stringify(hostInitImportId)})
645
+ .then(function(mod) { return mod.hostInitPromise; })
646
+ .then(function(runtime) {
647
+ ${initResolveExpression}(runtime);
648
+ return true;
649
+ })
650
+ .catch(function() {
651
+ return false;
652
+ })` : "Promise.resolve(false)"}.then(function(resolved) {
653
+ if (resolved) return;
654
+ return import(/* @vite-ignore */ '@module-federation/runtime').then(function(runtimeMod) {
655
+ return import(/* @vite-ignore */ '@module-federation/vite/ssrEntryLoader').then(
656
+ function(loaderMod) { return [runtimeMod, [loaderMod.default()]]; },
657
+ function() { return [runtimeMod, []]; }
658
+ );
659
+ }).then(function(pair) {
660
+ var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${JSON.stringify(_ssrRemotes)}, shared: {}, plugins: pair[1] });
661
+ ${initResolveExpression}(runtime);
662
+ }, function() {
663
+ ${initResolveExpression}(_noop);
664
+ });
687
665
  });
688
666
  }`;
689
667
  }
@@ -703,7 +681,7 @@ if (!${options.stateVar}) {
703
681
  const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
704
682
  `;
705
683
  }
706
- function getRuntimeInitBootstrapCode(enableSsrInit = false) {
684
+ function getRuntimeInitBootstrapCode(enableSsrInit = false, hostInitImportId) {
707
685
  return `
708
686
  const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
709
687
  const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
@@ -712,14 +690,18 @@ globalThis[moduleCacheGlobalKey].share ||= {};
712
690
  globalThis[moduleCacheGlobalKey].remote ||= {};
713
691
  if (!globalThis[globalKey]) {
714
692
  ${getDeferredInitPromiseCode()}
715
- globalThis[globalKey] = {
693
+ globalThis[globalKey] = {
716
694
  initPromise,
717
695
  initResolve,
718
696
  initReject,
719
697
  moduleCache: globalThis[moduleCacheGlobalKey],
720
698
  };
721
- ${getSsrNoopResolveCode(enableSsrInit)}
722
699
  }
700
+ ${enableSsrInit ? `
701
+ if (typeof window === 'undefined' && !globalThis[globalKey].ssrInitStarted) {
702
+ globalThis[globalKey].ssrInitStarted = true;
703
+ ${getSsrNoopResolveCode(enableSsrInit, hostInitImportId, "globalThis[globalKey].initResolve")}
704
+ }` : ""}
723
705
  globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
724
706
  globalThis[globalKey].moduleCache.share ||= {};
725
707
  globalThis[globalKey].moduleCache.remote ||= {};
@@ -752,11 +734,11 @@ function getRuntimeInitResolveBootstrapCode(enableSsrInit = false) {
752
734
  enableSsrInit
753
735
  });
754
736
  }
755
- function writeRuntimeInitStatus(command, enableSsrInit = false) {
737
+ function writeRuntimeInitStatus(command, enableSsrInit = false, hostInitImportId) {
756
738
  const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
757
739
  export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
758
740
  virtualRuntimeInitStatus.writeSync(`
759
- ${getRuntimeInitBootstrapCode(enableSsrInit)}
741
+ ${getRuntimeInitBootstrapCode(enableSsrInit, hostInitImportId)}
760
742
  ${exportStatement}
761
743
  `);
762
744
  }
@@ -791,10 +773,9 @@ function isValidEsmExportName(name) {
791
773
  return !!name && name !== "default" && name !== "__esModule" && isValidJsIdentifier(name);
792
774
  }
793
775
  const JS_IDENTIFIER_PATTERN = `[\$_\\p{ID_Start}][\$_\\u200C\\u200D\\p{ID_Continue}]*`;
794
- const localRequire = createRequire(import.meta.url);
795
776
  function resolvePackageEntryFromProjectRoot(pkg) {
796
777
  try {
797
- return createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
778
+ return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
798
779
  } catch {
799
780
  return;
800
781
  }
@@ -811,29 +792,20 @@ function getPackageEsmEntryPath(pkg) {
811
792
  }) || resolvePackageEntryFromProjectRoot(pkg);
812
793
  }
813
794
  function getEsmNamedExportsFromFile(entryPath) {
814
- let source = "";
815
795
  try {
816
796
  if (!entryPath) return [];
817
- const { initSync, parse } = localRequire("es-module-lexer");
818
- initSync();
819
- source = readFileSync(entryPath, "utf-8");
820
- const [, exports] = parse(source, entryPath);
821
- const names = exports.map((item) => item.n).filter((name) => isValidEsmExportName(name));
822
- const regexNames = getNamedExportsViaRegex(source, entryPath);
823
- const filteredNames = names.filter((name) => name !== "type" || regexNames.includes(name));
824
- if (filteredNames.length > 0) return Array.from(new Set([...filteredNames, ...regexNames]));
825
- return regexNames;
797
+ return getNamedExportsViaRegex(readFileSync(entryPath, "utf-8"), entryPath);
826
798
  } catch {
827
- return source ? getNamedExportsViaRegex(source, entryPath) : [];
799
+ return [];
828
800
  }
829
801
  }
830
802
  function getEsmNamedExports(pkg) {
831
803
  return getEsmNamedExportsFromFile(getPackageEsmEntryPath(pkg));
832
804
  }
833
805
  function resolveConfiguredImportPath(importSource) {
834
- if (path.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
806
+ if (path$1.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
835
807
  const projectRoot = getPackageDetectionCwd();
836
- if (importSource.startsWith(".")) return resolveFileLikeModule(path.resolve(projectRoot, importSource));
808
+ if (importSource.startsWith(".")) return resolveFileLikeModule(path$1.resolve(projectRoot, importSource));
837
809
  const esmEntry = getInstalledPackageEntry(importSource, {
838
810
  conditions: [
839
811
  "browser",
@@ -845,7 +817,7 @@ function resolveConfiguredImportPath(importSource) {
845
817
  });
846
818
  if (esmEntry) return esmEntry;
847
819
  try {
848
- return createRequire(new URL(`file://${path.join(projectRoot, "package.json")}`)).resolve(importSource);
820
+ return createRequire$1(pathToFileURL(path$1.join(projectRoot, "package.json"))).resolve(importSource);
849
821
  } catch {
850
822
  return;
851
823
  }
@@ -865,13 +837,13 @@ function resolveFileLikeModule(filePath) {
865
837
  if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
866
838
  }
867
839
  for (const ext of extensions) {
868
- const candidate = path.join(filePath, "index" + ext);
840
+ const candidate = path$1.join(filePath, "index" + ext);
869
841
  if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
870
842
  }
871
843
  }
872
844
  function resolveRelativeModule(filePath, specifier) {
873
- const dir = path.dirname(filePath);
874
- const exact = path.resolve(dir, specifier);
845
+ const dir = path$1.dirname(filePath);
846
+ const exact = path$1.resolve(dir, specifier);
875
847
  if (existsSync(exact) && !statSync(exact).isDirectory()) return exact;
876
848
  const extensions = [
877
849
  ".ts",
@@ -882,12 +854,12 @@ function resolveRelativeModule(filePath, specifier) {
882
854
  ".mts"
883
855
  ];
884
856
  for (const ext of extensions) {
885
- const candidate = path.resolve(dir, specifier + ext);
857
+ const candidate = path$1.resolve(dir, specifier + ext);
886
858
  if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
887
859
  }
888
- const resolved = path.resolve(dir, specifier);
860
+ const resolved = path$1.resolve(dir, specifier);
889
861
  for (const ext of extensions) {
890
- const candidate = path.join(resolved, "index" + ext);
862
+ const candidate = path$1.join(resolved, "index" + ext);
891
863
  if (existsSync(candidate)) return candidate;
892
864
  }
893
865
  }
@@ -928,6 +900,8 @@ function getNamedExportsViaRegex(source, filePath, visited) {
928
900
  if (isValidEsmExportName(name)) names.add(name);
929
901
  }
930
902
  }
903
+ const namespaceReExportRegex = new RegExp(`export\\s+\\*\\s+as\\s+(${JS_IDENTIFIER_PATTERN})\\s+from\\s+['"][^'"]+['"]`, "gu");
904
+ while ((match = namespaceReExportRegex.exec(source)) !== null) if (isValidEsmExportName(match[1])) names.add(match[1]);
931
905
  if (filePath) {
932
906
  const starExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g;
933
907
  while ((match = starExportRegex.exec(source)) !== null) {
@@ -945,7 +919,7 @@ function getNamedExportsViaRegex(source, filePath, visited) {
945
919
  }
946
920
  function getPackageNamedExports(pkg) {
947
921
  try {
948
- const mod = createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`))(pkg);
922
+ const mod = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json")))(pkg);
949
923
  return Object.keys(mod).filter((k) => isValidEsmExportName(k));
950
924
  } catch {
951
925
  return getEsmNamedExports(pkg);
@@ -961,7 +935,7 @@ function getSharedNamedExports(pkg, shareItem) {
961
935
  }
962
936
  function getLocalProviderImportPath(pkg) {
963
937
  try {
964
- const resolved = createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
938
+ const resolved = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
965
939
  return isWorkspaceFilePath(resolved) ? resolved : void 0;
966
940
  } catch {
967
941
  const resolved = getInstalledPackageEntry(pkg, {
@@ -982,7 +956,7 @@ function getProjectResolvedImportPath(pkg) {
982
956
  if (esmEntry) return esmEntry;
983
957
  }
984
958
  try {
985
- return createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
959
+ return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
986
960
  } catch {
987
961
  return;
988
962
  }
@@ -996,7 +970,7 @@ function isWorkspaceFilePath(resolved) {
996
970
  return !realResolved.includes("/node_modules/") && !realResolved.includes("\\node_modules\\");
997
971
  }
998
972
  function isWorkspacePackageEntry(pkg, resolved) {
999
- if (!resolved || !path.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
973
+ if (!resolved || !path$1.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
1000
974
  return !!getInstalledPackageJson(pkg, {
1001
975
  packageName: getPackageName(pkg),
1002
976
  fromResolvedEntry: resolved
@@ -1004,7 +978,7 @@ function isWorkspacePackageEntry(pkg, resolved) {
1004
978
  }
1005
979
  function tryResolveImportFromPackageRoot(pkg, root) {
1006
980
  try {
1007
- return createRequire(new URL(`file://${path.join(root, "package.json")}`)).resolve(pkg);
981
+ return createRequire$1(pathToFileURL(path$1.join(root, "package.json"))).resolve(pkg);
1008
982
  } catch {
1009
983
  return;
1010
984
  }
@@ -1014,11 +988,11 @@ function getConcreteSharedImportSource(pkg, shareItem) {
1014
988
  if (typeof configuredImport === "string") return configuredImport;
1015
989
  const projectRoot = getPackageDetectionCwd();
1016
990
  if (tryResolveImportFromPackageRoot(pkg, projectRoot)) return;
1017
- let currentDir = path.dirname(projectRoot);
1018
- while (currentDir !== path.dirname(currentDir)) {
991
+ let currentDir = path$1.dirname(projectRoot);
992
+ while (currentDir !== path$1.dirname(currentDir)) {
1019
993
  const resolved = tryResolveImportFromPackageRoot(pkg, currentDir);
1020
994
  if (resolved) return resolved;
1021
- currentDir = path.dirname(currentDir);
995
+ currentDir = path$1.dirname(currentDir);
1022
996
  }
1023
997
  return tryResolveImportFromPackageRoot(pkg, currentDir);
1024
998
  }
@@ -1127,6 +1101,33 @@ function materializeCachedLoadShareModule(options) {
1127
1101
  options.addUsedShares(pkg);
1128
1102
  options.writeLocalSharedImportMap();
1129
1103
  }
1104
+ function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheKey, eagerLocalFallback) {
1105
+ const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
1106
+ const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
1107
+ const assignments = namedExports.length > 0 ? [...namedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ") : "__mf_default = mod.default ?? mod;";
1108
+ const namedExportLine = namedExports.length > 0 ? `\n export { ${namedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
1109
+ const body = `${declarations}
1110
+ const __mfApplyLazyShareExports = (mod) => {
1111
+ ${assignments}
1112
+ };
1113
+ let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}];
1114
+ if (exportModule === undefined) {
1115
+ ${eagerLocalFallback ? `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1116
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;
1117
+ __mfApplyLazyShareExports(exportModule);` : `initPromise.then(() =>
1118
+ import(${escapeGeneratedStringLiteral(importSource)}).then((mod) => {
1119
+ exportModule = __mfNormalizeShareModule(mod);
1120
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;
1121
+ __mfApplyLazyShareExports(exportModule);
1122
+ })
1123
+ );`}
1124
+ } else {
1125
+ __mfApplyLazyShareExports(exportModule);
1126
+ }
1127
+ export { __mf_default as default };${namedExportLine}`;
1128
+ return eagerLocalFallback ? `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(importSource)};
1129
+ ${body}` : body;
1130
+ }
1130
1131
  function generateDeferredHostProvidedExports(namedExports, pkg, cacheKey) {
1131
1132
  const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
1132
1133
  const declarations = ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ");
@@ -1169,7 +1170,7 @@ const normalizeLocalShareModuleCode = `const __mfNormalizeShareModule = (mod) =>
1169
1170
  };`;
1170
1171
  function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1171
1172
  if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
1172
- const importLine = getRuntimeModuleCacheBootstrapCode();
1173
+ let importLine = getRuntimeModuleCacheBootstrapCode();
1173
1174
  const cacheKey = getSharedCacheKey(pkg, shareItem);
1174
1175
  if (shareItem.shareConfig.import === false) {
1175
1176
  const namedExports = getPackageNamedExports(pkg);
@@ -1196,7 +1197,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1196
1197
  const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
1197
1198
  const namedExports = getSharedNamedExports(pkg, shareItem);
1198
1199
  let exportLine;
1199
- if (namedExports.length > 0) {
1200
+ let initBlock = "";
1201
+ if (usesLazyLocalFallback) {
1202
+ importLine = `${getRuntimeInitPromiseBootstrapCode()}\n ${importLine}`;
1203
+ exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheKey, command !== "build");
1204
+ } else if (namedExports.length > 0) {
1200
1205
  const destructure = `const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`;
1201
1206
  const namedExportLine = `export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`;
1202
1207
  exportLine = `const __mfDefaultExport = (() => {
@@ -1209,23 +1214,33 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1209
1214
  export default __mfDefaultExport;
1210
1215
  ${destructure}
1211
1216
  ${namedExportLine}`;
1212
- } else if (usesLazyLocalFallback) exportLine = `export default exportModule.default ?? exportModule`;
1213
- else exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
1217
+ initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1218
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`;
1219
+ } else {
1220
+ exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
1221
+ initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1222
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`;
1223
+ }
1214
1224
  const prebuildImportLine = usesLazyLocalFallback || isWorkspacePackage && command !== "build" ? "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
1215
1225
  const devDynamicImportLine = isWorkspacePackage ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
1216
- loadShareCacheMap[pkg].writeSync(`
1226
+ const moduleBody = usesLazyLocalFallback ? `
1227
+ ${prebuildImportLine}
1228
+ ${devDynamicImportLine}
1229
+ ${importLine}
1230
+ ${normalizeLocalShareModuleCode}
1231
+ ${exportLine}
1232
+ ` : `
1217
1233
  ${prebuildImportLine}
1218
1234
  ${devDynamicImportLine}
1219
1235
  ${importLine}
1220
1236
  ${normalizeLocalShareModuleCode}
1221
1237
  let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}]
1222
1238
  if (exportModule === undefined) {
1223
- ${usesLazyLocalFallback ? `exportModule = __mfNormalizeShareModule(await import(${escapeGeneratedStringLiteral(lazyLocalFallbackSource)}));
1224
- __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;` : `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1225
- __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`}
1239
+ ${initBlock}
1226
1240
  }
1227
1241
  ${exportLine}
1228
- `, true);
1242
+ `;
1243
+ loadShareCacheMap[pkg].writeSync(moduleBody, true);
1229
1244
  }
1230
1245
  //#endregion
1231
1246
  //#region src/virtualModules/virtualRemoteEntry.ts
@@ -1653,11 +1668,12 @@ function getHostAutoInitPath() {
1653
1668
  //#region src/virtualModules/virtualRemotes.ts
1654
1669
  const cacheRemoteMap = {};
1655
1670
  const LOAD_REMOTE_TAG = "__loadRemote__";
1656
- function getRemoteVirtualModule(remote, command, enableSsrInit = false) {
1657
- const cacheKey = `${remote}__${command}__${enableSsrInit ? "ssr" : "no-ssr"}`;
1671
+ function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer = "unified") {
1672
+ const { shareStrategy } = getNormalizeModuleFederationOptions();
1673
+ const cacheKey = `${remote}__${command}__${shareStrategy}__${consumer}__${enableSsrInit ? "ssr-init" : "no-ssr-init"}`;
1658
1674
  if (!cacheRemoteMap[cacheKey]) {
1659
1675
  cacheRemoteMap[cacheKey] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
1660
- cacheRemoteMap[cacheKey].writeSync(generateRemotes(remote, command, enableSsrInit));
1676
+ cacheRemoteMap[cacheKey].writeSync(generateRemotes(remote, command, enableSsrInit, consumer));
1661
1677
  }
1662
1678
  return cacheRemoteMap[cacheKey];
1663
1679
  }
@@ -1673,138 +1689,89 @@ function getRemoteFromId(id, remotes) {
1673
1689
  const remoteName = Object.keys(remotes).filter((name) => id === name || id.startsWith(name + "/")).sort((a, b) => b.length - a.length)[0];
1674
1690
  return remoteName ? remotes[remoteName] : void 0;
1675
1691
  }
1676
- function generateRemotes(id, command, enableSsrInit = false) {
1677
- const useReactProxy = hasPackageDependency("react");
1678
- const useVueProxy = !useReactProxy && hasPackageDependency("vue");
1679
- const options = getNormalizeModuleFederationOptions();
1680
- const isLoadedFirst = options.shareStrategy === "loaded-first";
1681
- const remote = getRemoteFromId(id, options.remotes);
1682
- const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
1683
- entryGlobalName: remote.entryGlobalName,
1684
- name: remote.name,
1685
- type: remote.type,
1686
- entry: remote.entry,
1687
- shareScope: remote.shareScope ?? "default"
1688
- })}]);` : "";
1689
- const reactImportLine = useReactProxy ? `import __mfReactDefault from "react";
1690
- import * as __mfReactNamespace from "react";
1691
- const __mfReact = __mfReactDefault ?? __mfReactNamespace.default ?? __mfReactNamespace;` : "";
1692
- const vueImportLine = useVueProxy ? `import { defineAsyncComponent as __mfDefineAsyncComponent } from "vue";` : "";
1693
- const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
1694
- import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(getHostAutoInitPath())};` : `${getRuntimeInitBootstrapCode(enableSsrInit)}
1695
- const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];
1696
- if (typeof window !== "undefined") {
1697
- import(${JSON.stringify(getHostAutoInitPath())})
1698
- .then((mod) => mod.hostInitPromise)
1699
- .then(initResolve, initReject);
1700
- }`;
1701
- const exportLine = command === "serve" ? `if (__mfRemotePending) {
1702
- __mfRemotePending = __mfRemotePending.then((mod) => {
1703
- if (mod !== undefined) exportModule = mod;
1704
- return exportModule;
1705
- });
1692
+ function resolveRemoteInitMode(shareStrategy, consumer) {
1693
+ if (shareStrategy !== "loaded-first") return "eager";
1694
+ if (consumer === "server") return "loaded-first-ssr";
1695
+ if (consumer === "client") return "loaded-first-client";
1696
+ return "loaded-first-unified";
1706
1697
  }
1707
- export { exportModule as __moduleExports };
1708
- export const __mf_remote_pending = __mfRemotePending || Promise.resolve(exportModule);
1709
- export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?.__esModule ? exportModule.default : exportModule.default ?? exportModule` : command === "build" ? `if (__mfRemotePending) {
1710
- __mfRemotePending = __mfRemotePending.then((mod) => {
1711
- if (mod !== undefined) exportModule = mod;
1712
- return exportModule;
1713
- });
1698
+ function shouldDeferRemoteLoad(initMode) {
1699
+ return initMode === "loaded-first-client" || initMode === "loaded-first-unified";
1714
1700
  }
1715
- export { exportModule as __moduleExports };
1716
- export const __mf_remote_pending = __mfRemotePending || Promise.resolve(exportModule);
1717
- export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?.__esModule ? exportModule.default : exportModule.default ?? exportModule` : "export default exportModule";
1718
- const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
1719
- const remoteLoadFailureHandler = command === "build" ? `.catch((error) => {
1720
- delete __mfModuleCache.remote[pendingKey];
1721
- throw error;
1722
- })` : `.catch(() => {
1723
- delete __mfModuleCache.remote[pendingKey];
1724
- })`;
1701
+ /** Dev SSR only build/preview client graphs must keep deferred proxies for static imports. */
1702
+ function clientNeedsRealRemoteForHydration(command, enableSsrInit) {
1703
+ return enableSsrInit && command === "serve";
1704
+ }
1705
+ function shouldIncludeDeferredProxy(initMode, consumer, clientNeedsRealRemote, deferRemoteLoad) {
1706
+ if (initMode === "eager") return consumer !== "server" && (consumer === "unified" || !clientNeedsRealRemote);
1707
+ if (consumer === "client" && clientNeedsRealRemote) return false;
1708
+ return deferRemoteLoad || consumer !== "server";
1709
+ }
1710
+ /** Codegen shared by every remote virtual module (no top-level await). */
1711
+ function getRemoteModuleRuntimeHelpers() {
1725
1712
  return `
1726
- ${reactImportLine}
1727
- ${vueImportLine}
1728
- ${importLine}
1729
- ${`
1730
- function __mfStartRemoteLoad() {
1731
- ${`
1732
- const pendingKey = ${JSON.stringify(`__mf_pending__${id}`)};
1733
- if (!__mfModuleCache.remote[pendingKey]) {
1734
- __mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
1735
- .then((runtime) => {
1736
- ${registerRemoteCode}
1737
- return runtime.loadRemote(${JSON.stringify(id)});
1738
- })
1739
- .then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
1740
- .then((mod) => {
1741
- __mfModuleCache.remote[${JSON.stringify(id)}] = mod;
1742
- delete __mfModuleCache.remote[pendingKey];
1743
- return mod;
1744
- })
1745
- ${remoteLoadFailureHandler};
1746
- }
1747
- return __mfModuleCache.remote[pendingKey];`}
1713
+ function __mfUnwrapRemoteDefault(mod) {
1714
+ if (mod == null) return mod;
1715
+ if (mod.__esModule && mod.default != null) return mod.default;
1716
+ return mod.default ?? mod;
1748
1717
  }
1749
- function __mfCreateRemoteProxy(pendingPromise) {
1718
+ let __mfDefaultExport;
1719
+ function __mfSyncDefaultExport() {
1720
+ __mfDefaultExport = exportModule?.__mf_is_remote_proxy
1721
+ ? exportModule
1722
+ : __mfUnwrapRemoteDefault(exportModule);
1723
+ }
1724
+ function __mfAssignRemoteModule(mod) {
1725
+ if (mod !== undefined) exportModule = mod;
1726
+ __mfSyncDefaultExport();
1727
+ return exportModule;
1728
+ }`;
1729
+ }
1730
+ function getDeferredProxyHelper(remoteId) {
1731
+ return `
1732
+ function __mfCreateDeferredRemoteProxy() {
1733
+ let pendingPromise;
1750
1734
  const ensurePending = () => {
1751
1735
  pendingPromise ||= __mfStartRemoteLoad();
1752
- ${useVueProxy ? "" : `pendingPromise?.finally(() => {
1753
- for (const listener of listeners) listener();
1754
- });`}
1755
1736
  return pendingPromise;
1756
1737
  };
1757
- ${useVueProxy ? `return __mfDefineAsyncComponent(() =>
1758
- ensurePending().then((mod) => mod?.default ?? mod)
1759
- );` : `
1760
- const listeners = new Set();
1761
- const getModule = () => __mfModuleCache.remote[${JSON.stringify(id)}];
1738
+ const getModule = () => __mfModuleCache.remote[${JSON.stringify(remoteId)}];
1762
1739
  const proxyTarget = function (...args) {
1763
- ${useReactProxy ? `const [, setVersion] = __mfReact.useState(0);
1764
- __mfReact.useEffect(() => {
1765
- ensurePending();
1766
- const listener = () => setVersion((value) => value + 1);
1767
- listeners.add(listener);
1768
- if (getModule()) listener();
1769
- return () => listeners.delete(listener);
1770
- }, []);` : ""}
1740
+ pendingPromise ||= __mfStartRemoteLoad();
1771
1741
  const mod = getModule();
1772
1742
  const fn = mod && (mod.default ?? mod);
1773
1743
  if (fn !== undefined && fn !== null) {
1774
- ${useReactProxy ? `return __mfReact.createElement(fn, args[0]);` : `return fn.apply(this, args);`}
1744
+ return fn.apply(this, args);
1775
1745
  }
1776
- ${useReactProxy ? `return null;` : `throw ensurePending();`}
1746
+ return null;
1777
1747
  };
1778
1748
  return new Proxy(proxyTarget, {
1779
1749
  get(_target, prop) {
1780
1750
  if (prop === "__mf_is_remote_proxy") return true;
1781
1751
  if (prop === "__esModule") return true;
1782
1752
  if (prop === "then") return undefined;
1783
- // Allow React's dev-mode console.warn to stringify the proxy without
1784
- // throwing "Cannot convert object to primitive value".
1785
1753
  if (prop === Symbol.toPrimitive || prop === "toString")
1786
- return () => "[MF remote proxy: pending]";
1754
+ return () => "[MF remote: pending]";
1787
1755
  const mod = getModule();
1788
1756
  if (mod) {
1789
1757
  return prop in mod ? mod[prop] : mod.default?.[prop];
1790
1758
  }
1791
- // When the module is pending and React.lazy() checks for "default",
1792
- // return the proxy function itself so React renders it (returns null)
1793
- // rather than crashing on undefined.
1794
- ${useReactProxy ? `if (prop === "default") return proxyTarget;
1795
- return undefined;` : `throw ensurePending();`}
1759
+ pendingPromise ||= __mfStartRemoteLoad();
1760
+ if (prop === "default") return proxyTarget;
1761
+ throw ensurePending();
1796
1762
  },
1797
1763
  has(_target, prop) {
1798
1764
  const mod = getModule();
1799
1765
  if (mod) return prop in mod;
1800
- // Tell React that "default" exists when module is pending so it
1801
- // doesn't warn "lazy: Expected the result of a dynamic import()".
1802
- ${useReactProxy ? `return prop === "default" || prop === "__esModule" || prop === "__mf_is_remote_proxy";` : `return false;`}
1766
+ return (
1767
+ prop === "default" ||
1768
+ prop === "__esModule" ||
1769
+ prop === "__mf_is_remote_proxy"
1770
+ );
1803
1771
  },
1804
1772
  ownKeys() {
1805
1773
  const mod = getModule();
1806
1774
  const keys = new Set(mod ? Reflect.ownKeys(mod) : []);
1807
- // Proxy invariant: must include non-configurable target own keys
1808
1775
  for (const k of Reflect.ownKeys(proxyTarget)) {
1809
1776
  const d = Object.getOwnPropertyDescriptor(proxyTarget, k);
1810
1777
  if (d && !d.configurable) keys.add(k);
@@ -1812,7 +1779,6 @@ export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?
1812
1779
  return Array.from(keys);
1813
1780
  },
1814
1781
  getOwnPropertyDescriptor(_target, prop) {
1815
- // Proxy invariant: non-configurable target props must be reported accurately
1816
1782
  const targetDesc = Object.getOwnPropertyDescriptor(proxyTarget, prop);
1817
1783
  if (targetDesc && !targetDesc.configurable) return targetDesc;
1818
1784
  const mod = getModule();
@@ -1826,15 +1792,119 @@ export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?
1826
1792
  apply(target, thisArg, args) {
1827
1793
  return target.apply(thisArg, args);
1828
1794
  }
1829
- });`}
1830
- }`}
1795
+ });
1796
+ }`;
1797
+ }
1798
+ function getLazyRemotePendingExport() {
1799
+ return `export const __mf_remote_pending = __mfRemotePending ?? {
1800
+ then(onFulfilled, onRejected) {
1801
+ return (__mfRemotePending ??= __mfStartRemoteLoad().then(__mfAssignRemoteModule)).then(onFulfilled, onRejected);
1802
+ },
1803
+ };`;
1804
+ }
1805
+ function getEagerRemotePendingExport() {
1806
+ return `export const __mf_remote_pending =
1807
+ __mfRemotePending ??
1808
+ __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
1809
+ }
1810
+ function getServerThenExport() {
1811
+ return `export function then(onFulfilled, onRejected) {
1812
+ return (__mfRemotePending ?? Promise.resolve(exportModule))
1813
+ .then(__mfAssignRemoteModule)
1814
+ .then(() => {
1815
+ __mfSyncDefaultExport();
1816
+ return {
1817
+ ...exportModule,
1818
+ default: __mfDefaultExport,
1819
+ __moduleExports: exportModule,
1820
+ __mf_remote_pending: __mfRemotePending,
1821
+ };
1822
+ })
1823
+ .then(onFulfilled, onRejected);
1824
+ }`;
1825
+ }
1826
+ function getRemoteExportBlock(command, deferRemoteLoad, consumer) {
1827
+ if (command !== "serve" && command !== "build") return `__mfSyncDefaultExport();
1828
+ export { __mfDefaultExport as default };`;
1829
+ return `__mfSyncDefaultExport();
1830
+ __mfRemotePending?.then(__mfSyncDefaultExport);
1831
+ export { exportModule as __moduleExports };
1832
+ ${deferRemoteLoad ? getLazyRemotePendingExport() : getEagerRemotePendingExport()}
1833
+ ${command === "serve" && consumer === "server" ? getServerThenExport() : ""}
1834
+ export { __mfDefaultExport as default };`;
1835
+ }
1836
+ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified") {
1837
+ const options = getNormalizeModuleFederationOptions();
1838
+ const isLoadedFirst = options.shareStrategy === "loaded-first";
1839
+ const initMode = resolveRemoteInitMode(options.shareStrategy, consumer);
1840
+ const deferRemoteLoad = shouldDeferRemoteLoad(initMode);
1841
+ const remote = getRemoteFromId(id, options.remotes);
1842
+ const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
1843
+ entryGlobalName: remote.entryGlobalName,
1844
+ name: remote.name,
1845
+ type: remote.type,
1846
+ entry: remote.entry,
1847
+ shareScope: remote.shareScope ?? "default"
1848
+ })}]);` : "";
1849
+ const browserHostInitCode = `import(${JSON.stringify(getHostAutoInitPath())})
1850
+ .then((mod) => mod.hostInitPromise)
1851
+ .then(initResolve, initReject);`;
1852
+ const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getHostAutoInitPath())}
1853
+ const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];`;
1854
+ const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
1855
+ import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(getHostAutoInitPath())};` : `${devRuntimeBootstrap}
1856
+ ${command === "serve" && consumer !== "server" ? browserHostInitCode : ""}`;
1857
+ const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
1858
+ const remoteLoadFailureHandler = command === "build" ? `.catch((error) => {
1859
+ delete __mfModuleCache.remote[pendingKey];
1860
+ throw error;
1861
+ })` : `.catch(() => {
1862
+ delete __mfModuleCache.remote[pendingKey];
1863
+ })`;
1864
+ const remoteLoadCode = `
1865
+ function __mfStartRemoteLoad() {
1866
+ ${`
1867
+ const pendingKey = ${JSON.stringify(`__mf_pending__${id}`)};
1868
+ if (!__mfModuleCache.remote[pendingKey]) {
1869
+ __mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
1870
+ .then((runtime) => {
1871
+ ${registerRemoteCode}
1872
+ return runtime.loadRemote(${JSON.stringify(id)});
1873
+ })
1874
+ .then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
1875
+ .then((mod) => {
1876
+ __mfModuleCache.remote[${JSON.stringify(id)}] = mod;
1877
+ delete __mfModuleCache.remote[pendingKey];
1878
+ return mod;
1879
+ })
1880
+ ${remoteLoadFailureHandler};
1881
+ }
1882
+ return __mfModuleCache.remote[pendingKey];`}
1883
+ }`;
1884
+ const realRemoteInit = `__mfRemotePending = __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
1885
+ const deferredClientInit = `exportModule = __mfCreateDeferredRemoteProxy();`;
1886
+ const clientNeedsRealRemote = clientNeedsRealRemoteForHydration(command, enableSsrInit);
1887
+ const eagerClientInit = clientNeedsRealRemote ? realRemoteInit : deferredClientInit;
1888
+ const loadedFirstClientInit = clientNeedsRealRemote ? realRemoteInit : deferredClientInit;
1889
+ const environmentSplitInit = (clientInit, serverInit) => consumer === "client" ? clientInit : consumer === "server" ? serverInit : `if (typeof window === "undefined") {
1890
+ ${serverInit}
1891
+ } else {
1892
+ ${clientInit}
1893
+ }`;
1894
+ const initExportModule = initMode === "eager" ? environmentSplitInit(eagerClientInit, realRemoteInit) : environmentSplitInit(loadedFirstClientInit, realRemoteInit);
1895
+ const includeProxyHelper = shouldIncludeDeferredProxy(initMode, consumer, clientNeedsRealRemote, deferRemoteLoad);
1896
+ const deferredProxyCode = getDeferredProxyHelper(id);
1897
+ return `
1898
+ ${importLine}
1899
+ ${remoteLoadCode}
1900
+ ${includeProxyHelper ? deferredProxyCode : ""}
1901
+ ${getRemoteModuleRuntimeHelpers()}
1831
1902
  let __mfRemotePending;
1832
1903
  let exportModule = __mfModuleCache.remote[${JSON.stringify(id)}]
1833
1904
  if (exportModule === undefined) {
1834
- __mfRemotePending = __mfStartRemoteLoad();
1835
- exportModule = __mfCreateRemoteProxy(__mfRemotePending);
1905
+ ${initExportModule}
1836
1906
  }
1837
- ${exportLine}
1907
+ ${getRemoteExportBlock(command, deferRemoteLoad, consumer)}
1838
1908
  `;
1839
1909
  }
1840
1910
  //#endregion
@@ -1901,6 +1971,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1901
1971
  function rewriteSvelteKitInlineStart(html, initPath) {
1902
1972
  return html.replace(/<script>([\s\S]*?)<\/script>/gi, (scriptTag, body) => {
1903
1973
  if (!body.includes("kit.start(app, element);") || !body.includes("Promise.all([")) return scriptTag;
1974
+ if (body.includes("initHost")) return scriptTag;
1904
1975
  const blockStart = body.indexOf("{");
1905
1976
  const blockEnd = body.lastIndexOf("}");
1906
1977
  if (blockStart === -1 || blockEnd <= blockStart) return scriptTag;
@@ -1924,7 +1995,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1924
1995
  return walkFiles(dir, (fileName) => fileName.endsWith(".html"));
1925
1996
  }
1926
1997
  function toRelativeImport(fromFile, targetFile) {
1927
- const relative = path$1.relative(path$1.dirname(fromFile), targetFile).replace(/\\/g, "/");
1998
+ const relative = normalizePathForImport(path$1.relative(path$1.dirname(fromFile), targetFile));
1928
1999
  return relative.startsWith(".") ? relative : `./${relative}`;
1929
2000
  }
1930
2001
  function patchSvelteKitStaticHtml() {
@@ -1946,14 +2017,14 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1946
2017
  }
1947
2018
  return patched;
1948
2019
  }
1949
- function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false) {
2020
+ function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false, options) {
1950
2021
  const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
1951
2022
  globalThis.System && typeof globalThis.System.import === 'function'
1952
2023
  ? globalThis.System.import(src)
1953
2024
  : import(src);
1954
2025
  ` : "";
1955
2026
  const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
1956
- const remotePreloads = getNormalizeModuleFederationOptions()?.shareStrategy !== "loaded-first" ? Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `__mfPreloadRemote(${JSON.stringify(remote)})`).join(",") : "";
2027
+ const remotePreloads = !options?.skipRemotePreload && getNormalizeModuleFederationOptions()?.shareStrategy !== "loaded-first" ? Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `__mfPreloadRemote(${JSON.stringify(remote)})`).join(",") : "";
1957
2028
  const preloadBlock = remotePreloads ? `
1958
2029
  const runtime = await initHost();
1959
2030
  const __mfPreloadRemote = (remote) => {
@@ -2241,12 +2312,13 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
2241
2312
  return mapCodeToCodeWithSourcemap(code.replace("vueApp.mount(vueAppRootContainer);", `${injection}vueApp.mount(vueAppRootContainer);`));
2242
2313
  }
2243
2314
  const isHydrationEntryFallback = inject === "entry" && entryFiles.length === 0 && (!htmlFilePath || !fs$1.existsSync(htmlFilePath)) && !clientInjected && !id.includes("node_modules") && (id.startsWith("\0") || /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id)) && /hydrateRoot|createRoot|ReactDOM\.render/.test(code);
2244
- const isNuxtClientEntryFallback = _command === "serve" && inject === "entry" && entryFiles.length === 0 && (!htmlFilePath || !fs$1.existsSync(htmlFilePath)) && !clientInjected && !hasEntryBootstrapParam(id) && !id.includes("node_modules/.vite") && /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
2245
- if (injectEntry() && entryFiles.some((file) => resolveProjectId(id) === file) || _command === "serve" && inject === "html" && !isVinext && !clientInjected && !id.startsWith("\0") && !id.includes("node_modules") && /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id) || isHydrationEntryFallback || isNuxtClientEntryFallback) {
2315
+ const isNuxtEntryAsyncModule = /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
2316
+ const isNuxtClientEntryFallback = _command === "serve" && inject === "entry" && (!htmlFilePath || !fs$1.existsSync(htmlFilePath)) && !clientInjected && !hasEntryBootstrapParam(id) && !id.includes("node_modules/.vite") && isNuxtEntryAsyncModule && !entryFiles.some((file) => resolveProjectId(id) === file);
2317
+ if (!(_command === "serve" && isNuxtEntryAsyncModule) && (injectEntry() && entryFiles.some((file) => resolveProjectId(id) === file) || _command === "serve" && inject === "html" && !isVinext && !clientInjected && !id.startsWith("\0") && !id.includes("node_modules") && /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id) || isHydrationEntryFallback || isNuxtClientEntryFallback)) {
2246
2318
  clientInjected = true;
2247
2319
  if (!waitsForInit || _command === "serve" && inject === "entry" && isHydrationEntryFallback) return mapCodeToCodeWithSourcemap(`import ${JSON.stringify(getEntryPath())};\n` + code);
2248
2320
  const entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
2249
- return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc));
2321
+ return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, { skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule }));
2250
2322
  }
2251
2323
  }
2252
2324
  }];
@@ -2297,17 +2369,35 @@ function checkAliasConflicts(options) {
2297
2369
  }
2298
2370
  //#endregion
2299
2371
  //#region src/plugins/hmr/react.ts
2372
+ const REACT_REFRESH_PATH = "/@react-refresh";
2373
+ const LOCAL_REACT_REFRESH_PATH = "/@mf-react-refresh-local";
2374
+ function stripQuery(url) {
2375
+ return url?.replace(/\?.*$/, "");
2376
+ }
2377
+ function resolveReactRefreshRuntime(root) {
2378
+ const reactPluginEntry = createRequire(pathToFileURL$1(path.join(root, "package.json"))).resolve("@vitejs/plugin-react");
2379
+ const requireFromReactPlugin = createRequire(reactPluginEntry);
2380
+ const reactPluginRoot = path.dirname(reactPluginEntry);
2381
+ const runtimePath = path.join(reactPluginRoot, "refresh-runtime.js");
2382
+ const refreshUtilsPath = path.join(reactPluginRoot, "refreshUtils.js");
2383
+ if (existsSync$1(runtimePath)) return readFileSync$1(runtimePath, "utf-8");
2384
+ const reactRefreshDir = path.dirname(requireFromReactPlugin.resolve("react-refresh/package.json"));
2385
+ return [
2386
+ "const exports = {}",
2387
+ readFileSync$1(path.join(reactRefreshDir, "cjs/react-refresh-runtime.development.js"), "utf-8"),
2388
+ readFileSync$1(refreshUtilsPath, "utf-8"),
2389
+ "export default exports"
2390
+ ].join("\n");
2391
+ }
2300
2392
  /**
2301
2393
  * Proxy module served for `/@react-refresh` on MF remote dev servers.
2302
- * Delegates to the host page's RefreshRuntime instance via
2303
- * `window.location.origin`, ensuring a single shared component registry
2304
- * across federation boundaries. A `configureServer` middleware is used
2305
- * instead of `resolveId` because `@vitejs/plugin-react`'s
2306
- * `vite:react-refresh` sub-plugin uses `enforce: 'pre'` and typically
2307
- * wins the `resolveId` race.
2394
+ * Delegates to the host page's RefreshRuntime when consumed by a host, but
2395
+ * falls back to this remote's local runtime when the remote is opened directly.
2308
2396
  */
2309
2397
  const REACT_REFRESH_PROXY_MODULE = [
2310
- `const __rt = await import(window.location.origin + '/@react-refresh');`,
2398
+ `const __remoteOrigin = new URL(import.meta.url).origin;`,
2399
+ `const __target = window.location.origin === __remoteOrigin ? '${LOCAL_REACT_REFRESH_PATH}' : window.location.origin + '${REACT_REFRESH_PATH}';`,
2400
+ `const __rt = await import(__target);`,
2311
2401
  `export const injectIntoGlobalHook = __rt.injectIntoGlobalHook;`,
2312
2402
  `export const register = __rt.register;`,
2313
2403
  `export const createSignatureFunctionForTransform = __rt.createSignatureFunctionForTransform;`,
@@ -2320,8 +2410,17 @@ const reactAdapter = {
2320
2410
  name: "react",
2321
2411
  pluginNames: ["vite:react-refresh", "vite:react-swc:refresh"],
2322
2412
  remote: { configureServer({ server }) {
2413
+ let reactRefreshRuntime;
2323
2414
  server.middlewares.use((req, res, next) => {
2324
- if (req.url?.replace(/\?.*$/, "") !== "/@react-refresh") return next();
2415
+ const url = stripQuery(req.url);
2416
+ if (url === LOCAL_REACT_REFRESH_PATH) {
2417
+ reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
2418
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
2419
+ res.setHeader("Access-Control-Allow-Origin", "*");
2420
+ res.end(reactRefreshRuntime);
2421
+ return;
2422
+ }
2423
+ if (url !== REACT_REFRESH_PATH) return next();
2325
2424
  res.setHeader("Content-Type", "application/javascript; charset=utf-8");
2326
2425
  res.setHeader("Access-Control-Allow-Origin", "*");
2327
2426
  res.end(REACT_REFRESH_PROXY_MODULE);
@@ -2746,7 +2845,7 @@ function pluginDevRemoteHmr(options) {
2746
2845
  function initVirtualModules(command, remoteEntryId, enableSsrInit = false) {
2747
2846
  writeLocalSharedImportMap();
2748
2847
  writeHostAutoInit(remoteEntryId, command);
2749
- writeRuntimeInitStatus(command, enableSsrInit);
2848
+ writeRuntimeInitStatus(command, enableSsrInit, getHostAutoInitPath());
2750
2849
  }
2751
2850
  //#endregion
2752
2851
  //#region src/utils/bundleHelpers.ts
@@ -3012,11 +3111,11 @@ const processModuleAssets = (bundle, filesMap, moduleMatcher, options = {}) => {
3012
3111
  if (fileData.type !== "chunk") continue;
3013
3112
  if (!fileData.modules) continue;
3014
3113
  for (const modulePath of Object.keys(fileData.modules)) {
3015
- const comparableModulePath = options.root ? path.resolve(options.root, modulePath) : modulePath;
3114
+ const comparableModulePath = options.root ? path$1.resolve(options.root, modulePath) : modulePath;
3016
3115
  const comparableModulePaths = [comparableModulePath];
3017
3116
  if (options.stripKnownJsExtensions) {
3018
- const ext = path.extname(comparableModulePath);
3019
- if (JS_EXTENSIONS.includes(ext)) comparableModulePaths.push(path.join(path.dirname(comparableModulePath), path.basename(comparableModulePath, ext)));
3117
+ const ext = path$1.extname(comparableModulePath);
3118
+ if (JS_EXTENSIONS.includes(ext)) comparableModulePaths.push(path$1.join(path$1.dirname(comparableModulePath), path$1.basename(comparableModulePath, ext)));
3020
3119
  }
3021
3120
  const matchKey = comparableModulePaths.map(moduleMatcher).find(Boolean);
3022
3121
  if (!matchKey) continue;
@@ -3692,7 +3791,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3692
3791
  });
3693
3792
  if (options.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
3694
3793
  const ensureRelativeImportPath = (fromFile, toFile) => {
3695
- let relativePath = path$1.relative(path$1.dirname(fromFile), toFile);
3794
+ let relativePath = normalizePathForImport(path$1.relative(path$1.dirname(fromFile), toFile));
3696
3795
  if (!relativePath.startsWith(".")) relativePath = `./${relativePath}`;
3697
3796
  return relativePath;
3698
3797
  };
@@ -3715,6 +3814,40 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3715
3814
  };
3716
3815
  }
3717
3816
  //#endregion
3817
+ //#region src/utils/remoteConsumerTarget.ts
3818
+ function getPluginEnvironmentName(ctx) {
3819
+ if (ctx == null || typeof ctx !== "object") return void 0;
3820
+ const environment = ctx["environment"];
3821
+ if (environment == null || typeof environment !== "object") return void 0;
3822
+ const name = environment["name"];
3823
+ return typeof name === "string" ? name : void 0;
3824
+ }
3825
+ function resolveRemoteConsumer(ctx, hasMultiEnvironment) {
3826
+ if (!hasMultiEnvironment) return "unified";
3827
+ const envName = getPluginEnvironmentName(ctx);
3828
+ if (!envName || envName === "client") return "client";
3829
+ return "server";
3830
+ }
3831
+ //#endregion
3832
+ //#region src/utils/ssrCapabilities.ts
3833
+ /**
3834
+ * Single source of truth for SSR-related feature gates.
3835
+ *
3836
+ * - Vite 8+ dev: ModuleRunner + FetchableDevEnvironment for `/__mf_ssr__/` entries.
3837
+ * - Any Vite major on build/preview: HTTP fetch + temp-file import via ssrEntryLoader.
3838
+ */
3839
+ function getSsrCapabilities(viteMajor, command, hasRemotes) {
3840
+ if (!hasRemotes) return {
3841
+ enableSsrInitBootstrap: false,
3842
+ injectSsrEntryLoader: false
3843
+ };
3844
+ const supported = command === "build" || command === "serve" && viteMajor >= 8;
3845
+ return {
3846
+ enableSsrInitBootstrap: supported,
3847
+ injectSsrEntryLoader: supported
3848
+ };
3849
+ }
3850
+ //#endregion
3718
3851
  //#region src/plugins/pluginProxyRemotes.ts
3719
3852
  function isNodeModulesImporter(importer) {
3720
3853
  return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
@@ -3739,13 +3872,15 @@ function pluginProxyRemotes_default(options) {
3739
3872
  let command;
3740
3873
  let root = process.cwd();
3741
3874
  let enableSsrInit = false;
3875
+ let hasMultiEnvironment = false;
3742
3876
  const { remotes } = options;
3743
- function resolveRemoteId(source, importer, remoteName) {
3877
+ function resolveRemoteId(pluginContext, source, importer, remoteName) {
3744
3878
  if (source === remoteName) {
3745
3879
  const installedPackageEntry = getInstalledPackageEntry(source, { cwd: root });
3746
3880
  if (installedPackageEntry && (importer === void 0 || isNodeModulesImporter(importer))) return installedPackageEntry;
3747
3881
  }
3748
- const remoteModule = getRemoteVirtualModule(source, command, enableSsrInit);
3882
+ const consumer = resolveRemoteConsumer(pluginContext, hasMultiEnvironment);
3883
+ const remoteModule = getRemoteVirtualModule(source, command, enableSsrInit, consumer);
3749
3884
  addUsedRemote(remoteName, source);
3750
3885
  refreshHostAutoInit();
3751
3886
  return remoteModule.getImportId();
@@ -3753,6 +3888,9 @@ function pluginProxyRemotes_default(options) {
3753
3888
  return {
3754
3889
  name: "proxyRemotes",
3755
3890
  enforce: "pre",
3891
+ applyToEnvironment() {
3892
+ return true;
3893
+ },
3756
3894
  config(config, { command: _command }) {
3757
3895
  command = _command;
3758
3896
  root = config.root || process.cwd();
@@ -3764,14 +3902,15 @@ function pluginProxyRemotes_default(options) {
3764
3902
  });
3765
3903
  });
3766
3904
  },
3767
- configResolved() {
3768
- enableSsrInit = command === "serve" && parseInt(version, 10) >= 8;
3905
+ configResolved(config) {
3906
+ hasMultiEnvironment = Boolean(config.environments?.ssr);
3907
+ enableSsrInit = getSsrCapabilities(parseInt(version, 10), command, Object.keys(remotes).length > 0).enableSsrInitBootstrap;
3769
3908
  },
3770
3909
  resolveId(source, importer) {
3771
3910
  if (!filterId(source)) return;
3772
3911
  for (const remote of Object.values(remotes)) {
3773
3912
  if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
3774
- return resolveRemoteId(source, importer, remote.name);
3913
+ return resolveRemoteId(this, source, importer, remote.name);
3775
3914
  }
3776
3915
  }
3777
3916
  };
@@ -3813,11 +3952,11 @@ function getPrebuildResolutionSource(pkgName, shareItem) {
3813
3952
  return getConcreteSharedImportSource(pkgName, shareItem) || pkgName;
3814
3953
  }
3815
3954
  function tryResolveFromProjectRoot(source) {
3816
- if (path.isAbsolute(source) || source.startsWith(".") || source.startsWith("/")) return source;
3955
+ if (path$1.isAbsolute(source) || source.startsWith(".") || source.startsWith("/")) return source;
3817
3956
  const browserEntry = getInstalledPackageEntry(source, { cwd: getPackageDetectionCwd() });
3818
3957
  if (browserEntry) return browserEntry;
3819
3958
  try {
3820
- return createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(source);
3959
+ return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(source);
3821
3960
  } catch {
3822
3961
  return;
3823
3962
  }
@@ -4005,36 +4144,28 @@ function proxySharedModule(options) {
4005
4144
  ];
4006
4145
  }
4007
4146
  //#endregion
4008
- //#region src/utils/loadWalk.ts
4009
- let walkPromise = null;
4010
- function loadWalk() {
4011
- walkPromise ||= import("estree-walker").then(({ walk }) => walk);
4012
- return walkPromise;
4013
- }
4014
- //#endregion
4015
4147
  //#region src/plugins/pluginRemoteNamedExports.ts
4016
- /**
4017
- * Transforms consumer-side imports of remote modules so that named exports
4018
- * are accessible even when the bundler does not support syntheticNamedExports
4019
- * (Rolldown / Vite 8+).
4020
- *
4021
- * The remote proxy module exports:
4022
- * export const __moduleExports = exportModule; // full namespace
4023
- * export default exportModule.default ?? exportModule; // unwrapped default
4024
- *
4025
- * This plugin rewrites consumer code:
4026
- * import { foo } from "remote/xxx"
4027
- * → import { __moduleExports as __mf_ns_0 } from "remote/xxx"; const { foo } = __mf_ns_0;
4028
- *
4029
- * import("remote/xxx")
4030
- * → import("remote/xxx").then(…) // spreads __moduleExports into namespace
4031
- *
4032
- * NOTE: `export * from "remote/xxx"` is not supported — Rolldown cannot
4033
- * statically resolve the set of exported names from a federated remote at
4034
- * build time. Use explicit named re-exports instead.
4035
- */
4036
4148
  const JS_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?|vue|svelte)(?:\?|$)/;
4037
4149
  const REGEX_FALLBACK_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?)(?:\?|$)/;
4150
+ function isAstNode(value) {
4151
+ return !!value && typeof value === "object" && typeof value.type === "string";
4152
+ }
4153
+ function walkAST(root, visitor) {
4154
+ const seen = /* @__PURE__ */ new WeakSet();
4155
+ function visit(node) {
4156
+ if (!isAstNode(node)) return;
4157
+ if (seen.has(node)) return;
4158
+ seen.add(node);
4159
+ let skipped = false;
4160
+ visitor.enter.call({ skip() {
4161
+ skipped = true;
4162
+ } }, node);
4163
+ if (skipped) return;
4164
+ for (const value of Object.values(node)) if (Array.isArray(value)) for (const item of value) visit(item);
4165
+ else visit(value);
4166
+ }
4167
+ visit(root);
4168
+ }
4038
4169
  function parseNamedSpecifiers(specifiersRaw, kind) {
4039
4170
  return specifiersRaw.split(",").map((s) => s.trim()).filter((s) => s.length > 0 && !s.startsWith("type ")).map((s) => {
4040
4171
  const asMatch = s.match(/^(\w+)\s+as\s+(\w+)$/);
@@ -4050,7 +4181,7 @@ function parseNamedSpecifiers(specifiersRaw, kind) {
4050
4181
  });
4051
4182
  }
4052
4183
  function wrapDynamicImport(original) {
4053
- return `${original}.then(function(__mf_m__) {\n var __mf_ready__ = __mf_m__ && __mf_m__.__mf_remote_pending ? __mf_m__.__mf_remote_pending.then(function(__mf_resolved__) { return __mf_resolved__ || __mf_m__; }) : __mf_m__;\n return Promise.resolve(__mf_ready__).then(function(__mf_m__) {\n if (!__mf_m__ || !__mf_m__.__moduleExports) {\n if (__mf_m__ && __mf_m__.default && typeof __mf_m__.default === "object" && __mf_m__.default.__esModule) {\n var __mf_nested_e__ = __mf_m__.default;\n var __mf_nested_ns__ = Object.create(null);\n Object.defineProperty(__mf_nested_ns__, Symbol.toStringTag, { value: "Module" });\n Object.keys(__mf_nested_e__).forEach(function(k) { if (k !== "__esModule") __mf_nested_ns__[k] = __mf_nested_e__[k] });\n if ("default" in __mf_nested_e__) __mf_nested_ns__.default = __mf_nested_e__.default;\n return __mf_nested_ns__;\n }\n return __mf_m__;\n }\n var __mf_ns__ = Object.create(null);\n Object.defineProperty(__mf_ns__, Symbol.toStringTag, { value: "Module" });\n var __mf_e__ = __mf_m__.__moduleExports;\n if (__mf_e__ && __mf_e__.default && typeof __mf_e__.default === "object" && __mf_e__.default.__esModule) __mf_e__ = __mf_e__.default;\n Object.keys(__mf_e__).forEach(function(k) { if (k !== "__esModule") __mf_ns__[k] = __mf_e__[k] });\n if ("default" in __mf_e__) __mf_ns__.default = __mf_e__.default;\n else if ("default" in __mf_m__) __mf_ns__.default = __mf_m__.default;\n return __mf_ns__;\n });\n})`;
4184
+ return `${original}.then(function(__mf_m__) {\n var __mf_pending__ = __mf_m__ && __mf_m__.__mf_remote_pending;\n var __mf_ready__ = __mf_pending__ && typeof __mf_pending__.then === "function"\n ? __mf_pending__.then(function(__mf_resolved__) { return __mf_resolved__ || __mf_m__; })\n : Promise.resolve(__mf_m__);\n return __mf_ready__.then(function(__mf_m__) {\n if (!__mf_m__ || !__mf_m__.__moduleExports) {\n if (__mf_m__ && __mf_m__.default && typeof __mf_m__.default === "object" && __mf_m__.default.__esModule) {\n var __mf_nested_e__ = __mf_m__.default;\n var __mf_nested_ns__ = Object.create(null);\n Object.defineProperty(__mf_nested_ns__, Symbol.toStringTag, { value: "Module" });\n Object.keys(__mf_nested_e__).forEach(function(k) { if (k !== "__esModule") __mf_nested_ns__[k] = __mf_nested_e__[k] });\n if ("default" in __mf_nested_e__) __mf_nested_ns__.default = __mf_nested_e__.default;\n return __mf_nested_ns__;\n }\n var __mf_flat_ns__ = Object.create(null);\n Object.defineProperty(__mf_flat_ns__, Symbol.toStringTag, { value: "Module" });\n var __mf_src__ = __mf_m__;\n if (__mf_src__ && __mf_src__.default && typeof __mf_src__.default === "object" && __mf_src__.default.__esModule) __mf_src__ = __mf_src__.default;\n if (__mf_src__) {\n Object.keys(__mf_src__).forEach(function(k) { if (k !== "__esModule") __mf_flat_ns__[k] = __mf_src__[k]; });\n __mf_flat_ns__.default = "default" in __mf_src__ ? __mf_src__.default : __mf_src__;\n }\n return __mf_flat_ns__;\n }\n var __mf_ns__ = Object.create(null);\n Object.defineProperty(__mf_ns__, Symbol.toStringTag, { value: "Module" });\n var __mf_e__ = __mf_m__.__moduleExports;\n if (__mf_e__ && __mf_e__.default && typeof __mf_e__.default === "object" && __mf_e__.default.__esModule) __mf_e__ = __mf_e__.default;\n Object.keys(__mf_e__).forEach(function(k) { if (k !== "__esModule") __mf_ns__[k] = __mf_e__[k] });\n if ("default" in __mf_e__) __mf_ns__.default = __mf_e__.default;\n else if ("default" in __mf_m__) __mf_ns__.default = __mf_m__.default;\n return __mf_ns__;\n });\n})`;
4054
4185
  }
4055
4186
  function applyRewrites(code, imports, id) {
4056
4187
  if (imports.length === 0) return;
@@ -4150,9 +4281,8 @@ function applyRewrites(code, imports, id) {
4150
4281
  };
4151
4282
  }
4152
4283
  async function collectFromAST(ast, code, isRemoteImport) {
4153
- const walk = await loadWalk();
4154
4284
  const result = [];
4155
- walk(ast, { enter(node) {
4285
+ walkAST(ast, { enter(node) {
4156
4286
  if (node.type === "ImportDeclaration" && node.source?.value) {
4157
4287
  if (!isRemoteImport(node.source.value)) return;
4158
4288
  const specifiers = node.specifiers || [];
@@ -4211,86 +4341,11 @@ async function collectFromAST(ast, code, isRemoteImport) {
4211
4341
  } });
4212
4342
  return result;
4213
4343
  }
4214
- async function collectFromEsLexer(code, isRemoteImport) {
4215
- await init;
4216
- let imports;
4217
- try {
4218
- [imports] = parse(code);
4219
- } catch {
4220
- return;
4221
- }
4222
- const result = [];
4223
- for (const imp of imports) {
4224
- if (imp.d === -2) continue;
4225
- if (!imp.n || !isRemoteImport(imp.n)) continue;
4226
- const stmtText = code.slice(imp.ss, imp.se);
4227
- if (imp.d >= 0) {
4228
- result.push({
4229
- kind: "dynamic",
4230
- start: imp.ss,
4231
- end: imp.se,
4232
- originalText: stmtText
4233
- });
4234
- continue;
4235
- }
4236
- if (/^\s*export\s*\*\s/.test(stmtText)) {
4237
- result.push({
4238
- kind: "export-all",
4239
- source: imp.n,
4240
- start: imp.ss,
4241
- end: imp.se
4242
- });
4243
- continue;
4244
- }
4245
- if (/^\s*export\s/.test(stmtText)) {
4246
- const braceMatch = stmtText.match(/\{([^}]*)\}/);
4247
- if (!braceMatch) continue;
4248
- const specifiers = parseNamedSpecifiers(braceMatch[1], "export");
4249
- if (specifiers.length === 0) continue;
4250
- result.push({
4251
- kind: "reexport",
4252
- source: imp.n,
4253
- start: imp.ss,
4254
- end: imp.se,
4255
- specifiers
4256
- });
4257
- continue;
4258
- }
4259
- const importMatch = stmtText.match(/^import\s+([\s\S]*?)\s+from\s/);
4260
- if (!importMatch) continue;
4261
- const specifiersPart = importMatch[1].trim();
4262
- if (/^type\s/.test(specifiersPart)) continue;
4263
- const nsMatch = specifiersPart.match(/^\*\s+as\s+(\w+)$/);
4264
- if (nsMatch) {
4265
- result.push({
4266
- kind: "static",
4267
- source: imp.n,
4268
- start: imp.ss,
4269
- end: imp.se,
4270
- named: [],
4271
- namespaceLocal: nsMatch[1]
4272
- });
4273
- continue;
4274
- }
4275
- const braceMatch = specifiersPart.match(/\{([^}]*)\}/);
4276
- if (!braceMatch) continue;
4277
- const named = parseNamedSpecifiers(braceMatch[1], "import");
4278
- if (named.length === 0) continue;
4279
- const defaultMatch = specifiersPart.match(/^(\w+)\s*,/);
4280
- result.push({
4281
- kind: "static",
4282
- source: imp.n,
4283
- start: imp.ss,
4284
- end: imp.se,
4285
- named,
4286
- defaultLocal: defaultMatch?.[1]
4287
- });
4288
- }
4289
- return result;
4290
- }
4291
4344
  function collectFromRegex(code, isRemoteImport) {
4292
4345
  const result = [];
4293
- for (const match of code.matchAll(/^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2\s*;?/gm)) {
4346
+ const importAttributes = String.raw`(?:\s+(?:with|assert)\s+\{[^;]*\})?`;
4347
+ const staticRe = new RegExp(String.raw`^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`, "gm");
4348
+ for (const match of code.matchAll(staticRe)) {
4294
4349
  const [full, specifiersPartRaw, , source] = match;
4295
4350
  if (!isRemoteImport(source)) continue;
4296
4351
  const specifiersPart = specifiersPartRaw.trim();
@@ -4321,7 +4376,8 @@ function collectFromRegex(code, isRemoteImport) {
4321
4376
  defaultLocal: defaultMatch?.[1]
4322
4377
  });
4323
4378
  }
4324
- for (const match of code.matchAll(/^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2\s*;?/gm)) {
4379
+ const reexportRe = new RegExp(String.raw`^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`, "gm");
4380
+ for (const match of code.matchAll(reexportRe)) {
4325
4381
  const [full, specifiersRaw, , source] = match;
4326
4382
  if (!isRemoteImport(source)) continue;
4327
4383
  const specifiers = parseNamedSpecifiers(specifiersRaw, "export");
@@ -4334,7 +4390,8 @@ function collectFromRegex(code, isRemoteImport) {
4334
4390
  specifiers
4335
4391
  });
4336
4392
  }
4337
- for (const match of code.matchAll(/^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1\s*;?/gm)) {
4393
+ const exportAllRe = new RegExp(String.raw`^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1${importAttributes}\s*;?`, "gm");
4394
+ for (const match of code.matchAll(exportAllRe)) {
4338
4395
  const [full, , source] = match;
4339
4396
  if (!isRemoteImport(source)) continue;
4340
4397
  result.push({
@@ -4344,7 +4401,7 @@ function collectFromRegex(code, isRemoteImport) {
4344
4401
  end: match.index + full.length
4345
4402
  });
4346
4403
  }
4347
- for (const match of code.matchAll(/import\(\s*(['"])([^'"]+)\1\s*\)/g)) {
4404
+ for (const match of code.matchAll(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])([^'"]+)\1\s*\)/g)) {
4348
4405
  const [full, , source] = match;
4349
4406
  if (!isRemoteImport(source)) continue;
4350
4407
  result.push({
@@ -4379,7 +4436,8 @@ function pluginRemoteNamedExports(options) {
4379
4436
  try {
4380
4437
  imports = await collectFromAST(this.parse(code), code, matchesRemoteImport);
4381
4438
  } catch {
4382
- imports = await collectFromEsLexer(code, matchesRemoteImport);
4439
+ if ((id.includes(".vue") || id.includes(".svelte")) && /^\s*</.test(code)) return;
4440
+ imports = collectFromRegex(code, matchesRemoteImport);
4383
4441
  }
4384
4442
  if ((!imports || imports.length === 0) && REGEX_FALLBACK_EXTENSIONS_RE.test(id)) imports = collectFromRegex(code, matchesRemoteImport);
4385
4443
  if (!imports) return;
@@ -4514,10 +4572,10 @@ function pluginSSRRemoteEntry(options) {
4514
4572
  const bareId = decodeViteId(id);
4515
4573
  try {
4516
4574
  const { createRequire } = await import("module");
4517
- const resolved = createRequire(new URL(`file://${server.config.root}/package.json`)).resolve(bareId.replace(/^\0/, ""));
4575
+ const path = await import("path");
4518
4576
  const { pathToFileURL } = await import("url");
4519
4577
  result = {
4520
- externalize: pathToFileURL(resolved).href,
4578
+ externalize: pathToFileURL(createRequire(pathToFileURL(path.join(server.config.root, "package.json"))).resolve(bareId.replace(/^\0/, ""))).href,
4521
4579
  type: "module"
4522
4580
  };
4523
4581
  } catch {
@@ -4539,6 +4597,12 @@ function pluginSSRRemoteEntry(options) {
4539
4597
  res.setHeader("Access-Control-Allow-Origin", "*");
4540
4598
  res.end(code);
4541
4599
  });
4600
+ const exposesPath = `${base}/${options.filename.replace(/\.[^.]+$/, "")}.exposes.js`;
4601
+ server.middlewares.use(exposesPath, (_req, res) => {
4602
+ res.setHeader("Content-Type", "application/javascript");
4603
+ res.setHeader("Access-Control-Allow-Origin", "*");
4604
+ res.end(generateExposesSSR(options));
4605
+ });
4542
4606
  },
4543
4607
  resolveId(id) {
4544
4608
  if (id === remoteEntrySSRId || id.startsWith(remoteEntrySSRId)) return id;
@@ -4831,13 +4895,13 @@ function escapeUnsafeJsSourceChars(str) {
4831
4895
  });
4832
4896
  }
4833
4897
  function isFederationHtmlPreloadDependency(dep, includeSharedRuntime = false) {
4834
- const file = path.basename(dep);
4898
+ const file = path$1.basename(dep);
4835
4899
  if (file.includes("__mfe_internal__") || file.includes("virtual_mf-") || file.includes("virtualExposes") || file.includes("localSharedImportMap") || file.includes("hostInit")) return true;
4836
4900
  return includeSharedRuntime && (file.includes("preload-helper") || file.includes("rolldown-runtime") || file.startsWith("dist-"));
4837
4901
  }
4838
4902
  function canResolveSharedSubpath(subpath, projectRoot) {
4839
4903
  try {
4840
- createRequire(new URL(`file://${projectRoot}/package.json`)).resolve(subpath);
4904
+ createRequire$1(pathToFileURL(path$1.join(projectRoot, "package.json"))).resolve(subpath);
4841
4905
  return true;
4842
4906
  } catch {
4843
4907
  return false;
@@ -4972,7 +5036,7 @@ export default __mfShared.default ?? __mfShared;`
4972
5036
  const optimizeDeps = config.optimizeDeps ??= {};
4973
5037
  optimizeDeps.include ??= [];
4974
5038
  optimizeDeps.exclude ??= [];
4975
- if (isLitShare(key)) optimizeDeps.exclude.push(key);
5039
+ if (isLitShare(key) || key === "react" && hasPackageDependency("react-redux", root)) optimizeDeps.exclude.push(key);
4976
5040
  else optimizeDeps.include.push(key);
4977
5041
  for (const subpath of getCommonSharedSubpaths(key)) {
4978
5042
  getLoadShareModulePath(subpath, isRolldown);
@@ -4988,12 +5052,13 @@ export default __mfShared.default ?? __mfShared;`
4988
5052
  }
4989
5053
  },
4990
5054
  configResolved(config) {
4991
- if (parseInt(version, 10) < 8) return;
4992
- if (!(Object.keys(options.exposes).length > 0 || Object.keys(options.remotes).length > 0)) return;
5055
+ const viteMajor = parseInt(version, 10);
5056
+ const hasRemotes = Object.keys(options.remotes).length > 0;
5057
+ if (!getSsrCapabilities(viteMajor, config.command, hasRemotes).injectSsrEntryLoader) return;
4993
5058
  if (options.runtimePlugins.some((p) => {
4994
5059
  return (typeof p === "string" ? p : p[0]) === "@module-federation/vite/ssrEntryLoader";
4995
5060
  })) return;
4996
- const projectRequire = createRequire(new URL(`file://${config.root}/package.json`));
5061
+ const projectRequire = createRequire$1(pathToFileURL(path$1.join(config.root, "package.json")));
4997
5062
  const sharedKeys = Object.keys(options.shared ?? {});
4998
5063
  const commonSharedPkgs = [
4999
5064
  "react",
@@ -5024,7 +5089,7 @@ export default __mfShared.default ?? __mfShared;`
5024
5089
  const SSR_ONLY_PLUGINS = new Set(["@module-federation/vite/ssrEntryLoader"]);
5025
5090
  function loadPluginDts(options) {
5026
5091
  if (options.dts === false) return [];
5027
- return [import("./pluginDts-Bgdw5ODE.js").then(({ default: pluginDts }) => pluginDts(options))];
5092
+ return [import("./pluginDts-BaVhdR6i.js").then(({ default: pluginDts }) => pluginDts(options))];
5028
5093
  }
5029
5094
  function federation(mfUserOptions) {
5030
5095
  if (isTestEnv()) return [];
@@ -5079,8 +5144,8 @@ function federation(mfUserOptions) {
5079
5144
  const environmentName = this.environment?.name;
5080
5145
  if (!environmentName || environmentName === "client") return;
5081
5146
  const target = reactServerEntryMap[id];
5082
- const reactPackageJson = createRequire(new URL(`file://${process.cwd()}/package.json`)).resolve("react/package.json");
5083
- return path.join(path.dirname(reactPackageJson), target.replace(/^react\//, ""));
5147
+ const reactPackageJson = createRequire$1(pathToFileURL(path$1.join(process.cwd(), "package.json"))).resolve("react/package.json");
5148
+ return path$1.join(path$1.dirname(reactPackageJson), target.replace(/^react\//, ""));
5084
5149
  }
5085
5150
  }] : [],
5086
5151
  {
@@ -5090,7 +5155,8 @@ function federation(mfUserOptions) {
5090
5155
  command = env.command;
5091
5156
  },
5092
5157
  configResolved() {
5093
- initVirtualModules(command, remoteEntryId, parseInt(version, 10) >= 8);
5158
+ const ssrCapabilities = getSsrCapabilities(parseInt(version, 10), command, Object.keys(options.remotes).length > 0);
5159
+ initVirtualModules(command, remoteEntryId, ssrCapabilities.enableSsrInitBootstrap);
5094
5160
  }
5095
5161
  },
5096
5162
  aliasToArrayPlugin_default,
@@ -5155,7 +5221,7 @@ function federation(mfUserOptions) {
5155
5221
  ...currentModulePreload,
5156
5222
  resolveDependencies(filename, deps, context) {
5157
5223
  const resolvedDeps = existingResolveDependencies ? existingResolveDependencies(filename, deps, context) : deps;
5158
- const hostFile = path.basename(context.hostId);
5224
+ const hostFile = path$1.basename(context.hostId);
5159
5225
  if (context.hostType === "js" && (hostFile === options.filename || hostFile.includes("hostInit") || hostFile.includes("virtualExposes") || hostFile.includes("localSharedImportMap"))) return [];
5160
5226
  const hasFederationHtmlDeps = context.hostType === "html" && resolvedDeps.some((dep) => isFederationHtmlPreloadDependency(dep));
5161
5227
  const hasFederationJsDeps = context.hostType === "js" && resolvedDeps.some((dep) => isFederationHtmlPreloadDependency(dep));
@@ -5269,23 +5335,7 @@ function federation(mfUserOptions) {
5269
5335
  let code = VirtualModule.findById(id)?.code ?? readFileSync(id, "utf-8");
5270
5336
  code = code.replace(/import\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
5271
5337
  code = code.replace(/export\s+\*\s+from\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
5272
- /**
5273
- * Shared/remote shims only have `export default exportModule`.
5274
- *
5275
- * We add a second named export (__moduleExports) that holds the full
5276
- * module namespace and point syntheticNamedExports at it. This lets
5277
- * Rollup resolve named imports (e.g. `import { useState } from 'react'`)
5278
- * from the namespace while still applying its normal default-export
5279
- * interop — which is needed for libraries like @emotion/styled where
5280
- * `import styled from '@emotion/styled'` must receive the .default
5281
- * function, not the raw namespace object.
5282
- *
5283
- * Using 'default' as the syntheticNamedExports key would skip the
5284
- * interop and break default imports.
5285
- *
5286
- * @see https://rollupjs.org/plugin-development/#synthetic-named-exports
5287
- */
5288
- if (!/\bexport\s+const\s+__moduleExports\b/.test(code) && !/\bexport\s*\{[^}]*__moduleExports/.test(code)) {
5338
+ if (!(/\b(?:var|let|const)\s+__moduleExports\b/.test(code) || /\bexport\s+const\s+__moduleExports\b/.test(code) || /\bexport\s*\{[^}]*__moduleExports/.test(code))) {
5289
5339
  const nextCode = code.replace("export default exportModule", "export const __moduleExports = exportModule;\nexport default exportModule.__esModule ? exportModule.default : exportModule");
5290
5340
  code = nextCode === code ? `${code}\nexport const __moduleExports = exportModule;\n` : nextCode;
5291
5341
  }
@@ -5333,7 +5383,7 @@ function federation(mfUserOptions) {
5333
5383
  for (const chunk of Object.values(bundle)) {
5334
5384
  if (!isOutputChunk(chunk)) continue;
5335
5385
  if (!isFederationControlChunk(chunk.fileName, filename)) continue;
5336
- const outputPath = path.join(outputOptions.dir, chunk.fileName);
5386
+ const outputPath = path$1.join(outputOptions.dir, chunk.fileName);
5337
5387
  writeFileSync(outputPath, sanitizeFederationControlChunk(readFileSync(outputPath, "utf-8"), chunk.fileName, filename));
5338
5388
  }
5339
5389
  }
@@ -5428,8 +5478,8 @@ function federation(mfUserOptions) {
5428
5478
  for (const chunk of Object.values(bundle)) {
5429
5479
  if (!isOutputChunk(chunk)) continue;
5430
5480
  if (!chunk.code.includes("modulepreload")) continue;
5431
- const chunkDir = path.dirname(chunk.fileName);
5432
- const prefixToRoot = chunkDir === "." ? "" : `${path.relative(chunkDir, ".")}/`;
5481
+ const chunkDir = path$1.dirname(chunk.fileName);
5482
+ const prefixToRoot = chunkDir === "." ? "" : `${normalizePathForImport(path$1.relative(chunkDir, "."))}/`;
5433
5483
  const replacementExpr = prefixToRoot ? `${escapeUnsafeJsSourceChars(JSON.stringify(prefixToRoot))}+$1` : "$1";
5434
5484
  const replacement = `=function($1){return new URL(${replacementExpr},import.meta.url).href}`;
5435
5485
  const replaced = chunk.code.replace(/=\(?(\w+)(?:,\w+)?\)?\s*=>\s*[`"'][./][^`"']*[`"']\s*\+\s*\1/, replacement);