@module-federation/vite 1.23.8 → 1.23.9

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.
@@ -1,5 +1,5 @@
1
- import { r as mfWarn, t as createModuleFederationError, u as normalizePathForImport } from "./logger-D67aJYOe.js";
2
- import { d as getNodeModulesSuffix, r as getSharedRuntimeKey } from "./sharedKeyMatcher-C04bVN1q.js";
1
+ import { p as normalizePathForImport, r as mfWarn, t as createModuleFederationError } from "./logger-Ckj1FMRH.js";
2
+ import { d as getNodeModulesSuffix, r as getSharedRuntimeKey } from "./sharedKeyMatcher-B5VKsEVQ.js";
3
3
  import { existsSync, readFileSync, readdirSync, realpathSync } from "fs";
4
4
  import { createRequire } from "module";
5
5
  import * as path$1 from "node:path";
@@ -28,6 +28,14 @@ const REACT_DOM_CLIENT_SHARE = "react-dom/client";
28
28
  function isReactCoreShare(pkg) {
29
29
  return pkg === "react" || pkg.startsWith("react/");
30
30
  }
31
+ /**
32
+ * React and its renderer, including subpath exports. Their wrappers bind
33
+ * synchronously and carry the mixed-mode guard, so the generic deferral of a
34
+ * negotiated singleton's local copy does not apply to them.
35
+ */
36
+ function isReactFamilyShare(pkg) {
37
+ return isReactCoreShare(pkg) || pkg === "react-dom" || pkg.startsWith("react-dom/");
38
+ }
31
39
  //#endregion
32
40
  //#region src/utils/packageUtils.ts
33
41
  const dependencyPresenceCache = /* @__PURE__ */ new Map();
@@ -790,4 +798,4 @@ function watchFileEvents(watcher, listener) {
790
798
  //#region src/utils/dtsConstants.ts
791
799
  const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
792
800
  //#endregion
793
- export { sharedCacheHelperCode as C, isReactCoreShare as D, REACT_DOM_CLIENT_SHARE as E, setPackageDetectionCwd as S, REACT_CLIENT_INTERNALS_KEY as T, isPackageInstalled as _, getDependencyNames as a, resolveImportPath as b, getIsRolldown as c, getPackageName as d, getPackageNameFromNodeModulePath as f, isPackageExportAvailable as g, isNuxtProjectRoot as h, findPackageInDependents as i, getPackageDetectionCwd as l, hasPackageDependency as m, formatDevServerHostForOrigin as n, getInstalledPackageEntry as o, getSharedCacheDescriptor as p, watchFileEvents as r, getInstalledPackageJson as s, DEFAULT_PUBLIC_TYPES_FOLDER as t, getPackageExportSpecifiersForFile as u, packageNameDecode as v, supportsCodeSplittingGroupDebugName as w, resolveModulePath as x, packageNameEncode as y };
801
+ export { sharedCacheHelperCode as C, isReactCoreShare as D, REACT_DOM_CLIENT_SHARE as E, isReactFamilyShare as O, setPackageDetectionCwd as S, REACT_CLIENT_INTERNALS_KEY as T, isPackageInstalled as _, getDependencyNames as a, resolveImportPath as b, getIsRolldown as c, getPackageName as d, getPackageNameFromNodeModulePath as f, isPackageExportAvailable as g, isNuxtProjectRoot as h, findPackageInDependents as i, getPackageDetectionCwd as l, hasPackageDependency as m, formatDevServerHostForOrigin as n, getInstalledPackageEntry as o, getSharedCacheDescriptor as p, watchFileEvents as r, getInstalledPackageJson as s, DEFAULT_PUBLIC_TYPES_FOLDER as t, getPackageExportSpecifiersForFile as u, packageNameDecode as v, supportsCodeSplittingGroupDebugName as w, resolveModulePath as x, packageNameEncode as y };
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as CodeRewriter, c as isAbsoluteUrl, d as rebaseImport, f as resolveHashPlaceholderFileName, i as createCodePositionMap, l as isHttpUrl, o as createSourceMap, r as mfWarn, t as createModuleFederationError, u as normalizePathForImport } from "./logger-D67aJYOe.js";
2
- 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, x as toRelativeImport, y as stripQueryAndHash } from "./sharedKeyMatcher-C04bVN1q.js";
3
- import { C as sharedCacheHelperCode, D as isReactCoreShare, E as REACT_DOM_CLIENT_SHARE, S as setPackageDetectionCwd, T as REACT_CLIENT_INTERNALS_KEY, _ as isPackageInstalled, a as getDependencyNames, b as resolveImportPath, c as getIsRolldown, d as getPackageName, f as getPackageNameFromNodeModulePath, g as isPackageExportAvailable, h as isNuxtProjectRoot, i as findPackageInDependents, l as getPackageDetectionCwd, m as hasPackageDependency, n as formatDevServerHostForOrigin, o as getInstalledPackageEntry, p as getSharedCacheDescriptor, r as watchFileEvents, s as getInstalledPackageJson, u as getPackageExportSpecifiersForFile, v as packageNameDecode, w as supportsCodeSplittingGroupDebugName, x as resolveModulePath, y as packageNameEncode } from "./dtsConstants-286VtFnC.js";
1
+ import { a as CodeRewriter, c as VITE_ID_PREFIX, d as isAbsoluteUrl, f as isHttpUrl, h as resolveHashPlaceholderFileName, i as createCodePositionMap, l as VITE_NULL_BYTE_PLACEHOLDER, m as rebaseImport, o as createSourceMap, p as normalizePathForImport, r as mfWarn, t as createModuleFederationError, u as decodeViteId } from "./logger-Ckj1FMRH.js";
2
+ 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, x as toRelativeImport, y as stripQueryAndHash } from "./sharedKeyMatcher-B5VKsEVQ.js";
3
+ import { C as sharedCacheHelperCode, D as isReactCoreShare, E as REACT_DOM_CLIENT_SHARE, O as isReactFamilyShare, S as setPackageDetectionCwd, T as REACT_CLIENT_INTERNALS_KEY, _ as isPackageInstalled, a as getDependencyNames, b as resolveImportPath, c as getIsRolldown, d as getPackageName, f as getPackageNameFromNodeModulePath, g as isPackageExportAvailable, h as isNuxtProjectRoot, i as findPackageInDependents, l as getPackageDetectionCwd, m as hasPackageDependency, n as formatDevServerHostForOrigin, o as getInstalledPackageEntry, p as getSharedCacheDescriptor, r as watchFileEvents, s as getInstalledPackageJson, u as getPackageExportSpecifiersForFile, v as packageNameDecode, w as supportsCodeSplittingGroupDebugName, x as resolveModulePath, y as packageNameEncode } from "./dtsConstants-DIcz34LN.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";
@@ -852,8 +852,7 @@ function getSuffix(name) {
852
852
  const patternMap = {};
853
853
  const cacheMap = {};
854
854
  const idCacheMap = {};
855
- const VITE_ID_PREFIX = "/@id/";
856
- const VITE_ENCODED_NULL_BYTE_PREFIX = `${VITE_ID_PREFIX}__x00__`;
855
+ const VITE_ENCODED_NULL_BYTE_PREFIX = `${VITE_ID_PREFIX}${VITE_NULL_BYTE_PLACEHOLDER}`;
857
856
  const MF_OWNER_INFIX = "__mf_owner__";
858
857
  function createViteEncodedIdPrefixRegExp(sourcePrefix = "") {
859
858
  return new RegExp(`^(?:${escapeRegExp(VITE_ENCODED_NULL_BYTE_PREFIX)})?${sourcePrefix}`);
@@ -861,11 +860,6 @@ function createViteEncodedIdPrefixRegExp(sourcePrefix = "") {
861
860
  function toViteEncodedId(id) {
862
861
  return `${VITE_ENCODED_NULL_BYTE_PREFIX}${id}`;
863
862
  }
864
- function decodeViteId(id) {
865
- if (!id.startsWith("/@id/")) return id;
866
- const viteId = id.slice(5);
867
- return viteId.startsWith("__x00__") ? `\0${viteId.slice(7)}` : viteId;
868
- }
869
863
  function assertModuleFound(tag, str = "") {
870
864
  const module = VirtualModule.findById(str) ?? VirtualModule.findModule(tag, str);
871
865
  if (!module) throw createModuleFederationError(`Module Federation shared module '${str}' not found. Please ensure it's installed as a dependency in your package.json.`);
@@ -1982,6 +1976,19 @@ function hasCodeMatch(source, regex, codePositions) {
1982
1976
  while ((match = regex.exec(source)) !== null) if (codePositions[match.index]) return true;
1983
1977
  return false;
1984
1978
  }
1979
+ /** True when the code before `index` is a `.`: member access (`obj.export`), not an identifier. */
1980
+ function isMemberName(source, index, codePositions) {
1981
+ let previousCodeIndex = index - 1;
1982
+ while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
1983
+ return source[previousCodeIndex] === ".";
1984
+ }
1985
+ /** TypeScript `export = value`; an assignment to a member named `export` (`e.export = 'export'`) is not one. */
1986
+ function hasExportAssignment(source, codePositions) {
1987
+ const regex = /\bexport\s*=/g;
1988
+ let match;
1989
+ while ((match = regex.exec(source)) !== null) if (codePositions[match.index] && !isMemberName(source, match.index, codePositions)) return true;
1990
+ return false;
1991
+ }
1985
1992
  /**
1986
1993
  * True when the file contains a top-level static `import`/`export` declaration.
1987
1994
  * Local identifiers named `module` or `exports` (webpack/rspack helpers,
@@ -2000,9 +2007,7 @@ function hasEsmModuleSyntax(source, codePositions) {
2000
2007
  }
2001
2008
  if (!codePositions[match.index]) continue;
2002
2009
  if (braceDepth !== 0) continue;
2003
- let previousCodeIndex = match.index - 1;
2004
- while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
2005
- if (source[previousCodeIndex] === ".") continue;
2010
+ if (isMemberName(source, match.index, codePositions)) continue;
2006
2011
  let nextCodeIndex = match.index + match[0].length;
2007
2012
  while (nextCodeIndex < source.length && (/\s/.test(source[nextCodeIndex]) || !codePositions[nextCodeIndex])) nextCodeIndex++;
2008
2013
  if (source[nextCodeIndex] === "(") continue;
@@ -2018,9 +2023,7 @@ function hasCommonJsExports(source) {
2018
2023
  let match;
2019
2024
  while ((match = exportsRegex.exec(source)) !== null) {
2020
2025
  if (!codePositions[match.index]) continue;
2021
- let previousCodeIndex = match.index - 1;
2022
- while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
2023
- if (source[previousCodeIndex] === ".") continue;
2026
+ if (isMemberName(source, match.index, codePositions)) continue;
2024
2027
  return true;
2025
2028
  }
2026
2029
  return false;
@@ -2289,7 +2292,7 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
2289
2292
  else for (const name of additionalNames) names.add(name);
2290
2293
  if (hasUnsupportedBindingPattern(source, exportedVariableDeclarationRegex.lastIndex)) scanState.complete = false;
2291
2294
  }
2292
- if (hasCodeMatch(source, /export\s+import\s+/g, codePositions) || hasCodeMatch(source, /export\s*=/g, codePositions)) scanState.complete = false;
2295
+ if (hasCodeMatch(source, /export\s+import\s+/g, codePositions) || hasExportAssignment(source, codePositions)) scanState.complete = false;
2293
2296
  if (hasCodeMatch(source, /export\s+@/g, codePositions)) scanState.complete = false;
2294
2297
  const destructureRegex = /export\s+(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*=/g;
2295
2298
  const bindingNameRegex = new RegExp(`^(${JS_IDENTIFIER_PATTERN})`, "u");
@@ -2373,9 +2376,7 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
2373
2376
  while ((match = exportKeywordRegex.exec(source)) !== null) {
2374
2377
  if (!codePositions[match.index]) continue;
2375
2378
  if (recognizedExportStarts.has(match.index)) continue;
2376
- let previousCodeIndex = match.index - 1;
2377
- while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
2378
- if (source[previousCodeIndex] === ".") continue;
2379
+ if (isMemberName(source, match.index, codePositions)) continue;
2379
2380
  let nextCodeIndex = match.index + match[0].length;
2380
2381
  while (nextCodeIndex < source.length && (/\s/.test(source[nextCodeIndex]) || !codePositions[nextCodeIndex])) nextCodeIndex++;
2381
2382
  if (source[nextCodeIndex] === "(") continue;
@@ -3168,7 +3169,8 @@ function writeLoadShareModule(pkg, shareItem, command, options, exportConditions
3168
3169
  const hasCompleteExportCoverage = detectedNamedExports !== void 0;
3169
3170
  const isSingleton = shareItem.shareConfig.singleton === true;
3170
3171
  const isWorkspaceSingleton = isWorkspacePackage && isSingleton;
3171
- const usesDeferredSingletonFallback = hasCompleteExportCoverage && shareItem.shareConfig.eager !== true && (isWorkspacePackage || command !== "build" && isRemoteOnlyContainer(options) && isSingleton || command === "build" && isRemoteContainer(options) && !isSharedSingletonConsumedByPeer(pkg, options, true));
3172
+ const negotiatesSingletonWithRemotes = isSingleton && !isReactFamilyShare(pkg) && options.shareStrategy === "version-first" && hasRemotes(options) && pkg !== "solid-js" && !isSharedSingletonConsumedByPeer(pkg, options, true);
3173
+ const usesDeferredSingletonFallback = hasCompleteExportCoverage && shareItem.shareConfig.eager !== true && (isWorkspacePackage || negotiatesSingletonWithRemotes || command !== "build" && isRemoteOnlyContainer(options) && isSingleton || command === "build" && isRemoteContainer(options) && !isSharedSingletonConsumedByPeer(pkg, options, true));
3172
3174
  const servesRemoteSingletonFallback = command !== "build" && isRemoteOnlyContainer(options) && isSingleton;
3173
3175
  const isConsumedByPeerSingleton = isSharedSingletonConsumedByPeer(pkg, options);
3174
3176
  const usesEntryInjectedRemoteFallback = hasCompleteExportCoverage && !isWorkspaceSingleton && isRemoteContainer(options) && isSingleton && options.hostInitInjectLocation === "entry" && (command === "build" || isConsumedByPeerSingleton);
@@ -4446,8 +4448,10 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy, options, command = "b
4446
4448
  const seedOrder = seedBatches.flat();
4447
4449
  const seedIndex = new Map(seedOrder.map((pkg, index) => [pkg, index]));
4448
4450
  const seedPrerequisites = Object.fromEntries(Array.from(getSharePrerequisites(seedOrder, options)).filter(([, prerequisites]) => prerequisites.length > 0).map(([pkg, prerequisites]) => [seedIndex.get(pkg), prerequisites.map((prerequisite) => seedIndex.get(prerequisite))]));
4451
+ const versionFirstDeferredSeeds = shareStrategy === "version-first" && hasRemotes(options) ? seedOrder.filter((pkg) => !isReactFamilyShare(pkg)) : [];
4449
4452
  return `
4450
4453
  const __mfSeedOrder = ${toSafeJsLiteral(seedOrder)};
4454
+ const __mfVersionFirstDeferredSeeds = new Set(${toSafeJsLiteral(versionFirstDeferredSeeds)});
4451
4455
  const __mfSeedBatches = ${toSafeJsLiteral(seedBatches)};
4452
4456
  const __mfSeedIndex = new Map(__mfSeedOrder.map((pkg, index) => [pkg, index]));
4453
4457
  const __mfSeedPrerequisites = ${toSafeJsLiteral(seedPrerequisites)};
@@ -4602,6 +4606,13 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy, options, command = "b
4602
4606
  : __mfReadSharedCache(__mfModuleCache.share, cacheDescriptor);
4603
4607
  if (cachedShare !== undefined) return false;
4604
4608
  if (share.treeShaking || share.shareConfig?.import === false) return true;
4609
+ // version-first negotiates a singleton against this container's remotes, which only
4610
+ // register during initializeSharing(). Seeding the local copy before that evaluates it
4611
+ // even when a remote's higher version is selected, so a package with top-level side
4612
+ // effects (custom element registration, polyfills) runs twice (#1527). Wait for the
4613
+ // remotes; the deferred pass seeds the local copy only when no remote outranks it.
4614
+ // The React family keeps the eager seed its synchronous wrappers rely on.
4615
+ if (__mfVersionFirstDeferredSeeds.has(pkg) && share.shareConfig?.singleton) return true;
4605
4616
  if (typeof __mfSelectExternalSharedProvider !== 'function') return false;
4606
4617
  return Boolean(__mfSelectExternalSharedProvider(
4607
4618
  initialShared[pkg],
@@ -5818,7 +5829,12 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
5818
5829
  if (__mfModuleCache.pendingShareLoads) {
5819
5830
  await Promise.all(__mfModuleCache.pendingShareLoads)
5820
5831
  }
5821
- return (exposesMap[moduleName])().then(res => () => res)
5832
+ const res = await exposesMap[moduleName]()
5833
+ // Wrappers evaluated by the expose import may queue share loads only now (#1535).
5834
+ if (__mfModuleCache.pendingShareLoads) {
5835
+ await Promise.all(__mfModuleCache.pendingShareLoads)
5836
+ }
5837
+ return () => res
5822
5838
  }
5823
5839
  ${guardHostAutoInit ? `let __mfInitPromise;
5824
5840
  function __mfGuardedInit(shared, initScope, remoteEntryInitOptions) {
@@ -8375,7 +8391,7 @@ function ${helperName}(names) {
8375
8391
  }
8376
8392
  //#endregion
8377
8393
  //#region package.json
8378
- var version$1 = "1.23.8";
8394
+ var version$1 = "1.23.9";
8379
8395
  //#endregion
8380
8396
  //#region src/virtualModules/virtualExposesSSR.ts
8381
8397
  /**
@@ -9659,9 +9675,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
9659
9675
  let dependencyInvalidationVersion = 0;
9660
9676
  let reactIslandExposes = /* @__PURE__ */ new Set();
9661
9677
  let isTanStackStart = false;
9662
- const isHostAutoInitId = (id) => {
9663
- return id.split("?")[0].includes(getHostAutoInitPath(options));
9664
- };
9678
+ const isHostAutoInitId = (id) => isOwnedHostAutoInitId(id, options);
9665
9679
  const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
9666
9680
  const isSsrBuild = (context) => isServerBuildContext(context, viteConfig);
9667
9681
  const loadRemoteEntryCode = (context) => getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(context), isSsrBuild(context)));
@@ -9738,7 +9752,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
9738
9752
  if (id === remoteEntryId) return remoteEntryId;
9739
9753
  if (id === virtualExposesId) return virtualExposesId;
9740
9754
  if (_command === "serve" && isHostAutoInitId(id)) return id;
9741
- if (importer === remoteEntryId && !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !id.startsWith("virtual:")) {
9755
+ if ((importer === remoteEntryId || importer !== void 0 && isHostAutoInitId(importer)) && !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !id.startsWith("virtual:")) {
9742
9756
  const importPath = typeof __filename === "string" ? __filename : fileURLToPath(import.meta.url);
9743
9757
  const resolved = await this.resolve(id, importPath, { skipSelf: true });
9744
9758
  if (resolved) return resolved;
@@ -11193,7 +11207,7 @@ function pluginSSRRemoteEntry(options) {
11193
11207
  } catch {}
11194
11208
  }
11195
11209
  const fetchedId = body.data.name === "fetchModule" ? body.data.data[0] : void 0;
11196
- const shared = typeof fetchedId === "string" && !!findSharedKey(fetchedId, options.shared);
11210
+ const shared = typeof fetchedId === "string" && !!findSharedKey(decodeViteId(fetchedId).replace(/^\0+/, ""), options.shared);
11197
11211
  res.setHeader("Content-Type", "application/json");
11198
11212
  res.end(JSON.stringify(shared ? {
11199
11213
  ...result,
@@ -12530,7 +12544,7 @@ function withoutDynamicRemoteTypeHints(options) {
12530
12544
  }
12531
12545
  function loadPluginDts(options) {
12532
12546
  if (options.dts === false) return [];
12533
- return [import("./pluginDts-DvTJxjaE.js").then(({ default: pluginDts }) => pluginDts(options))];
12547
+ return [import("./pluginDts-CSCuhD4x.js").then(({ default: pluginDts }) => pluginDts(options))];
12534
12548
  }
12535
12549
  const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
12536
12550
  function isInjectExternalRuntimeCorePlugin(specifier) {
@@ -65,6 +65,13 @@ function resolveHashPlaceholderFileName(fileName) {
65
65
  const normalized = fileName.replace(HASH_PLACEHOLDER_RE, "");
66
66
  return hasFileExtension(normalized) ? normalized : `${normalized}.js`;
67
67
  }
68
+ const VITE_ID_PREFIX = "/@id/";
69
+ const VITE_NULL_BYTE_PLACEHOLDER = "__x00__";
70
+ function decodeViteId(id) {
71
+ if (!id.startsWith("/@id/")) return id;
72
+ const viteId = id.slice(5);
73
+ return viteId.startsWith("__x00__") ? `\0${viteId.slice(7)}` : viteId;
74
+ }
68
75
  //#endregion
69
76
  //#region src/utils/codeRewriter.ts
70
77
  const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -457,4 +464,4 @@ const moduleFederationConsole = {
457
464
  const mfWarn = moduleFederationConsole.warn;
458
465
  const mfError = moduleFederationConsole.error;
459
466
  //#endregion
460
- export { CodeRewriter as a, isAbsoluteUrl as c, rebaseImport as d, resolveHashPlaceholderFileName as f, createCodePositionMap as i, isHttpUrl as l, mfError as n, createSourceMap as o, mfWarn as r, EXTERNAL_URL_RE as s, createModuleFederationError as t, normalizePathForImport as u };
467
+ export { CodeRewriter as a, VITE_ID_PREFIX as c, isAbsoluteUrl as d, isHttpUrl as f, resolveHashPlaceholderFileName as h, createCodePositionMap as i, VITE_NULL_BYTE_PLACEHOLDER as l, rebaseImport as m, mfError as n, createSourceMap as o, normalizePathForImport as p, mfWarn as r, EXTERNAL_URL_RE as s, createModuleFederationError as t, decodeViteId as u };
@@ -1,5 +1,5 @@
1
- import { l as isHttpUrl, n as mfError, t as createModuleFederationError, u as normalizePathForImport } from "./logger-D67aJYOe.js";
2
- import { b as resolveImportPath, m as hasPackageDependency, r as watchFileEvents } from "./dtsConstants-286VtFnC.js";
1
+ import { f as isHttpUrl, n as mfError, p as normalizePathForImport, t as createModuleFederationError } from "./logger-Ckj1FMRH.js";
2
+ import { b as resolveImportPath, m as hasPackageDependency, r as watchFileEvents } from "./dtsConstants-DIcz34LN.js";
3
3
  import fs from "fs";
4
4
  import * as path$1 from "node:path";
5
5
  import { normalizeOptions } from "@module-federation/sdk";
@@ -1,4 +1,4 @@
1
- import { u as normalizePathForImport } from "./logger-D67aJYOe.js";
1
+ import { p as normalizePathForImport } from "./logger-Ckj1FMRH.js";
2
2
  import * as path$1 from "node:path";
3
3
  //#region src/utils/pathNormalization.ts
4
4
  const COMMON_SHARED_SUBPATHS = {
@@ -1,4 +1,4 @@
1
- import { a as CodeRewriter, i as createCodePositionMap, l as isHttpUrl, r as mfWarn, s as EXTERNAL_URL_RE } from "./logger-D67aJYOe.js";
1
+ import { a as CodeRewriter, f as isHttpUrl, i as createCodePositionMap, r as mfWarn, s as EXTERNAL_URL_RE, u as decodeViteId } from "./logger-Ckj1FMRH.js";
2
2
  import { simpleJoinRemoteEntry } from "@module-federation/sdk";
3
3
  //#region src/utils/fetchWithTimeout.ts
4
4
  const DEFAULT_SSR_FETCH_TIMEOUT_MS = 1e4;
@@ -225,7 +225,8 @@ async function resolveEsmSubpath(id, base) {
225
225
  if (!existsSync(packageJson)) continue;
226
226
  const { exports } = JSON.parse(readFileSync(packageJson, "utf8"));
227
227
  const target = getEsmExportTarget(exports?.[subpath]);
228
- return target && join(dirname(packageJson), target);
228
+ const esmPath = target && join(dirname(packageJson), target);
229
+ return esmPath && existsSync(esmPath) ? esmPath : void 0;
229
230
  }
230
231
  }
231
232
  /**
@@ -235,15 +236,17 @@ async function resolveEsmSubpath(id, base) {
235
236
  */
236
237
  async function resolveSharedPath(id, resolvedShared) {
237
238
  if (typeof id !== "string") return null;
238
- const matchedKey = findResolvedSharedKey(id, resolvedShared);
239
+ const normalizedId = decodeViteId(id);
240
+ const matchedKey = findResolvedSharedKey(normalizedId, resolvedShared);
239
241
  if (!matchedKey) return null;
240
242
  const resolved = resolvedShared[matchedKey];
241
243
  if (!resolved) return null;
242
- if (matchedKey === id || EXTERNAL_URL_RE.test(resolved)) return resolved;
244
+ if (EXTERNAL_URL_RE.test(resolved)) return resolved;
245
+ if (matchedKey === normalizedId) return await resolveEsmSubpath(normalizedId, resolved).catch(() => void 0) ?? resolved;
243
246
  const { createRequire } = await _module();
244
247
  const { join } = await _path();
245
248
  for (const base of [resolved, join(process.cwd(), "noop.js")]) try {
246
- return await resolveEsmSubpath(id, base).catch(() => void 0) ?? createRequire(base).resolve(id);
249
+ return await resolveEsmSubpath(normalizedId, base).catch(() => void 0) ?? createRequire(base).resolve(normalizedId);
247
250
  } catch {}
248
251
  return null;
249
252
  }
@@ -789,14 +792,14 @@ function findSsrModuleSpecifiers(code) {
789
792
  function isNodeModuleSpecifier(specifier) {
790
793
  return specifier === "node:module" || specifier === "module";
791
794
  }
792
- function transformSsrCode(code, base, specifiers, sharedPkgMap, requireShimUrl, tempFileUrlMap) {
795
+ function transformSsrCode(code, base, specifiers, sharedImports, requireShimUrl, tempFileUrlMap) {
793
796
  const rewriter = new CodeRewriter(code);
794
797
  for (const { start, end, value } of specifiers) {
795
798
  if (requireShimUrl && isNodeModuleSpecifier(value)) {
796
799
  rewriter.overwrite(start, end, `"${requireShimUrl}"`);
797
800
  continue;
798
801
  }
799
- const resolvedShared = sharedPkgMap?.get(value);
802
+ const resolvedShared = sharedImports?.get(value);
800
803
  const relativeUrl = isRelativeSpecifier(value) ? new URL(value, base).href : void 0;
801
804
  const absoluteHttpUrl = isHttpUrl(value) ? value : void 0;
802
805
  const httpUrl = relativeUrl ?? absoluteHttpUrl;
@@ -805,14 +808,17 @@ function transformSsrCode(code, base, specifiers, sharedPkgMap, requireShimUrl,
805
808
  }
806
809
  return neutralizeBrowserPreloadHelpers(rewriter.toString());
807
810
  }
808
- async function materializeSharedSubpaths(specifiers, sharedPkgMap) {
811
+ async function resolveSharedImports(specifiers, sharedPkgMap) {
809
812
  const uniqueSpecifiers = new Set(specifiers.map(({ value }) => value));
810
813
  const resolvedShared = Object.fromEntries(sharedPkgMap);
814
+ const sharedImports = /* @__PURE__ */ new Map();
811
815
  for (const specifier of uniqueSpecifiers) {
812
- if (sharedPkgMap.has(specifier)) continue;
813
816
  const resolved = await resolveSharedPath(specifier, resolvedShared);
814
- if (resolved) sharedPkgMap.set(specifier, resolved);
817
+ if (!resolved) continue;
818
+ sharedImports.set(specifier, resolved);
819
+ if (!sharedPkgMap.has(specifier)) sharedPkgMap.set(specifier, resolved);
815
820
  }
821
+ return sharedImports;
816
822
  }
817
823
  function isVitePreloadHelperSpecifier(specifier) {
818
824
  return specifier.includes("preload-helper");
@@ -870,9 +876,9 @@ async function fetchEsmToTempFile(url, graph) {
870
876
  const tmpPath = await fetchEsmToTempFile(u, graph);
871
877
  subMap.set(u, getTempFileImportUrl(tmpPath, versionKey));
872
878
  }));
873
- if (sharedPkgMap) await materializeSharedSubpaths(specifiers, sharedPkgMap);
879
+ const sharedImports = sharedPkgMap && await resolveSharedImports(specifiers, sharedPkgMap);
874
880
  const requireShimUrl = sharedPkgMap?.size && specifiers.some(({ value }) => isNodeModuleSpecifier(value)) ? await getRequireShimUrl(tmpDir, sharedPkgMap, contextKey) : void 0;
875
- code = transformSsrCode(code, base, specifiers, sharedPkgMap, requireShimUrl, subMap);
881
+ code = transformSsrCode(code, base, specifiers, sharedImports, requireShimUrl, subMap);
876
882
  const { writeFileSync } = await _fs();
877
883
  writeFileSync(tmpFile, code, "utf8");
878
884
  return tmpFile;
@@ -916,7 +922,7 @@ async function importTempModule(filePath, versionKey) {
916
922
  }
917
923
  let warnedVmUnavailable = false;
918
924
  function getVmStrategyModule() {
919
- if (!loaderState.vmStrategyModulePromise) loaderState.vmStrategyModulePromise = import("./ssrVmStrategy-D1cSKUV-.js");
925
+ if (!loaderState.vmStrategyModulePromise) loaderState.vmStrategyModulePromise = import("./ssrVmStrategy-uJaUmHLS.js");
920
926
  return loaderState.vmStrategyModulePromise;
921
927
  }
922
928
  /**
@@ -1,6 +1,6 @@
1
- import { l as isHttpUrl, s as EXTERNAL_URL_RE } from "./logger-D67aJYOe.js";
2
- import { t as findSharedKey } from "./sharedKeyMatcher-C04bVN1q.js";
3
- import { d as readResponseTextBounded, i as resolveSharedPath, l as fetchWithTimeout, n as SsrEntryHttpError, r as neutralizeBrowserPreloadHelpers, u as getBodyPreview } from "./ssrEntryLoader-DKpOrW8D.js";
1
+ import { f as isHttpUrl, s as EXTERNAL_URL_RE } from "./logger-Ckj1FMRH.js";
2
+ import { t as findSharedKey } from "./sharedKeyMatcher-B5VKsEVQ.js";
3
+ import { d as readResponseTextBounded, i as resolveSharedPath, l as fetchWithTimeout, n as SsrEntryHttpError, r as neutralizeBrowserPreloadHelpers, u as getBodyPreview } from "./ssrEntryLoader--NkahIOF.js";
4
4
  //#region src/utils/ssrVmStrategy.ts
5
5
  /**
6
6
  * vm.SourceTextModule strategy for loading remote SSR entries.
@@ -1,2 +1,2 @@
1
- import { a as revalidate, i as resolveSharedPath, n as SsrEntryHttpError, o as ssrEntryLoaderPlugin, r as neutralizeBrowserPreloadHelpers, t as SSR_ENTRY_LOADER_STATE_KEY } from "../ssrEntryLoader-DKpOrW8D.js";
1
+ import { a as revalidate, i as resolveSharedPath, n as SsrEntryHttpError, o as ssrEntryLoaderPlugin, r as neutralizeBrowserPreloadHelpers, t as SSR_ENTRY_LOADER_STATE_KEY } from "../ssrEntryLoader--NkahIOF.js";
2
2
  export { SSR_ENTRY_LOADER_STATE_KEY, SsrEntryHttpError, ssrEntryLoaderPlugin as default, neutralizeBrowserPreloadHelpers, resolveSharedPath, revalidate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.23.8",
3
+ "version": "1.23.9",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -77,9 +77,9 @@
77
77
  "vite": "^5.1.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
78
78
  },
79
79
  "dependencies": {
80
- "@module-federation/dts-plugin": "2.9.2",
81
- "@module-federation/runtime": "2.9.2",
82
- "@module-federation/sdk": "2.9.2"
80
+ "@module-federation/dts-plugin": "2.9.3",
81
+ "@module-federation/runtime": "2.9.3",
82
+ "@module-federation/sdk": "2.9.3"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@playwright/test": "1.62.0",