@module-federation/vite 1.23.2 → 1.23.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -278,6 +278,21 @@ federation({
278
278
 
279
279
  The `"vm"` strategy requires Node.js to run with `--experimental-vm-modules`. When unavailable, the loader warns once and falls back to `"temp-file"`. Vite 8 development uses `ModuleRunner`; this option primarily affects build and preview SSR entry loading.
280
280
 
281
+ `ssrEntryLoader` also accepts network and cache options:
282
+
283
+ ```ts
284
+ federation({
285
+ // ...
286
+ ssrEntryLoader: {
287
+ maxAgeMs: 60_000, // re-check each remote's manifest after 60s; omit to cache until process exit
288
+ fetchTimeoutMs: 5_000, // per-request timeout, default 10s, 0 disables it
289
+ fetchMaxBytes: 5 * 1024 * 1024, // per-response size limit, default 10 MiB, 0 disables it
290
+ },
291
+ });
292
+ ```
293
+
294
+ With `maxAgeMs`, a remote redeployed at the same URL is picked up once its manifest version changes. Only manifest-resolved entries can be revalidated.
295
+
281
296
  The SSR remote entry is emitted as `<filename base>.ssr.js` next to the browser entry, or under the exact name given by `ssrFilename`, and is advertised as `metaData.ssrRemoteEntry` in `mf-manifest.json`. It keeps `@module-federation/runtime`, `@module-federation/runtime-core` and `@module-federation/sdk` external by default so Node resolves them from the host. Hosts that cannot resolve those packages, such as a plain `@module-federation/enhanced` host using the SDK's reference Node loader, need a self-contained entry: opt the packages back in with Vite's `ssr.noExternal` (for example `ssr: { noExternal: true }`) on the remote.
282
297
 
283
298
  ## Runtime capability optimization
@@ -36,6 +36,7 @@ function getDependencyCacheKey(cwd, dependencyName) {
36
36
  }
37
37
  const installedPackageJsonCache = /* @__PURE__ */ new Map();
38
38
  const dependentsLookupCache = /* @__PURE__ */ new Map();
39
+ const reachableDependencyNames = /* @__PURE__ */ new Map();
39
40
  function setPackageDetectionCwd(cwd) {
40
41
  packageDetectionCwd = cwd;
41
42
  }
@@ -471,10 +472,17 @@ function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
471
472
  */
472
473
  function findPackageInDependents(packageName, cwd) {
473
474
  const cacheKey = `${cwd}\0${packageName}`;
474
- if (!dependentsLookupCache.has(cacheKey)) dependentsLookupCache.set(cacheKey, walkDependents(packageName, cwd));
475
+ if (!dependentsLookupCache.has(cacheKey)) {
476
+ if (!reachableDependencyNames.has(cwd)) {
477
+ const names = /* @__PURE__ */ new Set();
478
+ walkDependents("", cwd, names);
479
+ reachableDependencyNames.set(cwd, names);
480
+ }
481
+ dependentsLookupCache.set(cacheKey, reachableDependencyNames.get(cwd).has(packageName) ? walkDependents(packageName, cwd) : void 0);
482
+ }
475
483
  return dependentsLookupCache.get(cacheKey);
476
484
  }
477
- function walkDependents(packageName, cwd) {
485
+ function walkDependents(packageName, cwd, reachedNames) {
478
486
  const root = tryReadPackageJson(path$1.join(cwd, "package.json"));
479
487
  if (!root) return void 0;
480
488
  const visited = /* @__PURE__ */ new Set();
@@ -492,6 +500,7 @@ function walkDependents(packageName, cwd) {
492
500
  const dependent = findPackageFrom(name, fromDir);
493
501
  if (!dependent || visited.has(dependent.dir)) continue;
494
502
  visited.add(dependent.dir);
503
+ reachedNames?.add(name);
495
504
  const dependencies = getDependencyNames(dependent.packageJson);
496
505
  if (dependencies.includes(packageName)) {
497
506
  const copy = findPackageFrom(packageName, dependent.dir);
package/lib/index.d.ts CHANGED
@@ -1,280 +1,4 @@
1
- import { moduleFederationPlugin } from "@module-federation/sdk";
2
- import { ShareStrategy } from "@module-federation/runtime/types";
3
- //#region src/utils/normalizeModuleFederationOptions.d.ts
4
- interface RemoteObjectConfig {
5
- type?: string;
6
- name: string;
7
- internalName?: string;
8
- entry: string;
9
- entryGlobalName?: string;
10
- shareScope?: string | string[];
11
- }
12
- interface TreeShakingConfig {
13
- mode: 'server-calc' | 'runtime-infer';
14
- usedExports?: string[];
15
- }
16
- interface PluginManifestOptions {
17
- filePath?: string;
18
- disableAssetsAnalyze?: boolean;
19
- fileName?: string;
20
- additionalData?: (options: {
21
- stats: Record<string, unknown>;
22
- manifest?: Record<string, unknown>;
23
- pluginOptions: Record<string, unknown>;
24
- compiler?: unknown;
25
- compilation?: unknown;
26
- bundler: 'vite';
27
- }) => Promise<Record<string, unknown> | void> | Record<string, unknown> | void;
28
- }
29
- type ModuleFederationOptions = {
30
- exposes?: Record<string, string | {
31
- import: string;
32
- }> | undefined;
33
- filename?: string;
34
- /**
35
- * Exact file name of the SSR remote entry emitted next to `filename`.
36
- * Defaults to `<filename base>.ssr<ext>` so it never clobbers the browser
37
- * entry when both builds share an output directory. `[hash]` is not supported.
38
- */
39
- ssrFilename?: string;
40
- library?: any;
41
- name: string;
42
- remotes?: Record<string, string | RemoteObjectConfig> | undefined;
43
- runtime?: any;
44
- shareScope?: string | string[];
45
- /**
46
- * Override the public path used for remote entries
47
- * Defaults to Vite's base config or "auto" if base is empty
48
- */
49
- publicPath?: string;
50
- /**
51
- * Controls whether all CSS assets from the bundle should be added to every exposed module.
52
- * When false (default), the plugin will not process any CSS assets.
53
- * When true, all CSS assets are bundled into every exposed module.
54
- */
55
- bundleAllCSS?: boolean;
56
- /** Directory reserved for deploy-service generated secondary shared artifacts. */
57
- treeShakingDir?: string;
58
- /** Whether inferred usedExports metadata is injected into generated runtime records. */
59
- injectTreeShakingUsedExports?: boolean;
60
- treeShakingSharedPlugins?: string[];
61
- treeShakingSharedExcludePlugins?: string[];
62
- shared?: string[] | Record<string, string | {
63
- name?: string;
64
- version?: string;
65
- shareScope?: string;
66
- request?: moduleFederationPlugin.SharedConfig['request'];
67
- shareKey?: moduleFederationPlugin.SharedConfig['shareKey'];
68
- singleton?: boolean;
69
- eager?: boolean;
70
- requiredVersion?: moduleFederationPlugin.SharedConfig['requiredVersion'];
71
- strictVersion?: boolean;
72
- allowNodeModulesSuffixMatch?: boolean;
73
- /** Suppress the missing local dependency warning for `import: false` shares. */
74
- suppressMissingImportWarning?: boolean;
75
- treeShaking?: TreeShakingConfig;
76
- import?: moduleFederationPlugin.SharedConfig['import'];
77
- }> | undefined;
78
- runtimePlugins?: Array<string | [string, Record<string, unknown>]>;
79
- getPublicPath?: string;
80
- implementation?: string;
81
- manifest?: PluginManifestOptions | boolean;
82
- dev?: boolean | PluginDevOptions;
83
- dts?: boolean | PluginDtsOptions;
84
- shareStrategy?: ShareStrategy;
85
- ignoreOrigin?: boolean;
86
- virtualModuleDir?: string;
87
- hostInitInjectLocation?: HostInitInjectLocationOptions;
88
- /**
89
- * Timeout for parsing modules in seconds.
90
- * Defaults to 10 seconds.
91
- */
92
- moduleParseTimeout?: number;
93
- /**
94
- * Idle timeout for parsing modules in seconds. When set, the timeout resets
95
- * on every parsed module and only fires when there has been no module activity
96
- * for the configured duration. Prefer this over `moduleParseTimeout` for large
97
- * codebases where the total build time may exceed the fixed timeout.
98
- */
99
- moduleParseIdleTimeout?: number;
100
- /**
101
- * Allows generate additional remoteEntry file for "var" host environment
102
- */
103
- varFilename?: string;
104
- /**
105
- * Target environment for the build to enable effective tree-shaking.
106
- *
107
- * @see https://module-federation.io/configure/experiments#target
108
- * @default 'web' (or 'node' if build.ssr is enabled)
109
- */
110
- target?: 'web' | 'node';
111
- /**
112
- * Removes remote-consumption support from the federation runtime.
113
- * Only enable this for builds that never load remotes.
114
- *
115
- * @default false
116
- */
117
- disableRemote?: boolean;
118
- /**
119
- * Removes shared-dependency support from the federation runtime.
120
- * Only enable this when the build has no shared dependencies.
121
- *
122
- * @default false
123
- */
124
- disableShared?: boolean;
125
- /**
126
- * Removes snapshot support, including manifest-based remotes, preload,
127
- * dynamic type hints, HMR, and devtools integration.
128
- *
129
- * @default false (true for Node/SSR builds)
130
- */
131
- disableSnapshot?: boolean;
132
- /**
133
- * Additional packages to mark as external in the SSR remote entry build.
134
- * Shared packages and MF runtime packages are external by default. Use this to
135
- * add any other Node-only packages that should not be bundled into the SSR entry.
136
- * To emit a self-contained SSR entry (loadable by hosts that cannot resolve the
137
- * MF runtime from Node, such as the `@module-federation/sdk` reference loader),
138
- * opt the MF runtime packages back in through Vite's `ssr.noExternal`.
139
- */
140
- ssrExternals?: string[];
141
- /**
142
- * Options for the auto-injected `@module-federation/vite/ssrEntryLoader`.
143
- * When omitted, the loader uses the `'temp-file'` strategy. Set
144
- * `strategy: 'vm'` to opt into `vm.SourceTextModule` evaluation while keeping
145
- * the computed `resolvedShared` map.
146
- */
147
- ssrEntryLoader?: SsrEntryLoaderConfig;
148
- /**
149
- * Experimental Module Federation capabilities.
150
- *
151
- * @see https://module-federation.io/configure/experiments
152
- */
153
- experiments?: PluginExperimentsOptions;
154
- };
155
- interface PluginExperimentsOptions {
156
- /**
157
- * Treat `@module-federation/runtime-core` as an external that reads
158
- * `globalThis._FEDERATION_RUNTIME_CORE` at runtime. Pair with a host that
159
- * sets `provideExternalRuntime: true`.
160
- */
161
- externalRuntime?: boolean;
162
- /**
163
- * Injects a local runtime plugin that publishes `runtime-core` on
164
- * `globalThis._FEDERATION_RUNTIME_CORE`. Set it on exactly one container
165
- * per page; that container may also `exposes`.
166
- */
167
- provideExternalRuntime?: boolean;
168
- /** Generate the React SSR/hydration island capability for eligible exposes. */
169
- ssrMode?: 'ISLAND';
170
- /**
171
- * The host provides every shared dependency; remotes bring none. Shared keys
172
- * are resolved by a native browser import map instead of the Module
173
- * Federation runtime: the host emits one entry chunk per shared key and
174
- * injects `<script type="importmap">`, remotes keep shared imports as bare
175
- * specifiers and emit one fixed-name entry per expose plus a standard
176
- * `mf-manifest.json` (without `remoteEntry`) the host maps from.
177
- *
178
- * Shared modules become ordinary static ES imports, so there is no
179
- * `loadShare` glue and no `eager` is needed for code that reads a shared
180
- * value at module-evaluation time. There is no version negotiation and no
181
- * runtime API: `requiredVersion`, `strictVersion`, `shareStrategy`,
182
- * `runtimePlugins` and `manifest` are ignored.
183
- *
184
- * @see https://github.com/module-federation/vite/issues/1381
185
- */
186
- hostProvidesAllShared?: boolean;
187
- }
188
- type SsrEntryLoaderStrategy = 'temp-file' | 'vm';
189
- type SsrEntryLoaderConfig = {
190
- /**
191
- * How the auto-injected `@module-federation/vite/ssrEntryLoader` evaluates
192
- * remote SSR entries.
193
- *
194
- * - `'temp-file'` (default when omitted): fetch the ESM graph, rewrite
195
- * specifiers, write temp files and `import()` them.
196
- * - `'vm'`: evaluate the graph with `vm.SourceTextModule`. Requires
197
- * `--experimental-vm-modules`; the loader emits a single warning and
198
- * falls back to `'temp-file'` when that API is unavailable.
199
- */
200
- strategy?: SsrEntryLoaderStrategy;
201
- };
202
- type HostInitInjectLocationOptions = 'entry' | 'html';
203
- interface PluginDevOptions {
204
- disableLiveReload?: boolean;
205
- disableHotTypesReload?: boolean;
206
- disableDynamicRemoteTypeHints?: boolean;
207
- /**
208
- * Controls cross-federation HMR for remote modules.
209
- *
210
- * - `false` / `undefined` — HMR disabled (default).
211
- * - `true` — HMR enabled with auto-detected strategy. When a framework
212
- * plugin with cross-federation HMR support is detected, broadcast/relay
213
- * is suppressed and the framework's native HMR handles updates:
214
- * - React (`@vitejs/plugin-react` / `@vitejs/plugin-react-swc`) — the
215
- * plugin serves a `/@react-refresh` proxy on remotes that delegates
216
- * to the host's `RefreshRuntime`, unifying the component registry.
217
- * - Vue (`@vitejs/plugin-vue` / `@vitejs/plugin-vue-jsx`) — the plugin
218
- * injects a `__VUE_HMR_RUNTIME__` guard into the host page so the
219
- * first-loaded (host) Vue runtime is pinned and remote-loaded Vue
220
- * copies cannot overwrite it.
221
- * For any host, the plugin also injects a script that clears the
222
- * federation `moduleCache` on `vite:beforeUpdate` so subsequent
223
- * `loadRemote()` calls return the freshly patched module.
224
- * Other frameworks fall back to full page reloads.
225
- * - `'full-reload'` — HMR enabled, always use full page reloads even when
226
- * a framework with native cross-federation HMR is detected.
227
- */
228
- remoteHmr?: boolean | 'full-reload';
229
- }
230
- interface RemoteTypeUrl {
231
- alias?: string;
232
- api: string;
233
- zip: string;
234
- }
235
- interface RemoteTypeUrls {
236
- [remoteName: string]: RemoteTypeUrl;
237
- }
238
- interface PluginDtsOptions {
239
- generateTypes?: boolean | DtsRemoteOptions;
240
- consumeTypes?: boolean | DtsHostOptions;
241
- tsConfigPath?: string;
242
- extraOptions?: Record<string, unknown>;
243
- implementation?: string;
244
- cwd?: string;
245
- displayErrorInTerminal?: boolean;
246
- }
247
- interface DtsRemoteOptions {
248
- tsConfigPath?: string;
249
- typesFolder?: string;
250
- compiledTypesFolder?: string;
251
- deleteTypesFolder?: boolean;
252
- additionalFilesToCompile?: string[];
253
- compilerInstance?: 'tsc' | 'vue-tsc' | 'tspc' | string;
254
- compileInChildProcess?: boolean;
255
- generateAPITypes?: boolean;
256
- extractThirdParty?: boolean | {
257
- exclude?: Array<string | RegExp>;
258
- };
259
- extractRemoteTypes?: boolean;
260
- abortOnError?: boolean;
261
- deleteTsConfig?: boolean;
262
- afterGenerate?: (options: moduleFederationPlugin.DtsGenerateTypesHookOptions) => Promise<void> | void;
263
- }
264
- interface DtsHostOptions {
265
- typesFolder?: string;
266
- abortOnError?: boolean;
267
- remoteTypesFolder?: string;
268
- deleteTypesFolder?: boolean;
269
- maxRetries?: number;
270
- consumeAPITypes?: boolean;
271
- runtimePkgs?: string[];
272
- remoteTypeUrls?: (() => Promise<RemoteTypeUrls>) | RemoteTypeUrls;
273
- timeout?: number;
274
- family?: 0 | 4 | 6;
275
- typesOnBuild?: boolean;
276
- }
277
- //#endregion
1
+ import { a as SsrEntryLoaderStrategy, i as SsrEntryLoaderConfig, n as PluginExperimentsOptions, o as TreeShakingConfig, r as PluginManifestOptions, t as ModuleFederationOptions } from "./normalizeModuleFederationOptions-DNUlv-AL.js";
278
2
  //#region src/index.d.ts
279
3
  declare function federation(mfUserOptions: ModuleFederationOptions): any[];
280
4
  declare function createModuleFederationConfig<T extends ModuleFederationOptions>(options: T): T;
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
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";
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-r5OfegUr.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";
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";
@@ -281,9 +281,17 @@ function isClientEnvironment(ctx) {
281
281
  * the legacy root `build.ssr` flag.
282
282
  */
283
283
  function isServerBuildContext(ctx, config) {
284
+ return isServerContext(ctx, Boolean(config?.build?.ssr));
285
+ }
286
+ /**
287
+ * Whether a hook runs for a server graph. Hooks without an environment context
288
+ * (Vite 5) use `legacySsr`, such as the root `build.ssr` flag or the load
289
+ * hook's `ssr` option.
290
+ */
291
+ function isServerContext(ctx, legacySsr) {
284
292
  const target = resolveEnvironmentConsumerTarget(ctx);
285
293
  if (target) return target === "server";
286
- return Boolean(config?.build?.ssr);
294
+ return legacySsr;
287
295
  }
288
296
  function resolveRemoteConsumer(ctx, hasMultiEnvironment) {
289
297
  if (!hasMultiEnvironment) return "unified";
@@ -730,9 +738,13 @@ function normalizeExperiments(experiments) {
730
738
  };
731
739
  }
732
740
  function normalizeSsrEntryLoader(ssrEntryLoader) {
733
- const strategy = ssrEntryLoader?.strategy;
734
- if (strategy !== "temp-file" && strategy !== "vm") return void 0;
735
- return { strategy };
741
+ if (!ssrEntryLoader) return void 0;
742
+ const normalized = {};
743
+ if (ssrEntryLoader.strategy === "temp-file" || ssrEntryLoader.strategy === "vm") normalized.strategy = ssrEntryLoader.strategy;
744
+ if (Number.isFinite(ssrEntryLoader.maxAgeMs)) normalized.maxAgeMs = ssrEntryLoader.maxAgeMs;
745
+ if (Number.isFinite(ssrEntryLoader.fetchTimeoutMs)) normalized.fetchTimeoutMs = ssrEntryLoader.fetchTimeoutMs;
746
+ if (Number.isFinite(ssrEntryLoader.fetchMaxBytes)) normalized.fetchMaxBytes = ssrEntryLoader.fetchMaxBytes;
747
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
736
748
  }
737
749
  let config;
738
750
  let explicitSharedKeys = /* @__PURE__ */ new Set();
@@ -3300,7 +3312,7 @@ function generateEagerWorkspaceSingletonExports(edges, namedExports, importSourc
3300
3312
  __mfApplyEagerShareExportsWhenReady(exportModule);
3301
3313
  export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
3302
3314
  }
3303
- function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false, mutableExports = [], deferredEntryFallback = false) {
3315
+ function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false, mutableExports = [], deferredEntryFallback = false, ssrLocalFallback = true) {
3304
3316
  const copiedExports = namedExports.filter((name) => !mutableExports.includes(name));
3305
3317
  const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
3306
3318
  const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
@@ -3340,7 +3352,7 @@ function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource
3340
3352
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});
3341
3353
  });
3342
3354
  })`;
3343
- const synchronousFallbackConditions = [...deferredEntryFallback ? [] : ["import.meta.env.SSR"], ...serveLocalFallback ? ["(import.meta.env.DEV && typeof __mfLocalShare !== 'undefined')"] : []];
3355
+ const synchronousFallbackConditions = [...ssrLocalFallback ? ["import.meta.env.SSR"] : [], ...serveLocalFallback ? ["(import.meta.env.DEV && typeof __mfLocalShare !== 'undefined')"] : []];
3344
3356
  const trackPendingLoad = `__mfTrackPendingShareLoad(${deferredEntryFallback ? deferredEntryLoad : deferredInitLoad});`;
3345
3357
  return `${declarations}
3346
3358
  const __mfApplyLazyShareExports = (mod) => {
@@ -3546,7 +3558,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
3546
3558
  exportLine = generateLazyWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
3547
3559
  } else if (usesDeferredEntryInjectedSingletonFallback) {
3548
3560
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
3549
- exportLine = generateLazyWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, false, liveNamedExports, true);
3561
+ exportLine = generateLazyWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, false, liveNamedExports, true, pkg !== REACT_DOM_CLIENT_SHARE);
3550
3562
  } else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
3551
3563
  else if (usesDeferredSingletonFallback) {
3552
3564
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
@@ -6221,9 +6233,23 @@ function getLazyRemotePendingExport() {
6221
6233
  };`;
6222
6234
  }
6223
6235
  function getEagerRemotePendingExport() {
6224
- return `export const __mf_remote_pending =
6236
+ return `export let __mf_remote_pending =
6225
6237
  __mfRemotePending ??
6226
- __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
6238
+ __mfStartRemoteLoad().then(__mfAssignRemoteModule);
6239
+ __mf_remote_pending.then(undefined, () => {
6240
+ let attempt;
6241
+ const retry = {
6242
+ then(onFulfilled, onRejected) {
6243
+ attempt ||= __mfStartRemoteLoad().then(__mfAssignRemoteModule, (error) => {
6244
+ attempt = undefined;
6245
+ throw error;
6246
+ });
6247
+ return attempt.then(onFulfilled, onRejected);
6248
+ },
6249
+ };
6250
+ if (__mfRemotePending) __mfRemotePending = retry;
6251
+ __mf_remote_pending = retry;
6252
+ });`;
6227
6253
  }
6228
6254
  function getServerThenExport() {
6229
6255
  return `export function then(onFulfilled, onRejected) {
@@ -6237,7 +6263,15 @@ function getServerThenExport() {
6237
6263
  __moduleExports: exportModule,
6238
6264
  __mf_remote_pending: __mfRemotePending,
6239
6265
  };
6240
- })
6266
+ }, () => ({
6267
+ get default() {
6268
+ return __mfDefaultExport;
6269
+ },
6270
+ get __moduleExports() {
6271
+ return exportModule;
6272
+ },
6273
+ __mf_remote_pending: { then: (resolve, reject) => __mf_remote_pending.then(resolve, reject) },
6274
+ }))
6241
6275
  .then(onFulfilled, onRejected);
6242
6276
  }`;
6243
6277
  }
@@ -6481,6 +6515,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
6481
6515
  let emittedFileName;
6482
6516
  let skipTransformIds = /* @__PURE__ */ new Set();
6483
6517
  let injectedTransformIds = /* @__PURE__ */ new Set();
6518
+ const virtualEntryCode = /* @__PURE__ */ new Map();
6484
6519
  const ignoredHtmlScriptSources = /* @__PURE__ */ new Set();
6485
6520
  let bootstrapDir = "";
6486
6521
  function skipSvelteKitSsrBuild() {
@@ -6866,7 +6901,12 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6866
6901
  }
6867
6902
  if (htmlFilePath) addHtmlScriptEntries(htmlFilePath);
6868
6903
  },
6869
- buildStart() {
6904
+ async buildStart() {
6905
+ if (inject === "entry" && waitsForInit && isClientEnvironment(this)) for (const entry of [...entryFiles]) {
6906
+ if (path$1.isAbsolute(entry)) continue;
6907
+ const resolved = await this.resolve(entry, void 0, { skipSelf: true }).catch(() => null);
6908
+ if (resolved && !resolved.external && (_command === "serve" || !resolved.id.startsWith("\0"))) addEntryFile(resolveProjectId(resolved.id));
6909
+ }
6870
6910
  if (_command === "serve") return;
6871
6911
  if (skipSvelteKitSsrBuild()) return;
6872
6912
  if (this.environment?.name === "ssr") return;
@@ -6972,11 +7012,18 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6972
7012
  };
6973
7013
  setTimeout(retry, 0);
6974
7014
  },
7015
+ load(id) {
7016
+ return virtualEntryCode.get(id);
7017
+ },
6975
7018
  transform(code, id) {
6976
7019
  if (skipSvelteKitSsrBuild()) return;
6977
7020
  if (viteConfig?.command === "build" && !waitsForInit) return;
6978
7021
  if (isSvelteKitServerModule(id)) return;
6979
- if (hasEntryBootstrapParam(id)) return;
7022
+ if (hasEntryBootstrapParam(id)) return {
7023
+ code,
7024
+ map: null,
7025
+ moduleSideEffects: true
7026
+ };
6980
7027
  if (normalizeModuleId(id).endsWith(".html")) return;
6981
7028
  const projectId = resolveProjectId(id);
6982
7029
  if (skipTransformIds.has(projectId)) return;
@@ -7010,7 +7057,11 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
7010
7057
  clientInjected = true;
7011
7058
  injectedTransformIds.add(projectId);
7012
7059
  if (!waitsForInit) return mapCodeToCodeWithSourcemap(`import ${JSON.stringify(getEntryPath())};\n` + code);
7013
- const entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
7060
+ let entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
7061
+ if (entrySrc.startsWith("\0")) {
7062
+ virtualEntryCode.set(entrySrc, code);
7063
+ entrySrc = toViteEncodedId(entrySrc.slice(1));
7064
+ }
7014
7065
  return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, { skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule }));
7015
7066
  }
7016
7067
  }
@@ -8083,7 +8134,7 @@ function ${helperName}(names) {
8083
8134
  }
8084
8135
  //#endregion
8085
8136
  //#region package.json
8086
- var version$1 = "1.23.2";
8137
+ var version$1 = "1.23.3";
8087
8138
  //#endregion
8088
8139
  //#region src/virtualModules/virtualExposesSSR.ts
8089
8140
  /**
@@ -10486,6 +10537,8 @@ function pluginSSRRemoteEntry(options) {
10486
10537
  return exposeKeys.every((key) => code.includes(JSON.stringify(key)));
10487
10538
  })?.fileName;
10488
10539
  };
10540
+ const isNuxtLike = () => isNuxtProject || isNuxtClientBase(getBasePath$1(viteConfig?.base));
10541
+ const findEmittedExposesChunk = (bundle) => Object.values(bundle).find((file) => file.type === "chunk" && file.facadeModuleId === virtualExposesSSRId)?.fileName;
10489
10542
  return [{
10490
10543
  name: "mf:ssr-remote-entry:pre",
10491
10544
  enforce: "pre",
@@ -10528,7 +10581,7 @@ function pluginSSRRemoteEntry(options) {
10528
10581
  const base = "/__mf_ssr__";
10529
10582
  const basePath = getBasePath$1(viteConfig?.base);
10530
10583
  const ssrEntryFileName = getSsrRemoteEntryFileName(options);
10531
- if (isNuxtProject || isNuxtClientBase(basePath)) server.middlewares.use((req, _res, next) => {
10584
+ if (isNuxtLike()) server.middlewares.use((req, _res, next) => {
10532
10585
  if (req.url?.replace(/\?.*/, "") === `${basePath}/${ssrEntryFileName}`) req.url = `${basePath}/__mf_ssr__/${ssrEntryFileName}`;
10533
10586
  next();
10534
10587
  });
@@ -10615,16 +10668,26 @@ function pluginSSRRemoteEntry(options) {
10615
10668
  fileName: ssrOutputFilename,
10616
10669
  preserveSignature: "strict"
10617
10670
  });
10671
+ else if (Object.keys(options.exposes).length > 0 && !isNuxtLike()) this.emitFile({
10672
+ type: "chunk",
10673
+ id: virtualExposesSSRId,
10674
+ name: "ssrExposes",
10675
+ preserveSignature: "strict"
10676
+ });
10618
10677
  },
10619
10678
  generateBundle: {
10620
10679
  order: "post",
10621
10680
  handler(_options, bundle) {
10622
10681
  const isRolldown = getIsRolldown(this);
10623
10682
  const environment = this.environment;
10624
- const exposesChunk = findNuxtExposesChunk(bundle);
10683
+ const exposesChunk = findNuxtExposesChunk(bundle) ?? findEmittedExposesChunk(bundle);
10625
10684
  if (!isRolldown && isSsrRemoteEntryBuild(environment)) {
10626
10685
  let source = getSsrRemoteEntrySource();
10627
- if (exposesChunk) source = source.replace(/import\("virtual:mf-exposes-ssr:[^"]+"\)/g, `import("./${exposesChunk}")`);
10686
+ if (exposesChunk) {
10687
+ let exposesImport = path$1.posix.relative(path$1.posix.dirname(ssrOutputFilename), exposesChunk);
10688
+ if (!exposesImport.startsWith(".")) exposesImport = `./${exposesImport}`;
10689
+ source = source.replace(/import\("virtual:mf-exposes-ssr:[^"]+"\)/g, `import("${exposesImport}")`);
10690
+ }
10628
10691
  this.emitFile({
10629
10692
  type: "asset",
10630
10693
  fileName: ssrOutputFilename,
@@ -11898,7 +11961,7 @@ export default __mfShared.default ?? __mfShared;`
11898
11961
  resolveImportPath(ssrEntryLoaderSpecifier);
11899
11962
  options.runtimePlugins.push([ssrEntryLoaderSpecifier, {
11900
11963
  resolvedShared,
11901
- ...options.ssrEntryLoader?.strategy ? { strategy: options.ssrEntryLoader.strategy } : {}
11964
+ ...options.ssrEntryLoader
11902
11965
  }]);
11903
11966
  } catch {}
11904
11967
  }
@@ -11927,7 +11990,7 @@ function withoutDynamicRemoteTypeHints(options) {
11927
11990
  }
11928
11991
  function loadPluginDts(options) {
11929
11992
  if (options.dts === false) return [];
11930
- return [import("./pluginDts-DnEX3cp_.js").then(({ default: pluginDts }) => pluginDts(options))];
11993
+ return [import("./pluginDts-CVyHPAEq.js").then(({ default: pluginDts }) => pluginDts(options))];
11931
11994
  }
11932
11995
  const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
11933
11996
  function isInjectExternalRuntimeCorePlugin(specifier) {
@@ -12077,7 +12140,11 @@ function federation(mfUserOptions) {
12077
12140
  const virtualModule = VirtualModule.findById(id);
12078
12141
  if (!virtualModule) return;
12079
12142
  if (command === "build" && (id.includes("__loadShare__") || id.includes("__loadRemote__"))) return;
12080
- return virtualModule.code;
12143
+ const code = virtualModule.code;
12144
+ if (code && id.includes("__loadShare__")) {
12145
+ if (isServerContext(this, loadOptions?.ssr === true)) return prependWorkspaceSingletonSsrImport(code);
12146
+ }
12147
+ return code;
12081
12148
  }
12082
12149
  },
12083
12150
  ...options.experiments.externalRuntime ? [pluginExternalRuntimeCore()] : [],
@@ -12337,8 +12404,7 @@ function federation(mfUserOptions) {
12337
12404
  const virtualModule = VirtualModule.findById(id);
12338
12405
  if (!virtualModule?.code) return null;
12339
12406
  let code = virtualModule.code;
12340
- const consumerTarget = resolveEnvironmentConsumerTarget(this);
12341
- if (consumerTarget === "server" || !consumerTarget && isSsrBuild) {
12407
+ if (isServerContext(this, isSsrBuild)) {
12342
12408
  const withSsrImport = prependWorkspaceSingletonSsrImport(code);
12343
12409
  if (withSsrImport !== code) {
12344
12410
  const pkg = getCachedLoadSharePkg(id);
@@ -0,0 +1,303 @@
1
+ import { moduleFederationPlugin } from "@module-federation/sdk";
2
+ import { ShareStrategy } from "@module-federation/runtime/types";
3
+ //#region src/utils/normalizeModuleFederationOptions.d.ts
4
+ interface RemoteObjectConfig {
5
+ type?: string;
6
+ name: string;
7
+ internalName?: string;
8
+ entry: string;
9
+ entryGlobalName?: string;
10
+ shareScope?: string | string[];
11
+ }
12
+ interface TreeShakingConfig {
13
+ mode: 'server-calc' | 'runtime-infer';
14
+ usedExports?: string[];
15
+ }
16
+ interface PluginManifestOptions {
17
+ filePath?: string;
18
+ disableAssetsAnalyze?: boolean;
19
+ fileName?: string;
20
+ additionalData?: (options: {
21
+ stats: Record<string, unknown>;
22
+ manifest?: Record<string, unknown>;
23
+ pluginOptions: Record<string, unknown>;
24
+ compiler?: unknown;
25
+ compilation?: unknown;
26
+ bundler: 'vite';
27
+ }) => Promise<Record<string, unknown> | void> | Record<string, unknown> | void;
28
+ }
29
+ type ModuleFederationOptions = {
30
+ exposes?: Record<string, string | {
31
+ import: string;
32
+ }> | undefined;
33
+ filename?: string;
34
+ /**
35
+ * Exact file name of the SSR remote entry emitted next to `filename`.
36
+ * Defaults to `<filename base>.ssr<ext>` so it never clobbers the browser
37
+ * entry when both builds share an output directory. `[hash]` is not supported.
38
+ */
39
+ ssrFilename?: string;
40
+ library?: any;
41
+ name: string;
42
+ remotes?: Record<string, string | RemoteObjectConfig> | undefined;
43
+ runtime?: any;
44
+ shareScope?: string | string[];
45
+ /**
46
+ * Override the public path used for remote entries
47
+ * Defaults to Vite's base config or "auto" if base is empty
48
+ */
49
+ publicPath?: string;
50
+ /**
51
+ * Controls whether all CSS assets from the bundle should be added to every exposed module.
52
+ * When false (default), the plugin will not process any CSS assets.
53
+ * When true, all CSS assets are bundled into every exposed module.
54
+ */
55
+ bundleAllCSS?: boolean;
56
+ /** Directory reserved for deploy-service generated secondary shared artifacts. */
57
+ treeShakingDir?: string;
58
+ /** Whether inferred usedExports metadata is injected into generated runtime records. */
59
+ injectTreeShakingUsedExports?: boolean;
60
+ treeShakingSharedPlugins?: string[];
61
+ treeShakingSharedExcludePlugins?: string[];
62
+ shared?: string[] | Record<string, string | {
63
+ name?: string;
64
+ version?: string;
65
+ shareScope?: string;
66
+ request?: moduleFederationPlugin.SharedConfig['request'];
67
+ shareKey?: moduleFederationPlugin.SharedConfig['shareKey'];
68
+ singleton?: boolean;
69
+ eager?: boolean;
70
+ requiredVersion?: moduleFederationPlugin.SharedConfig['requiredVersion'];
71
+ strictVersion?: boolean;
72
+ allowNodeModulesSuffixMatch?: boolean;
73
+ /** Suppress the missing local dependency warning for `import: false` shares. */
74
+ suppressMissingImportWarning?: boolean;
75
+ treeShaking?: TreeShakingConfig;
76
+ import?: moduleFederationPlugin.SharedConfig['import'];
77
+ }> | undefined;
78
+ runtimePlugins?: Array<string | [string, Record<string, unknown>]>;
79
+ getPublicPath?: string;
80
+ implementation?: string;
81
+ manifest?: PluginManifestOptions | boolean;
82
+ dev?: boolean | PluginDevOptions;
83
+ dts?: boolean | PluginDtsOptions;
84
+ shareStrategy?: ShareStrategy;
85
+ ignoreOrigin?: boolean;
86
+ virtualModuleDir?: string;
87
+ hostInitInjectLocation?: HostInitInjectLocationOptions;
88
+ /**
89
+ * Timeout for parsing modules in seconds.
90
+ * Defaults to 10 seconds.
91
+ */
92
+ moduleParseTimeout?: number;
93
+ /**
94
+ * Idle timeout for parsing modules in seconds. When set, the timeout resets
95
+ * on every parsed module and only fires when there has been no module activity
96
+ * for the configured duration. Prefer this over `moduleParseTimeout` for large
97
+ * codebases where the total build time may exceed the fixed timeout.
98
+ */
99
+ moduleParseIdleTimeout?: number;
100
+ /**
101
+ * Allows generate additional remoteEntry file for "var" host environment
102
+ */
103
+ varFilename?: string;
104
+ /**
105
+ * Target environment for the build to enable effective tree-shaking.
106
+ *
107
+ * @see https://module-federation.io/configure/experiments#target
108
+ * @default 'web' (or 'node' if build.ssr is enabled)
109
+ */
110
+ target?: 'web' | 'node';
111
+ /**
112
+ * Removes remote-consumption support from the federation runtime.
113
+ * Only enable this for builds that never load remotes.
114
+ *
115
+ * @default false
116
+ */
117
+ disableRemote?: boolean;
118
+ /**
119
+ * Removes shared-dependency support from the federation runtime.
120
+ * Only enable this when the build has no shared dependencies.
121
+ *
122
+ * @default false
123
+ */
124
+ disableShared?: boolean;
125
+ /**
126
+ * Removes snapshot support, including manifest-based remotes, preload,
127
+ * dynamic type hints, HMR, and devtools integration.
128
+ *
129
+ * @default false (true for Node/SSR builds)
130
+ */
131
+ disableSnapshot?: boolean;
132
+ /**
133
+ * Additional packages to mark as external in the SSR remote entry build.
134
+ * Shared packages and MF runtime packages are external by default. Use this to
135
+ * add any other Node-only packages that should not be bundled into the SSR entry.
136
+ * To emit a self-contained SSR entry (loadable by hosts that cannot resolve the
137
+ * MF runtime from Node, such as the `@module-federation/sdk` reference loader),
138
+ * opt the MF runtime packages back in through Vite's `ssr.noExternal`.
139
+ */
140
+ ssrExternals?: string[];
141
+ /**
142
+ * Options for the auto-injected `@module-federation/vite/ssrEntryLoader`.
143
+ * When omitted, the loader uses the `'temp-file'` strategy. Set
144
+ * `strategy: 'vm'` to opt into `vm.SourceTextModule` evaluation while keeping
145
+ * the computed `resolvedShared` map. Optional `maxAgeMs`, `fetchTimeoutMs`,
146
+ * and `fetchMaxBytes` are forwarded to the loader when set.
147
+ */
148
+ ssrEntryLoader?: SsrEntryLoaderConfig;
149
+ /**
150
+ * Experimental Module Federation capabilities.
151
+ *
152
+ * @see https://module-federation.io/configure/experiments
153
+ */
154
+ experiments?: PluginExperimentsOptions;
155
+ };
156
+ interface PluginExperimentsOptions {
157
+ /**
158
+ * Treat `@module-federation/runtime-core` as an external that reads
159
+ * `globalThis._FEDERATION_RUNTIME_CORE` at runtime. Pair with a host that
160
+ * sets `provideExternalRuntime: true`.
161
+ */
162
+ externalRuntime?: boolean;
163
+ /**
164
+ * Injects a local runtime plugin that publishes `runtime-core` on
165
+ * `globalThis._FEDERATION_RUNTIME_CORE`. Set it on exactly one container
166
+ * per page; that container may also `exposes`.
167
+ */
168
+ provideExternalRuntime?: boolean;
169
+ /** Generate the React SSR/hydration island capability for eligible exposes. */
170
+ ssrMode?: 'ISLAND';
171
+ /**
172
+ * The host provides every shared dependency; remotes bring none. Shared keys
173
+ * are resolved by a native browser import map instead of the Module
174
+ * Federation runtime: the host emits one entry chunk per shared key and
175
+ * injects `<script type="importmap">`, remotes keep shared imports as bare
176
+ * specifiers and emit one fixed-name entry per expose plus a standard
177
+ * `mf-manifest.json` (without `remoteEntry`) the host maps from.
178
+ *
179
+ * Shared modules become ordinary static ES imports, so there is no
180
+ * `loadShare` glue and no `eager` is needed for code that reads a shared
181
+ * value at module-evaluation time. There is no version negotiation and no
182
+ * runtime API: `requiredVersion`, `strictVersion`, `shareStrategy`,
183
+ * `runtimePlugins` and `manifest` are ignored.
184
+ *
185
+ * @see https://github.com/module-federation/vite/issues/1381
186
+ */
187
+ hostProvidesAllShared?: boolean;
188
+ }
189
+ type SsrEntryLoaderStrategy = 'temp-file' | 'vm';
190
+ type SsrEntryLoaderConfig = {
191
+ /**
192
+ * How the auto-injected `@module-federation/vite/ssrEntryLoader` evaluates
193
+ * remote SSR entries.
194
+ *
195
+ * - `'temp-file'` (default when omitted): fetch the ESM graph, rewrite
196
+ * specifiers, write temp files and `import()` them. Works on stock Node;
197
+ * shared packages are pinned to the host's copies via `resolvedShared`
198
+ * (no version negotiation).
199
+ * - `'vm'`: evaluate the graph with `vm.SourceTextModule` and link bare
200
+ * shared imports through the host's federation share scope (`loadShare`),
201
+ * restoring version negotiation. Requires `--experimental-vm-modules`; the
202
+ * loader emits a single warning and falls back to `'temp-file'` when that
203
+ * API is unavailable.
204
+ */
205
+ strategy?: SsrEntryLoaderStrategy;
206
+ /**
207
+ * Re-check each remote's manifest when the cached SSR entry resolution is
208
+ * older than this many milliseconds. When the manifest's version changes
209
+ * (remote redeployed at the same URL), the loader drops its caches for that
210
+ * remote so subsequent loads use the new build. Omit to cache until process
211
+ * exit or an explicit `revalidate()` call. Only manifest-resolved entries
212
+ * can be revalidated this way — convention-resolved entries have no version
213
+ * source.
214
+ */
215
+ maxAgeMs?: number;
216
+ /**
217
+ * Maximum time in milliseconds for each SSR network request. Defaults to
218
+ * 10 seconds. Set to `0` to disable the timeout.
219
+ */
220
+ fetchTimeoutMs?: number;
221
+ /**
222
+ * Maximum response body size in bytes for each SSR network request. Defaults
223
+ * to 10 MiB. Set to `0` to disable the limit.
224
+ */
225
+ fetchMaxBytes?: number;
226
+ };
227
+ type HostInitInjectLocationOptions = 'entry' | 'html';
228
+ interface PluginDevOptions {
229
+ disableLiveReload?: boolean;
230
+ disableHotTypesReload?: boolean;
231
+ disableDynamicRemoteTypeHints?: boolean;
232
+ /**
233
+ * Controls cross-federation HMR for remote modules.
234
+ *
235
+ * - `false` / `undefined` — HMR disabled (default).
236
+ * - `true` — HMR enabled with auto-detected strategy. When a framework
237
+ * plugin with cross-federation HMR support is detected, broadcast/relay
238
+ * is suppressed and the framework's native HMR handles updates:
239
+ * - React (`@vitejs/plugin-react` / `@vitejs/plugin-react-swc`) — the
240
+ * plugin serves a `/@react-refresh` proxy on remotes that delegates
241
+ * to the host's `RefreshRuntime`, unifying the component registry.
242
+ * - Vue (`@vitejs/plugin-vue` / `@vitejs/plugin-vue-jsx`) — the plugin
243
+ * injects a `__VUE_HMR_RUNTIME__` guard into the host page so the
244
+ * first-loaded (host) Vue runtime is pinned and remote-loaded Vue
245
+ * copies cannot overwrite it.
246
+ * For any host, the plugin also injects a script that clears the
247
+ * federation `moduleCache` on `vite:beforeUpdate` so subsequent
248
+ * `loadRemote()` calls return the freshly patched module.
249
+ * Other frameworks fall back to full page reloads.
250
+ * - `'full-reload'` — HMR enabled, always use full page reloads even when
251
+ * a framework with native cross-federation HMR is detected.
252
+ */
253
+ remoteHmr?: boolean | 'full-reload';
254
+ }
255
+ interface RemoteTypeUrl {
256
+ alias?: string;
257
+ api: string;
258
+ zip: string;
259
+ }
260
+ interface RemoteTypeUrls {
261
+ [remoteName: string]: RemoteTypeUrl;
262
+ }
263
+ interface PluginDtsOptions {
264
+ generateTypes?: boolean | DtsRemoteOptions;
265
+ consumeTypes?: boolean | DtsHostOptions;
266
+ tsConfigPath?: string;
267
+ extraOptions?: Record<string, unknown>;
268
+ implementation?: string;
269
+ cwd?: string;
270
+ displayErrorInTerminal?: boolean;
271
+ }
272
+ interface DtsRemoteOptions {
273
+ tsConfigPath?: string;
274
+ typesFolder?: string;
275
+ compiledTypesFolder?: string;
276
+ deleteTypesFolder?: boolean;
277
+ additionalFilesToCompile?: string[];
278
+ compilerInstance?: 'tsc' | 'vue-tsc' | 'tspc' | string;
279
+ compileInChildProcess?: boolean;
280
+ generateAPITypes?: boolean;
281
+ extractThirdParty?: boolean | {
282
+ exclude?: Array<string | RegExp>;
283
+ };
284
+ extractRemoteTypes?: boolean;
285
+ abortOnError?: boolean;
286
+ deleteTsConfig?: boolean;
287
+ afterGenerate?: (options: moduleFederationPlugin.DtsGenerateTypesHookOptions) => Promise<void> | void;
288
+ }
289
+ interface DtsHostOptions {
290
+ typesFolder?: string;
291
+ abortOnError?: boolean;
292
+ remoteTypesFolder?: string;
293
+ deleteTypesFolder?: boolean;
294
+ maxRetries?: number;
295
+ consumeAPITypes?: boolean;
296
+ runtimePkgs?: string[];
297
+ remoteTypeUrls?: (() => Promise<RemoteTypeUrls>) | RemoteTypeUrls;
298
+ timeout?: number;
299
+ family?: 0 | 4 | 6;
300
+ typesOnBuild?: boolean;
301
+ }
302
+ //#endregion
303
+ export { SsrEntryLoaderStrategy as a, SsrEntryLoaderConfig as i, PluginExperimentsOptions as n, TreeShakingConfig as o, PluginManifestOptions as r, ModuleFederationOptions as t };
@@ -1,5 +1,5 @@
1
1
  import { l as normalizePathForImport, n as mfError, t as createModuleFederationError } from "./logger-DOwfTlw5.js";
2
- import { g as resolveImportPath, u as hasPackageDependency } from "./dtsConstants-r5OfegUr.js";
2
+ import { g as resolveImportPath, u as hasPackageDependency } from "./dtsConstants-DSTzyKSG.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,5 @@
1
1
  import { a as CodeRewriter, i as createCodePositionMap, r as mfWarn, s as EXTERNAL_URL_RE } from "./logger-DOwfTlw5.js";
2
+ import { simpleJoinRemoteEntry } from "@module-federation/sdk";
2
3
  //#region src/utils/fetchWithTimeout.ts
3
4
  const DEFAULT_SSR_FETCH_TIMEOUT_MS = 1e4;
4
5
  const DEFAULT_SSR_FETCH_MAX_BYTES = 10 * 1024 * 1024;
@@ -361,15 +362,14 @@ function getEntryFilename(entryUrl) {
361
362
  }
362
363
  function resolveEntryAssetUrl(entry, manifestUrl) {
363
364
  const base = manifestUrl.replace(/\/[^/]+$/, "/");
364
- return new URL(`${entry.path || ""}${entry.name}`, base).href;
365
+ return new URL(simpleJoinRemoteEntry(entry.path || "", entry.name), base).href;
365
366
  }
366
367
  function resolveSSREntryUrl(manifest, manifestUrl) {
367
368
  const entry = parseManifestEntry(manifest.metaData?.ssrRemoteEntry);
368
369
  if (!entry) return null;
369
370
  const base = manifestUrl.replace(/\/[^/]+$/, "/");
370
- const entryPath = entry.path + entry.name;
371
371
  return {
372
- url: new URL(entryPath, base).href,
372
+ url: new URL(simpleJoinRemoteEntry(entry.path, entry.name), base).href,
373
373
  type: entry.type,
374
374
  versionKey: computeManifestVersionKey(manifest)
375
375
  };
@@ -834,7 +834,7 @@ async function importTempModule(filePath, versionKey) {
834
834
  let warnedVmUnavailable = false;
835
835
  let vmStrategyModulePromise;
836
836
  function getVmStrategyModule() {
837
- if (!vmStrategyModulePromise) vmStrategyModulePromise = import("./ssrVmStrategy-COMHOCN2.js");
837
+ if (!vmStrategyModulePromise) vmStrategyModulePromise = import("./ssrVmStrategy-Dk5xXVvR.js");
838
838
  return vmStrategyModulePromise;
839
839
  }
840
840
  /**
@@ -902,9 +902,12 @@ async function loadSSRRemoteEntry(ssrEntry, options, rootEntryUrl) {
902
902
  const cacheDir = await getSSRCacheDir();
903
903
  mkdirSync(cacheDir, { recursive: true });
904
904
  const sharedPkgMap = new Map(Object.entries(resolvedShared));
905
- const extension = type === "commonjs-module" || type === "commonjs" ? ".js" : ".mjs";
905
+ const isCommonJs = type === "commonjs-module" || type === "commonjs";
906
+ const extension = isCommonJs ? ".cjs" : ".mjs";
906
907
  try {
907
- return await importTempModule(await fetchEsmGraphToTempFile(url, cacheDir, sharedPkgMap, versionKey, options.fetchTimeoutMs, getSsrTransformContextKey(resolvedShared, options.shareScopeName), options.fetchMaxBytes, extension, rootEntryUrl), versionKey);
908
+ const tmpFile = await fetchEsmGraphToTempFile(url, cacheDir, sharedPkgMap, versionKey, options.fetchTimeoutMs, getSsrTransformContextKey(resolvedShared, options.shareScopeName), options.fetchMaxBytes, extension, rootEntryUrl);
909
+ if (isCommonJs) return (await _module()).createRequire(import.meta.url)(tmpFile);
910
+ return await importTempModule(tmpFile, versionKey);
908
911
  } catch (error) {
909
912
  if (isSsrEntryHttpError(error) || isSsrFetchBodyTooLargeError(error)) throw error;
910
913
  warnStrategyFallback("temp-file", url, "the federation runtime's loader", error);
@@ -941,7 +944,10 @@ function ssrEntryLoaderPlugin(options = {}) {
941
944
  } : resolved;
942
945
  const ssrEntry = await getSSREntry(remoteInfo.entry, loadOptions.maxAgeMs, loadOptions.fetchTimeoutMs, loadOptions.fetchMaxBytes);
943
946
  if (!ssrEntry) return;
944
- const mod = await loadSSRRemoteEntry(ssrEntry, loadOptions, remoteInfo.entry);
947
+ const mod = await loadSSRRemoteEntry(ssrEntry.url === remoteInfo.entry && remoteInfo.type ? {
948
+ ...ssrEntry,
949
+ type: remoteInfo.type
950
+ } : ssrEntry, loadOptions, remoteInfo.entry);
945
951
  if (!mod) return;
946
952
  return mod;
947
953
  }
@@ -1,5 +1,5 @@
1
1
  import { t as findSharedKey } from "./sharedKeyMatcher-Od_nYxJA.js";
2
- import { c as readResponseTextBounded, n as neutralizeBrowserPreloadHelpers, s as fetchWithTimeout, t as SsrEntryHttpError } from "./ssrEntryLoader-DEH3eV1e.js";
2
+ import { c as readResponseTextBounded, n as neutralizeBrowserPreloadHelpers, s as fetchWithTimeout, t as SsrEntryHttpError } from "./ssrEntryLoader-DjZj-5Lw.js";
3
3
  //#region src/utils/ssrVmStrategy.ts
4
4
  /**
5
5
  * vm.SourceTextModule strategy for loading remote SSR entries.
@@ -1,30 +1,5 @@
1
+ import { i as SsrEntryLoaderConfig } from "../normalizeModuleFederationOptions-DNUlv-AL.js";
1
2
  //#region src/utils/ssrEntryLoader.d.ts
2
- /**
3
- * MF runtime plugin that intercepts the `loadEntry` lifecycle hook on the
4
- * server and loads the SSR-compatible remote entry instead of the browser one.
5
- *
6
- * This completely replaces the need for any `@module-federation/sdk` patches.
7
- * The `loadEntry` hook is emitted by `runtime-core` before it falls through to
8
- * `loadScriptNode` — if the hook returns a value, the runtime uses it directly.
9
- *
10
- * Strategy:
11
- * - In Node (detected through process.versions.node), fetch the remote's mf-manifest.json
12
- * to discover the ssrRemoteEntry URL and its type.
13
- * - ESM entry: use a dynamic `import()` — the SSR entry has no browser
14
- * globals and all shared packages are external.
15
- * - Dev mode (Vite 8+ only): use `ModuleRunner` with an HTTP transport backed
16
- * by the remote's `/__mf_runner__` endpoint. This fetches fully-transformed
17
- * module source through Vite's plugin pipeline, avoiding serialisation which
18
- * cannot faithfully represent React components or closures.
19
- *
20
- * Dev mode on Vite < 8 is NOT supported by this integration because the
21
- * cross-process `fetchModule` proxy uses Vite 8's environment APIs.
22
- * `ModuleRunner` itself is available in earlier Vite versions, but an older
23
- * remote needs a different transport and server endpoint.
24
- *
25
- * Exported as a plain factory function so it can be serialised into the
26
- * generated runtimePlugins list in virtualRemotes.ts.
27
- */
28
3
  interface RemoteInfo {
29
4
  name: string;
30
5
  entry: string;
@@ -63,7 +38,7 @@ declare function neutralizeBrowserPreloadHelpers(code: string): string;
63
38
  *
64
39
  * The plugin is also injected automatically for SSR contexts by the vite plugin.
65
40
  */
66
- interface SsrEntryLoaderOptions {
41
+ interface SsrEntryLoaderOptions extends SsrEntryLoaderConfig {
67
42
  /**
68
43
  * Pre-resolved absolute file paths for common shared packages, keyed by
69
44
  * bare specifier. Populated at build time by the Vite plugin from the MF
@@ -72,43 +47,11 @@ interface SsrEntryLoaderOptions {
72
47
  * in remote SSR entry temp files — no runtime createRequire walk-up needed.
73
48
  */
74
49
  resolvedShared?: Record<string, string>;
75
- /**
76
- * How to evaluate remote SSR entries on the server.
77
- *
78
- * - `'temp-file'` (default): fetch the ESM graph, rewrite specifiers, write
79
- * temp files and `import()` them. Works on stock Node; shared packages are
80
- * pinned to the host's copies via `resolvedShared` (no version negotiation).
81
- * - `'vm'`: evaluate the graph with `vm.SourceTextModule` and link bare
82
- * shared imports through the host's federation share scope (`loadShare`),
83
- * restoring version negotiation. Requires `--experimental-vm-modules`;
84
- * falls back to `'temp-file'` when unavailable.
85
- */
86
- strategy?: 'temp-file' | 'vm';
87
50
  /**
88
51
  * Share scope consulted by the `'vm'` strategy when linking bare imports.
89
52
  * Defaults to `'default'`.
90
53
  */
91
54
  shareScopeName?: string;
92
- /**
93
- * Re-check each remote's manifest when the cached SSR entry resolution is
94
- * older than this many milliseconds. When the manifest's version changes
95
- * (remote redeployed at the same URL), the loader drops its caches for that
96
- * remote so subsequent loads use the new build. Omit to cache until process
97
- * exit or an explicit `revalidate()` call. Only manifest-resolved entries
98
- * can be revalidated this way — convention-resolved entries have no version
99
- * source.
100
- */
101
- maxAgeMs?: number;
102
- /**
103
- * Maximum time in milliseconds for each SSR network request. Defaults to
104
- * 10 seconds. Set to `0` to disable the timeout.
105
- */
106
- fetchTimeoutMs?: number;
107
- /**
108
- * Maximum response body size in bytes for each SSR network request. Defaults
109
- * to 10 MiB. Set to `0` to disable the limit.
110
- */
111
- fetchMaxBytes?: number;
112
55
  }
113
56
  declare function ssrEntryLoaderPlugin(options?: SsrEntryLoaderOptions): {
114
57
  name: string;
@@ -1,2 +1,2 @@
1
- import { i as ssrEntryLoaderPlugin, n as neutralizeBrowserPreloadHelpers, r as revalidate, t as SsrEntryHttpError } from "../ssrEntryLoader-DEH3eV1e.js";
1
+ import { i as ssrEntryLoaderPlugin, n as neutralizeBrowserPreloadHelpers, r as revalidate, t as SsrEntryHttpError } from "../ssrEntryLoader-DjZj-5Lw.js";
2
2
  export { SsrEntryHttpError, ssrEntryLoaderPlugin as default, neutralizeBrowserPreloadHelpers, revalidate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.23.2",
3
+ "version": "1.23.3",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",