@module-federation/vite 1.23.3 → 1.23.5

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,6 +1,6 @@
1
- import { _ as resolvePublicPath, a as matchesSharedSource, c as filterId, d as getNodeModulesSuffix, f as isAssetLikeImport, g as normalizeNodeModulePath, h as isViteOptimizableEntry, i as invalidateSharedKeyMatcher, l as getBasePath$1, m as isNuxtClientBase, n as getSharedRequest, p as isNodeModulePath, r as getSharedRuntimeKey, s as ensureTrailingSlash, t as findSharedKey, u as getCommonSharedSubpaths, v as stripQueryAndHash, y as stripViteFsPrefix } from "./sharedKeyMatcher-Od_nYxJA.js";
1
+ import { _ as removeTrailingSlash, a as matchesSharedSource, b as stripViteFsPrefix, c as filterId, d as getNodeModulesSuffix, f as isAssetLikeImport, g as normalizeNodeModulePath, h as isViteOptimizableEntry, i as invalidateSharedKeyMatcher, l as getBasePath$1, m as isNuxtClientBase, n as getSharedRequest, p as isNodeModulePath, r as getSharedRuntimeKey, s as ensureTrailingSlash, t as findSharedKey, u as getCommonSharedSubpaths, v as resolvePublicPath, y as stripQueryAndHash } from "./sharedKeyMatcher-CHp4QRNq.js";
2
2
  import { a as CodeRewriter, c as isAbsoluteUrl, d as resolveHashPlaceholderFileName, i as createCodePositionMap, l as normalizePathForImport, o as createSourceMap, r as mfWarn, t as createModuleFederationError, u as rebaseImport } from "./logger-DOwfTlw5.js";
3
- import { C as isReactCoreShare, S as REACT_DOM_CLIENT_SHARE, _ as resolveModulePath, a as getIsRolldown, b as supportsCodeSplittingGroupDebugName, c as getPackageNameFromNodeModulePath, d as isNuxtProjectRoot, f as isPackageExportAvailable, g as resolveImportPath, h as packageNameEncode, i as getInstalledPackageJson, l as getSharedCacheDescriptor, m as packageNameDecode, n as getDependencyNames, o as getPackageDetectionCwd, p as isPackageInstalled, r as getInstalledPackageEntry, s as getPackageName, u as hasPackageDependency, v as setPackageDetectionCwd, x as REACT_CLIENT_INTERNALS_KEY, y as sharedCacheHelperCode } from "./dtsConstants-DSTzyKSG.js";
3
+ import { C as REACT_DOM_CLIENT_SHARE, S as REACT_CLIENT_INTERNALS_KEY, _ as resolveImportPath, a as getIsRolldown, b as sharedCacheHelperCode, c as getPackageName, d as hasPackageDependency, f as isNuxtProjectRoot, g as packageNameEncode, h as packageNameDecode, i as getInstalledPackageJson, l as getPackageNameFromNodeModulePath, m as isPackageInstalled, n as getDependencyNames, o as getPackageDetectionCwd, p as isPackageExportAvailable, r as getInstalledPackageEntry, s as getPackageExportSpecifiersForFile, u as getSharedCacheDescriptor, v as resolveModulePath, w as isReactCoreShare, x as supportsCodeSplittingGroupDebugName, y as setPackageDetectionCwd } from "./dtsConstants-BQdFpgKb.js";
4
4
  import { createRequire } from "node:module";
5
5
  import * as fs$2 from "fs";
6
6
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "fs";
@@ -977,6 +977,16 @@ function getSsrCapabilities(viteMajor, command, hasRemotes, isSsr = false) {
977
977
  };
978
978
  }
979
979
  //#endregion
980
+ //#region src/utils/runtimePluginSpecifier.ts
981
+ function getRuntimePluginSpecifier(plugin) {
982
+ return typeof plugin === "string" ? plugin : plugin[0];
983
+ }
984
+ /** Drop SSR-only plugins from a client graph; a server graph keeps them all. */
985
+ function filterRuntimePluginsForTarget(runtimePlugins, ssrOnlySpecifiers, isServer) {
986
+ if (isServer) return [...runtimePlugins];
987
+ return runtimePlugins.filter((plugin) => !ssrOnlySpecifiers.has(getRuntimePluginSpecifier(plugin)));
988
+ }
989
+ //#endregion
980
990
  //#region src/utils/serializeRuntimeOptions.ts
981
991
  const UNSAFE_JS_CHAR_MAP = {
982
992
  "<": "\\u003C",
@@ -1074,16 +1084,6 @@ function isParsableExpression(source) {
1074
1084
  }
1075
1085
  }
1076
1086
  //#endregion
1077
- //#region src/utils/runtimePluginSpecifier.ts
1078
- function getRuntimePluginSpecifier(plugin) {
1079
- return typeof plugin === "string" ? plugin : plugin[0];
1080
- }
1081
- /** Drop SSR-only plugins from a client graph; a server graph keeps them all. */
1082
- function filterRuntimePluginsForTarget(runtimePlugins, ssrOnlySpecifiers, isServer) {
1083
- if (isServer) return [...runtimePlugins];
1084
- return runtimePlugins.filter((plugin) => !ssrOnlySpecifiers.has(getRuntimePluginSpecifier(plugin)));
1085
- }
1086
- //#endregion
1087
1087
  //#region src/utils/importAnalysis.ts
1088
1088
  const analysisByBuild = /* @__PURE__ */ new WeakMap();
1089
1089
  /**
@@ -2281,8 +2281,37 @@ function hasCodeMatch(source, regex, codePositions) {
2281
2281
  while ((match = regex.exec(source)) !== null) if (codePositions[match.index]) return true;
2282
2282
  return false;
2283
2283
  }
2284
+ /**
2285
+ * True when the file contains a top-level static `import`/`export` declaration.
2286
+ * Local identifiers named `module` or `exports` (webpack/rspack helpers,
2287
+ * function parameters, etc.) must not override that module format.
2288
+ */
2289
+ function hasEsmModuleSyntax(source, codePositions) {
2290
+ const keywordRegex = /(?<![$\w])(?:import|export)\b/g;
2291
+ let match;
2292
+ let braceDepth = 0;
2293
+ let braceScanIndex = 0;
2294
+ while ((match = keywordRegex.exec(source)) !== null) {
2295
+ for (; braceScanIndex < match.index; braceScanIndex++) {
2296
+ if (!codePositions[braceScanIndex]) continue;
2297
+ if (source[braceScanIndex] === "{") braceDepth++;
2298
+ else if (source[braceScanIndex] === "}") braceDepth--;
2299
+ }
2300
+ if (!codePositions[match.index]) continue;
2301
+ if (braceDepth !== 0) continue;
2302
+ let previousCodeIndex = match.index - 1;
2303
+ while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
2304
+ if (source[previousCodeIndex] === ".") continue;
2305
+ let nextCodeIndex = match.index + match[0].length;
2306
+ while (nextCodeIndex < source.length && (/\s/.test(source[nextCodeIndex]) || !codePositions[nextCodeIndex])) nextCodeIndex++;
2307
+ if (source[nextCodeIndex] === "(") continue;
2308
+ return true;
2309
+ }
2310
+ return false;
2311
+ }
2284
2312
  function hasCommonJsExports(source) {
2285
2313
  const codePositions = createCodePositionMap(source);
2314
+ if (hasEsmModuleSyntax(source, codePositions)) return false;
2286
2315
  if (hasCodeMatch(source, /\bmodule\s*(?:\.exports|\[\s*['"]exports['"]\s*\])/g, codePositions)) return true;
2287
2316
  const exportsRegex = /\bexports\s*(?:\.|\[|[,)]|=(?!=|>))/g;
2288
2317
  let match;
@@ -2895,7 +2924,15 @@ function getWorkspacePackageJson(pkg) {
2895
2924
  fromResolvedEntry: resolved
2896
2925
  })?.packageJson;
2897
2926
  }
2927
+ const sharedDependencyGraphPackageJsonCache = /* @__PURE__ */ new Map();
2898
2928
  function getSharedDependencyGraphPackageJson(pkg) {
2929
+ const cacheKey = `${getPackageDetectionCwd()}\0${pkg}`;
2930
+ if (sharedDependencyGraphPackageJsonCache.has(cacheKey)) return sharedDependencyGraphPackageJsonCache.get(cacheKey);
2931
+ const packageJson = resolveSharedDependencyGraphPackageJson(pkg);
2932
+ sharedDependencyGraphPackageJsonCache.set(cacheKey, packageJson);
2933
+ return packageJson;
2934
+ }
2935
+ function resolveSharedDependencyGraphPackageJson(pkg) {
2899
2936
  const installedPackageJson = getInstalledPackageJson(pkg, { packageName: getPackageName(pkg) })?.packageJson;
2900
2937
  if (installedPackageJson) return installedPackageJson;
2901
2938
  try {
@@ -2904,7 +2941,16 @@ function getSharedDependencyGraphPackageJson(pkg) {
2904
2941
  } catch {}
2905
2942
  return getWorkspacePackageJson(pkg);
2906
2943
  }
2944
+ const sharedSingletonConsumedByPeerCache = /* @__PURE__ */ new WeakMap();
2907
2945
  function isSharedSingletonConsumedByPeer(pkg, options = getNormalizeModuleFederationOptions(), requireFederationRuntimeDependency = false) {
2946
+ if (!options) return computeSharedSingletonConsumedByPeer(pkg, options, requireFederationRuntimeDependency);
2947
+ let cache = sharedSingletonConsumedByPeerCache.get(options);
2948
+ if (!cache) sharedSingletonConsumedByPeerCache.set(options, cache = /* @__PURE__ */ new Map());
2949
+ const cacheKey = `${getPackageDetectionCwd()}\0${pkg}\0${requireFederationRuntimeDependency}`;
2950
+ if (!cache.has(cacheKey)) cache.set(cacheKey, computeSharedSingletonConsumedByPeer(pkg, options, requireFederationRuntimeDependency));
2951
+ return cache.get(cacheKey);
2952
+ }
2953
+ function computeSharedSingletonConsumedByPeer(pkg, options, requireFederationRuntimeDependency) {
2908
2954
  const shared = options?.shared || {};
2909
2955
  if (!requireFederationRuntimeDependency && Object.entries(shared).some(([key, item]) => key !== pkg && key.startsWith(`${pkg}/`) && item.shareConfig.singleton === true)) return true;
2910
2956
  const sharedKeyByPackageName = /* @__PURE__ */ new Map();
@@ -3356,6 +3402,7 @@ function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource
3356
3402
  const trackPendingLoad = `__mfTrackPendingShareLoad(${deferredEntryFallback ? deferredEntryLoad : deferredInitLoad});`;
3357
3403
  return `${declarations}
3358
3404
  const __mfApplyLazyShareExports = (mod) => {
3405
+ exportModule = mod;
3359
3406
  ${assignments}
3360
3407
  };
3361
3408
  __mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplyLazyShareExports);
@@ -3369,7 +3416,7 @@ function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource
3369
3416
  } else {
3370
3417
  __mfApplyLazyShareExports(exportModule);
3371
3418
  }
3372
- export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
3419
+ export { __mf_default as default, exportModule as __moduleExports };${namedExportLine}${mutableExportLine}`;
3373
3420
  }
3374
3421
  const WORKSPACE_SINGLETON_SSR_LOCAL_SHARE = "__mfNormalizeShareModule(__mfLocalShare)";
3375
3422
  function prependWorkspaceSingletonSsrImport(code) {
@@ -3769,7 +3816,24 @@ function generateLocalSharedImportMap(options) {
3769
3816
  // A host seed from an older React family is not coherent with the newer cached react
3770
3817
  const cachedVersion = cached?.version ?? cached?.default?.version;
3771
3818
  if (cachedVersion !== undefined && isOlder(cachedVersion)) continue;
3772
- if (!requiredExport || typeof cached?.[requiredExport] === 'function' || typeof cached?.default?.[requiredExport] === 'function') return cached;
3819
+ if (!requiredExport || typeof cached?.[requiredExport] === 'function' || typeof cached?.default?.[requiredExport] === 'function') {
3820
+ const dom = typeof cached?.[requiredExport] === 'function' ? cached : cached?.default;
3821
+ const internals = dom?.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
3822
+ if (!requiredExport || key.endsWith('/client') || !internals) return cached;
3823
+ // React 18 root: mirror react-dom/client.js, or createRoot warns it was imported from "react-dom"
3824
+ const client = {};
3825
+ for (const name of ['createRoot', 'hydrateRoot']) {
3826
+ client[name] = (...args) => {
3827
+ internals.usingClientEntryPoint = true;
3828
+ try {
3829
+ return dom[name](...args);
3830
+ } finally {
3831
+ internals.usingClientEntryPoint = false;
3832
+ }
3833
+ };
3834
+ }
3835
+ return { ...client, default: client };
3836
+ }
3773
3837
  }
3774
3838
  return undefined;
3775
3839
  };
@@ -3807,7 +3871,7 @@ function generateLocalSharedImportMap(options) {
3807
3871
  return pkg;`}
3808
3872
  }
3809
3873
  `;
3810
- }).join(",")}
3874
+ }).filter(Boolean).join(",")}
3811
3875
  }
3812
3876
  const usedShared = {
3813
3877
  ${orderedShares.map((key) => {
@@ -3992,7 +4056,8 @@ function getMaterializedShares(options) {
3992
4056
  const dependencies = {
3993
4057
  ...packageJson?.dependencies || {},
3994
4058
  ...packageJson?.peerDependencies || {},
3995
- ...packageJson?.optionalDependencies || {}
4059
+ ...packageJson?.optionalDependencies || {},
4060
+ ...packageJson?.peerDependenciesMeta || {}
3996
4061
  };
3997
4062
  for (const dependency of Object.keys(dependencies)) {
3998
4063
  const sharedDependency = configured.get(dependency);
@@ -4028,7 +4093,8 @@ function getSharePrerequisites(ordered) {
4028
4093
  const dependencies = {
4029
4094
  ...packageJson?.dependencies || {},
4030
4095
  ...packageJson?.peerDependencies || {},
4031
- ...packageJson?.optionalDependencies || {}
4096
+ ...packageJson?.optionalDependencies || {},
4097
+ ...packageJson?.peerDependenciesMeta || {}
4032
4098
  };
4033
4099
  const prerequisites = Object.keys(dependencies).map((dependency) => roots.get(dependency)).filter((dependency) => Boolean(dependency));
4034
4100
  if (pkg !== packageName && (packageName === "react" || packageName === "react-dom")) {
@@ -4072,7 +4138,8 @@ function orderSharedDependenciesFirst(sharedPackages) {
4072
4138
  const dependencies = {
4073
4139
  ...packageJson?.dependencies || {},
4074
4140
  ...packageJson?.peerDependencies || {},
4075
- ...packageJson?.optionalDependencies || {}
4141
+ ...packageJson?.optionalDependencies || {},
4142
+ ...packageJson?.peerDependenciesMeta || {}
4076
4143
  };
4077
4144
  Object.keys(dependencies).forEach((dependency) => {
4078
4145
  const sharedDependency = sharedKeyByPackageName.get(dependency);
@@ -4312,21 +4379,33 @@ const externalSharedProviderSelectionHelperCode = `const __mfSelectExternalShare
4312
4379
  /**
4313
4380
  * A consume-only stub never outranks a provider: when registering this container's
4314
4381
  * `import: false` share replaces an unloaded provider of the same version (#1311),
4315
- * the `afterRegisterShare` hook restores the provider. Registered once per instance.
4382
+ * the `afterRegisterShare` hook restores the provider, and a provider kept out by an
4383
+ * unloaded stub takes its slot. Registered once per instance.
4316
4384
  */
4317
4385
  function generateKeepProvidersOverStubsCode(runtimeVar) {
4318
4386
  return `if (!${runtimeVar}.__mfKeepAdoptedProviders) {
4319
4387
  ${runtimeVar}.__mfKeepAdoptedProviders = true;
4320
4388
  ${runtimeVar}.sharedHandler?.hooks?.lifecycle?.afterRegisterShare?.on?.((args) => {
4321
4389
  const { shared, previousShared, registeredShared } = args || {};
4390
+ const versions = ${runtimeVar}.shareScopeMap?.[args.scope]?.[args.pkgName];
4391
+ if (!shared || !versions) return;
4392
+ // The reverse: a stub already in the slot (e.g. a loaded-first parent's) keeps a provider
4393
+ // out, and a webpack consumer reading the scope then falls back to its own copy.
4394
+ if (shared.shareConfig?.import !== false) {
4395
+ if (
4396
+ registeredShared !== shared &&
4397
+ registeredShared?.shareConfig?.import === false &&
4398
+ !registeredShared.loaded &&
4399
+ versions[shared.version] === registeredShared
4400
+ ) versions[shared.version] = shared;
4401
+ return;
4402
+ }
4322
4403
  if (
4323
- shared?.shareConfig?.import !== false ||
4324
4404
  registeredShared !== shared ||
4325
4405
  !previousShared ||
4326
4406
  previousShared.shareConfig?.import === false
4327
4407
  ) return;
4328
- const versions = ${runtimeVar}.shareScopeMap?.[args.scope]?.[args.pkgName];
4329
- if (versions && versions[shared.version] === shared) versions[shared.version] = previousShared;
4408
+ if (versions[shared.version] === shared) versions[shared.version] = previousShared;
4330
4409
  });
4331
4410
  }`;
4332
4411
  }
@@ -4408,7 +4487,14 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy, options, command = "b
4408
4487
  );
4409
4488
  return;
4410
4489
  }
4411
- if (typeof isWebpackProvider === 'function' && isWebpackProvider(externalProvider)) return;
4490
+ // Leave an unloaded webpack provider to the late bridge, which only takes a
4491
+ // non-singleton of this share's own version; any other version seeds locally.
4492
+ if (
4493
+ typeof isWebpackProvider === 'function' &&
4494
+ isWebpackProvider(externalProvider) &&
4495
+ (share.shareConfig?.singleton ||
4496
+ __mfFindSharedProviderEntry(initialShared[pkg], externalProvider)?.version === share.version)
4497
+ ) return;
4412
4498
  }
4413
4499
  const providerKey = cacheDescriptor.canonical;
4414
4500
  const resolved = await __mfInitializeProviderOnce(providerKey, async () => {
@@ -4503,7 +4589,7 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy, options, command = "b
4503
4589
  var __mfDeferredSeedKeys = __mfSeedKeys.filter(
4504
4590
  (pkg) => __mfPreInitBlockedSeedKeys.has(__mfSeedIndex.get(pkg))
4505
4591
  );
4506
- await __mfSeedLocalShared(__mfImmediateSeedKeys);`;
4592
+ await __mfSeedLocalShared(__mfImmediateSeedKeys).catch(__mfRejectInit);`;
4507
4593
  }
4508
4594
  function getBrowserImportPath(importPath) {
4509
4595
  if (/^(?:[a-zA-Z]:[\\/]|\/)/.test(importPath) && !importPath.startsWith("/@")) return `/@fs/${importPath}`;
@@ -4754,7 +4840,12 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
4754
4840
  ${runtimeHelperImports.length ? `import {${runtimeHelperImports.join(", ")}} from "@module-federation/runtime/helpers";` : ""}
4755
4841
  ${pluginImportNames.filter((item) => !isSsrOnlyPlugin(item[1])).map((item) => item[1]).join("\n")}
4756
4842
  import __mfExposesMap from "${virtualExposesId}"
4757
- ${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options), void 0, void 0, exportConditions) + "\n const { initResolve } = globalThis[globalKey];"}
4843
+ ${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) + "\n const { initReject } = __mfResolveState;" : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options), void 0, void 0, exportConditions) + "\n const { initResolve, initReject } = globalThis[globalKey];"}
4844
+ // A failed seed must settle initPromise, or every pending share load hangs forever.
4845
+ const __mfRejectInit = (err) => {
4846
+ initReject(err);
4847
+ throw err;
4848
+ };
4758
4849
  ${getRuntimeModuleCacheBootstrapCode(exportConditions)}
4759
4850
  const initTokens = {}
4760
4851
  const shareScopeNames = Array.isArray(${toSafeJsLiteral(options.shareScope)}) ? ${toSafeJsLiteral(options.shareScope)} : [${toSafeJsLiteral(options.shareScope)}]
@@ -5648,7 +5739,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
5648
5739
  __mfReadyDeferredSeedKeys.push(...__mfDeferredSeedKeys.filter(
5649
5740
  (pkg) => !__mfBlockedSeedKeys.has(__mfSeedIndex.get(pkg))
5650
5741
  ));
5651
- await __mfSeedLocalShared(__mfReadyDeferredSeedKeys);
5742
+ await __mfSeedLocalShared(__mfReadyDeferredSeedKeys).catch(__mfRejectInit);
5652
5743
  ${command === "build" ? `// A consume-only share reached only through import() is bridged when that import runs
5653
5744
  // (see pluginLazyConsumeOnlyShares), through the same provider selection init() uses.
5654
5745
  const __mfLazyShareLoads = new Map();
@@ -5784,7 +5875,8 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
5784
5875
  const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
5785
5876
  if (
5786
5877
  __mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined &&
5787
- ${_command === "serve" ? `__mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) !== undefined` : `(
5878
+ ${_command === "serve" ? `__mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) !== undefined &&
5879
+ !(share.shareConfig?.singleton && __mfHasAlternativeSharedVersion(pkg, share))` : `(
5788
5880
  (!share.shareConfig?.singleton && __mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) === ${cacheOwner}) ||
5789
5881
  (share.shareConfig?.singleton && !__mfHasAlternativeSharedVersion(pkg, share))
5790
5882
  )`}
@@ -6496,6 +6588,27 @@ function patchHashEntryFileNames(config, entryName, fileName) {
6496
6588
  patchBundlerOutput(config.build.rolldownOptions);
6497
6589
  Object.values(config.environments ?? {}).forEach((environment) => patchHashEntryFileNames(environment, entryName, fileName));
6498
6590
  }
6591
+ const ROLLDOWN_RUNTIME_GLOBAL = "__rolldown_runtime__";
6592
+ /**
6593
+ * Rolldown's dev runtime lives on `globalThis.__rolldown_runtime__`, and its
6594
+ * module registry is keyed by cwd-relative ids (`src/App.jsx`). A bundledDev
6595
+ * remote loaded into a bundledDev host would share the host's runtime, so the
6596
+ * remote's modules, hot contexts and HMR factories would collide with the
6597
+ * host's. Give each remote its own same-length global (sourcemaps stay valid)
6598
+ * in every chunk and HMR patch it serves.
6599
+ */
6600
+ function renameBundledDevRuntime(req, res, remoteName) {
6601
+ if (!req.url || !stripQueryAndHash(req.url).endsWith(".js")) return;
6602
+ const runtimeGlobal = `__mf_rt_${createHash("sha256").update(remoteName).digest("hex").slice(0, 10)}__`;
6603
+ const end = res.end;
6604
+ res.end = function(chunk, ...args) {
6605
+ if (typeof chunk === "string" || chunk instanceof Uint8Array) {
6606
+ const code = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
6607
+ if (code.includes(ROLLDOWN_RUNTIME_GLOBAL)) chunk = code.replace(/\b__rolldown_runtime__\b/g, runtimeGlobal);
6608
+ }
6609
+ return end.call(this, chunk, ...args);
6610
+ };
6611
+ }
6499
6612
  const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClientInjected, skipTransformFor = [], federationOptions }) => {
6500
6613
  const DEV_HTML_PROXY_PREFIX = "virtual:mf-html-entry-proxy?";
6501
6614
  const ENTRY_BOOTSTRAP_PARAM = "mf-entry-bootstrap";
@@ -6518,6 +6631,9 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
6518
6631
  const virtualEntryCode = /* @__PURE__ */ new Map();
6519
6632
  const ignoredHtmlScriptSources = /* @__PURE__ */ new Set();
6520
6633
  let bootstrapDir = "";
6634
+ let isBundledDevRemote = false;
6635
+ let bundledDevRemoteEntryCode;
6636
+ let resolveBundledDevRemoteEntryCode;
6521
6637
  function skipSvelteKitSsrBuild() {
6522
6638
  return (_command === "build" || viteConfig?.command === "build") && viteConfig?.build?.ssr && hasPackageDependency("@sveltejs/kit");
6523
6639
  }
@@ -6616,7 +6732,7 @@ const __mfCurrentScript = document.currentScript;
6616
6732
  : import(src);
6617
6733
  ` : "";
6618
6734
  const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
6619
- const isEncodedVirtualEntry = entrySrc.startsWith(VITE_ENCODED_NULL_BYTE_PREFIX);
6735
+ const isEncodedVirtualEntry = !options?.isBundled && entrySrc.startsWith(VITE_ENCODED_NULL_BYTE_PREFIX);
6620
6736
  const entryImportDeclaration = isEncodedVirtualEntry ? `const __mfEntryUrl = ${JSON.stringify(entrySrc)};
6621
6737
  ` : "";
6622
6738
  const entryImportExpression = isEncodedVirtualEntry ? "import(/* @vite-ignore */ __mfEntryUrl)" : importExpression(entrySrc);
@@ -6638,10 +6754,11 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6638
6754
  const shareItem = getNormalizeShareItem(pkg, federationOptions);
6639
6755
  const isExplicitShare = Object.hasOwn(federationOptions.shared, pkg);
6640
6756
  return shareItem?.shareConfig?.singleton === true && shareItem?.shareConfig?.import !== false && !shareItem?.shareConfig?.treeShaking && (isExplicitShare || typeof shareItem?.shareConfig?.import === "string" || Boolean(getProjectResolvedImportPath(pkg)));
6641
- }).map((pkg) => toViteEncodedId(getLoadShareModulePath(pkg, false, federationOptions))) : [];
6642
- const sharedPreloadBlock = sharedPreloadSources.length > 0 ? `
6643
- const __mfSharedPreloadUrls = ${JSON.stringify(sharedPreloadSources)};
6644
- await Promise.all(__mfSharedPreloadUrls.map((src) => import(/* @vite-ignore */ src).catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));` : "";
6757
+ }).map((pkg) => getLoadShareModulePath(pkg, false, federationOptions)) : [];
6758
+ const sharedPreloadBlock = sharedPreloadSources.length === 0 ? "" : options?.isBundled ? `
6759
+ await Promise.all([${sharedPreloadSources.map((src) => `[${JSON.stringify(src)}, import(${JSON.stringify(src)})]`).join(", ")}].map(([src, load]) => load.catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));` : `
6760
+ const __mfSharedPreloadUrls = ${JSON.stringify(sharedPreloadSources.map(toViteEncodedId))};
6761
+ await Promise.all(__mfSharedPreloadUrls.map((src) => import(/* @vite-ignore */ src).catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));`;
6645
6762
  const remoteCachePrefix = getRuntimeRemoteCachePrefix(federationOptions);
6646
6763
  const preloadBlock = remotePreloads ? `
6647
6764
  const runtime = await initHost();
@@ -6768,19 +6885,6 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6768
6885
  apply: "serve",
6769
6886
  config(_config, { command }) {
6770
6887
  _command = command;
6771
- const isRemoteEntry = entryName === "remoteEntry" && federationOptions !== void 0 && isRemoteContainer(federationOptions);
6772
- if (command === "serve" && _config.experimental?.bundledDev && isRemoteEntry) {
6773
- _config.experimental = {
6774
- ..._config.experimental,
6775
- bundledDev: false
6776
- };
6777
- _config.environments ??= {};
6778
- _config.environments.client ??= {};
6779
- if (_config.environments.client.isBundled !== false) {
6780
- _config.environments.client.isBundled = false;
6781
- mfWarn("Vite bundledDev is disabled for the client environment of a Module Federation remote container so its remoteEntry keeps the standard init/get contract.");
6782
- }
6783
- }
6784
6888
  },
6785
6889
  configResolved(config) {
6786
6890
  viteConfig = config;
@@ -6793,6 +6897,10 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6793
6897
  devEntryPath = config.base + relativePath.replace(/^\//, "");
6794
6898
  }
6795
6899
  skipTransformIds = new Set(skipTransformFor.map(resolveProjectId));
6900
+ isBundledDevRemote = config.command === "serve" && entryName === "remoteEntry" && federationOptions !== void 0 && isRemoteContainer(federationOptions) && (config.environments?.client)?.isBundled === true;
6901
+ if (isBundledDevRemote) bundledDevRemoteEntryCode = new Promise((resolve) => {
6902
+ resolveBundledDevRemoteEntryCode = resolve;
6903
+ });
6796
6904
  },
6797
6905
  configureServer(server) {
6798
6906
  devServer = server;
@@ -6820,7 +6928,18 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6820
6928
  }
6821
6929
  const devFileName = resolveHashPlaceholderFileName(fileName);
6822
6930
  if (devFileName !== fileName && req.url?.startsWith((viteConfig.base + devFileName).replace(/^\/?/, "/"))) req.url = req.url.replace(devFileName, fileName);
6931
+ if (isBundledDevRemote) renameBundledDevRuntime(req, res, federationOptions.name);
6823
6932
  if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, "/"))) {
6933
+ if (isBundledDevRemote) {
6934
+ const bundledDev = (server.environments?.client)?.bundledDev;
6935
+ Promise.all([bundledDevRemoteEntryCode, bundledDev?.waitForInitialBuildFinish?.()]).then(([code]) => {
6936
+ if (code === void 0) return next();
6937
+ res.setHeader("Content-Type", "text/javascript");
6938
+ res.setHeader("Cache-Control", "no-cache");
6939
+ res.end(code);
6940
+ }, next);
6941
+ return;
6942
+ }
6824
6943
  req.url = devEntryPath;
6825
6944
  req.headers["sec-fetch-dest"] = "script";
6826
6945
  }
@@ -6858,7 +6977,7 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6858
6977
  const initSrc = params.get("init");
6859
6978
  const entrySrc = params.get("entry");
6860
6979
  if (!initSrc || !entrySrc) return;
6861
- const source = getBootstrapSource(initSrc, entrySrc);
6980
+ const source = getBootstrapSource(initSrc, entrySrc, false, { isBundled: this.environment?.config?.isBundled === true });
6862
6981
  return warmupDevEntryGraph(entrySrc).then(() => source);
6863
6982
  },
6864
6983
  transform(code, id) {
@@ -6901,6 +7020,24 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6901
7020
  }
6902
7021
  if (htmlFilePath) addHtmlScriptEntries(htmlFilePath);
6903
7022
  },
7023
+ options(inputOptions) {
7024
+ if (!isBundledDevRemote || !isClientEnvironment(this)) return;
7025
+ const input = inputOptions.input;
7026
+ if (typeof input === "object" && input !== null && !Array.isArray(input)) return {
7027
+ ...inputOptions,
7028
+ input: {
7029
+ ...input,
7030
+ [entryName]: getEntryPath()
7031
+ }
7032
+ };
7033
+ return {
7034
+ ...inputOptions,
7035
+ input: [...input === void 0 ? [] : [input].flat(), getEntryPath()]
7036
+ };
7037
+ },
7038
+ buildEnd(error) {
7039
+ if (error && isBundledDevRemote) resolveBundledDevRemoteEntryCode?.(void 0);
7040
+ },
6904
7041
  async buildStart() {
6905
7042
  if (inject === "entry" && waitsForInit && isClientEnvironment(this)) for (const entry of [...entryFiles]) {
6906
7043
  if (path$1.isAbsolute(entry)) continue;
@@ -6928,6 +7065,15 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6928
7065
  if (htmlFilePath) addHtmlScriptEntries(htmlFilePath);
6929
7066
  },
6930
7067
  generateBundle(_options, bundle) {
7068
+ if (isBundledDevRemote && _command === "serve") {
7069
+ const remoteEntryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry && output.facadeModuleId === getEntryPath());
7070
+ if (remoteEntryChunk?.type === "chunk") {
7071
+ const code = `export { ${remoteEntryChunk.exports.join(", ")} } from ${JSON.stringify(`./${remoteEntryChunk.fileName}`)};\n`;
7072
+ bundledDevRemoteEntryCode = Promise.resolve(code);
7073
+ resolveBundledDevRemoteEntryCode?.(code);
7074
+ }
7075
+ return;
7076
+ }
6931
7077
  if (skipSvelteKitSsrBuild()) return;
6932
7078
  if (entryName === "remoteEntry" && emitFileId && fileName && !viteConfig?.build?.ssr && _options?.format === "es" && viteConfig?.build?.modulePreload !== false) {
6933
7079
  const remoteEntryFile = findRemoteEntryFile(fileName, bundle);
@@ -7062,7 +7208,10 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
7062
7208
  virtualEntryCode.set(entrySrc, code);
7063
7209
  entrySrc = toViteEncodedId(entrySrc.slice(1));
7064
7210
  }
7065
- return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, { skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule }));
7211
+ return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, {
7212
+ skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule,
7213
+ isBundled: _command === "serve" && this.environment?.config?.isBundled === true
7214
+ }));
7066
7215
  }
7067
7216
  }
7068
7217
  }];
@@ -7124,6 +7273,16 @@ function checkAliasConflicts(options) {
7124
7273
  const REACT_REFRESH_PATH = "/@react-refresh";
7125
7274
  const LOCAL_REACT_REFRESH_PATH = "/@mf-react-refresh-local";
7126
7275
  const HOST_REACT_REFRESH_URL = "__MF_REACT_REFRESH_URL__";
7276
+ const HOST_REACT_REFRESH_RUNTIME = "__MF_REACT_REFRESH_RUNTIME__";
7277
+ const LOCAL_REACT_REFRESH_ID = "virtual:mf-react-refresh-local";
7278
+ const REACT_REFRESH_EXPORTS = [
7279
+ "injectIntoGlobalHook",
7280
+ "register",
7281
+ "getRefreshReg",
7282
+ "createSignatureFunctionForTransform",
7283
+ "registerExportsForReactRefresh",
7284
+ "validateRefreshBoundaryAndEnqueueUpdate"
7285
+ ];
7127
7286
  function stripQuery(url) {
7128
7287
  return url?.replace(/\?.*$/, "");
7129
7288
  }
@@ -7149,8 +7308,9 @@ function resolveReactRefreshRuntime(root) {
7149
7308
  */
7150
7309
  const REACT_REFRESH_PROXY_MODULE = [
7151
7310
  `const __remoteUrl = new URL(import.meta.url);`,
7152
- `const __target = window.location.origin === __remoteUrl.origin ? new URL('.${LOCAL_REACT_REFRESH_PATH}', __remoteUrl).href : globalThis.${HOST_REACT_REFRESH_URL} || window.location.origin + '${REACT_REFRESH_PATH}';`,
7153
- `const __rt = await import(__target);`,
7311
+ `const __isHost = window.location.origin !== __remoteUrl.origin;`,
7312
+ `const __target = __isHost ? globalThis.${HOST_REACT_REFRESH_URL} || window.location.origin + '${REACT_REFRESH_PATH}' : new URL('.${LOCAL_REACT_REFRESH_PATH}', __remoteUrl).href;`,
7313
+ `const __rt = (__isHost && globalThis.${HOST_REACT_REFRESH_RUNTIME}) || await import(__target);`,
7154
7314
  `export const injectIntoGlobalHook = __rt.injectIntoGlobalHook;`,
7155
7315
  `export const register = __rt.register;`,
7156
7316
  `export const getRefreshReg = __rt.getRefreshReg;`,
@@ -7160,34 +7320,64 @@ const REACT_REFRESH_PROXY_MODULE = [
7160
7320
  `export const __hmr_import = __rt.__hmr_import;`,
7161
7321
  `export default __rt.default || __rt;`
7162
7322
  ].join("\n");
7323
+ /**
7324
+ * `/@react-refresh` for a bundledDev remote. The bundle cannot fetch the
7325
+ * host's runtime by URL, so it binds lazily to the runtime the host page
7326
+ * publishes on a global and falls back to its own copy when opened directly.
7327
+ * Both share one component registry with the host's React.
7328
+ */
7329
+ const BUNDLED_REACT_REFRESH_MODULE = [
7330
+ `import * as __local from '${LOCAL_REACT_REFRESH_ID}';`,
7331
+ `const __rt = () => globalThis.${HOST_REACT_REFRESH_RUNTIME} || __local;`,
7332
+ ...REACT_REFRESH_EXPORTS.map((name) => `export function ${name}(...args) { return __rt().${name}(...args); }`),
7333
+ `export const __hmr_import = __local.__hmr_import;`,
7334
+ `export const __mfLocalRuntime = __local;`,
7335
+ `export default { injectIntoGlobalHook };`
7336
+ ].join("\n");
7163
7337
  const reactAdapter = {
7164
7338
  name: "react",
7165
7339
  pluginNames: ["vite:react-refresh", "vite:react-swc"],
7166
7340
  host: { transformIndexHtml({ server }) {
7167
7341
  const refreshPath = `${server.config.base.replace(/\/$/, "")}${REACT_REFRESH_PATH}`;
7342
+ const isBundled = server.config.experimental?.bundledDev === true;
7168
7343
  return [{
7169
7344
  tag: "script",
7170
7345
  children: `globalThis.${HOST_REACT_REFRESH_URL} = new URL(${JSON.stringify(refreshPath)}, window.location.origin).href;`,
7171
7346
  injectTo: "head-prepend"
7347
+ }, {
7348
+ tag: "script",
7349
+ attrs: { type: "module" },
7350
+ children: `import * as rt from ${JSON.stringify(isBundled ? REACT_REFRESH_PATH : refreshPath)};\nglobalThis.${HOST_REACT_REFRESH_RUNTIME} ??= rt.__mfLocalRuntime || rt;`,
7351
+ injectTo: "head-prepend"
7172
7352
  }];
7173
7353
  } },
7174
- remote: { configureServer({ server }) {
7175
- let reactRefreshRuntime;
7176
- server.middlewares.use((req, res, next) => {
7177
- const url = stripQuery(req.url);
7178
- if (url?.endsWith(LOCAL_REACT_REFRESH_PATH)) {
7179
- reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
7354
+ remote: {
7355
+ configureServer({ server }) {
7356
+ let reactRefreshRuntime;
7357
+ server.middlewares.use((req, res, next) => {
7358
+ const url = stripQuery(req.url);
7359
+ if (url?.endsWith(LOCAL_REACT_REFRESH_PATH)) {
7360
+ reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
7361
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
7362
+ res.setHeader("Access-Control-Allow-Origin", "*");
7363
+ res.end(reactRefreshRuntime);
7364
+ return;
7365
+ }
7366
+ if (!url?.endsWith(REACT_REFRESH_PATH)) return next();
7180
7367
  res.setHeader("Content-Type", "application/javascript; charset=utf-8");
7181
7368
  res.setHeader("Access-Control-Allow-Origin", "*");
7182
- res.end(reactRefreshRuntime);
7183
- return;
7184
- }
7185
- if (!url?.endsWith(REACT_REFRESH_PATH)) return next();
7186
- res.setHeader("Content-Type", "application/javascript; charset=utf-8");
7187
- res.setHeader("Access-Control-Allow-Origin", "*");
7188
- res.end(REACT_REFRESH_PROXY_MODULE);
7189
- });
7190
- } }
7369
+ res.end(REACT_REFRESH_PROXY_MODULE);
7370
+ });
7371
+ },
7372
+ resolveId(id) {
7373
+ if (id === LOCAL_REACT_REFRESH_ID) return `\0${LOCAL_REACT_REFRESH_ID}`;
7374
+ },
7375
+ load(id, { root, isBundled }) {
7376
+ if (!isBundled) return;
7377
+ if (id === REACT_REFRESH_PATH) return BUNDLED_REACT_REFRESH_MODULE;
7378
+ if (id === `\0${LOCAL_REACT_REFRESH_ID}`) return resolveReactRefreshRuntime(root);
7379
+ }
7380
+ }
7191
7381
  };
7192
7382
  //#endregion
7193
7383
  //#region src/plugins/hmr/vue.ts
@@ -7574,14 +7764,18 @@ function pluginDevRemoteHmr(options) {
7574
7764
  const isRemote = Object.keys(options.exposes).length > 0;
7575
7765
  let adapters = [];
7576
7766
  let strategy = "full-reload";
7767
+ let root;
7768
+ let devServer;
7577
7769
  return {
7578
7770
  name: "module-federation-dev-remote-hmr",
7579
7771
  apply: "serve",
7580
7772
  configResolved(config) {
7773
+ root = config.root;
7581
7774
  adapters = resolveAdapters(config.plugins);
7582
7775
  strategy = resolveHmrStrategy(options.dev, config.plugins);
7583
7776
  },
7584
7777
  configureServer(server) {
7778
+ devServer = server;
7585
7779
  if (!isRemoteHmrEnabled(options.dev)) return;
7586
7780
  if (isRemote) {
7587
7781
  for (const adapter of adapters) adapter.remote?.configureServer?.({
@@ -7599,6 +7793,27 @@ function pluginDevRemoteHmr(options) {
7599
7793
  if (strategy === "full-reload") setupHostFullReloadRelay(server, options);
7600
7794
  }
7601
7795
  },
7796
+ resolveId(id) {
7797
+ if (!isRemote || !isRemoteHmrEnabled(options.dev)) return;
7798
+ for (const adapter of adapters) {
7799
+ const resolved = adapter.remote?.resolveId?.(id);
7800
+ if (resolved) return resolved;
7801
+ }
7802
+ },
7803
+ load: {
7804
+ order: "pre",
7805
+ handler(id) {
7806
+ if (!isRemote || !isRemoteHmrEnabled(options.dev) || !root) return;
7807
+ const isBundled = this.environment?.config?.isBundled === true;
7808
+ for (const adapter of adapters) {
7809
+ const code = adapter.remote?.load?.(id, {
7810
+ root,
7811
+ isBundled
7812
+ });
7813
+ if (code !== void 0) return code;
7814
+ }
7815
+ }
7816
+ },
7602
7817
  transform: {
7603
7818
  order: "post",
7604
7819
  handler(code, id) {
@@ -7617,8 +7832,9 @@ function pluginDevRemoteHmr(options) {
7617
7832
  order: "pre",
7618
7833
  handler(_html, ctx) {
7619
7834
  if (!isRemoteHmrEnabled(options.dev)) return;
7620
- if (!isHost || !ctx.server) return;
7621
- return collectHostTags(ctx.server, options, adapters);
7835
+ const server = ctx.server ?? devServer;
7836
+ if (!isHost || !server) return;
7837
+ return collectHostTags(server, options, adapters);
7622
7838
  }
7623
7839
  }
7624
7840
  };
@@ -8134,7 +8350,7 @@ function ${helperName}(names) {
8134
8350
  }
8135
8351
  //#endregion
8136
8352
  //#region package.json
8137
- var version$1 = "1.23.3";
8353
+ var version$1 = "1.23.5";
8138
8354
  //#endregion
8139
8355
  //#region src/virtualModules/virtualExposesSSR.ts
8140
8356
  /**
@@ -8856,43 +9072,89 @@ function getStatsFileName(manifestFileName) {
8856
9072
  //#endregion
8857
9073
  //#region src/utils/sharedSource.ts
8858
9074
  const pendingEntryLookups = /* @__PURE__ */ new Map();
9075
+ const pendingLookupImporters = /* @__PURE__ */ new Map();
9076
+ const increment = (map, key) => map.set(key, (map.get(key) ?? 0) + 1);
9077
+ const decrement = (map, key) => {
9078
+ const remaining = map.get(key) - 1;
9079
+ if (remaining) map.set(key, remaining);
9080
+ else map.delete(key);
9081
+ };
8859
9082
  const getEntryLookupKey = (source, importer) => `${source}\0${importer}`;
9083
+ /**
9084
+ * Rolldown saves each this.resolve() call's options under the map's current size and deletes the
9085
+ * entry when the call settles, so an overlapping call can receive the wrong `custom` metadata.
9086
+ * Taking the first free key keeps every in-flight entry intact. A no-op when the internals differ.
9087
+ */
9088
+ function patchRolldownResolveOptionKeys(context) {
9089
+ const data = context?.data;
9090
+ const map = data?.resolveOptionsMap;
9091
+ if (!data || !(map instanceof Map) || typeof data.saveResolveOptions !== "function") return;
9092
+ if (data.__mfFreeKeyPatch) return;
9093
+ data.saveResolveOptions = (options) => {
9094
+ let index = map.size;
9095
+ while (map.has(index)) index++;
9096
+ map.set(index, options);
9097
+ return index;
9098
+ };
9099
+ data.__mfFreeKeyPatch = true;
9100
+ }
8860
9101
  /** Whether a resolveId call is one of the shared source resolver's own entry lookups. */
8861
9102
  function isSharedEntryLookup(source, importer, options) {
8862
- return options.custom?.__mfSharedEntryLookup === true || pendingEntryLookups.has(getEntryLookupKey(source, importer));
9103
+ if (pendingEntryLookups.has(getEntryLookupKey(source, importer))) return true;
9104
+ return options?.custom?.__mfSharedEntryLookupImporter === importer && pendingLookupImporters.has(importer);
8863
9105
  }
8864
9106
  /**
8865
9107
  * Runs one of the plugin's own `this.resolve()` calls (a shared entry lookup, a
8866
- * parse-barrier external probe), marked so `isSharedEntryLookup` recognizes it
9108
+ * parse-barrier external probe), tracked so `isSharedEntryLookup` recognizes it
8867
9109
  * and the share hooks neither proxy it nor register a used share for it.
8868
9110
  */
8869
9111
  async function resolveInternally(context, source, importer, options = {}) {
8870
9112
  const lookupKey = getEntryLookupKey(source, importer);
8871
- pendingEntryLookups.set(lookupKey, (pendingEntryLookups.get(lookupKey) ?? 0) + 1);
9113
+ increment(pendingEntryLookups, lookupKey);
9114
+ increment(pendingLookupImporters, importer);
8872
9115
  try {
8873
9116
  return await context.resolve(source, importer, {
8874
9117
  ...options,
8875
- skipSelf: true,
8876
9118
  custom: {
8877
9119
  ...options.custom,
8878
- __mfSharedEntryLookup: true
8879
- }
9120
+ __mfSharedEntryLookupImporter: importer
9121
+ },
9122
+ skipSelf: true
8880
9123
  });
8881
9124
  } finally {
8882
- const remaining = pendingEntryLookups.get(lookupKey) - 1;
8883
- if (remaining) pendingEntryLookups.set(lookupKey, remaining);
8884
- else pendingEntryLookups.delete(lookupKey);
9125
+ decrement(pendingEntryLookups, lookupKey);
9126
+ decrement(pendingLookupImporters, importer);
8885
9127
  }
8886
9128
  }
8887
9129
  /** Identify shared entries through Vite, with a cache scoped to this federation instance. */
8888
9130
  function createSharedSourceResolver(shared, getResolutionConfig) {
8889
9131
  const caches = /* @__PURE__ */ new Map();
8890
- async function matchEntry(source, suffix, resolveEntry) {
9132
+ const wildcardSubpathCaches = /* @__PURE__ */ new Map();
9133
+ async function resolveEntry(context, request, options, { root, conditions }) {
9134
+ if (!path$1.isAbsolute(request) && !isPackageExportAvailable(request, {
9135
+ cwd: root,
9136
+ conditions
9137
+ })) return void 0;
9138
+ const importer = path$1.join(root, "package.json");
9139
+ try {
9140
+ const resolved = await resolveInternally(context, request, importer, options);
9141
+ return resolved && !resolved.external ? resolved.id : void 0;
9142
+ } catch {
9143
+ return;
9144
+ }
9145
+ }
9146
+ async function matchEntry(source, suffix, entryOptions, resolveEntry) {
8891
9147
  const packageName = getPackageNameFromNodeModulePath(source);
8892
9148
  if (!packageName) return;
8893
9149
  const candidates = /* @__PURE__ */ new Set();
8894
9150
  if (findSharedKey(packageName, shared)) candidates.add(packageName);
8895
- if (findSharedKey(suffix, shared)) candidates.add(suffix);
9151
+ const packageSubpath = suffix.slice(packageName.length + 1);
9152
+ if (packageSubpath) {
9153
+ for (const specifier of getPackageExportSpecifiersForFile(packageName, packageSubpath, {
9154
+ ...entryOptions,
9155
+ fromResolvedEntry: source
9156
+ })) if (findSharedKey(specifier, shared)) candidates.add(specifier);
9157
+ }
8896
9158
  for (const key of Object.keys(shared)) {
8897
9159
  const request = getSharedRequest(key, shared[key]);
8898
9160
  if (getPackageName(request) !== packageName) continue;
@@ -8912,6 +9174,7 @@ function createSharedSourceResolver(shared, getResolutionConfig) {
8912
9174
  return {
8913
9175
  clear() {
8914
9176
  caches.clear();
9177
+ wildcardSubpathCaches.clear();
8915
9178
  },
8916
9179
  async resolve(context, source, options = {}) {
8917
9180
  if (source.startsWith("\0") || source.includes("#")) return;
@@ -8922,32 +9185,39 @@ function createSharedSourceResolver(shared, getResolutionConfig) {
8922
9185
  "t",
8923
9186
  "import"
8924
9187
  ].includes(key))) return;
8925
- if (findSharedKey(source, shared)) return source;
8926
- const suffix = getNodeModulesSuffix(source);
8927
- if (!suffix) return;
8928
- const normalizedSource = stripViteFsPrefix(normalizeNodeModulePath(source));
8929
9188
  const environment = context.environment ?? !!options.ssr;
8930
9189
  const cacheable = !options.isEntry && !options.scan && (!options.kind || options.kind === "import-statement") && Object.keys(options.attributes ?? {}).length === 0 && Object.keys(options.custom ?? {}).length === 0;
8931
- let cache = cacheable ? caches.get(environment) : void 0;
8932
- if (cacheable && !cache) {
8933
- cache = /* @__PURE__ */ new Map();
8934
- caches.set(environment, cache);
9190
+ const getCache = (byEnvironment) => {
9191
+ if (!cacheable) return;
9192
+ let cache = byEnvironment.get(environment);
9193
+ if (!cache) {
9194
+ cache = /* @__PURE__ */ new Map();
9195
+ byEnvironment.set(environment, cache);
9196
+ }
9197
+ return cache;
9198
+ };
9199
+ const directKey = findSharedKey(source, shared);
9200
+ if (directKey) {
9201
+ const request = getSharedRequest(directKey, shared[directKey]);
9202
+ if (!(request.endsWith("/") && source !== removeTrailingSlash(request) && !getCommonSharedSubpaths(request).includes(source))) return source;
9203
+ const cache = getCache(wildcardSubpathCaches);
9204
+ let resolvable = cache?.get(source);
9205
+ if (resolvable === void 0) {
9206
+ resolvable = await resolveEntry(context, source, options, getResolutionConfig(context, options)) !== void 0;
9207
+ cache?.set(source, resolvable);
9208
+ }
9209
+ return resolvable ? source : void 0;
8935
9210
  }
9211
+ const suffix = getNodeModulesSuffix(source);
9212
+ if (!suffix) return;
9213
+ const normalizedSource = stripViteFsPrefix(normalizeNodeModulePath(source));
9214
+ const cache = getCache(caches);
8936
9215
  if (cache?.has(normalizedSource)) return cache.get(normalizedSource);
8937
- const { root, conditions } = getResolutionConfig(context, options);
8938
- const result = await matchEntry(normalizedSource, suffix, async (request) => {
8939
- if (!path$1.isAbsolute(request) && !isPackageExportAvailable(request, {
8940
- cwd: root,
8941
- conditions
8942
- })) return void 0;
8943
- const importer = path$1.join(root, "package.json");
8944
- try {
8945
- const resolved = await resolveInternally(context, request, importer, options);
8946
- return resolved && !resolved.external ? resolved.id : void 0;
8947
- } catch {
8948
- return;
8949
- }
8950
- });
9216
+ const config = getResolutionConfig(context, options);
9217
+ const result = await matchEntry(normalizedSource, suffix, {
9218
+ cwd: config.root,
9219
+ conditions: config.conditions
9220
+ }, (request) => resolveEntry(context, request, options, config));
8951
9221
  cache?.set(normalizedSource, result);
8952
9222
  return result;
8953
9223
  }
@@ -9063,8 +9333,7 @@ function pluginModuleParseEnd_default(excludeFn, options, controller = createMod
9063
9333
  },
9064
9334
  async buildStart() {
9065
9335
  resetParseState(controller);
9066
- if (idleTimeout) resetIdleTimeout(controller, idleTimeout);
9067
- else if (options.moduleParseTimeout) setParseTimeout(controller, options.moduleParseTimeout);
9336
+ if (!idleTimeout && options.moduleParseTimeout) setParseTimeout(controller, options.moduleParseTimeout);
9068
9337
  const entryImports = /* @__PURE__ */ new Set([...options.exposedModuleImports || [], ...configuredInputImports]);
9069
9338
  for (const importSource of entryImports) {
9070
9339
  const resolved = await this.resolve(importSource);
@@ -9947,6 +10216,7 @@ function proxySharedModule(options) {
9947
10216
  },
9948
10217
  buildStart() {
9949
10218
  sharedSourceResolver.clear();
10219
+ patchRolldownResolveOptionKeys(this);
9950
10220
  if (_command !== "build") return;
9951
10221
  if (hasAnalyzableShares) getBuildImportAnalysis(this.environment).clear();
9952
10222
  resetTreeShakingExports(federationOptions);
@@ -10347,8 +10617,15 @@ function pluginRemoteNamedExports(options) {
10347
10617
  if (id.includes("__loadRemote__") || id.includes("__loadShare__")) return;
10348
10618
  if (!JS_EXTENSIONS_RE.test(id)) return;
10349
10619
  if (!remoteNames.some((name) => code.includes(name))) return;
10350
- const matchesRemoteImport = (source) => isRemoteImport(source, id);
10351
- for (const { kind, source, typeOnly } of findModuleImportDescriptors(code)) if (kind === "static" && !typeOnly && matchesRemoteImport(source)) markStaticRemote(source, options);
10620
+ const descriptors = findModuleImportDescriptors(code);
10621
+ const resolvedElsewhere = /* @__PURE__ */ new Set();
10622
+ for (const source of new Set(descriptors.map((d) => d.source))) {
10623
+ if (source.includes("__loadRemote__") || !isRemoteImport(source, id)) continue;
10624
+ const resolved = await this.resolve(source, id);
10625
+ if (resolved && !resolved.id.includes("__loadRemote__")) resolvedElsewhere.add(source);
10626
+ }
10627
+ const matchesRemoteImport = (source) => !resolvedElsewhere.has(source) && isRemoteImport(source, id);
10628
+ for (const { kind, source, typeOnly } of descriptors) if (kind === "static" && !typeOnly && matchesRemoteImport(source)) markStaticRemote(source, options);
10352
10629
  let imports;
10353
10630
  try {
10354
10631
  imports = await collectFromAST(this.parse(code), code, matchesRemoteImport);
@@ -10806,6 +11083,7 @@ const VarRemoteEntry = (providedOptions) => {
10806
11083
  */
10807
11084
  async generateBundle(_options, bundle) {
10808
11085
  if (!varFilename) return;
11086
+ if (viteConfig?.command === "serve") return;
10809
11087
  if (!isValidVarName(name)) mfWarn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);
10810
11088
  const remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
10811
11089
  if (!remoteEntryFile) throw createModuleFederationError(`Couldn't find a remoteEntry chunk file for ${mfOptions.filename}, can't generate varRemoteEntry file`);
@@ -11429,6 +11707,15 @@ const PRELOAD_HELPER_CHUNK = "vite-preload-helper";
11429
11707
  const PRELOAD_HELPER_TEST = /\0?vite\/preload-helper/;
11430
11708
  const MF_GROUP_PRIORITY = 1e6;
11431
11709
  const USER_GROUP_MAX_PRIORITY = MF_GROUP_PRIORITY - 1;
11710
+ function getBundledDevHtmlPreambleChunk(id, ctx) {
11711
+ let importers;
11712
+ try {
11713
+ importers = ctx.getModuleInfo(id)?.importers;
11714
+ } catch {
11715
+ return null;
11716
+ }
11717
+ return importers?.some((importer) => importer.includes("?html-proxy")) ? "mf-html-preamble" : null;
11718
+ }
11432
11719
  function normalizeVinextRscPreloadHints(code) {
11433
11720
  return code.replace(/(:HL\[[^\]\n]*?,)"stylesheet"/g, "$1\"style\"").replace(/(:HL\[[^\]\n]*?,)\\"stylesheet\\"/g, "$1\\\"style\\\"");
11434
11721
  }
@@ -11990,7 +12277,7 @@ function withoutDynamicRemoteTypeHints(options) {
11990
12277
  }
11991
12278
  function loadPluginDts(options) {
11992
12279
  if (options.dts === false) return [];
11993
- return [import("./pluginDts-CVyHPAEq.js").then(({ default: pluginDts }) => pluginDts(options))];
12280
+ return [import("./pluginDts-DShMdjzR.js").then(({ default: pluginDts }) => pluginDts(options))];
11994
12281
  }
11995
12282
  const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
11996
12283
  function isInjectExternalRuntimeCorePlugin(specifier) {
@@ -12100,6 +12387,124 @@ function federation(mfUserOptions) {
12100
12387
  return getSharedExportUsage(pkg, shared[key], key, options);
12101
12388
  });
12102
12389
  };
12390
+ function applyFederationChunking(config, ctx, snapshotOutput) {
12391
+ const runtimeInitId = getRuntimeInitStatusImportId(options);
12392
+ config.build = config.build || {};
12393
+ let warnedAboutCodeSplitting = false;
12394
+ const ensureCodeSplitting = (output) => {
12395
+ if (output?.codeSplitting !== false) return;
12396
+ delete output.codeSplitting;
12397
+ if (warnedAboutCodeSplitting) return;
12398
+ warnedAboutCodeSplitting = true;
12399
+ mfWarn("Ignoring `output.codeSplitting = false` because module federation requires chunk splitting.");
12400
+ };
12401
+ const isFederationGroup = (group) => typeof group === "object" && group !== null && federationGroups.has(group);
12402
+ let warnedAboutGroupPriority = false;
12403
+ const clampUserGroup = (group) => {
12404
+ const candidate = group;
12405
+ if (typeof candidate?.priority !== "number") return group;
12406
+ if (candidate.priority <= USER_GROUP_MAX_PRIORITY) return group;
12407
+ if (!warnedAboutGroupPriority) {
12408
+ warnedAboutGroupPriority = true;
12409
+ mfWarn(`Clamping \`output.codeSplitting.groups\` priority to ${USER_GROUP_MAX_PRIORITY} — module federation groups must keep the highest priority so shared dependency init wrappers stay isolated in their own chunks.`);
12410
+ }
12411
+ return {
12412
+ ...candidate,
12413
+ priority: USER_GROUP_MAX_PRIORITY
12414
+ };
12415
+ };
12416
+ const federationGroupDebugName = supportsCodeSplittingGroupDebugName(ctx) ? { debugName: "module-federation" } : {};
12417
+ let warnedAboutManualChunks = false;
12418
+ let warnedAboutObjectManualChunks = false;
12419
+ const applyManualChunks = (output, useCodeSplitting) => {
12420
+ ensureCodeSplitting(output);
12421
+ const isPatchedByPlugin = typeof output.manualChunks === "function" && patchedManualChunks.has(output.manualChunks);
12422
+ const mfChunkName = function(id) {
12423
+ if (id.includes(runtimeInitId) || id.includes("__mf_v__runtimeInit__mf_v__")) return "runtimeInit";
12424
+ if (isSharedCacheHelpersId(id)) return getSharedChunkName(id);
12425
+ if (id.includes("__loadShare__")) {
12426
+ const pkg = getCachedLoadSharePkg(id);
12427
+ const key = pkg && findSharedKey(pkg, shared);
12428
+ if (key && shared[key].shareConfig.eager === true) return "loadShare-eager";
12429
+ if (key && shared[key].shareConfig.import === false) return null;
12430
+ if (pkg && !id.includes("commonjs-proxy") && isCoalescableLoadShareWrapper(pkg, options, id)) return getSharedChunkName(id);
12431
+ const match = id.match(/([^/\\]+__loadShare__[^/\\]+)/);
12432
+ return match ? match[1] : "loadShare";
12433
+ }
12434
+ return null;
12435
+ };
12436
+ patchedManualChunks.add(mfChunkName);
12437
+ if (!useCodeSplitting) {
12438
+ if (isPatchedByPlugin) return;
12439
+ const userManualChunks = output.manualChunks;
12440
+ if (userManualChunks && typeof userManualChunks !== "function" && !warnedAboutObjectManualChunks) {
12441
+ warnedAboutObjectManualChunks = true;
12442
+ mfWarn("Ignoring the object form of `output.manualChunks` because module federation cannot safely compose with it. Use the function form instead: federation modules are claimed first and your function runs for everything else.");
12443
+ }
12444
+ const mfManualChunks = function(id, ...rest) {
12445
+ if (PRELOAD_HELPER_TEST.test(id)) return PRELOAD_HELPER_CHUNK;
12446
+ const mfChunk = mfChunkName(id);
12447
+ if (mfChunk) return mfChunk;
12448
+ if (typeof userManualChunks === "function") return userManualChunks(id, ...rest) ?? void 0;
12449
+ };
12450
+ patchedManualChunks.add(mfManualChunks);
12451
+ output.manualChunks = mfManualChunks;
12452
+ return;
12453
+ }
12454
+ if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
12455
+ warnedAboutManualChunks = true;
12456
+ mfWarn("Ignoring `output.manualChunks` for the Rolldown build because module federation manages chunking with `output.codeSplitting.groups`. Move your grouping there — user groups are kept below the federation groups.");
12457
+ }
12458
+ const existingGroups = output.codeSplitting && typeof output.codeSplitting === "object" ? output.codeSplitting.groups : void 0;
12459
+ const userGroups = Array.isArray(existingGroups) ? existingGroups.filter((group) => !isFederationGroup(group)).map(clampUserGroup) : [];
12460
+ const mfPreloadGroup = {
12461
+ name: PRELOAD_HELPER_CHUNK,
12462
+ test: PRELOAD_HELPER_TEST,
12463
+ priority: 1000001
12464
+ };
12465
+ const mfNameGroup = {
12466
+ name: mfChunkName,
12467
+ priority: MF_GROUP_PRIORITY,
12468
+ ...federationGroupDebugName
12469
+ };
12470
+ federationGroups.add(mfPreloadGroup);
12471
+ federationGroups.add(mfNameGroup);
12472
+ const groups = [mfPreloadGroup, mfNameGroup];
12473
+ if (!snapshotOutput) {
12474
+ const htmlPreambleGroup = {
12475
+ name: getBundledDevHtmlPreambleChunk,
12476
+ priority: 1000002
12477
+ };
12478
+ federationGroups.add(htmlPreambleGroup);
12479
+ groups.push(htmlPreambleGroup);
12480
+ }
12481
+ groups.push(...userGroups);
12482
+ output.codeSplitting = {
12483
+ ...output.codeSplitting || {},
12484
+ groups
12485
+ };
12486
+ delete output.manualChunks;
12487
+ };
12488
+ config.build.rollupOptions = config.build.rollupOptions || {};
12489
+ const rollupOutput = config.build.rollupOptions.output;
12490
+ if (Array.isArray(rollupOutput)) rollupOutput.forEach((output) => applyManualChunks(output, false));
12491
+ else applyManualChunks(config.build.rollupOptions.output ||= {}, false);
12492
+ const buildWithRolldown = config.build;
12493
+ buildWithRolldown.rolldownOptions = buildWithRolldown.rolldownOptions || {};
12494
+ const rolldownOutput = buildWithRolldown.rolldownOptions.output;
12495
+ const snapshotRolldownOutput = (output) => ({
12496
+ entryFileNames: output.entryFileNames,
12497
+ chunkFileNames: output.chunkFileNames,
12498
+ assetFileNames: output.assetFileNames
12499
+ });
12500
+ if (Array.isArray(rolldownOutput)) {
12501
+ rolldownOutput.forEach((output) => applyManualChunks(output, true));
12502
+ if (snapshotOutput) desiredRolldownOutput = rolldownOutput.map((output) => snapshotRolldownOutput(output));
12503
+ } else {
12504
+ applyManualChunks(buildWithRolldown.rolldownOptions.output ||= {}, true);
12505
+ if (snapshotOutput) desiredRolldownOutput = [snapshotRolldownOutput(buildWithRolldown.rolldownOptions.output)];
12506
+ }
12507
+ }
12103
12508
  return [
12104
12509
  {
12105
12510
  name: "vite:module-federation-virtual-modules",
@@ -12229,13 +12634,20 @@ function federation(mfUserOptions) {
12229
12634
  getParsePromise: () => moduleParseController.parsePromise
12230
12635
  }),
12231
12636
  pluginLazyConsumeOnlyShares(options),
12637
+ {
12638
+ name: "module-federation-bundled-dev-chunks",
12639
+ apply: "serve",
12640
+ config(config) {
12641
+ if (!config.experimental?.bundledDev) return;
12642
+ applyFederationChunking(config, this, false);
12643
+ }
12644
+ },
12232
12645
  {
12233
12646
  name: "module-federation-esm-shims",
12234
12647
  enforce: "pre",
12235
12648
  apply: "build",
12236
12649
  config(config) {
12237
12650
  isSsrBuild = Boolean(config.build?.ssr);
12238
- const runtimeInitId = getRuntimeInitStatusImportId(options);
12239
12651
  config.build = config.build || {};
12240
12652
  if (config.build.modulePreload !== false) {
12241
12653
  const remoteEntryBasename = path$1.posix.basename(options.filename);
@@ -12257,115 +12669,7 @@ function federation(mfUserOptions) {
12257
12669
  }
12258
12670
  };
12259
12671
  }
12260
- let warnedAboutCodeSplitting = false;
12261
- const ensureCodeSplitting = (output) => {
12262
- if (output?.codeSplitting !== false) return;
12263
- delete output.codeSplitting;
12264
- if (warnedAboutCodeSplitting) return;
12265
- warnedAboutCodeSplitting = true;
12266
- mfWarn("Ignoring `output.codeSplitting = false` because module federation requires chunk splitting.");
12267
- };
12268
- const isFederationGroup = (group) => typeof group === "object" && group !== null && federationGroups.has(group);
12269
- let warnedAboutGroupPriority = false;
12270
- const clampUserGroup = (group) => {
12271
- const candidate = group;
12272
- if (typeof candidate?.priority !== "number") return group;
12273
- if (candidate.priority <= USER_GROUP_MAX_PRIORITY) return group;
12274
- if (!warnedAboutGroupPriority) {
12275
- warnedAboutGroupPriority = true;
12276
- mfWarn(`Clamping \`output.codeSplitting.groups\` priority to ${USER_GROUP_MAX_PRIORITY} — module federation groups must keep the highest priority so shared dependency init wrappers stay isolated in their own chunks.`);
12277
- }
12278
- return {
12279
- ...candidate,
12280
- priority: USER_GROUP_MAX_PRIORITY
12281
- };
12282
- };
12283
- const federationGroupDebugName = supportsCodeSplittingGroupDebugName(this) ? { debugName: "module-federation" } : {};
12284
- let warnedAboutManualChunks = false;
12285
- let warnedAboutObjectManualChunks = false;
12286
- const applyManualChunks = (output, useCodeSplitting) => {
12287
- ensureCodeSplitting(output);
12288
- const isPatchedByPlugin = typeof output.manualChunks === "function" && patchedManualChunks.has(output.manualChunks);
12289
- const mfChunkName = function(id) {
12290
- if (id.includes(runtimeInitId) || id.includes("__mf_v__runtimeInit__mf_v__")) return "runtimeInit";
12291
- if (isSharedCacheHelpersId(id)) return getSharedChunkName(id);
12292
- if (id.includes("__loadShare__")) {
12293
- const pkg = getCachedLoadSharePkg(id);
12294
- const key = pkg && findSharedKey(pkg, shared);
12295
- if (key && shared[key].shareConfig.eager === true) return "loadShare-eager";
12296
- if (key && shared[key].shareConfig.import === false) return null;
12297
- if (pkg && !id.includes("commonjs-proxy") && isCoalescableLoadShareWrapper(pkg, options, id)) return getSharedChunkName(id);
12298
- const match = id.match(/([^/\\]+__loadShare__[^/\\]+)/);
12299
- return match ? match[1] : "loadShare";
12300
- }
12301
- return null;
12302
- };
12303
- patchedManualChunks.add(mfChunkName);
12304
- if (!useCodeSplitting) {
12305
- if (isPatchedByPlugin) return;
12306
- const userManualChunks = output.manualChunks;
12307
- if (userManualChunks && typeof userManualChunks !== "function" && !warnedAboutObjectManualChunks) {
12308
- warnedAboutObjectManualChunks = true;
12309
- mfWarn("Ignoring the object form of `output.manualChunks` because module federation cannot safely compose with it. Use the function form instead: federation modules are claimed first and your function runs for everything else.");
12310
- }
12311
- const mfManualChunks = function(id, ...rest) {
12312
- if (PRELOAD_HELPER_TEST.test(id)) return PRELOAD_HELPER_CHUNK;
12313
- const mfChunk = mfChunkName(id);
12314
- if (mfChunk) return mfChunk;
12315
- if (typeof userManualChunks === "function") return userManualChunks(id, ...rest) ?? void 0;
12316
- };
12317
- patchedManualChunks.add(mfManualChunks);
12318
- output.manualChunks = mfManualChunks;
12319
- return;
12320
- }
12321
- if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
12322
- warnedAboutManualChunks = true;
12323
- mfWarn("Ignoring `output.manualChunks` for the Rolldown build because module federation manages chunking with `output.codeSplitting.groups`. Move your grouping there — user groups are kept below the federation groups.");
12324
- }
12325
- const existingGroups = output.codeSplitting && typeof output.codeSplitting === "object" ? output.codeSplitting.groups : void 0;
12326
- const userGroups = Array.isArray(existingGroups) ? existingGroups.filter((group) => !isFederationGroup(group)).map(clampUserGroup) : [];
12327
- const mfPreloadGroup = {
12328
- name: PRELOAD_HELPER_CHUNK,
12329
- test: PRELOAD_HELPER_TEST,
12330
- priority: 1000001
12331
- };
12332
- const mfNameGroup = {
12333
- name: mfChunkName,
12334
- priority: MF_GROUP_PRIORITY,
12335
- ...federationGroupDebugName
12336
- };
12337
- federationGroups.add(mfPreloadGroup);
12338
- federationGroups.add(mfNameGroup);
12339
- const groups = [
12340
- mfPreloadGroup,
12341
- mfNameGroup,
12342
- ...userGroups
12343
- ];
12344
- output.codeSplitting = {
12345
- ...output.codeSplitting || {},
12346
- groups
12347
- };
12348
- delete output.manualChunks;
12349
- };
12350
- config.build.rollupOptions = config.build.rollupOptions || {};
12351
- const rollupOutput = config.build.rollupOptions.output;
12352
- if (Array.isArray(rollupOutput)) rollupOutput.forEach((output) => applyManualChunks(output, false));
12353
- else applyManualChunks(config.build.rollupOptions.output ||= {}, false);
12354
- const buildWithRolldown = config.build;
12355
- buildWithRolldown.rolldownOptions = buildWithRolldown.rolldownOptions || {};
12356
- const rolldownOutput = buildWithRolldown.rolldownOptions.output;
12357
- const snapshotRolldownOutput = (output) => ({
12358
- entryFileNames: output.entryFileNames,
12359
- chunkFileNames: output.chunkFileNames,
12360
- assetFileNames: output.assetFileNames
12361
- });
12362
- if (Array.isArray(rolldownOutput)) {
12363
- rolldownOutput.forEach((output) => applyManualChunks(output, true));
12364
- desiredRolldownOutput = rolldownOutput.map((output) => snapshotRolldownOutput(output));
12365
- } else {
12366
- applyManualChunks(buildWithRolldown.rolldownOptions.output ||= {}, true);
12367
- desiredRolldownOutput = [snapshotRolldownOutput(buildWithRolldown.rolldownOptions.output)];
12368
- }
12672
+ applyFederationChunking(config, this, true);
12369
12673
  },
12370
12674
  async buildApp(builder) {
12371
12675
  const desiredOutput = desiredRolldownOutput;