@module-federation/vite 1.23.4 → 1.23.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  <br />
10
10
 
11
11
  <a href="https://github.com/sponsors/gioboa">
12
- <img src="./docs/sponsors.png" alt="Sponsors" />
12
+ <img src="./docs/sponsors.png" alt="Sponsors" width="677" />
13
13
  </a>
14
14
 
15
15
  ## Become a sponsor
@@ -257,6 +257,21 @@ You can specify the place the host initialization file is injected with the **ho
257
257
  The **moduleParseTimeout** option allows you to configure the maximum time to wait for module parsing during the build process.
258
258
  The **moduleParseIdleTimeout** option is an alternative that resets the timer on every parsed module. It only fires when there has been no module activity for the configured duration, making it suitable for large codebases where the total build time exceeds the fixed timeout.
259
259
 
260
+ ## SSR runtime initialization
261
+
262
+ For applications with configured remotes, SSR entries and modules importing
263
+ `@module-federation/runtime` initialize the owning runtime before plain
264
+ `getInstance()` or `loadRemote()` calls run. Startup registers remotes and shares
265
+ without fetching remote entries or manifests, or requesting a root expose. Remote
266
+ loading stays lazy, including with `loaded-first`. Apps without remotes receive no
267
+ SSR host bootstrap. Cold development SSR follows the existing Vite 8+ support gate;
268
+ independent SSR builds are supported on Vite 5–8.
269
+
270
+ Dependencies externalized by Vite keep Node's own runtime resolution. Their runtime
271
+ imports are not bound to the application's instance by this bootstrap.
272
+ Include runtime-consuming dependencies in Vite's `ssr.noExternal` when they need
273
+ to use the application's runtime instance.
274
+
260
275
  ## SSR entry loading strategy
261
276
 
262
277
  SSR hosts can choose how HTTP ESM remote entries are evaluated during build and preview:
@@ -1,10 +1,11 @@
1
- import { d as getNodeModulesSuffix, r as getSharedRuntimeKey } from "./sharedKeyMatcher-Od_nYxJA.js";
2
- import { r as mfWarn, t as createModuleFederationError } from "./logger-DOwfTlw5.js";
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";
3
3
  import { existsSync, readFileSync, readdirSync, realpathSync } from "fs";
4
4
  import { createRequire } from "module";
5
5
  import * as path$1 from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "url";
7
7
  import { createHash } from "node:crypto";
8
+ import { isIPv6 } from "node:net";
8
9
  //#region src/utils/reactShares.ts
9
10
  /** Property under which React 19 exposes its internals object. */
10
11
  const REACT_CLIENT_INTERNALS_KEY = "__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE";
@@ -37,6 +38,7 @@ function getDependencyCacheKey(cwd, dependencyName) {
37
38
  const installedPackageJsonCache = /* @__PURE__ */ new Map();
38
39
  const dependentsLookupCache = /* @__PURE__ */ new Map();
39
40
  const reachableDependencyNames = /* @__PURE__ */ new Map();
41
+ const pnpmStorePackageIndexCache = /* @__PURE__ */ new Map();
40
42
  function setPackageDetectionCwd(cwd) {
41
43
  packageDetectionCwd = cwd;
42
44
  }
@@ -93,22 +95,34 @@ function substituteExportsWildcard(target, patternMatch) {
93
95
  }
94
96
  return target;
95
97
  }
98
+ /** Splits an exports pattern at its wildcard. Node substitutes only the first one, so a second never matches. */
99
+ function splitExportsPattern(pattern) {
100
+ const wildcardIndex = pattern.indexOf("*");
101
+ if (wildcardIndex === -1) return void 0;
102
+ const trailer = pattern.slice(wildcardIndex + 1);
103
+ if (trailer.includes("*")) return void 0;
104
+ return {
105
+ base: pattern.slice(0, wildcardIndex),
106
+ trailer
107
+ };
108
+ }
109
+ /** The text `value` substitutes for the wildcard of a pattern split by `splitExportsPattern`. */
110
+ function matchExportsPatternPart(value, { base, trailer }) {
111
+ if (!value.startsWith(base) || !value.endsWith(trailer)) return void 0;
112
+ if (value.length <= base.length + trailer.length) return void 0;
113
+ return value.slice(base.length, value.length - trailer.length);
114
+ }
96
115
  function matchExportsSubpath(record, subpath) {
97
116
  if (subpath in record) return record[subpath];
98
117
  let bestKey;
99
118
  let bestBaseLength = -1;
100
119
  let bestKeyLength = -1;
101
120
  for (const key of Object.keys(record)) {
102
- const wildcardIndex = key.indexOf("*");
103
- if (wildcardIndex === -1) continue;
104
- const patternBase = key.slice(0, wildcardIndex);
105
- const patternTrailer = key.slice(wildcardIndex + 1);
106
- if (patternTrailer.includes("*")) continue;
107
- if (!subpath.startsWith(patternBase) || !subpath.endsWith(patternTrailer)) continue;
108
- if (subpath.length <= patternBase.length + patternTrailer.length) continue;
109
- if (patternBase.length > bestBaseLength || patternBase.length === bestBaseLength && key.length > bestKeyLength) {
121
+ const pattern = splitExportsPattern(key);
122
+ if (!pattern || matchExportsPatternPart(subpath, pattern) === void 0) continue;
123
+ if (pattern.base.length > bestBaseLength || pattern.base.length === bestBaseLength && key.length > bestKeyLength) {
110
124
  bestKey = key;
111
- bestBaseLength = patternBase.length;
125
+ bestBaseLength = pattern.base.length;
112
126
  bestKeyLength = key.length;
113
127
  }
114
128
  }
@@ -139,6 +153,74 @@ function isPackageExportAvailable(pkg, opts = {}) {
139
153
  if (installed?.packageJson.exports == null) return true;
140
154
  return resolveExportsEntry(getPackageExportsTarget(pkg, packageName, installed.packageJson.exports), opts.conditions) !== void 0;
141
155
  }
156
+ function stripRelativePrefix(target) {
157
+ return normalizePathForImport(target).replace(/^\.\//, "");
158
+ }
159
+ /**
160
+ * Specifiers the installed package publishes for the file at `relFilePath` — a path below the
161
+ * package root, such as `dist/button.js` — ordered most specific first.
162
+ *
163
+ * `exports` maps specifiers to files, so a specifier rebuilt from a resolved path is only valid
164
+ * when the package happens to publish its files at the paths they occupy on disk. A package that
165
+ * remaps directories (`"./*": "./dist/*.js"`) publishes `pkg/button` and never
166
+ * `pkg/dist/button.js`, so the rebuilt specifier names a file the package does not export.
167
+ * Reversing the map recovers the specifiers that do resolve back to that file.
168
+ *
169
+ * Candidates are ordered by the same precedence `matchExportsSubpath` applies when resolving
170
+ * forwards — exact keys, then the longest pattern prefix, then the longest key — so a caller
171
+ * that takes the first match picks the same specifier for a file in every build, and in every
172
+ * container that shares the package.
173
+ *
174
+ * Empty when the package exports nothing that resolves to the file, which is the case for its
175
+ * internals and for subpaths an explicit `null` blocks. Lenient when the package cannot be found
176
+ * or has no `exports`, matching `isPackageExportAvailable`: every file is then reachable at its
177
+ * own path, so the path is the specifier.
178
+ */
179
+ function getPackageExportSpecifiersForFile(packageName, relFilePath, opts = {}) {
180
+ const file = `./${stripRelativePrefix(relFilePath)}`;
181
+ const toSpecifier = (subpath) => subpath === "." ? packageName : `${packageName}${subpath.slice(1)}`;
182
+ const exportsField = getInstalledPackageJson(packageName, opts)?.packageJson.exports;
183
+ if (exportsField == null) return [toSpecifier(file)];
184
+ if (typeof exportsField === "string") return stripRelativePrefix(exportsField) === stripRelativePrefix(file) ? [packageName] : [];
185
+ if (typeof exportsField !== "object") return [];
186
+ const record = exportsField;
187
+ const subpathKeys = Object.keys(record).filter((key) => key.startsWith("."));
188
+ if (subpathKeys.length === 0) {
189
+ const target = resolveExportsEntry(record, opts.conditions);
190
+ return typeof target === "string" && stripRelativePrefix(target) === stripRelativePrefix(file) ? [packageName] : [];
191
+ }
192
+ const candidates = [];
193
+ for (const key of subpathKeys) {
194
+ if (!key.includes("*")) {
195
+ candidates.push({
196
+ subpath: key,
197
+ isPattern: false,
198
+ baseLength: key.length,
199
+ keyLength: key.length
200
+ });
201
+ continue;
202
+ }
203
+ const keyPattern = splitExportsPattern(key);
204
+ if (!keyPattern) continue;
205
+ const target = resolveExportsEntry(record[key], opts.conditions);
206
+ const targetPattern = typeof target === "string" ? splitExportsPattern(target) : void 0;
207
+ if (!targetPattern) continue;
208
+ const patternMatch = matchExportsPatternPart(file, targetPattern);
209
+ if (patternMatch === void 0) continue;
210
+ candidates.push({
211
+ subpath: keyPattern.base + patternMatch + keyPattern.trailer,
212
+ isPattern: true,
213
+ baseLength: keyPattern.base.length,
214
+ keyLength: key.length
215
+ });
216
+ }
217
+ const verified = candidates.filter((candidate) => {
218
+ const target = resolveExportsEntry(getPackageExportsTarget(toSpecifier(candidate.subpath), packageName, record), opts.conditions);
219
+ return typeof target === "string" && stripRelativePrefix(target) === stripRelativePrefix(file);
220
+ });
221
+ verified.sort((a, b) => Number(a.isPattern) - Number(b.isPattern) || b.baseLength - a.baseLength || b.keyLength - a.keyLength || (a.subpath < b.subpath ? -1 : a.subpath > b.subpath ? 1 : 0));
222
+ return [...new Set(verified.map((candidate) => toSpecifier(candidate.subpath)))];
223
+ }
142
224
  /**
143
225
  * Escaping rules:
144
226
  * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
@@ -414,7 +496,6 @@ function getInstalledPackageJson(pkg, opts) {
414
496
  return result;
415
497
  }
416
498
  function tryReadPackageJson(packageJsonPath, expectedName) {
417
- if (!existsSync(packageJsonPath)) return void 0;
418
499
  try {
419
500
  const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
420
501
  if (expectedName !== void 0 && packageJson.name !== expectedName) return void 0;
@@ -428,19 +509,6 @@ function tryReadPackageJson(packageJsonPath, expectedName) {
428
509
  }
429
510
  }
430
511
  function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
431
- const findPackageInPnpmStore = (startDir) => {
432
- for (const dir of ancestorDirs(startDir)) {
433
- const pnpmStoreDir = path$1.join(dir, "node_modules", ".pnpm");
434
- if (!existsSync(pnpmStoreDir)) continue;
435
- try {
436
- for (const entry of readdirSync(pnpmStoreDir, { withFileTypes: true })) {
437
- if (!entry.isDirectory()) continue;
438
- const candidate = tryReadPackageJson(path$1.join(pnpmStoreDir, entry.name, "node_modules", packageName, "package.json"));
439
- if (candidate?.packageJson.name === packageName) return candidate;
440
- }
441
- } catch {}
442
- }
443
- };
444
512
  let resolvedPath;
445
513
  try {
446
514
  const rootPackageJson = path$1.join(cwd, "package.json");
@@ -462,7 +530,54 @@ function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
462
530
  const directCandidate = tryReadPackageJson(path$1.join(dir, "node_modules", packageName, "package.json"), packageName);
463
531
  if (directCandidate) return directCandidate;
464
532
  }
465
- return findPackageInDependents(packageName, cwd) ?? findPackageInPnpmStore(cwd);
533
+ return findPackageInDependents(packageName, cwd) ?? findPackageInPnpmStore(packageName, cwd);
534
+ }
535
+ function readDirEntries(dir) {
536
+ try {
537
+ return readdirSync(dir, { withFileTypes: true });
538
+ } catch {
539
+ return [];
540
+ }
541
+ }
542
+ function isDirOrLink(entry) {
543
+ return entry.isDirectory() || entry.isSymbolicLink();
544
+ }
545
+ function getPnpmStorePackageIndex(startDir) {
546
+ const cached = pnpmStorePackageIndexCache.get(startDir);
547
+ if (cached) return cached;
548
+ const index = /* @__PURE__ */ new Map();
549
+ const add = (name, packageJsonPath) => {
550
+ const paths = index.get(name);
551
+ if (paths) paths.push(packageJsonPath);
552
+ else index.set(name, [packageJsonPath]);
553
+ };
554
+ for (const dir of ancestorDirs(startDir)) {
555
+ const pnpmStoreDir = path$1.join(dir, "node_modules", ".pnpm");
556
+ for (const entry of readDirEntries(pnpmStoreDir)) {
557
+ if (!entry.isDirectory()) continue;
558
+ const storeNodeModules = path$1.join(pnpmStoreDir, entry.name, "node_modules");
559
+ for (const packageEntry of readDirEntries(storeNodeModules)) {
560
+ if (!isDirOrLink(packageEntry)) continue;
561
+ const entryDir = path$1.join(storeNodeModules, packageEntry.name);
562
+ if (!packageEntry.name.startsWith("@")) {
563
+ add(packageEntry.name, path$1.join(entryDir, "package.json"));
564
+ continue;
565
+ }
566
+ for (const scopedEntry of readDirEntries(entryDir)) {
567
+ if (!isDirOrLink(scopedEntry)) continue;
568
+ add(`${packageEntry.name}/${scopedEntry.name}`, path$1.join(entryDir, scopedEntry.name, "package.json"));
569
+ }
570
+ }
571
+ }
572
+ }
573
+ pnpmStorePackageIndexCache.set(startDir, index);
574
+ return index;
575
+ }
576
+ function findPackageInPnpmStore(packageName, startDir) {
577
+ for (const packageJsonPath of getPnpmStorePackageIndex(startDir).get(packageName) ?? []) {
578
+ const candidate = tryReadPackageJson(packageJsonPath, packageName);
579
+ if (candidate) return candidate;
580
+ }
466
581
  }
467
582
  /**
468
583
  * A package installed only under a dependent is invisible to the walks above.
@@ -529,12 +644,13 @@ function warnOnAmbiguousDependents(packageName, candidates) {
529
644
  const versions = [...viaByVersion].map(([version, via]) => `${version} (via ${via})`);
530
645
  mfWarn(`Shared package "${packageName}" is not a dependency of the project, and its closest dependents install different versions: ${versions.join(", ")}. The fallback uses ${versions[0]}. Add "${packageName}" to the project's dependencies or set its shared "import" to choose the version.`);
531
646
  }
647
+ const realpath = process.platform === "win32" ? realpathSync : realpathSync.native;
532
648
  /** The package Node's `node_modules` lookup finds from `fromDir`, read at its real path. */
533
649
  function findPackageFrom(packageName, fromDir) {
534
650
  const entry = findNodeModulesEntry(packageName, fromDir);
535
651
  if (!entry) return void 0;
536
652
  try {
537
- return tryReadPackageJson(path$1.join(realpathSync(entry), "package.json"), packageName);
653
+ return tryReadPackageJson(path$1.join(realpath(entry), "package.json"), packageName);
538
654
  } catch {
539
655
  return;
540
656
  }
@@ -609,14 +725,11 @@ function getInstalledPackageEntry(pkg, opts) {
609
725
  const explicitEntry = resolveExportsEntry(getPackageExportsTarget(pkg, packageName, packageJson.exports), opts?.conditions) || (typeof packageJson.module === "string" ? packageJson.module : void 0) || (typeof packageJson.main === "string" ? packageJson.main : void 0) || "index.js";
610
726
  return path$1.join(installed.dir, explicitEntry);
611
727
  }
612
- /**
613
- * Detect whether the current runtime is Vite 8+ by checking for a Vite version flag
614
- * on the plugin hook context, with Rolldown metadata kept as a compatibility fallback.
615
- */
728
+ /** Detect Vite 8+ (Rolldown) from the Vite version on the plugin hook context. */
616
729
  function getIsRolldown(ctx) {
617
730
  const viteVersion = ctx?.meta?.viteVersion;
618
731
  const viteMajor = Number(String(viteVersion ?? "").split(".")[0]);
619
- return Number.isFinite(viteMajor) && viteMajor >= 8 || !!ctx?.meta?.rolldownVersion;
732
+ return Number.isFinite(viteMajor) && viteMajor >= 8;
620
733
  }
621
734
  /**
622
735
  * Rolldown 1.2.10 added `codeSplitting.groups[].debugName` and warns when a group's
@@ -661,7 +774,34 @@ function hasPackageDependency(dependencyName, cwd = packageDetectionCwd || proce
661
774
  }
662
775
  }
663
776
  //#endregion
777
+ //#region src/utils/devServerHost.ts
778
+ const UNSPECIFIED_HOSTS = /* @__PURE__ */ new Set(["0.0.0.0", "::"]);
779
+ /**
780
+ * Hostname for client-facing HTTP/WS origins built from Vite `server.host`.
781
+ *
782
+ * Unspecified bind addresses (`0.0.0.0`, `::`) map to `localhost`, matching
783
+ * Vite's own printed local URL. IPv6 addresses are wrapped in brackets so
784
+ * `http://[::1]:5173` / `ws://[::1]:5173` parse as valid URLs.
785
+ */
786
+ function formatDevServerHostForOrigin(host) {
787
+ if (typeof host !== "string" || UNSPECIFIED_HOSTS.has(host)) return "localhost";
788
+ if (host.startsWith("[") && host.endsWith("]")) return host;
789
+ return isIPv6(host) ? `[${host}]` : host;
790
+ }
791
+ const FILE_EVENTS = [
792
+ "change",
793
+ "add",
794
+ "unlink"
795
+ ];
796
+ /** Runs `listener` on every file change, add, or unlink; returns a function that unsubscribes it. */
797
+ function watchFileEvents(watcher, listener) {
798
+ for (const event of FILE_EVENTS) watcher.on(event, listener);
799
+ return () => {
800
+ for (const event of FILE_EVENTS) watcher.off(event, listener);
801
+ };
802
+ }
803
+ //#endregion
664
804
  //#region src/utils/dtsConstants.ts
665
805
  const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
666
806
  //#endregion
667
- export { isReactCoreShare as C, REACT_DOM_CLIENT_SHARE as S, resolveModulePath as _, getIsRolldown as a, supportsCodeSplittingGroupDebugName as b, getPackageNameFromNodeModulePath as c, isNuxtProjectRoot as d, isPackageExportAvailable as f, resolveImportPath as g, packageNameEncode as h, getInstalledPackageJson as i, getSharedCacheDescriptor as l, packageNameDecode as m, getDependencyNames as n, getPackageDetectionCwd as o, isPackageInstalled as p, getInstalledPackageEntry as r, getPackageName as s, DEFAULT_PUBLIC_TYPES_FOLDER as t, hasPackageDependency as u, setPackageDetectionCwd as v, REACT_CLIENT_INTERNALS_KEY as x, sharedCacheHelperCode as y };
807
+ export { supportsCodeSplittingGroupDebugName as C, isReactCoreShare as E, sharedCacheHelperCode as S, REACT_DOM_CLIENT_SHARE as T, packageNameDecode as _, getInstalledPackageEntry as a, resolveModulePath as b, getPackageDetectionCwd as c, getPackageNameFromNodeModulePath as d, getSharedCacheDescriptor as f, isPackageInstalled as g, isPackageExportAvailable as h, getDependencyNames as i, getPackageExportSpecifiersForFile as l, isNuxtProjectRoot as m, formatDevServerHostForOrigin as n, getInstalledPackageJson as o, hasPackageDependency as p, watchFileEvents as r, getIsRolldown as s, DEFAULT_PUBLIC_TYPES_FOLDER as t, getPackageName as u, packageNameEncode as v, REACT_CLIENT_INTERNALS_KEY as w, setPackageDetectionCwd as x, resolveImportPath as y };