@module-federation/vite 1.20.0 → 1.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,7 +1,6 @@
1
- import { _ as createModuleFederationError, a as getIsRolldown, b as rebaseImport, c as getPackageNameFromNodeModulePath, d as isNuxtProjectRoot, f as packageNameDecode, g as sharedCacheHelperCode, h as setPackageDetectionCwd, i as getInstalledPackageJson, l as getSharedCacheDescriptor, m as resolveImportPath, o as getPackageDetectionCwd, p as packageNameEncode, r as getInstalledPackageEntry, s as getPackageName, u as hasPackageDependency, v as mfWarn, y as normalizePathForImport } from "./pluginDts-Dbbi4cnh.js";
2
1
  import { createRequire } from "node:module";
3
2
  import * as fs$2 from "fs";
4
- import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
3
+ import fs, { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "fs";
5
4
  import { createRequire as createRequire$1 } from "module";
6
5
  import * as path$1 from "node:path";
7
6
  import path, { basename } from "node:path";
@@ -11,9 +10,71 @@ import { createHash } from "node:crypto";
11
10
  import * as fs$1 from "node:fs";
12
11
  import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
13
12
  import { pathToFileURL as pathToFileURL$1 } from "node:url";
13
+ import { normalizeOptions } from "@module-federation/sdk";
14
+ import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
15
+ import { rpc } from "@module-federation/dts-plugin/core";
16
+ //#region \0rolldown/runtime.js
17
+ var __defProp = Object.defineProperty;
18
+ var __exportAll = (all, no_symbols) => {
19
+ let target = {};
20
+ for (var name in all) __defProp(target, name, {
21
+ get: all[name],
22
+ enumerable: true
23
+ });
24
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
25
+ return target;
26
+ };
27
+ //#endregion
28
+ //#region src/utils/buildPaths.ts
29
+ /**
30
+ * Rebase an import path for a bootstrap file that moved from root into `dir`.
31
+ *
32
+ * When entryFileNames places entries in a subdirectory (e.g. `static/js/`),
33
+ * the bootstrap file moves there too. Paths that resolved from the HTML root
34
+ * must resolve from the new directory instead.
35
+ *
36
+ * Cases: `/static/js/hostInit.js` → `./hostInit.js` (strip dir prefix)
37
+ * `./src/main.tsx` → `../../src/main.tsx` (climb back up for each dir level)
38
+ * `https://cdn.example.com` → unchanged (absolute URL)
39
+ */
40
+ function rebaseImport(importSrc, dir) {
41
+ if (!dir) return importSrc;
42
+ if (isAbsoluteUrl(importSrc)) return importSrc;
43
+ const normalizedDir = dir.replace(/^\/+|\/+$/g, "");
44
+ if (!normalizedDir) return importSrc;
45
+ const stripDirPrefix = (src, prefix) => {
46
+ if (src === prefix) return "";
47
+ if (src.startsWith(prefix + "/")) return src.slice(prefix.length);
48
+ };
49
+ const absoluteRemainder = stripDirPrefix(importSrc, "/" + normalizedDir);
50
+ if (absoluteRemainder !== void 0) {
51
+ const remainder = absoluteRemainder.replace(/^\/+/, "");
52
+ return remainder ? "./" + remainder : "./";
53
+ }
54
+ const relativeRemainder = stripDirPrefix(importSrc, normalizedDir);
55
+ if (relativeRemainder !== void 0) {
56
+ const remainder = relativeRemainder.replace(/^\/+/, "");
57
+ return remainder ? "./" + remainder : "./";
58
+ }
59
+ const upLevels = normalizedDir.split("/").filter(Boolean).length;
60
+ const prefix = upLevels > 0 ? "../".repeat(upLevels) : "./";
61
+ if (importSrc.startsWith("./")) return prefix + importSrc.slice(2);
62
+ if (importSrc.startsWith("/")) return prefix + importSrc.slice(1);
63
+ return prefix + importSrc;
64
+ }
65
+ function normalizePathForImport(path) {
66
+ return path.replace(/\\/g, "/");
67
+ }
68
+ const EXTERNAL_URL_RE = /^(?:[a-z]+:|\/\/)/i;
69
+ function isAbsoluteUrl(src) {
70
+ if (/^[a-z]:[\\/]/i.test(src)) return false;
71
+ return EXTERNAL_URL_RE.test(src);
72
+ }
73
+ //#endregion
14
74
  //#region src/utils/codeRewriter.ts
15
75
  const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
16
76
  var CodeRewriter = class {
77
+ original;
17
78
  replacements = [];
18
79
  constructor(original) {
19
80
  this.original = original;
@@ -149,7 +210,7 @@ async function mapCodeToCodeWithSourcemap(code) {
149
210
  }
150
211
  //#endregion
151
212
  //#region src/utils/codePositionMap.ts
152
- const REGEX_PREFIX_KEYWORDS = new Set([
213
+ const REGEX_PREFIX_KEYWORDS = /* @__PURE__ */ new Set([
153
214
  "await",
154
215
  "case",
155
216
  "delete",
@@ -321,6 +382,475 @@ function injectEntryScript(html, initSrc) {
321
382
  return html.replace("<head>", `<head><script type="module" src=${JSON.stringify(src)}><\/script>`);
322
383
  }
323
384
  //#endregion
385
+ //#region src/utils/logger.ts
386
+ const MODULE_FEDERATION_LOG_PREFIX = "[Module Federation]";
387
+ function formatModuleFederationMessage(message) {
388
+ return `${MODULE_FEDERATION_LOG_PREFIX} ${message}`;
389
+ }
390
+ function createModuleFederationError(message) {
391
+ return new Error(formatModuleFederationMessage(message));
392
+ }
393
+ function toConsoleArgs(message, rest = []) {
394
+ if (typeof message === "string") return [formatModuleFederationMessage(message), ...rest];
395
+ if (message === void 0) return [MODULE_FEDERATION_LOG_PREFIX, ...rest];
396
+ return [
397
+ MODULE_FEDERATION_LOG_PREFIX,
398
+ message,
399
+ ...rest
400
+ ];
401
+ }
402
+ const moduleFederationConsole = {
403
+ log(message, ...rest) {
404
+ console.log(...toConsoleArgs(message, rest));
405
+ },
406
+ warn(message, ...rest) {
407
+ console.warn(...toConsoleArgs(message, rest));
408
+ },
409
+ error(message, ...rest) {
410
+ console.error(...toConsoleArgs(message, rest));
411
+ }
412
+ };
413
+ moduleFederationConsole.log;
414
+ const mfWarn = moduleFederationConsole.warn;
415
+ const mfError = moduleFederationConsole.error;
416
+ //#endregion
417
+ //#region src/utils/packageUtils.ts
418
+ const dependencyPresenceCache = /* @__PURE__ */ new Map();
419
+ let packageDetectionCwd;
420
+ function getDependencyCacheKey(cwd, dependencyName) {
421
+ return `${cwd}:${dependencyName}`;
422
+ }
423
+ const installedPackageJsonCache = /* @__PURE__ */ new Map();
424
+ function setPackageDetectionCwd(cwd) {
425
+ packageDetectionCwd = cwd;
426
+ }
427
+ function getPackageDetectionCwd() {
428
+ return packageDetectionCwd || process.cwd();
429
+ }
430
+ function resolveImportPath(specifier) {
431
+ const resolved = import.meta.resolve(specifier);
432
+ if (!resolved.startsWith("file:")) return resolved;
433
+ const filePath = fileURLToPath(resolved);
434
+ if (!existsSync(filePath)) {
435
+ const error = /* @__PURE__ */ new Error(`Cannot find module '${specifier}'`);
436
+ error.code = "MODULE_NOT_FOUND";
437
+ throw error;
438
+ }
439
+ return filePath;
440
+ }
441
+ const DEFAULT_EXPORT_CONDITIONS = [
442
+ "browser",
443
+ "import",
444
+ "module",
445
+ "default"
446
+ ];
447
+ function resolveExportsEntry(exportsField, conditions = DEFAULT_EXPORT_CONDITIONS) {
448
+ return resolveExportsEntryWithConditions(exportsField, new Set(conditions));
449
+ }
450
+ function resolveExportsEntryWithConditions(exportsField, conditions) {
451
+ if (typeof exportsField === "string") return exportsField;
452
+ if (!exportsField || typeof exportsField !== "object") return void 0;
453
+ if (Array.isArray(exportsField)) {
454
+ for (const target of exportsField) {
455
+ const resolved = resolveExportsEntryWithConditions(target, conditions);
456
+ if (resolved) return resolved;
457
+ }
458
+ return;
459
+ }
460
+ const record = exportsField;
461
+ const rootExport = record["."];
462
+ if (rootExport) return resolveExportsEntryWithConditions(rootExport, conditions);
463
+ for (const [condition, value] of Object.entries(record)) {
464
+ if (condition !== "default" && !conditions.has(condition)) continue;
465
+ const target = resolveExportsEntryWithConditions(value, conditions);
466
+ if (target) return target;
467
+ }
468
+ }
469
+ function substituteExportsWildcard(target, patternMatch) {
470
+ if (typeof target === "string") return target.split("*").join(patternMatch);
471
+ if (Array.isArray(target)) return target.map((entry) => substituteExportsWildcard(entry, patternMatch));
472
+ if (target && typeof target === "object") {
473
+ const source = target;
474
+ const out = {};
475
+ for (const key of Object.keys(source)) out[key] = substituteExportsWildcard(source[key], patternMatch);
476
+ return out;
477
+ }
478
+ return target;
479
+ }
480
+ function matchExportsSubpath(record, subpath) {
481
+ if (subpath in record) return record[subpath];
482
+ let bestKey;
483
+ let bestBaseLength = -1;
484
+ let bestKeyLength = -1;
485
+ for (const key of Object.keys(record)) {
486
+ const wildcardIndex = key.indexOf("*");
487
+ if (wildcardIndex === -1) continue;
488
+ const patternBase = key.slice(0, wildcardIndex);
489
+ const patternTrailer = key.slice(wildcardIndex + 1);
490
+ if (patternTrailer.includes("*")) continue;
491
+ if (!subpath.startsWith(patternBase) || !subpath.endsWith(patternTrailer)) continue;
492
+ if (subpath.length <= patternBase.length + patternTrailer.length) continue;
493
+ if (patternBase.length > bestBaseLength || patternBase.length === bestBaseLength && key.length > bestKeyLength) {
494
+ bestKey = key;
495
+ bestBaseLength = patternBase.length;
496
+ bestKeyLength = key.length;
497
+ }
498
+ }
499
+ if (bestKey === void 0) return void 0;
500
+ const patternTrailer = bestKey.slice(bestKey.indexOf("*") + 1);
501
+ const patternMatch = subpath.slice(bestBaseLength, subpath.length - patternTrailer.length);
502
+ return substituteExportsWildcard(record[bestKey], patternMatch);
503
+ }
504
+ function getPackageExportsTarget(pkg, packageName, exportsField) {
505
+ if (typeof exportsField === "string") return pkg === packageName ? exportsField : void 0;
506
+ if (!exportsField || typeof exportsField !== "object") return void 0;
507
+ const record = exportsField;
508
+ const subpath = pkg === packageName ? "." : `.${pkg.slice(packageName.length)}`;
509
+ if (subpath !== ".") return matchExportsSubpath(record, subpath);
510
+ return record["."] ?? (!Object.keys(record).some((key) => key.startsWith(".")) ? record : void 0);
511
+ }
512
+ /**
513
+ * Escaping rules:
514
+ * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
515
+ * @ => 1
516
+ * / => 2
517
+ * - => 3
518
+ * . => 4
519
+ */
520
+ /**
521
+ * Encodes a package name into a valid file name.
522
+ * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
523
+ * @returns {string} - The encoded file name.
524
+ */
525
+ function packageNameEncode(name) {
526
+ if (typeof name !== "string") throw createModuleFederationError("A string package name is required");
527
+ return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
528
+ }
529
+ /**
530
+ * Decodes an encoded file name back to the original package name.
531
+ * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
532
+ * @returns {string} - The decoded package name.
533
+ */
534
+ function packageNameDecode(encoded) {
535
+ if (typeof encoded !== "string") throw createModuleFederationError("A string encoded file name is required");
536
+ return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
537
+ }
538
+ /**
539
+ * Removes any subpath from an npm package specifier and returns the package name only.
540
+ * @param {string} packageString - The package specifier, e.g., "@scope/pkg/runtime" or "react/jsx-runtime".
541
+ * @returns {string} - The base npm package name.
542
+ */
543
+ function getPackageName(packageString) {
544
+ const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
545
+ return match ? match[0] : packageString;
546
+ }
547
+ function getPackageNameFromNodeModulePath(source) {
548
+ const normalized = source.replace(/\\/g, "/");
549
+ const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
550
+ if (nodeModulesIndex < 0) return;
551
+ const parts = normalized.slice(nodeModulesIndex + 14).split("/");
552
+ if (!parts[0]) return;
553
+ if (parts[0].startsWith("@")) return parts[1] ? `${parts[0]}/${parts[1]}` : void 0;
554
+ return parts[0];
555
+ }
556
+ function getSharedCacheKeyParts(input) {
557
+ const scope = (Array.isArray(input.scope) ? input.scope[0] : input.scope) || "default";
558
+ const id = input.singleton || !input.version ? input.pkg : `${input.pkg}@${input.version}`;
559
+ return {
560
+ scope,
561
+ id,
562
+ key: `${scope}:${id}`
563
+ };
564
+ }
565
+ function getSharedCacheDescriptor(pkg, shareItem) {
566
+ const parts = getSharedCacheKeyParts({
567
+ pkg,
568
+ singleton: shareItem.shareConfig.singleton,
569
+ version: shareItem.version,
570
+ scope: shareItem.scope
571
+ });
572
+ return {
573
+ canonical: parts.key,
574
+ ...parts.scope === "default" ? { aliases: [parts.id] } : {}
575
+ };
576
+ }
577
+ const sharedCacheHelperCode = `const __mfGetSharedCacheDescriptor = (pkg, singleton, version, scope) => {
578
+ const normalizedScope = Array.isArray(scope) ? scope[0] : scope;
579
+ const scopeName = normalizedScope || "default";
580
+ const id = singleton || !version ? pkg : pkg + "@" + version;
581
+ const descriptor = { canonical: scopeName + ":" + id };
582
+ if (scopeName === "default") descriptor.aliases = [id];
583
+ return descriptor;
584
+ };
585
+ const __mfReadSharedCache = (cache, descriptor) => {
586
+ const value = cache[descriptor.canonical];
587
+ if (value !== undefined) return value;
588
+ const aliases = descriptor.aliases || [];
589
+ for (const alias of aliases) {
590
+ if (!Object.prototype.hasOwnProperty.call(cache, alias)) continue;
591
+ const aliasValue = cache[alias];
592
+ if (aliasValue !== undefined) {
593
+ cache[descriptor.canonical] = aliasValue;
594
+ return aliasValue;
595
+ }
596
+ }
597
+ return undefined;
598
+ };
599
+ const __mfSharedCacheListenersKey = Symbol.for("module-federation.shared-cache-listeners");
600
+ const __mfGetSharedCacheListeners = (cache) => {
601
+ let listeners = cache[__mfSharedCacheListenersKey];
602
+ if (listeners === undefined) {
603
+ listeners = Object.create(null);
604
+ Object.defineProperty(cache, __mfSharedCacheListenersKey, {
605
+ value: listeners,
606
+ enumerable: false,
607
+ configurable: false,
608
+ writable: false
609
+ });
610
+ }
611
+ return listeners;
612
+ };
613
+ const __mfSubscribeSharedCache = (cache, descriptor, listener) => {
614
+ const listeners = __mfGetSharedCacheListeners(cache);
615
+ (listeners[descriptor.canonical] ||= new Set()).add(listener);
616
+ };
617
+ const __mfSharedCacheOwnersKey = Symbol.for("module-federation.shared-cache-owners");
618
+ const __mfGetSharedCacheOwners = (cache) => {
619
+ let owners = cache[__mfSharedCacheOwnersKey];
620
+ if (owners === undefined) {
621
+ owners = Object.create(null);
622
+ Object.defineProperty(cache, __mfSharedCacheOwnersKey, {
623
+ value: owners,
624
+ enumerable: false,
625
+ configurable: false,
626
+ writable: false
627
+ });
628
+ }
629
+ return owners;
630
+ };
631
+ const __mfReadSharedCacheOwner = (cache, descriptor) =>
632
+ cache[__mfSharedCacheOwnersKey]?.[descriptor.canonical];
633
+ const __mfWriteSharedCache = (cache, descriptor, value, owner) => {
634
+ cache[descriptor.canonical] = value;
635
+ const aliases = descriptor.aliases || [];
636
+ for (const alias of aliases) {
637
+ Object.defineProperty(cache, alias, {
638
+ value,
639
+ enumerable: true,
640
+ configurable: true,
641
+ writable: true
642
+ });
643
+ }
644
+ const owners = cache[__mfSharedCacheOwnersKey];
645
+ if (owner === undefined) {
646
+ if (owners) delete owners[descriptor.canonical];
647
+ } else {
648
+ __mfGetSharedCacheOwners(cache)[descriptor.canonical] = owner;
649
+ }
650
+ const listeners = cache[__mfSharedCacheListenersKey]?.[descriptor.canonical];
651
+ if (listeners) {
652
+ for (const listener of listeners) listener(value);
653
+ }
654
+ return value;
655
+ };
656
+ const __mfTreeShakingSharedCacheKey = Symbol.for("module-federation.tree-shaking-shared-cache");
657
+ const __mfGetTreeShakingSharedCache = (cache) => {
658
+ let metadata = cache[__mfTreeShakingSharedCacheKey];
659
+ if (metadata === undefined) {
660
+ metadata = Object.create(null);
661
+ Object.defineProperty(cache, __mfTreeShakingSharedCacheKey, {
662
+ value: metadata,
663
+ enumerable: false,
664
+ configurable: false,
665
+ writable: false
666
+ });
667
+ }
668
+ return metadata;
669
+ };
670
+ const __mfReadTreeShakingSharedCache = (cache, descriptor, requiredExports) => {
671
+ const fullModule = __mfReadSharedCache(cache, descriptor);
672
+ if (fullModule !== undefined) return fullModule;
673
+ if (!Array.isArray(requiredExports)) return undefined;
674
+ const metadata = cache[__mfTreeShakingSharedCacheKey];
675
+ const entries = metadata?.[descriptor.canonical] || [];
676
+ let compatibleEntry;
677
+ for (const entry of entries) {
678
+ if (!requiredExports.every((name) => entry.providedExports.includes(name))) continue;
679
+ if (!compatibleEntry || entry.providedExports.length < compatibleEntry.providedExports.length) {
680
+ compatibleEntry = entry;
681
+ }
682
+ }
683
+ return compatibleEntry?.value;
684
+ };
685
+ const __mfWriteTreeShakingSharedCache = (cache, descriptor, providedExports, value) => {
686
+ if (!Array.isArray(providedExports)) return value;
687
+ const normalizedExports = [...new Set(providedExports)].sort();
688
+ const metadata = __mfGetTreeShakingSharedCache(cache);
689
+ const entries = (metadata[descriptor.canonical] ||= []);
690
+ const existing = entries.find((entry) =>
691
+ entry.providedExports.length === normalizedExports.length &&
692
+ entry.providedExports.every((name, index) => name === normalizedExports[index])
693
+ );
694
+ if (existing) existing.value = value;
695
+ else entries.push({ providedExports: normalizedExports, value });
696
+ return value;
697
+ };
698
+ const __mfTreeShakingSelectionCacheKey = Symbol.for("module-federation.tree-shaking-shared-selection-cache");
699
+ const __mfGetTreeShakingSelectionCache = (cache) => {
700
+ let selections = cache[__mfTreeShakingSelectionCacheKey];
701
+ if (selections === undefined) {
702
+ selections = Object.create(null);
703
+ Object.defineProperty(cache, __mfTreeShakingSelectionCacheKey, {
704
+ value: selections,
705
+ enumerable: false,
706
+ configurable: false,
707
+ writable: false
708
+ });
709
+ }
710
+ return selections;
711
+ };
712
+ const __mfReadTreeShakingSharedSelection = (cache, descriptor, consumer) => {
713
+ const fullModule = __mfReadSharedCache(cache, descriptor);
714
+ if (fullModule !== undefined) return fullModule;
715
+ return cache[__mfTreeShakingSelectionCacheKey]?.[descriptor.canonical]?.[consumer];
716
+ };
717
+ const __mfWriteTreeShakingSharedSelection = (cache, descriptor, consumer, value) => {
718
+ const selections = __mfGetTreeShakingSelectionCache(cache);
719
+ const byConsumer = (selections[descriptor.canonical] ||= Object.create(null));
720
+ byConsumer[consumer] = value;
721
+ return value;
722
+ };`;
723
+ function getInstalledPackageJson(pkg, opts) {
724
+ const cwd = opts?.cwd || getPackageDetectionCwd();
725
+ const packageName = opts?.packageName || getPackageName(pkg);
726
+ const cacheKey = `${cwd}\0${pkg}\0${packageName}\0${opts?.fromResolvedEntry ?? ""}`;
727
+ if (installedPackageJsonCache.has(cacheKey)) return installedPackageJsonCache.get(cacheKey);
728
+ const result = resolveInstalledPackageJson(pkg, cwd, packageName, opts);
729
+ installedPackageJsonCache.set(cacheKey, result);
730
+ return result;
731
+ }
732
+ function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
733
+ const tryReadPackageJson = (packageJsonPath) => {
734
+ if (!existsSync(packageJsonPath)) return void 0;
735
+ try {
736
+ return {
737
+ path: packageJsonPath,
738
+ dir: path$1.dirname(packageJsonPath),
739
+ packageJson: JSON.parse(readFileSync(packageJsonPath, "utf-8"))
740
+ };
741
+ } catch {
742
+ return;
743
+ }
744
+ };
745
+ const findPackageInPnpmStore = (startDir) => {
746
+ let currentDir = startDir;
747
+ const rootDir = path$1.parse(currentDir).root;
748
+ while (true) {
749
+ const pnpmStoreDir = path$1.join(currentDir, "node_modules", ".pnpm");
750
+ if (existsSync(pnpmStoreDir)) try {
751
+ for (const entry of readdirSync(pnpmStoreDir, { withFileTypes: true })) {
752
+ if (!entry.isDirectory()) continue;
753
+ const candidate = tryReadPackageJson(path$1.join(pnpmStoreDir, entry.name, "node_modules", packageName, "package.json"));
754
+ if (candidate?.packageJson.name === packageName) return candidate;
755
+ }
756
+ } catch {}
757
+ if (currentDir === rootDir) break;
758
+ currentDir = path$1.dirname(currentDir);
759
+ }
760
+ };
761
+ try {
762
+ const projectRequire = createRequire$1(pathToFileURL(path$1.join(cwd, "package.json")));
763
+ let resolvedPath;
764
+ if (opts?.fromResolvedEntry) resolvedPath = opts.fromResolvedEntry;
765
+ else try {
766
+ resolvedPath = projectRequire.resolve(pkg);
767
+ } catch {
768
+ resolvedPath = projectRequire.resolve(packageName);
769
+ }
770
+ let currentDir = path$1.dirname(resolvedPath);
771
+ const rootDir = path$1.parse(currentDir).root;
772
+ while (true) {
773
+ const packageJsonPath = path$1.join(currentDir, "package.json");
774
+ if (existsSync(packageJsonPath)) {
775
+ const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
776
+ try {
777
+ const packageJson = JSON.parse(packageJsonContent);
778
+ if (packageJson.name === packageName) return {
779
+ path: packageJsonPath,
780
+ dir: currentDir,
781
+ packageJson
782
+ };
783
+ } catch (error) {
784
+ if (!(error instanceof SyntaxError)) throw error;
785
+ }
786
+ }
787
+ if (currentDir === rootDir) break;
788
+ currentDir = path$1.dirname(currentDir);
789
+ }
790
+ } catch {
791
+ let currentDir = cwd;
792
+ const rootDir = path$1.parse(currentDir).root;
793
+ while (true) {
794
+ const directCandidate = tryReadPackageJson(path$1.join(currentDir, "node_modules", packageName, "package.json"));
795
+ if (directCandidate?.packageJson.name === packageName) return directCandidate;
796
+ if (currentDir === rootDir) break;
797
+ currentDir = path$1.dirname(currentDir);
798
+ }
799
+ return findPackageInPnpmStore(cwd);
800
+ }
801
+ }
802
+ function getInstalledPackageEntry(pkg, opts) {
803
+ const installed = getInstalledPackageJson(pkg, opts);
804
+ if (!installed) return void 0;
805
+ const cwd = opts?.cwd || getPackageDetectionCwd();
806
+ const packageName = opts?.packageName || getPackageName(pkg);
807
+ const packageJson = installed.packageJson;
808
+ if (pkg !== packageName && (opts?.resolveSubpathWithRequire !== false || packageJson.exports === void 0)) try {
809
+ return createRequire$1(pathToFileURL(path$1.join(cwd, "package.json"))).resolve(pkg);
810
+ } catch {}
811
+ 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";
812
+ return path$1.join(installed.dir, explicitEntry);
813
+ }
814
+ /**
815
+ * Detect whether the current runtime is Vite 8+ by checking for a Vite version flag
816
+ * on the plugin hook context, with Rolldown metadata kept as a compatibility fallback.
817
+ */
818
+ function getIsRolldown(ctx) {
819
+ const viteVersion = ctx?.meta?.viteVersion;
820
+ const viteMajor = Number(String(viteVersion ?? "").split(".")[0]);
821
+ return Number.isFinite(viteMajor) && viteMajor >= 8 || !!ctx?.meta?.rolldownVersion;
822
+ }
823
+ /** Walk up from Vite `config.root` (Nuxt may point at `.nuxt` cache dirs). */
824
+ function isNuxtProjectRoot(root) {
825
+ let dir = root;
826
+ for (let i = 0; i < 8; i++) {
827
+ if (hasPackageDependency("nuxt", dir) || hasPackageDependency("nuxt-nightly", dir)) return true;
828
+ const parent = path$1.dirname(dir);
829
+ if (parent === dir) break;
830
+ dir = parent;
831
+ }
832
+ return false;
833
+ }
834
+ function hasPackageDependency(dependencyName, cwd = packageDetectionCwd || process.cwd()) {
835
+ const cacheKey = getDependencyCacheKey(cwd, dependencyName);
836
+ const cached = dependencyPresenceCache.get(cacheKey);
837
+ if (cached !== void 0) return cached;
838
+ try {
839
+ const packageJson = JSON.parse(readFileSync(path$1.join(cwd, "package.json"), "utf8"));
840
+ const hasDependency = [
841
+ packageJson.dependencies,
842
+ packageJson.devDependencies,
843
+ packageJson.peerDependencies,
844
+ packageJson.optionalDependencies
845
+ ].some((deps) => !!deps?.[dependencyName]);
846
+ dependencyPresenceCache.set(cacheKey, hasDependency);
847
+ return hasDependency;
848
+ } catch {
849
+ dependencyPresenceCache.set(cacheKey, false);
850
+ return false;
851
+ }
852
+ }
853
+ //#endregion
324
854
  //#region src/utils/pathNormalization.ts
325
855
  const COMMON_SHARED_SUBPATHS = {
326
856
  react: [
@@ -396,14 +926,15 @@ function removeTrailingSlash(value) {
396
926
  function ensureTrailingSlash(value) {
397
927
  return `${removeTrailingSlash(value)}/`;
398
928
  }
399
- function getBasePath$1(base) {
929
+ function getBasePath$2(base) {
400
930
  return removeTrailingSlash(base || "/");
401
931
  }
402
932
  function isNuxtClientBase(base) {
403
- return getBasePath$1(base).endsWith("/_nuxt");
933
+ return getBasePath$2(base).endsWith("/_nuxt");
404
934
  }
405
935
  function normalizeNodeModulePath(source) {
406
- return source.replace(/\\/g, "/").replace(/\?.*$/, "");
936
+ const queryIndex = source.indexOf("?");
937
+ return (queryIndex === -1 ? source : source.slice(0, queryIndex)).replace(/\\/g, "/");
407
938
  }
408
939
  function isNodeModulePath(source) {
409
940
  return source.includes("/node_modules/") || source.includes("\\node_modules\\");
@@ -1016,6 +1547,104 @@ function generateReactIslandSSRDefinition(enabled) {
1016
1547
  }
1017
1548
  }`;
1018
1549
  }
1550
+ const REACT_ISLAND_CLIENT_ID_PREFIX = "virtual:mf-react-island-client:";
1551
+ const REACT_ISLAND_SERVER_ID_PREFIX = "virtual:mf-react-island-server:";
1552
+ const RESOLVED_REACT_ISLAND_CLIENT_ID_PREFIX = `\0${REACT_ISLAND_CLIENT_ID_PREFIX}`;
1553
+ const RESOLVED_REACT_ISLAND_SERVER_ID_PREFIX = `\0${REACT_ISLAND_SERVER_ID_PREFIX}`;
1554
+ function encodeIslandRemoteId(remoteId) {
1555
+ return encodeURIComponent(remoteId);
1556
+ }
1557
+ function decodeIslandRemoteId(encodedRemoteId) {
1558
+ return decodeURIComponent(encodedRemoteId);
1559
+ }
1560
+ function getReactIslandImportRemoteId(source) {
1561
+ const queryIndex = source.indexOf("?");
1562
+ if (queryIndex === -1) return;
1563
+ if (!new URLSearchParams(source.slice(queryIndex + 1)).has("mf-island")) return;
1564
+ return source.slice(0, queryIndex);
1565
+ }
1566
+ function getReactIslandServerImportId(remoteId) {
1567
+ return `${REACT_ISLAND_SERVER_ID_PREFIX}${encodeIslandRemoteId(remoteId)}`;
1568
+ }
1569
+ function getReactIslandClientImportId(remoteId) {
1570
+ return `${REACT_ISLAND_CLIENT_ID_PREFIX}${encodeIslandRemoteId(remoteId)}`;
1571
+ }
1572
+ function resolveReactIslandConsumerId(id) {
1573
+ if (id.startsWith("virtual:mf-react-island-server:")) return `\0${id}`;
1574
+ if (id.startsWith("virtual:mf-react-island-client:")) return `\0${id}`;
1575
+ }
1576
+ function remoteIdFromResolvedIslandId(id, prefix) {
1577
+ if (!id.startsWith(prefix)) return;
1578
+ return decodeIslandRemoteId(id.slice(prefix.length));
1579
+ }
1580
+ /** Generates the server half of the opt-in `?mf-island` consumer component. */
1581
+ function generateReactIslandConsumerServer(remoteId) {
1582
+ const source = JSON.stringify(remoteId);
1583
+ return `import * as React from "react";
1584
+ import IslandClient from ${JSON.stringify(getReactIslandClientImportId(remoteId))};
1585
+
1586
+ const islandModulePromise = import(${source});
1587
+
1588
+ async function loadIslandModule() {
1589
+ const namespace = await islandModulePromise;
1590
+ const pending = namespace && namespace.__mf_remote_pending;
1591
+ if (pending && typeof pending.then === "function") return pending;
1592
+ return namespace && namespace.__moduleExports || namespace;
1593
+ }
1594
+
1595
+ export default async function ModuleFederationIsland(props) {
1596
+ const remoteModule = await loadIslandModule();
1597
+ const shell = remoteModule && remoteModule.__mf_island;
1598
+ if (!shell || typeof shell.renderToHtml !== "function") {
1599
+ throw new Error(${JSON.stringify(`[Module Federation] ${remoteId} does not expose an SSR island capability`)});
1600
+ }
1601
+ const html = await shell.renderToHtml(props);
1602
+ return React.createElement(IslandClient, { html, islandProps: props });
1603
+ }`;
1604
+ }
1605
+ /** Generates the client boundary which hydrates with the remote-owned React. */
1606
+ function generateReactIslandConsumerClient(remoteId) {
1607
+ return `"use client";
1608
+
1609
+ import * as React from "react";
1610
+
1611
+ const islandModulePromise = import(${JSON.stringify(remoteId)});
1612
+
1613
+ async function loadIslandModule() {
1614
+ const namespace = await islandModulePromise;
1615
+ const pending = namespace && namespace.__mf_remote_pending;
1616
+ if (pending && typeof pending.then === "function") return pending;
1617
+ return namespace && namespace.__moduleExports || namespace;
1618
+ }
1619
+
1620
+ export default function ModuleFederationIslandClient({ html, islandProps }) {
1621
+ const ref = React.useRef(null);
1622
+
1623
+ React.useEffect(() => {
1624
+ const element = ref.current;
1625
+ if (!element) return;
1626
+ void loadIslandModule().then((remoteModule) => {
1627
+ const shell = remoteModule && remoteModule.__mf_island;
1628
+ if (!shell || typeof shell.hydrate !== "function") {
1629
+ throw new Error(${JSON.stringify(`[Module Federation] ${remoteId} does not expose a client island capability`)});
1630
+ }
1631
+ return shell.hydrate(element, islandProps);
1632
+ });
1633
+ }, []);
1634
+
1635
+ return React.createElement("div", {
1636
+ ref,
1637
+ suppressHydrationWarning: true,
1638
+ dangerouslySetInnerHTML: { __html: html },
1639
+ });
1640
+ }`;
1641
+ }
1642
+ function loadReactIslandConsumerModule(id) {
1643
+ const serverRemoteId = remoteIdFromResolvedIslandId(id, RESOLVED_REACT_ISLAND_SERVER_ID_PREFIX);
1644
+ if (serverRemoteId !== void 0) return generateReactIslandConsumerServer(serverRemoteId);
1645
+ const clientRemoteId = remoteIdFromResolvedIslandId(id, RESOLVED_REACT_ISLAND_CLIENT_ID_PREFIX);
1646
+ if (clientRemoteId !== void 0) return generateReactIslandConsumerClient(clientRemoteId);
1647
+ }
1019
1648
  //#endregion
1020
1649
  //#region src/virtualModules/virtualExposes.ts
1021
1650
  const EXPOSES_CSS_MAP_PLACEHOLDER = "__MF_EXPOSES_CSS_MAP__";
@@ -1286,6 +1915,9 @@ ${exportStatement}
1286
1915
  }
1287
1916
  //#endregion
1288
1917
  //#region src/utils/treeShaking.ts
1918
+ function shouldAnalyzeSharedExports(shareItem) {
1919
+ return !!(shareItem && (shareItem.shareConfig.treeShaking || shareItem.shareConfig.import === false));
1920
+ }
1289
1921
  const legacyTreeShakingState = {
1290
1922
  inferredUsage: /* @__PURE__ */ new Map(),
1291
1923
  buildMode: false
@@ -1359,12 +1991,12 @@ function getExportRecords(sharedKey, request, options) {
1359
1991
  * fallback lookup across keys keeps aliases/backwards-compatible callers
1360
1992
  * working, while still keeping each concrete request's exports isolated.
1361
1993
  */
1362
- function getTreeShakingExportUsage(request, shareItem, sharedKey, options) {
1994
+ function getSharedExportUsage(request, shareItem, sharedKey, options) {
1363
1995
  const treeShaking = shareItem?.shareConfig.treeShaking;
1364
- if (!treeShaking || !getTreeShakingState(options).buildMode) return void 0;
1996
+ if (!shouldAnalyzeSharedExports(shareItem) || !getTreeShakingState(options).buildMode) return;
1365
1997
  const records = getExportRecords(sharedKey, request, options);
1366
1998
  if (records.some((record) => record.requiresFullBundle)) return { kind: "full" };
1367
- const configured = treeShaking.usedExports ?? [];
1999
+ const configured = treeShaking?.usedExports ?? [];
1368
2000
  const result = new Set(configured);
1369
2001
  records.forEach((record) => record.usedExports.forEach((name) => result.add(name)));
1370
2002
  if (result.size > 0) return {
@@ -1376,6 +2008,10 @@ function getTreeShakingExportUsage(request, shareItem, sharedKey, options) {
1376
2008
  usedExports: []
1377
2009
  } : { kind: "unknown" };
1378
2010
  }
2011
+ function getTreeShakingExportUsage(request, shareItem, sharedKey, options) {
2012
+ if (!shareItem?.shareConfig.treeShaking) return void 0;
2013
+ return getSharedExportUsage(request, shareItem, sharedKey, options);
2014
+ }
1379
2015
  function getModuleSource(node) {
1380
2016
  if (!node || typeof node !== "object") return void 0;
1381
2017
  const source = node;
@@ -1490,8 +2126,8 @@ function collectReExport(node, source, record, markUnsafe) {
1490
2126
  *
1491
2127
  * Parsing the module avoids treating import-looking text in comments, strings,
1492
2128
  * templates, or regular expressions as real dependencies. If parsing fails,
1493
- * every configured tree-shaken share is conservatively marked as requiring its
1494
- * full bundle instead of guessing from source text.
2129
+ * every configured share whose exports are analyzed is conservatively marked
2130
+ * as requiring its full export surface instead of guessing from source text.
1495
2131
  *
1496
2132
  * Generated federation wrappers are excluded because their imports describe
1497
2133
  * the wrapper implementation, not the consumer's requirements.
@@ -1504,13 +2140,13 @@ function collectTreeShakingImports(code, id, shared, findSharedKey, record, mark
1504
2140
  ast = parseAst(code);
1505
2141
  } catch {
1506
2142
  Object.entries(shared).forEach(([sharedKey, shareItem]) => {
1507
- if (shareItem.shareConfig.treeShaking) markUnsafe(sharedKey, "*");
2143
+ if (shouldAnalyzeSharedExports(shareItem)) markUnsafe(sharedKey, "*");
1508
2144
  });
1509
2145
  return;
1510
2146
  }
1511
2147
  const matchShared = (source) => {
1512
2148
  const sharedKey = findSharedKey(source, shared);
1513
- return sharedKey && shared[sharedKey]?.shareConfig.treeShaking ? sharedKey : void 0;
2149
+ return sharedKey && shouldAnalyzeSharedExports(shared[sharedKey]) ? sharedKey : void 0;
1514
2150
  };
1515
2151
  const recordSource = (names, source) => {
1516
2152
  const sharedKey = matchShared(source);
@@ -1684,7 +2320,18 @@ function hasCodeMatch(source, regex, codePositions) {
1684
2320
  return false;
1685
2321
  }
1686
2322
  function hasCommonJsExports(source) {
1687
- return hasCodeMatch(source, /\bmodule\s*(?:\.exports|\[\s*['"]exports['"]\s*\])|\bexports\s*(?:\.|\[|[,)]|=(?!=|>))/g, createCodePositionMap(source));
2323
+ const codePositions = createCodePositionMap(source);
2324
+ if (hasCodeMatch(source, /\bmodule\s*(?:\.exports|\[\s*['"]exports['"]\s*\])/g, codePositions)) return true;
2325
+ const exportsRegex = /\bexports\s*(?:\.|\[|[,)]|=(?!=|>))/g;
2326
+ let match;
2327
+ while ((match = exportsRegex.exec(source)) !== null) {
2328
+ if (!codePositions[match.index]) continue;
2329
+ let previousCodeIndex = match.index - 1;
2330
+ while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
2331
+ if (source[previousCodeIndex] === ".") continue;
2332
+ return true;
2333
+ }
2334
+ return false;
1688
2335
  }
1689
2336
  function inspectSharedExportsFromFile(entryPath, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
1690
2337
  try {
@@ -1701,6 +2348,64 @@ function inspectSharedExportsFromFile(entryPath, exportConditions = DEFAULT_SHAR
1701
2348
  return;
1702
2349
  }
1703
2350
  }
2351
+ function getMutableExportsFromFile(entryPath, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS, visited = /* @__PURE__ */ new Set()) {
2352
+ if (!entryPath || visited.has(entryPath)) return [];
2353
+ visited.add(entryPath);
2354
+ try {
2355
+ const source = readFileSync(entryPath, "utf-8");
2356
+ const codePositions = createCodePositionMap(source);
2357
+ const mutableBindings = /* @__PURE__ */ new Set();
2358
+ const mutableExports = /* @__PURE__ */ new Set();
2359
+ let match;
2360
+ const declarationRegex = new RegExp(`\\b(?:export\\s+)?(?:let|var)\\s+(${JS_IDENTIFIER_PATTERN})`, "gu");
2361
+ let declarationScanIndex = 0;
2362
+ let braceDepth = 0;
2363
+ while ((match = declarationRegex.exec(source)) !== null) {
2364
+ if (!codePositions[match.index]) continue;
2365
+ for (let index = declarationScanIndex; index < match.index; index++) {
2366
+ if (!codePositions[index]) continue;
2367
+ if (source[index] === "{") braceDepth++;
2368
+ else if (source[index] === "}") braceDepth--;
2369
+ }
2370
+ declarationScanIndex = match.index;
2371
+ if (braceDepth !== 0) continue;
2372
+ mutableBindings.add(match[1]);
2373
+ if (match[0].trimStart().startsWith("export")) mutableExports.add(match[1]);
2374
+ }
2375
+ const listRegex = /export\s*\{([^}]+)\}(?:\s*from\s*['"]([^'"]+)['"])?/g;
2376
+ while ((match = listRegex.exec(source)) !== null) {
2377
+ if (!codePositions[match.index]) continue;
2378
+ const reExportPath = match[2] ? resolveReExportModule(entryPath, match[2], exportConditions) : void 0;
2379
+ const reExportedMutable = new Set(reExportPath ? getMutableExportsFromFile(reExportPath, exportConditions, visited) : []);
2380
+ for (const rawSpecifier of match[1].split(",")) {
2381
+ const specifier = rawSpecifier.trim();
2382
+ if (!specifier || specifier.startsWith("type ")) continue;
2383
+ const parts = specifier.split(/\s+as\s+/);
2384
+ const local = parts[0].trim();
2385
+ const exported = (parts[1] || local).trim();
2386
+ if (isValidEsmExportName(exported) && (mutableBindings.has(local) || reExportedMutable.has(local))) mutableExports.add(exported);
2387
+ }
2388
+ }
2389
+ const starExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g;
2390
+ while ((match = starExportRegex.exec(source)) !== null) {
2391
+ if (!codePositions[match.index]) continue;
2392
+ const resolved = resolveReExportModule(entryPath, match[1], exportConditions);
2393
+ for (const name of getMutableExportsFromFile(resolved, exportConditions, visited)) mutableExports.add(name);
2394
+ }
2395
+ visited.delete(entryPath);
2396
+ return Array.from(mutableExports);
2397
+ } catch {
2398
+ visited.delete(entryPath);
2399
+ return [];
2400
+ }
2401
+ }
2402
+ function getSharedMutableExports(pkg, shareItem, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
2403
+ const configuredImport = shareItem?.shareConfig.import;
2404
+ return getMutableExportsFromFile(typeof configuredImport === "string" ? resolveConfiguredImportPath(configuredImport, exportConditions) : getInstalledPackageEntry(pkg, {
2405
+ conditions: exportConditions,
2406
+ resolveSubpathWithRequire: false
2407
+ }), exportConditions);
2408
+ }
1704
2409
  function resolveConfiguredImportPath(importSource, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
1705
2410
  if (path$1.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
1706
2411
  const projectRoot = getPackageDetectionCwd();
@@ -1948,6 +2653,7 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
1948
2653
  const specifiers = match[1].split(",");
1949
2654
  for (const specifier of specifiers) {
1950
2655
  const trimmed = specifier.trim();
2656
+ if (!trimmed) continue;
1951
2657
  if (typeOnlySpecifierRegex.test(trimmed)) continue;
1952
2658
  const asMatch = trimmed.match(exportSpecifierRegex);
1953
2659
  if (!asMatch) {
@@ -2011,7 +2717,22 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
2011
2717
  }
2012
2718
  return Array.from(names);
2013
2719
  }
2720
+ /**
2721
+ * Reading a module's export names runs its top-level code inside the build
2722
+ * process, and getPackageNamedExports deliberately resolves the browser entry.
2723
+ * A browser entry may open a handle Node never closes — react-dom/server.browser
2724
+ * holds a module-scope MessageChannel — and one ref'd handle keeps the event loop
2725
+ * alive forever, so `vite build` writes a correct bundle and then never exits.
2726
+ *
2727
+ * Unref'ing whatever the require created is safe here because the module is
2728
+ * loaded purely to read Object.keys off it and is never used afterwards. The
2729
+ * handle list is undocumented, so its absence degrades to the previous behaviour
2730
+ * rather than failing the build. Side effects that are not handles (an exit
2731
+ * listener, a global mutation) are still not contained.
2732
+ */
2014
2733
  function getRequiredNamedExports(specifier) {
2734
+ const getActiveHandles = process._getActiveHandles;
2735
+ const handlesBeforeRequire = typeof getActiveHandles === "function" ? new Set(getActiveHandles.call(process)) : void 0;
2015
2736
  try {
2016
2737
  const mod = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json")))(specifier);
2017
2738
  const runtimeNamedKeys = Object.keys(mod).filter((key) => key !== "default" && key !== "__esModule");
@@ -2019,6 +2740,12 @@ function getRequiredNamedExports(specifier) {
2019
2740
  return runtimeNamedKeys;
2020
2741
  } catch {
2021
2742
  return;
2743
+ } finally {
2744
+ if (handlesBeforeRequire && typeof getActiveHandles === "function") for (const handle of getActiveHandles.call(process)) {
2745
+ if (handlesBeforeRequire.has(handle)) continue;
2746
+ const unref = handle?.unref;
2747
+ if (typeof unref === "function") unref.call(handle);
2748
+ }
2022
2749
  }
2023
2750
  }
2024
2751
  function getPackageNamedExports(pkg, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
@@ -2163,11 +2890,14 @@ function isSharedSingletonConsumedByPeer(pkg, options = getNormalizeModuleFedera
2163
2890
  }
2164
2891
  return false;
2165
2892
  };
2166
- return Array.from(sharedKeyByPackageName.values()).some((sharedPkg) => sharedPkg !== pkg && reachesPkg(sharedPkg, new Set([sharedPkg])));
2893
+ return Array.from(sharedKeyByPackageName.values()).some((sharedPkg) => sharedPkg !== pkg && reachesPkg(sharedPkg, /* @__PURE__ */ new Set([sharedPkg])));
2167
2894
  }
2168
2895
  function isRemoteOnlyContainer(options = getNormalizeModuleFederationOptions()) {
2169
2896
  return Object.keys(options.exposes || {}).length > 0 && Object.keys(options.remotes || {}).length === 0;
2170
2897
  }
2898
+ function isLocalOnlyContainer(options = getNormalizeModuleFederationOptions()) {
2899
+ return Object.keys(options.exposes || {}).length === 0 && Object.keys(options.remotes || {}).length === 0;
2900
+ }
2171
2901
  function tryResolveImportFromPackageRoot(pkg, root) {
2172
2902
  try {
2173
2903
  return resolveWorkspaceEsmEntry(pkg, createRequire$1(pathToFileURL(path$1.join(root, "package.json"))).resolve(pkg), root);
@@ -2317,6 +3047,7 @@ export default { get, init };
2317
3047
  materializedTreeShakingProviders.add(pkg);
2318
3048
  }
2319
3049
  function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
3050
+ const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
2320
3051
  const { preBuildCacheMap, preBuildShareItemMap } = getSharedVirtualModuleState(options);
2321
3052
  if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = createScopedSharedVirtualModule(pkg, PREBUILD_TAG, options);
2322
3053
  preBuildShareItemMap[pkg] = shareItem;
@@ -2368,14 +3099,19 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
2368
3099
  }
2369
3100
  const namedExports = getSharedNamedExports(pkg, shareItem, exportConditions) ?? [];
2370
3101
  if (namedExports.length > 0) {
2371
- const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
2372
- const declarations = namedExports.map((name, i) => `const ${namedExportVars[i]} = __mfPrebuildExports[${escapeGeneratedStringLiteral(name)}];`).join("\n ");
2373
- const namedExportLine = `export { ${namedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };`;
3102
+ const mutableExports = new Set(isLocalOnlyContainer(resolvedOptions) ? getSharedMutableExports(pkg, shareItem, exportConditions) : []);
3103
+ const copiedExports = namedExports.filter((name) => !mutableExports.has(name));
3104
+ const liveExports = namedExports.filter((name) => mutableExports.has(name));
3105
+ const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
3106
+ const declarations = copiedExports.map((name, i) => `const ${namedExportVars[i]} = __mfPrebuildExports[${escapeGeneratedStringLiteral(name)}];`).join("\n ");
3107
+ const namedExportLine = copiedExports.length ? `export { ${copiedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
3108
+ const liveExportLine = liveExports.length ? `export { ${liveExports.join(", ")} } from ${escapeGeneratedStringLiteral(importSource)};` : "";
2374
3109
  preBuildCacheMap[pkg].writeSync(`
2375
3110
  import * as __mfPrebuildNamespace from ${escapeGeneratedStringLiteral(importSource)};
2376
3111
  const __mfPrebuildExports = __mfPrebuildNamespace;
2377
3112
  ${declarations}
2378
3113
  ${namedExportLine}
3114
+ ${liveExportLine}
2379
3115
  export default Reflect.get(__mfPrebuildNamespace, "default") ?? __mfPrebuildNamespace;
2380
3116
  `, true);
2381
3117
  return;
@@ -2463,11 +3199,13 @@ function findCurrentLoadShareForStaleOwnerId(id, shared, findSharedKey, options)
2463
3199
  function getSharedCacheReadExpression(cacheDescriptor, treeShakingConsumer) {
2464
3200
  return treeShakingConsumer ? `__mfReadTreeShakingSharedSelection(__mfModuleCache.share, ${cacheDescriptor}, ${JSON.stringify(treeShakingConsumer)})` : `__mfReadSharedCache(__mfModuleCache.share, ${cacheDescriptor})`;
2465
3201
  }
2466
- function generateEagerWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer) {
2467
- const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
3202
+ function generateEagerWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, mutableExports = []) {
3203
+ const copiedExports = namedExports.filter((name) => !mutableExports.includes(name));
3204
+ const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
2468
3205
  const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
2469
- const assignments = [...namedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ");
2470
- const namedExportLine = namedExports.length > 0 ? `\n export { ${namedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
3206
+ const assignments = [...copiedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ");
3207
+ const namedExportLine = copiedExports.length > 0 ? `\n export { ${copiedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
3208
+ const mutableExportLine = mutableExports.length ? `\n export { ${mutableExports.join(", ")} } from ${escapeGeneratedStringLiteral(importSource)};` : "";
2471
3209
  return `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(importSource)};
2472
3210
  let exportModule = ${getSharedCacheReadExpression(cacheDescriptor, treeShakingConsumer)};
2473
3211
  if (exportModule === undefined) {
@@ -2484,13 +3222,15 @@ function generateEagerWorkspaceSingletonExports(namedExports, importSource, cach
2484
3222
  };
2485
3223
  __mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplyEagerShareExports);
2486
3224
  __mfApplyEagerShareExports(exportModule);
2487
- export { __mf_default as default };${namedExportLine}`;
3225
+ export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
2488
3226
  }
2489
- function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false) {
2490
- const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
3227
+ function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false, mutableExports = []) {
3228
+ const copiedExports = namedExports.filter((name) => !mutableExports.includes(name));
3229
+ const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
2491
3230
  const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
2492
- const assignments = namedExports.length > 0 ? [...namedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ") : "__mf_default = mod.default ?? mod;";
2493
- const namedExportLine = namedExports.length > 0 ? `\n export { ${namedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
3231
+ const assignments = copiedExports.length > 0 ? [...copiedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ") : "__mf_default = mod.default ?? mod;";
3232
+ const namedExportLine = copiedExports.length > 0 ? `\n export { ${copiedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
3233
+ const mutableExportLine = mutableExports.length ? `\n export { ${mutableExports.join(", ")} } from ${escapeGeneratedStringLiteral(importSource)};` : "";
2494
3234
  const applyLocalFallback = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
2495
3235
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});
2496
3236
  __mfApplyLazyShareExports(exportModule);`;
@@ -2519,7 +3259,7 @@ function generateLazyWorkspaceSingletonExports(namedExports, importSource, cache
2519
3259
  } else {
2520
3260
  __mfApplyLazyShareExports(exportModule);
2521
3261
  }
2522
- export { __mf_default as default };${namedExportLine}`;
3262
+ export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
2523
3263
  }
2524
3264
  const WORKSPACE_SINGLETON_SSR_LOCAL_SHARE = "__mfNormalizeShareModule(__mfLocalShare)";
2525
3265
  function prependWorkspaceSingletonSsrImport(code) {
@@ -2561,6 +3301,12 @@ function generateDeferredHostProvidedExports(namedExports, pkg, cacheDescriptor,
2561
3301
  }
2562
3302
  export { __mf_default as default };${namedExportLine}`;
2563
3303
  }
3304
+ function selectImportFalseNamedExports(detectedNamedExports, usage) {
3305
+ if (!detectedNamedExports || usage?.kind !== "exports") return detectedNamedExports ?? [];
3306
+ const usedNamedExports = new Set(usage.usedExports.filter((name) => name !== "default"));
3307
+ if ([...usedNamedExports].some((name) => !detectedNamedExports.includes(name))) return detectedNamedExports;
3308
+ return detectedNamedExports.filter((name) => usedNamedExports.has(name));
3309
+ }
2564
3310
  function generateShareModuleUnwrapCode({ source, preserveNamedExports, stopWithReturn }) {
2565
3311
  return `let current = ${source};
2566
3312
  for (let i = 0; i < 5; i++) {
@@ -2583,7 +3329,7 @@ const normalizeLocalShareModuleCode = `const __mfNormalizeShareModule = (mod) =>
2583
3329
  ? Object.assign({}, normalized)
2584
3330
  : normalized;
2585
3331
  };`;
2586
- function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exportConditions) {
3332
+ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exportConditions, importFalseExportUsage) {
2587
3333
  const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
2588
3334
  const { loadShareCacheMap } = getSharedVirtualModuleState(options);
2589
3335
  if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = createScopedSharedVirtualModule(pkg, LOAD_SHARE_TAG, options);
@@ -2594,7 +3340,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2594
3340
  const treeShakingConsumer = command === "build" && shareItem.shareConfig.treeShaking ? resolvedOptions.name : void 0;
2595
3341
  if (shareItem.shareConfig.import === false) {
2596
3342
  const detectedNamedExports = getPackageNamedExports(pkg, exportConditions);
2597
- const namedExports = detectedNamedExports ?? [];
3343
+ const namedExports = selectImportFalseNamedExports(detectedNamedExports, importFalseExportUsage);
2598
3344
  let exportLine;
2599
3345
  if (namedExports.length > 0) exportLine = generateDeferredHostProvidedExports(namedExports, pkg, cacheDescriptor, treeShakingConsumer);
2600
3346
  else {
@@ -2619,6 +3365,10 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2619
3365
  const skipServePrebuildWarmup = command !== "build" && (pkg === "lit" || pkg.startsWith("lit/"));
2620
3366
  const detectedNamedExports = getSharedNamedExports(pkg, shareItem, exportConditions);
2621
3367
  const namedExports = detectedNamedExports ?? [];
3368
+ const mutableExports = new Set(isLocalOnlyContainer(resolvedOptions) ? getSharedMutableExports(pkg, shareItem, exportConditions) : []);
3369
+ const copiedNamedExports = namedExports.filter((name) => !mutableExports.has(name));
3370
+ const liveNamedExports = namedExports.filter((name) => mutableExports.has(name));
3371
+ const liveNamedExportLine = liveNamedExports.length ? `export { ${liveNamedExports.join(", ")} } from ${escapeGeneratedStringLiteral(sharedImportSource)};` : "";
2622
3372
  const hasCompleteExportCoverage = detectedNamedExports !== void 0;
2623
3373
  const isWorkspaceSingleton = isWorkspacePackage && shareItem.shareConfig.singleton === true;
2624
3374
  const isDefaultShareScope = shareItem.scope === void 0 || shareItem.scope === "default" || Array.isArray(shareItem.scope) && shareItem.scope[0] === "default";
@@ -2632,11 +3382,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2632
3382
  let initBlock = "";
2633
3383
  if (usesDeferredTreeShakingFallback) {
2634
3384
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
2635
- exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback));
2636
- } else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer);
3385
+ exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback), liveNamedExports);
3386
+ } else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
2637
3387
  else if (usesDeferredSingletonFallback) {
2638
3388
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
2639
- exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback));
3389
+ exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback), liveNamedExports);
2640
3390
  } else if (detectedNamedExports === void 0) {
2641
3391
  exportLine = `const __mfDefaultExport = (() => {
2642
3392
  ${generateShareModuleUnwrapCode({
@@ -2650,10 +3400,10 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2650
3400
  initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
2651
3401
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
2652
3402
  } else if (namedExports.length > 0 && shareItem.shareConfig.singleton === true) {
2653
- const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
3403
+ const namedExportVars = copiedNamedExports.map((_name, i) => `__mf_${i}`);
2654
3404
  exportLine = `${["let __mfDefaultExport;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ")}
2655
3405
  const __mfApplySharedExports = (mod) => {
2656
- ${[...namedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), `__mfDefaultExport = (() => {
3406
+ ${[...copiedNamedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), `__mfDefaultExport = (() => {
2657
3407
  ${generateShareModuleUnwrapCode({
2658
3408
  source: "mod",
2659
3409
  preserveNamedExports: false,
@@ -2664,12 +3414,13 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2664
3414
  __mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplySharedExports);
2665
3415
  __mfApplySharedExports(exportModule);
2666
3416
  export { __mfDefaultExport as default };
2667
- ${`export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`}`;
3417
+ ${copiedNamedExports.length ? `export { ${copiedNamedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };` : ""}
3418
+ ${liveNamedExportLine}`;
2668
3419
  initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
2669
3420
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
2670
3421
  } else if (namedExports.length > 0) {
2671
- const destructure = `const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`;
2672
- const namedExportLine = `export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`;
3422
+ const destructure = copiedNamedExports.length ? `const { ${copiedNamedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;` : "";
3423
+ const namedExportLine = copiedNamedExports.length ? `export { ${copiedNamedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };` : "";
2673
3424
  exportLine = `const __mfDefaultExport = (() => {
2674
3425
  ${generateShareModuleUnwrapCode({
2675
3426
  source: "exportModule",
@@ -2679,7 +3430,8 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2679
3430
  })();
2680
3431
  export default __mfDefaultExport;
2681
3432
  ${destructure}
2682
- ${namedExportLine}`;
3433
+ ${namedExportLine}
3434
+ ${liveNamedExportLine}`;
2683
3435
  initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
2684
3436
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
2685
3437
  } else if (shareItem.shareConfig.singleton === true) {
@@ -2754,7 +3506,8 @@ function getLocalOwnerKey(options) {
2754
3506
  }
2755
3507
  function getLocalSharedImportMapPath(options) {
2756
3508
  const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
2757
- return `${LOCAL_SHARED_IMPORT_MAP_ID}:${packageNameEncode(options ? getLocalOwnerKey(resolvedOptions) : resolvedOptions.internalName || resolvedOptions.name)}`;
3509
+ const ownerName = options ? getLocalOwnerKey(resolvedOptions) : resolvedOptions.internalName || resolvedOptions.name;
3510
+ return `${LOCAL_SHARED_IMPORT_MAP_ID}:${packageNameEncode(ownerName)}`;
2758
3511
  }
2759
3512
  function getResolvedLocalSharedImportMapId(options) {
2760
3513
  return `\0${getLocalSharedImportMapPath(options)}`;
@@ -2874,7 +3627,7 @@ function generateLocalSharedImportMap(options) {
2874
3627
  if (!remote) return null;
2875
3628
  return `
2876
3629
  {
2877
- alias: ${JSON.stringify(getRuntimeRemoteAlias(key, options))},
3630
+ alias: ${JSON.stringify(key)},
2878
3631
  entryGlobalName: ${JSON.stringify(remote.entryGlobalName)},
2879
3632
  name: ${JSON.stringify(options ? getRuntimeRemoteAlias(key, options) : remote.name)},
2880
3633
  type: ${JSON.stringify(remote.type)},
@@ -3272,9 +4025,10 @@ function generateHostAutoInitSharedCacheSeedCode(command = "build", options) {
3272
4025
  }
3273
4026
  const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
3274
4027
  function getRemoteEntryId(options) {
3275
- return `${REMOTE_ENTRY_ID}:${`${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
4028
+ const scopedKey = `${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_");
4029
+ return `${REMOTE_ENTRY_ID}:${scopedKey}`;
3276
4030
  }
3277
- const SSR_ONLY_PLUGIN_SPECIFIERS = new Set(["@module-federation/vite/ssrEntryLoader"]);
4031
+ const SSR_ONLY_PLUGIN_SPECIFIERS = /* @__PURE__ */ new Set(["@module-federation/vite/ssrEntryLoader"]);
3278
4032
  const isSsrOnlyPlugin = (importStatement) => [...SSR_ONLY_PLUGIN_SPECIFIERS].some((s) => importStatement.includes(s));
3279
4033
  const getSsrOnlyPluginSpecifier = (importStatement) => [...SSR_ONLY_PLUGIN_SPECIFIERS].find((s) => importStatement.includes(s));
3280
4034
  function generateTreeShakingSharedResolutionCode(enabled) {
@@ -4240,8 +4994,9 @@ function getHostAutoInitState(options) {
4240
4994
  if (!options) return legacyHostAutoInitState;
4241
4995
  let state = hostAutoInitStates.get(options);
4242
4996
  if (!state) {
4997
+ const ownerKey = getLocalOwnerKey(options);
4243
4998
  state = {
4244
- module: new VirtualModule("hostAutoInit", HOST_AUTO_INIT_TAG, "", getLocalOwnerKey(options)),
4999
+ module: new VirtualModule("hostAutoInit", HOST_AUTO_INIT_TAG, "", ownerKey),
4245
5000
  remoteEntryId: REMOTE_ENTRY_ID,
4246
5001
  command: "build"
4247
5002
  };
@@ -4354,6 +5109,8 @@ function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer
4354
5109
  }
4355
5110
  const usedRemotesMap = {};
4356
5111
  const usedRemotesByOptions = /* @__PURE__ */ new WeakMap();
5112
+ const dynamicRemotesByOptions = /* @__PURE__ */ new WeakMap();
5113
+ const staticRemotesByOptions = /* @__PURE__ */ new WeakMap();
4357
5114
  function getScopedUsedRemotesMap(options) {
4358
5115
  let scoped = usedRemotesByOptions.get(options);
4359
5116
  if (!scoped) {
@@ -4374,6 +5131,25 @@ function getUsedRemotesMap(options) {
4374
5131
  if (options) return getScopedUsedRemotesMap(options);
4375
5132
  return usedRemotesMap;
4376
5133
  }
5134
+ function markDynamicRemote(remote, options) {
5135
+ let remotes = dynamicRemotesByOptions.get(options);
5136
+ if (!remotes) {
5137
+ remotes = /* @__PURE__ */ new Set();
5138
+ dynamicRemotesByOptions.set(options, remotes);
5139
+ }
5140
+ remotes.add(remote);
5141
+ }
5142
+ function markStaticRemote(remote, options) {
5143
+ let remotes = staticRemotesByOptions.get(options);
5144
+ if (!remotes) {
5145
+ remotes = /* @__PURE__ */ new Set();
5146
+ staticRemotesByOptions.set(options, remotes);
5147
+ }
5148
+ remotes.add(remote);
5149
+ }
5150
+ function isDynamicOnlyRemote(remote, options) {
5151
+ return (dynamicRemotesByOptions.get(options)?.has(remote) ?? false) && !(staticRemotesByOptions.get(options)?.has(remote) ?? false);
5152
+ }
4377
5153
  function getRemoteAliasFromId(id, remotes) {
4378
5154
  return Object.keys(remotes).filter((name) => id === name || id.startsWith(name + "/")).sort((a, b) => b.length - a.length)[0];
4379
5155
  }
@@ -4558,7 +5334,7 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
4558
5334
  const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
4559
5335
  entryGlobalName: remote.entryGlobalName,
4560
5336
  name: options ? runtimeRemoteAlias : remote.name,
4561
- alias: runtimeRemoteAlias,
5337
+ alias: remoteAlias,
4562
5338
  type: remote.type,
4563
5339
  entry: remote.entry,
4564
5340
  shareScope: remote.shareScope ?? "default"
@@ -4796,7 +5572,7 @@ const __mfCurrentScript = document.currentScript;
4796
5572
  const entryImportDeclaration = isEncodedVirtualEntry ? `const __mfEntryUrl = ${JSON.stringify(entrySrc)};
4797
5573
  ` : "";
4798
5574
  const entryImportExpression = isEncodedVirtualEntry ? "import(/* @vite-ignore */ __mfEntryUrl)" : importExpression(entrySrc);
4799
- const remotePreloads = !options?.skipRemotePreload && (federationOptions ?? getNormalizeModuleFederationOptions())?.shareStrategy !== "loaded-first" ? Object.entries(getUsedRemotesMap(federationOptions)).flatMap(([, remotes]) => Array.from(remotes)).sort().map((remote) => `__mfPreloadRemote(${JSON.stringify(getRuntimeRemoteId(remote, (federationOptions ?? getNormalizeModuleFederationOptions()).remotes, federationOptions))}, ${JSON.stringify(remote)})`).join(",") : "";
5575
+ const remotePreloads = !options?.skipRemotePreload && (federationOptions ?? getNormalizeModuleFederationOptions())?.shareStrategy !== "loaded-first" ? Object.entries(getUsedRemotesMap(federationOptions)).flatMap(([, remotes]) => Array.from(remotes)).filter((remote) => !federationOptions || !isDynamicOnlyRemote(remote, federationOptions)).sort().map((remote) => `__mfPreloadRemote(${JSON.stringify(getRuntimeRemoteId(remote, (federationOptions ?? getNormalizeModuleFederationOptions()).remotes, federationOptions))}, ${JSON.stringify(remote)})`).join(",") : "";
4800
5576
  const remoteCachePrefix = getRuntimeRemoteCachePrefix(federationOptions);
4801
5577
  const preloadBlock = remotePreloads ? `
4802
5578
  const runtime = await initHost();
@@ -4943,10 +5719,11 @@ const __mfCurrentScript = document.currentScript;
4943
5719
  const entrySrc = stripBase(originalSrc);
4944
5720
  addEntryRemoteImports(entrySrc);
4945
5721
  const resolvedEntrySrc = entrySrc.startsWith("virtual:") ? toViteEncodedId(entrySrc) : entrySrc;
4946
- return toViteEncodedId(`${DEV_HTML_PROXY_PREFIX}${new URLSearchParams({
5722
+ const query = new URLSearchParams({
4947
5723
  init: sanitizeDevEntryPath(stripBase(devEntryPath)),
4948
5724
  entry: sanitizeDevEntryPath(resolvedEntrySrc)
4949
- }).toString()}`);
5725
+ }).toString();
5726
+ return toViteEncodedId(`${DEV_HTML_PROXY_PREFIX}${query}`);
4950
5727
  });
4951
5728
  return html === c ? injectEntryScript(c, stripBase(devEntryPath)) : html;
4952
5729
  }
@@ -5332,7 +6109,7 @@ const REMOTE_HMR_ENDPOINT = "__mf_hmr";
5332
6109
  const REMOTE_HMR_EVENT = "mf:remote-update";
5333
6110
  const REMOTE_HMR_CONNECT_RETRY_DELAY_MS = 1e3;
5334
6111
  const REMOTE_HMR_CONNECT_MAX_RETRIES = 10;
5335
- function getBasePath(base) {
6112
+ function getBasePath$1(base) {
5336
6113
  if (!base) return "/";
5337
6114
  if (base.startsWith("http://") || base.startsWith("https://")) try {
5338
6115
  return new URL(base).pathname || "/";
@@ -5342,11 +6119,11 @@ function getBasePath(base) {
5342
6119
  return base;
5343
6120
  }
5344
6121
  function getRemoteHmrPath(base) {
5345
- return `${getBasePath(base).replace(/\/?$/, "/")}${REMOTE_HMR_ENDPOINT}`.replace(/\/{2,}/g, "/");
6122
+ return `${getBasePath$1(base).replace(/\/?$/, "/")}${REMOTE_HMR_ENDPOINT}`.replace(/\/{2,}/g, "/");
5346
6123
  }
5347
6124
  function getHmrWsPath(base, hmrPath) {
5348
- const normalizedBase = getBasePath(base);
5349
- const normalizedPath = getBasePath(hmrPath || "");
6125
+ const normalizedBase = getBasePath$1(base);
6126
+ const normalizedPath = getBasePath$1(hmrPath || "");
5350
6127
  if (!normalizedPath || normalizedPath === "/") return normalizedBase;
5351
6128
  return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
5352
6129
  }
@@ -6267,7 +7044,8 @@ function generateExposesSSR(options, reactIslandExposes = /* @__PURE__ */ new Se
6267
7044
  //#region src/virtualModules/virtualRemoteEntrySSR.ts
6268
7045
  const REMOTE_ENTRY_SSR_ID = "virtual:mf-REMOTE_ENTRY_SSR_ID";
6269
7046
  function getRemoteEntrySSRId(options) {
6270
- return `${REMOTE_ENTRY_SSR_ID}:${`${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
7047
+ const scopedKey = `${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_");
7048
+ return `${REMOTE_ENTRY_SSR_ID}:${scopedKey}`;
6271
7049
  }
6272
7050
  function getSsrRemoteEntryFileName(browserFilename) {
6273
7051
  const ext = browserFilename.match(/\.[^.]+$/)?.[0] || ".js";
@@ -6345,6 +7123,318 @@ function generateRemoteEntrySSR(options) {
6345
7123
  `;
6346
7124
  }
6347
7125
  //#endregion
7126
+ //#region src/plugins/pluginDts.ts
7127
+ var pluginDts_exports = /* @__PURE__ */ __exportAll({
7128
+ DEFAULT_PUBLIC_TYPES_FOLDER: () => DEFAULT_PUBLIC_TYPES_FOLDER,
7129
+ createDevDtsAssetMiddleware: () => createDevDtsAssetMiddleware,
7130
+ default: () => pluginDts,
7131
+ getDevDtsAssetPaths: () => getDevDtsAssetPaths,
7132
+ resolveDtsPluginOptions: () => resolveDtsPluginOptions
7133
+ });
7134
+ const DEFAULT_DEV_OPTIONS = {
7135
+ disableLiveReload: true,
7136
+ disableHotTypesReload: false,
7137
+ disableDynamicRemoteTypeHints: false
7138
+ };
7139
+ const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
7140
+ const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
7141
+ const DEV_TYPES_FOLDER = ".dev-server";
7142
+ const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
7143
+ const forkDevWorkerPath = (() => {
7144
+ return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
7145
+ })();
7146
+ var DevWorker = class {
7147
+ worker = rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
7148
+ constructor(options) {
7149
+ this.worker.connect(options);
7150
+ }
7151
+ update() {
7152
+ this.worker.process?.send?.({
7153
+ type: rpc.RpcGMCallTypes.CALL,
7154
+ id: this.worker.id,
7155
+ args: [void 0, "update"]
7156
+ });
7157
+ }
7158
+ exit() {
7159
+ this.worker.terminate();
7160
+ }
7161
+ };
7162
+ const normalizeDevOptions = (dev) => {
7163
+ if (dev === false) return false;
7164
+ if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
7165
+ return {
7166
+ ...DEFAULT_DEV_OPTIONS,
7167
+ ...dev
7168
+ };
7169
+ };
7170
+ const buildDtsModuleFederationConfig = (options) => {
7171
+ const exposes = {};
7172
+ Object.entries(options.exposes).forEach(([key, value]) => {
7173
+ if (value.import) exposes[key] = value.import;
7174
+ });
7175
+ const remotes = {};
7176
+ Object.entries(options.remotes).forEach(([key, remote]) => {
7177
+ if (!remote.entry) return;
7178
+ const entryGlobalName = remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key;
7179
+ remotes[key] = `${entryGlobalName}@${remote.entry}`;
7180
+ });
7181
+ return {
7182
+ ...options,
7183
+ exposes,
7184
+ remotes
7185
+ };
7186
+ };
7187
+ const resolveOutputDir = (config) => {
7188
+ const { outDir } = config.build;
7189
+ if (path$1.isAbsolute(outDir)) return normalizePathForImport(path$1.relative(config.root, outDir));
7190
+ return outDir;
7191
+ };
7192
+ const ensureRuntimePlugin = (options, pluginId) => {
7193
+ if (!options.runtimePlugins.some((plugin) => {
7194
+ if (typeof plugin === "string") return plugin === pluginId;
7195
+ return plugin[0] === pluginId;
7196
+ })) options.runtimePlugins.push(pluginId);
7197
+ };
7198
+ const getExposeImportPaths = (options) => {
7199
+ return Object.values(options.exposes).map((value) => {
7200
+ return value.import;
7201
+ }).filter((value) => Boolean(value));
7202
+ };
7203
+ const usesVueSfcExposes = (options) => {
7204
+ return getExposeImportPaths(options).some((value) => value.endsWith(".vue"));
7205
+ };
7206
+ const resolveDtsPluginOptions = (dts, options, context) => {
7207
+ if (dts === false) return false;
7208
+ const inferredGenerateTypesDefaults = { generateAPITypes: true };
7209
+ if (usesVueSfcExposes(options) && hasPackageDependency("vue-tsc", context)) inferredGenerateTypesDefaults.compilerInstance = "vue-tsc";
7210
+ if (dts === true || typeof dts === "undefined") return { generateTypes: inferredGenerateTypesDefaults };
7211
+ const generateTypes = dts.generateTypes;
7212
+ return {
7213
+ ...dts,
7214
+ generateTypes: generateTypes === false ? false : {
7215
+ ...inferredGenerateTypesDefaults,
7216
+ ...generateTypes === true || typeof generateTypes === "undefined" ? {} : generateTypes
7217
+ }
7218
+ };
7219
+ };
7220
+ const getBasePath = (base) => {
7221
+ if (base.startsWith("http://") || base.startsWith("https://")) return new URL(base).pathname.replace(/\/$/, "") || "/";
7222
+ return base.replace(/\/$/, "") || "/";
7223
+ };
7224
+ const joinBaseAndAsset = (base, assetFileName) => {
7225
+ const basePath = getBasePath(base);
7226
+ return `${basePath === "/" ? "" : basePath}/${assetFileName}`.replace(/\/{2,}/g, "/");
7227
+ };
7228
+ const getDevDtsAssetPaths = (options) => {
7229
+ const { outputDir, publicTypesFolder, root, base } = options;
7230
+ return {
7231
+ apiFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.d.ts`),
7232
+ apiRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.d.ts`),
7233
+ zipFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.zip`),
7234
+ zipRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.zip`)
7235
+ };
7236
+ };
7237
+ const createDevDtsAssetMiddleware = (assetPaths) => {
7238
+ return (req, res, next) => {
7239
+ const requestPath = req.url?.split("?")[0];
7240
+ const isZipRequest = requestPath === assetPaths.zipRequestPath;
7241
+ const isApiRequest = requestPath === assetPaths.apiRequestPath;
7242
+ if (!isZipRequest && !isApiRequest) {
7243
+ next();
7244
+ return;
7245
+ }
7246
+ const filePath = isZipRequest ? assetPaths.zipFilePath : assetPaths.apiFilePath;
7247
+ if (!fs.existsSync(filePath)) {
7248
+ res.statusCode = 404;
7249
+ res.end();
7250
+ return;
7251
+ }
7252
+ res.statusCode = 200;
7253
+ res.setHeader("Content-Type", isZipRequest ? "application/x-gzip" : "application/typescript");
7254
+ if (req.method === "HEAD") {
7255
+ res.end();
7256
+ return;
7257
+ }
7258
+ const stream = fs.createReadStream(filePath);
7259
+ stream.on("error", () => {
7260
+ if (!res.headersSent) res.statusCode = 500;
7261
+ res.end();
7262
+ });
7263
+ res.on("close", () => {
7264
+ stream.destroy();
7265
+ });
7266
+ stream.pipe(res);
7267
+ };
7268
+ };
7269
+ const normalizeDevDtsOptions = (dts, context) => {
7270
+ return normalizeOptions(isTSProject(dts, context), {
7271
+ generateTypes: { compileInChildProcess: true },
7272
+ consumeTypes: { consumeAPITypes: true },
7273
+ extraOptions: {},
7274
+ displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
7275
+ }, "mfOptions.dts")(dts);
7276
+ };
7277
+ const logDtsError = (error, dtsOptions) => {
7278
+ if (dtsOptions === false) return;
7279
+ if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
7280
+ mfError(error);
7281
+ };
7282
+ function pluginDts(options) {
7283
+ if (options.dts === false) return [];
7284
+ const baseDtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
7285
+ const getDtsModuleFederationConfig = (context) => ({
7286
+ ...baseDtsModuleFederationConfig,
7287
+ dts: resolveDtsPluginOptions(options.dts, options, context)
7288
+ });
7289
+ let resolvedConfig;
7290
+ let devWorker;
7291
+ let normalizedDevOptions;
7292
+ let hasGeneratedBundle = false;
7293
+ return [{
7294
+ name: "module-federation-dts-dev",
7295
+ apply: "serve",
7296
+ config(config) {
7297
+ normalizedDevOptions = normalizeDevOptions(options.dev);
7298
+ if (!normalizedDevOptions) return;
7299
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
7300
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
7301
+ const define = config.define ? { ...config.define } : {};
7302
+ if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
7303
+ config.define = define;
7304
+ },
7305
+ configResolved(config) {
7306
+ resolvedConfig = config;
7307
+ },
7308
+ configureServer(server) {
7309
+ if (!normalizedDevOptions || !resolvedConfig) return;
7310
+ const devOptions = normalizedDevOptions;
7311
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
7312
+ if (!options.name) throw createModuleFederationError("name is required if you want to enable dev server!");
7313
+ const outputDir = resolveOutputDir(resolvedConfig);
7314
+ const dtsModuleFederationConfig = getDtsModuleFederationConfig(resolvedConfig.root);
7315
+ const normalizedDtsOptions = normalizeDevDtsOptions(dtsModuleFederationConfig.dts, resolvedConfig.root);
7316
+ if (typeof normalizedDtsOptions !== "object") return;
7317
+ const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
7318
+ const remote = normalizedGenerateTypes === false ? void 0 : {
7319
+ implementation: normalizedDtsOptions.implementation,
7320
+ context: resolvedConfig.root,
7321
+ outputDir,
7322
+ moduleFederationConfig: { ...dtsModuleFederationConfig },
7323
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
7324
+ ...normalizedGenerateTypes,
7325
+ typesFolder: DEV_TYPES_FOLDER
7326
+ };
7327
+ if (remote) server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({
7328
+ outputDir,
7329
+ publicTypesFolder: remote.hostRemoteTypesFolder || "@mf-types",
7330
+ root: resolvedConfig.root,
7331
+ base: resolvedConfig.base
7332
+ })));
7333
+ if (remote && !remote.tsConfigPath && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
7334
+ const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
7335
+ const host = normalizedConsumeTypes === false ? void 0 : {
7336
+ implementation: normalizedDtsOptions.implementation,
7337
+ context: resolvedConfig.root,
7338
+ moduleFederationConfig: dtsModuleFederationConfig,
7339
+ typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
7340
+ abortOnError: false,
7341
+ ...normalizedConsumeTypes
7342
+ };
7343
+ const extraOptions = normalizedDtsOptions.extraOptions || {};
7344
+ if (!remote && !host && devOptions.disableLiveReload) return;
7345
+ const startDevWorker = async () => {
7346
+ let remoteTypeUrls;
7347
+ if (host) remoteTypeUrls = await new Promise((resolve) => {
7348
+ consumeTypesAPI({
7349
+ host,
7350
+ extraOptions,
7351
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
7352
+ }, resolve);
7353
+ });
7354
+ devWorker = new DevWorker({
7355
+ name: options.name,
7356
+ remote,
7357
+ host: host ? {
7358
+ ...host,
7359
+ remoteTypeUrls
7360
+ } : void 0,
7361
+ extraOptions,
7362
+ disableLiveReload: devOptions.disableLiveReload,
7363
+ disableHotTypesReload: devOptions.disableHotTypesReload
7364
+ });
7365
+ const update = () => devWorker?.update();
7366
+ server.watcher.on("change", update);
7367
+ server.watcher.on("add", update);
7368
+ server.watcher.on("unlink", update);
7369
+ server.httpServer?.once("close", () => {
7370
+ devWorker?.exit();
7371
+ server.watcher.off("change", update);
7372
+ server.watcher.off("add", update);
7373
+ server.watcher.off("unlink", update);
7374
+ });
7375
+ };
7376
+ startDevWorker().catch((error) => {
7377
+ logDtsError(error, normalizedDtsOptions);
7378
+ });
7379
+ }
7380
+ }, {
7381
+ name: "module-federation-dts-build",
7382
+ apply: "build",
7383
+ configResolved(config) {
7384
+ resolvedConfig = config;
7385
+ },
7386
+ async generateBundle() {
7387
+ if (hasGeneratedBundle) return;
7388
+ hasGeneratedBundle = true;
7389
+ if (!resolvedConfig) return;
7390
+ let normalizedDtsOptions;
7391
+ try {
7392
+ normalizedDtsOptions = normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root), resolvedConfig.root);
7393
+ } catch (error) {
7394
+ logDtsError(error, options.dts);
7395
+ return;
7396
+ }
7397
+ if (typeof normalizedDtsOptions !== "object") return;
7398
+ const context = resolvedConfig.root;
7399
+ const outputDir = resolveOutputDir(resolvedConfig);
7400
+ let consumeOptions;
7401
+ try {
7402
+ consumeOptions = normalizeConsumeTypesOptions({
7403
+ context,
7404
+ dtsOptions: normalizedDtsOptions,
7405
+ pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
7406
+ });
7407
+ } catch (error) {
7408
+ logDtsError(error, normalizedDtsOptions);
7409
+ return;
7410
+ }
7411
+ if (consumeOptions?.host?.typesOnBuild) try {
7412
+ await consumeTypesAPI(consumeOptions);
7413
+ } catch (error) {
7414
+ logDtsError(error, normalizedDtsOptions);
7415
+ }
7416
+ let generateOptions;
7417
+ try {
7418
+ generateOptions = normalizeGenerateTypesOptions({
7419
+ context,
7420
+ outputDir,
7421
+ dtsOptions: normalizedDtsOptions,
7422
+ pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
7423
+ });
7424
+ } catch (error) {
7425
+ logDtsError(error, normalizedDtsOptions);
7426
+ return;
7427
+ }
7428
+ if (!generateOptions) return;
7429
+ try {
7430
+ await generateTypesAPI({ dtsManagerOptions: generateOptions });
7431
+ } catch (error) {
7432
+ logDtsError(error, normalizedDtsOptions);
7433
+ }
7434
+ }
7435
+ }];
7436
+ }
7437
+ //#endregion
6348
7438
  //#region src/plugins/pluginMFManifest.ts
6349
7439
  /**
6350
7440
  * Resolves the build version for the module federation manifest.
@@ -6447,9 +7537,20 @@ const Manifest = (providedOptions) => {
6447
7537
  return [{
6448
7538
  name: "module-federation-manifest",
6449
7539
  apply: "serve",
7540
+ /**
7541
+ * Stores resolved Vite config for later use
7542
+ */
7543
+ /**
7544
+ * Finalizes configuration after all plugins are resolved
7545
+ * @param config - Fully resolved Vite config
7546
+ */
6450
7547
  configResolved(config) {
6451
7548
  viteConfig = config;
6452
7549
  },
7550
+ /**
7551
+ * Configures dev server middleware to handle manifest requests
7552
+ * @param server - Vite dev server instance
7553
+ */
6453
7554
  configureServer(server) {
6454
7555
  server.middlewares.use((req, res, next) => {
6455
7556
  const devRemoteEntryFile = resolveDevRemoteEntryFileName(filename);
@@ -6507,6 +7608,11 @@ const Manifest = (providedOptions) => {
6507
7608
  }, {
6508
7609
  name: "module-federation-manifest",
6509
7610
  enforce: "post",
7611
+ /**
7612
+ * Initial plugin configuration
7613
+ * @param config - Vite config object
7614
+ * @param command - Current Vite command (serve/build)
7615
+ */
6510
7616
  config(config, { command }) {
6511
7617
  _command = command;
6512
7618
  if (!config.build) config.build = {};
@@ -6521,6 +7627,11 @@ const Manifest = (providedOptions) => {
6521
7627
  if (_command === "serve") base = (config.server.origin || "") + config.base;
6522
7628
  publicPath = mfOptions.publicPath === "auto" ? "auto" : resolvePublicPath(mfOptions, base, _originalConfigBase);
6523
7629
  },
7630
+ /**
7631
+ * Generates the module federation manifest file
7632
+ * @param options - Rollup output options
7633
+ * @param bundle - Generated bundle assets
7634
+ */
6524
7635
  async generateBundle(_options, bundle) {
6525
7636
  if (!mfManifestName) return;
6526
7637
  if (this.environment?.name === "ssr") return;
@@ -6716,116 +7827,174 @@ function getStatsFileName(manifestFileName) {
6716
7827
  }
6717
7828
  //#endregion
6718
7829
  //#region src/plugins/pluginModuleParseEnd.ts
6719
- let _resolve = null;
6720
- let _parseTimeout = null;
6721
- let _settleTimeout = null;
6722
- let parsePromise = Promise.resolve(1);
6723
- let parseStartSet = /* @__PURE__ */ new Set();
6724
- let parseEndSet = /* @__PURE__ */ new Set();
6725
- let lastLoadedModule = "";
6726
- let lastParsedModule = "";
6727
- function clearParseTimeout() {
6728
- if (_parseTimeout) {
6729
- clearTimeout(_parseTimeout);
6730
- _parseTimeout = null;
6731
- }
6732
- }
6733
- function clearSettleTimeout() {
6734
- if (_settleTimeout) {
6735
- clearTimeout(_settleTimeout);
6736
- _settleTimeout = null;
6737
- }
6738
- }
6739
- function resetParseState() {
6740
- clearParseTimeout();
6741
- clearSettleTimeout();
6742
- parseStartSet = /* @__PURE__ */ new Set();
6743
- parseEndSet = /* @__PURE__ */ new Set();
6744
- lastLoadedModule = "";
6745
- lastParsedModule = "";
6746
- parsePromise = new Promise((resolve) => {
6747
- _resolve = (v) => {
6748
- clearParseTimeout();
6749
- clearSettleTimeout();
6750
- resolve(v);
7830
+ function createModuleParseController() {
7831
+ return {
7832
+ resolve: null,
7833
+ parseTimeout: null,
7834
+ settleTimeout: null,
7835
+ parsePromise: Promise.resolve({
7836
+ complete: false,
7837
+ reason: "initial"
7838
+ }),
7839
+ parseStartSet: /* @__PURE__ */ new Set(),
7840
+ parseEndSet: /* @__PURE__ */ new Set(),
7841
+ discardWarned: false,
7842
+ externalSet: /* @__PURE__ */ new Set(),
7843
+ resolutionProbed: /* @__PURE__ */ new Set(),
7844
+ lastLoadedModule: "",
7845
+ lastParsedModule: ""
7846
+ };
7847
+ }
7848
+ function clearParseTimeout(controller) {
7849
+ if (controller.parseTimeout) {
7850
+ clearTimeout(controller.parseTimeout);
7851
+ controller.parseTimeout = null;
7852
+ }
7853
+ }
7854
+ function clearSettleTimeout(controller) {
7855
+ if (controller.settleTimeout) {
7856
+ clearTimeout(controller.settleTimeout);
7857
+ controller.settleTimeout = null;
7858
+ }
7859
+ }
7860
+ function resetParseState(controller) {
7861
+ clearParseTimeout(controller);
7862
+ clearSettleTimeout(controller);
7863
+ controller.parseStartSet = /* @__PURE__ */ new Set();
7864
+ controller.parseEndSet = /* @__PURE__ */ new Set();
7865
+ controller.externalSet = /* @__PURE__ */ new Set();
7866
+ controller.resolutionProbed = /* @__PURE__ */ new Set();
7867
+ controller.discardWarned = false;
7868
+ controller.lastLoadedModule = "";
7869
+ controller.lastParsedModule = "";
7870
+ controller.parsePromise = new Promise((resolve) => {
7871
+ controller.resolve = (result) => {
7872
+ clearParseTimeout(controller);
7873
+ clearSettleTimeout(controller);
7874
+ resolve(result);
6751
7875
  };
6752
7876
  });
6753
7877
  }
6754
- function setParseTimeout(timeout) {
6755
- if (!_parseTimeout) _parseTimeout = setTimeout(() => {
7878
+ function setParseTimeout(controller, timeout) {
7879
+ if (!controller.parseTimeout) controller.parseTimeout = setTimeout(() => {
6756
7880
  mfWarn(`Parse timeout (${timeout}s) - forcing resolve`);
6757
- _resolve?.(1);
7881
+ controller.resolve?.({
7882
+ complete: false,
7883
+ reason: "timeout"
7884
+ });
6758
7885
  }, timeout * 1e3);
6759
7886
  }
6760
- function resetIdleTimeout(timeout) {
6761
- clearParseTimeout();
6762
- _parseTimeout = setTimeout(() => {
6763
- const pendingModules = Array.from(parseStartSet).filter((moduleId) => !parseEndSet.has(moduleId));
6764
- mfWarn(`moduleParseIdleTimeout: no module activity for ${timeout}s, forcing resolve. Some shared/remote dependencies may be missing. Consider increasing moduleParseIdleTimeout. Tracked modules: ${parseEndSet.size}/${parseStartSet.size}.` + (lastLoadedModule ? ` Last loaded: ${lastLoadedModule}.` : "") + (lastParsedModule ? ` Last parsed: ${lastParsedModule}.` : "") + (pendingModules.length ? ` Pending modules: ${pendingModules.slice(0, 10).join(", ")}` : ""));
6765
- _resolve?.(1);
7887
+ function resetIdleTimeout(controller, timeout) {
7888
+ clearParseTimeout(controller);
7889
+ controller.parseTimeout = setTimeout(() => {
7890
+ const pendingModules = Array.from(controller.parseStartSet).filter((moduleId) => !controller.parseEndSet.has(moduleId));
7891
+ mfWarn(`moduleParseIdleTimeout: no module activity for ${timeout}s, forcing resolve. Some shared/remote dependencies may be missing. Consider increasing moduleParseIdleTimeout. Tracked modules: ${controller.parseEndSet.size}/${controller.parseStartSet.size}.` + (controller.lastLoadedModule ? ` Last loaded: ${controller.lastLoadedModule}.` : "") + (controller.lastParsedModule ? ` Last parsed: ${controller.lastParsedModule}.` : "") + (pendingModules.length ? ` Pending modules: ${pendingModules.slice(0, 10).join(", ")}` : ""));
7892
+ controller.resolve?.({
7893
+ complete: false,
7894
+ reason: "idle-timeout"
7895
+ });
6766
7896
  }, timeout * 1e3);
6767
7897
  }
6768
- function scheduleParseCompletionCheck() {
6769
- clearSettleTimeout();
6770
- _settleTimeout = setTimeout(() => {
6771
- _settleTimeout = null;
6772
- if (parseStartSet.size > 0 && Array.from(parseStartSet).every((moduleId) => parseEndSet.has(moduleId))) _resolve?.(1);
7898
+ function scheduleParseCompletionCheck(controller) {
7899
+ clearSettleTimeout(controller);
7900
+ controller.settleTimeout = setTimeout(() => {
7901
+ controller.settleTimeout = null;
7902
+ if (controller.parseStartSet.size > 0 && Array.from(controller.parseStartSet).every((moduleId) => controller.parseEndSet.has(moduleId))) controller.resolve?.({
7903
+ complete: true,
7904
+ reason: "graph-complete"
7905
+ });
6773
7906
  }, 10);
6774
7907
  }
6775
- function pluginModuleParseEnd_default(excludeFn, options) {
7908
+ function matchesExternal(external, id, importer) {
7909
+ if (!external) return false;
7910
+ if (typeof external === "function") return external(id, importer, true) === true;
7911
+ return (Array.isArray(external) ? external : [external]).some((entry) => {
7912
+ if (typeof entry === "string") return entry === id;
7913
+ entry.lastIndex = 0;
7914
+ return entry.test(id);
7915
+ });
7916
+ }
7917
+ function getConfiguredInputImports(input) {
7918
+ if (typeof input === "string") return [input];
7919
+ if (Array.isArray(input)) return input.filter((entry) => typeof entry === "string");
7920
+ if (!input || typeof input !== "object") return [];
7921
+ return Object.values(input).filter((entry) => typeof entry === "string");
7922
+ }
7923
+ function pluginModuleParseEnd_default(excludeFn, options, controller = createModuleParseController()) {
6776
7924
  const idleTimeout = options.moduleParseIdleTimeout ?? options.moduleParseTimeout;
6777
- return [
6778
- {
6779
- name: "_",
6780
- apply: "serve",
6781
- config() {
6782
- _resolve?.(1);
7925
+ let configuredInputImports = [];
7926
+ let configuredExternal;
7927
+ return [{
7928
+ enforce: "pre",
7929
+ name: "parseStart",
7930
+ apply: "build",
7931
+ configResolved(config) {
7932
+ const buildOptions = config.build;
7933
+ configuredInputImports = getConfiguredInputImports(buildOptions.rollupOptions.input ?? buildOptions.rolldownOptions?.input);
7934
+ configuredExternal = buildOptions.rollupOptions.external ?? buildOptions.rolldownOptions?.external;
7935
+ },
7936
+ async buildStart() {
7937
+ resetParseState(controller);
7938
+ if (idleTimeout) resetIdleTimeout(controller, idleTimeout);
7939
+ else if (options.moduleParseTimeout) setParseTimeout(controller, options.moduleParseTimeout);
7940
+ const entryImports = /* @__PURE__ */ new Set([...options.exposedModuleImports || [], ...configuredInputImports]);
7941
+ for (const importSource of entryImports) {
7942
+ const resolved = await this.resolve(importSource);
7943
+ if (resolved && !resolved.external && !excludeFn(resolved.id)) controller.parseStartSet.add(resolved.id);
6783
7944
  }
6784
7945
  },
6785
- {
6786
- enforce: "pre",
6787
- name: "parseStart",
6788
- apply: "build",
6789
- async buildStart() {
6790
- resetParseState();
6791
- if (idleTimeout) resetIdleTimeout(idleTimeout);
6792
- else if (options.moduleParseTimeout) setParseTimeout(options.moduleParseTimeout);
6793
- for (const importSource of options.exposedModuleImports || []) {
6794
- const resolved = await this.resolve(importSource);
6795
- if (resolved && !resolved.external && !excludeFn(resolved.id)) parseStartSet.add(resolved.id);
7946
+ load(id) {
7947
+ controller.lastLoadedModule = id;
7948
+ if (excludeFn(id)) return;
7949
+ clearSettleTimeout(controller);
7950
+ if (idleTimeout) resetIdleTimeout(controller, idleTimeout);
7951
+ controller.parseStartSet.add(id);
7952
+ }
7953
+ }, {
7954
+ enforce: "post",
7955
+ name: "parseEnd",
7956
+ apply: "build",
7957
+ moduleParsed(module) {
7958
+ clearSettleTimeout(controller);
7959
+ const id = module.id;
7960
+ controller.lastParsedModule = id;
7961
+ if (idleTimeout) resetIdleTimeout(controller, idleTimeout);
7962
+ const parsedModule = module;
7963
+ const addPendingResolutions = (resolutions) => {
7964
+ for (const resolution of resolutions || []) if (!resolution.external && !excludeFn(resolution.id)) controller.parseStartSet.add(resolution.id);
7965
+ };
7966
+ const probeExternal = (pendingId) => {
7967
+ if (typeof this.resolve !== "function") return;
7968
+ if (controller.resolutionProbed.has(pendingId)) return;
7969
+ controller.resolutionProbed.add(pendingId);
7970
+ this.resolve(pendingId, id, { skipSelf: true }).then((resolved) => {
7971
+ if (!resolved?.external) return;
7972
+ controller.externalSet.add(pendingId);
7973
+ controller.parseStartSet.delete(pendingId);
7974
+ scheduleParseCompletionCheck(controller);
7975
+ }).catch(() => {});
7976
+ };
7977
+ const addPendingIds = (ids) => {
7978
+ for (const pendingId of ids || []) {
7979
+ if (!this.getModuleInfo(pendingId) || controller.externalSet.has(pendingId) || matchesExternal(configuredExternal, pendingId, id) || excludeFn(pendingId)) continue;
7980
+ controller.parseStartSet.add(pendingId);
7981
+ if (!controller.parseEndSet.has(pendingId)) probeExternal(pendingId);
6796
7982
  }
6797
- },
6798
- load(id) {
6799
- lastLoadedModule = id;
6800
- if (excludeFn(id)) return;
6801
- clearSettleTimeout();
6802
- if (idleTimeout) resetIdleTimeout(idleTimeout);
6803
- parseStartSet.add(id);
6804
- }
7983
+ };
7984
+ addPendingResolutions(parsedModule.importedIdResolutions);
7985
+ addPendingResolutions(parsedModule.dynamicallyImportedIdResolutions);
7986
+ if (parsedModule.importedIdResolutions === void 0) addPendingIds(module.importedIds);
7987
+ if (parsedModule.dynamicallyImportedIdResolutions === void 0) addPendingIds(module.dynamicallyImportedIds);
7988
+ if (!excludeFn(id)) controller.parseEndSet.add(id);
7989
+ scheduleParseCompletionCheck(controller);
6805
7990
  },
6806
- {
6807
- enforce: "post",
6808
- name: "parseEnd",
6809
- apply: "build",
6810
- moduleParsed(module) {
6811
- clearSettleTimeout();
6812
- const id = module.id;
6813
- lastParsedModule = id;
6814
- if (idleTimeout) resetIdleTimeout(idleTimeout);
6815
- const parsedModule = module;
6816
- const addPendingResolutions = (resolutions) => {
6817
- for (const resolution of resolutions || []) if (!resolution.external && !excludeFn(resolution.id)) parseStartSet.add(resolution.id);
6818
- };
6819
- addPendingResolutions(parsedModule.importedIdResolutions);
6820
- addPendingResolutions(parsedModule.dynamicallyImportedIdResolutions);
6821
- if (!excludeFn(id)) parseEndSet.add(id);
6822
- scheduleParseCompletionCheck();
6823
- },
6824
- buildEnd() {
6825
- _resolve?.(1);
6826
- }
7991
+ buildEnd() {
7992
+ controller.resolve?.({
7993
+ complete: false,
7994
+ reason: "build-end"
7995
+ });
6827
7996
  }
6828
- ];
7997
+ }];
6829
7998
  }
6830
7999
  //#endregion
6831
8000
  //#region src/plugins/pluginProxyRemoteEntry.ts
@@ -6835,7 +8004,7 @@ function resolveDevHashEntryFileName(fileName) {
6835
8004
  const baseName = path$1.basename(normalized);
6836
8005
  return path$1.extname(baseName) ? normalized : `${normalized}.js`;
6837
8006
  }
6838
- function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId }) {
8007
+ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId, getParsePromise = () => Promise.resolve() }) {
6839
8008
  let viteConfig, _command, root, originalConfigBase;
6840
8009
  let exposeRemoteDependencies = {};
6841
8010
  let exposeRemoteDependenciesDirty = true;
@@ -6945,7 +8114,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
6945
8114
  }
6946
8115
  },
6947
8116
  async load(id) {
6948
- if (id === remoteEntryId) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId, _command));
8117
+ if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
6949
8118
  if (id === virtualExposesId) {
6950
8119
  await refreshExposeRemoteDependencies(this);
6951
8120
  return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
@@ -6955,7 +8124,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
6955
8124
  async transform(code, id) {
6956
8125
  return mapCodeToCodeWithSourcemap(await (async () => {
6957
8126
  if (!filterId(id)) return;
6958
- if (id.includes(remoteEntryId)) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId, _command));
8127
+ if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
6959
8128
  if (id === virtualExposesId) {
6960
8129
  await refreshExposeRemoteDependencies(this);
6961
8130
  return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
@@ -7091,11 +8260,58 @@ function pluginProxyRemotes_default(options) {
7091
8260
  enableSsrInit = getSsrCapabilities(parseInt(version, 10), command, Object.keys(remotes).length > 0).enableSsrInitBootstrap;
7092
8261
  },
7093
8262
  resolveId(source, importer) {
8263
+ const resolvedIslandConsumerId = resolveReactIslandConsumerId(source);
8264
+ if (resolvedIslandConsumerId) return resolvedIslandConsumerId;
8265
+ const islandRemoteId = getReactIslandImportRemoteId(source);
8266
+ if (islandRemoteId) for (const remoteAlias of Object.keys(remotes)) {
8267
+ if (islandRemoteId !== remoteAlias && !islandRemoteId.startsWith(`${remoteAlias}/`)) continue;
8268
+ addUsedRemote(remoteAlias, islandRemoteId, options);
8269
+ refreshHostAutoInit(options);
8270
+ return `\0${getReactIslandServerImportId(islandRemoteId)}`;
8271
+ }
7094
8272
  if (!filterId(source)) return;
7095
8273
  for (const remoteAlias of Object.keys(remotes)) {
7096
8274
  if (source !== remoteAlias && !source.startsWith(`${remoteAlias}/`)) continue;
7097
8275
  return resolveRemoteId(this, source, importer, remoteAlias);
7098
8276
  }
8277
+ },
8278
+ load(id) {
8279
+ return loadReactIslandConsumerModule(id);
8280
+ }
8281
+ };
8282
+ }
8283
+ //#endregion
8284
+ //#region src/plugins/pluginReactMixedModeGuard.ts
8285
+ const REACT_DEVELOPMENT_RUNTIME = /[\\/]react[\\/]cjs[\\/]react(?:-jsx-(?:dev-)?runtime)?\.development\.js$/;
8286
+ const UNSAFE_GET_OWNER = "return null === dispatcher ? null : dispatcher.getOwner();";
8287
+ const SAFE_GET_OWNER = "return typeof dispatcher?.getOwner === \"function\" ? dispatcher.getOwner() : null;";
8288
+ const REACT_MIXED_MODE_ROLLDOWN_PLUGIN = "module-federation:react-mixed-mode-rolldown";
8289
+ const REACT_MIXED_MODE_ESBUILD_PLUGIN = "module-federation:react-mixed-mode-esbuild";
8290
+ function patchReactDevelopmentRuntime(code, id) {
8291
+ if (!REACT_DEVELOPMENT_RUNTIME.test(id)) return;
8292
+ const patched = code.replaceAll(UNSAFE_GET_OWNER, SAFE_GET_OWNER);
8293
+ return patched === code ? void 0 : patched;
8294
+ }
8295
+ function createRolldownReactMixedModeGuard() {
8296
+ return {
8297
+ name: REACT_MIXED_MODE_ROLLDOWN_PLUGIN,
8298
+ transform(code, id) {
8299
+ return patchReactDevelopmentRuntime(code, id);
8300
+ }
8301
+ };
8302
+ }
8303
+ function createEsbuildReactMixedModeGuard() {
8304
+ return {
8305
+ name: REACT_MIXED_MODE_ESBUILD_PLUGIN,
8306
+ setup(build) {
8307
+ build.onLoad({ filter: REACT_DEVELOPMENT_RUNTIME }, (args) => {
8308
+ const patched = patchReactDevelopmentRuntime(readFileSync$1(args.path, "utf8"), args.path);
8309
+ if (patched === void 0) return;
8310
+ return {
8311
+ contents: patched,
8312
+ loader: "js"
8313
+ };
8314
+ });
7099
8315
  }
7100
8316
  };
7101
8317
  }
@@ -7244,7 +8460,7 @@ function excludeSharedSubDependencies(shared) {
7244
8460
  }
7245
8461
  }
7246
8462
  function proxySharedModule(options) {
7247
- const { shared = {}, federationOptions } = options;
8463
+ const { shared = {}, federationOptions, getParsePromise = () => Promise.resolve() } = options;
7248
8464
  let _config;
7249
8465
  let _command = "serve";
7250
8466
  let useDirectReactImport = false;
@@ -7253,6 +8469,7 @@ function proxySharedModule(options) {
7253
8469
  let devServer;
7254
8470
  const materializedLoadShareSources = /* @__PURE__ */ new Set();
7255
8471
  const emittedTreeShakingProviders = /* @__PURE__ */ new Set();
8472
+ const hasAnalyzableShares = Object.values(shared).some((share) => shouldAnalyzeSharedExports(share));
7256
8473
  const normalizeTreeShakingOutputPath = (value) => {
7257
8474
  const normalized = normalizePathForImport(value);
7258
8475
  if (path$1.posix.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized) || normalized.split("/").includes("..")) throw new Error(`Invalid treeShakingDir "${value}": absolute paths and parent segments are not allowed.`);
@@ -7297,9 +8514,9 @@ function proxySharedModule(options) {
7297
8514
  if (source === getLocalSharedImportMapPath(federationOptions)) return getResolvedLocalSharedImportMapId(federationOptions);
7298
8515
  },
7299
8516
  load(id) {
7300
- if (id === getResolvedLocalSharedImportMapId(federationOptions)) return parsePromise.then((_) => {
8517
+ if (id === getResolvedLocalSharedImportMapId(federationOptions)) return getParsePromise().then((_) => {
7301
8518
  refreshTreeShakingModules(federationOptions);
7302
- const providerPackages = new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
8519
+ const providerPackages = /* @__PURE__ */ new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
7303
8520
  for (const pkg of providerPackages) {
7304
8521
  const sharedKey = findSharedKeyForSource(pkg, shared);
7305
8522
  const shareItem = shared[pkg] || (sharedKey ? shared[sharedKey] : void 0);
@@ -7352,10 +8569,10 @@ function proxySharedModule(options) {
7352
8569
  refreshTreeShakingModules(federationOptions);
7353
8570
  },
7354
8571
  shouldTransformCachedModule() {
7355
- return _command === "build" && Object.values(shared).some((share) => !!share.shareConfig.treeShaking);
8572
+ return _command === "build" && hasAnalyzableShares;
7356
8573
  },
7357
8574
  transform(code, id) {
7358
- if (_command !== "build" || !Object.keys(shared).some((key) => shared[key].shareConfig.treeShaking)) return;
8575
+ if (_command !== "build" || !hasAnalyzableShares) return;
7359
8576
  collectTreeShakingImports(code, id, shared, findSharedKeyForSource, (sharedKey, exports, request) => recordTreeShakingExports(sharedKey, exports, request, federationOptions), (sharedKey, request) => markTreeShakingPackageUnsafe(sharedKey, request, federationOptions));
7360
8577
  refreshTreeShakingModules(federationOptions);
7361
8578
  }
@@ -7459,6 +8676,15 @@ const JS_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?|vue|svelte)(?:\?|$)/;
7459
8676
  function isAstNode(value) {
7460
8677
  return !!value && typeof value === "object" && typeof value.type === "string";
7461
8678
  }
8679
+ function findStaticRemoteSources(code, isRemoteImport) {
8680
+ const codePositions = createCodePositionMap(code);
8681
+ const sources = /* @__PURE__ */ new Set();
8682
+ for (const pattern of [/\b(?:import|export)\s+[^;]*?\bfrom\s*["']([^"']+)["']/g, /\bimport\s*["']([^"']+)["']/g]) for (const match of code.matchAll(pattern)) {
8683
+ const source = match[1];
8684
+ if (codePositions[match.index] && isRemoteImport(source)) sources.add(source);
8685
+ }
8686
+ return sources;
8687
+ }
7462
8688
  function walkAST(root, visitor) {
7463
8689
  const seen = /* @__PURE__ */ new WeakSet();
7464
8690
  function visit(node) {
@@ -7611,6 +8837,7 @@ async function collectFromAST(ast, code, isRemoteImport) {
7611
8837
  if (!value || !isRemoteImport(value)) return;
7612
8838
  result.push({
7613
8839
  kind: "dynamic",
8840
+ source: value,
7614
8841
  start: node.start,
7615
8842
  end: node.end,
7616
8843
  originalText: code.slice(node.start, node.end)
@@ -7689,6 +8916,7 @@ function collectFromRegex(code, isRemoteImport) {
7689
8916
  if (!isRemoteImport(source)) continue;
7690
8917
  result.push({
7691
8918
  kind: "dynamic",
8919
+ source,
7692
8920
  start: match.index,
7693
8921
  end: match.index + full.length,
7694
8922
  originalText: full
@@ -7715,6 +8943,7 @@ function pluginRemoteNamedExports(options) {
7715
8943
  if (!JS_EXTENSIONS_RE.test(id)) return;
7716
8944
  if (!remoteNames.some((name) => code.includes(name))) return;
7717
8945
  const matchesRemoteImport = (source) => isRemoteImport(source, id);
8946
+ for (const source of findStaticRemoteSources(code, matchesRemoteImport)) markStaticRemote(source, options);
7718
8947
  let imports;
7719
8948
  try {
7720
8949
  imports = await collectFromAST(this.parse(code), code, matchesRemoteImport);
@@ -7723,6 +8952,7 @@ function pluginRemoteNamedExports(options) {
7723
8952
  imports = collectFromRegex(code, matchesRemoteImport);
7724
8953
  }
7725
8954
  if (!imports) return;
8955
+ for (const remoteImport of imports) if (remoteImport.kind === "dynamic") markDynamicRemote(remoteImport.source, options);
7726
8956
  return applyRewrites(code, imports, id);
7727
8957
  }
7728
8958
  };
@@ -7731,14 +8961,14 @@ function pluginRemoteNamedExports(options) {
7731
8961
  //#region src/plugins/pluginSSRRemoteEntry.ts
7732
8962
  const MAX_RUNNER_BODY_BYTES = 1024 * 1024;
7733
8963
  const MAX_RUNNER_START_OFFSET = 1024 * 1024;
7734
- const ALLOWED_RUNNER_INVOKE_NAMES = new Set(["fetchModule", "getBuiltins"]);
8964
+ const ALLOWED_RUNNER_INVOKE_NAMES = /* @__PURE__ */ new Set(["fetchModule", "getBuiltins"]);
7735
8965
  const VITE_FS_PREFIX = "/@fs/";
7736
8966
  function isPlainObject(value) {
7737
8967
  return !!value && typeof value === "object" && !Array.isArray(value);
7738
8968
  }
7739
8969
  function isSafeRunnerFetchModuleOptions(value) {
7740
8970
  if (!isPlainObject(value)) return false;
7741
- const allowedKeys = new Set([
8971
+ const allowedKeys = /* @__PURE__ */ new Set([
7742
8972
  "cached",
7743
8973
  "startOffset",
7744
8974
  "inlineSourceMap"
@@ -7876,7 +9106,7 @@ function pluginSSRRemoteEntry(options) {
7876
9106
  ...options.ssrExternals ?? []
7877
9107
  ];
7878
9108
  const ssrOnlyExternalPattern = new RegExp(`^(${ssrOnlyExternals.map((e) => e.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&")).join("|")})(\\/.*)?$`);
7879
- const ssrModuleIds = new Set([remoteEntrySSRId, virtualExposesSSRId]);
9109
+ const ssrModuleIds = /* @__PURE__ */ new Set([remoteEntrySSRId, virtualExposesSSRId]);
7880
9110
  const resolvedAbsToPackage = /* @__PURE__ */ new Map();
7881
9111
  let isServe = false;
7882
9112
  let viteConfig;
@@ -7929,7 +9159,7 @@ function pluginSSRRemoteEntry(options) {
7929
9159
  },
7930
9160
  configureServer(server) {
7931
9161
  const base = "/__mf_ssr__";
7932
- const basePath = getBasePath$1(viteConfig?.base);
9162
+ const basePath = getBasePath$2(viteConfig?.base);
7933
9163
  const ssrEntryFileName = getSsrRemoteEntryFileName(options.filename);
7934
9164
  if (isNuxtProject || isNuxtClientBase(basePath)) server.middlewares.use((req, _res, next) => {
7935
9165
  if (req.url?.replace(/\?.*/, "") === `${basePath}/${ssrEntryFileName}`) req.url = `${basePath}/__mf_ssr__/${ssrEntryFileName}`;
@@ -8073,7 +9303,7 @@ function collectEntryOutputFiles(bundle, entryFileName) {
8073
9303
  const file = bundle[fileName];
8074
9304
  if (!file) return;
8075
9305
  files.add(fileName);
8076
- const dependencies = new Set([
9306
+ const dependencies = /* @__PURE__ */ new Set([
8077
9307
  ...file.imports || [],
8078
9308
  ...file.dynamicImports || [],
8079
9309
  ...file.implicitlyLoadedBefore || [],
@@ -8102,9 +9332,20 @@ const VarRemoteEntry = (providedOptions) => {
8102
9332
  return [{
8103
9333
  name: "module-federation-var-remote-entry",
8104
9334
  apply: "serve",
9335
+ /**
9336
+ * Stores resolved Vite config for later use
9337
+ */
9338
+ /**
9339
+ * Finalizes configuration after all plugins are resolved
9340
+ * @param config - Fully resolved Vite config
9341
+ */
8105
9342
  configResolved(config) {
8106
9343
  viteConfig = config;
8107
9344
  },
9345
+ /**
9346
+ * Configures dev server middleware to handle varRemoteEntry requests
9347
+ * @param server - Vite dev server instance
9348
+ */
8108
9349
  configureServer(server) {
8109
9350
  server.middlewares.use((req, res, next) => {
8110
9351
  if (!varFilename) {
@@ -8121,12 +9362,22 @@ const VarRemoteEntry = (providedOptions) => {
8121
9362
  }, {
8122
9363
  name: "module-federation-var-remote-entry",
8123
9364
  enforce: "post",
9365
+ /**
9366
+ * Initial plugin configuration
9367
+ * @param config - Vite config object
9368
+ * @param command - Current Vite command (serve/build)
9369
+ */
8124
9370
  config(config) {
8125
9371
  if (!config.build) config.build = {};
8126
9372
  },
8127
9373
  configResolved(config) {
8128
9374
  viteConfig = config;
8129
9375
  },
9376
+ /**
9377
+ * Generates the module federation "var" remote entry file
9378
+ * @param options - Rollup output options
9379
+ * @param bundle - Generated bundle assets
9380
+ */
8130
9381
  async generateBundle(_options, bundle) {
8131
9382
  if (!varFilename) return;
8132
9383
  if (!isValidVarName(name)) mfWarn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);
@@ -8278,7 +9529,7 @@ const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
8278
9529
  ];
8279
9530
  const VITE_DEV_PROD_CONDITION = "development|production";
8280
9531
  function appendConditions(conditions, fallbackConditions) {
8281
- return [...new Set([...conditions, ...fallbackConditions])];
9532
+ return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
8282
9533
  }
8283
9534
  function resolveViteModeCondition(conditions, isProduction) {
8284
9535
  const modeCondition = isProduction ? "production" : "development";
@@ -8448,7 +9699,7 @@ function canResolveSharedSubpath(subpath, projectRoot) {
8448
9699
  return false;
8449
9700
  }
8450
9701
  }
8451
- const VITE_DEV_IMPORT_CONDITIONS = new Set([
9702
+ const VITE_DEV_IMPORT_CONDITIONS = /* @__PURE__ */ new Set([
8452
9703
  "browser",
8453
9704
  "development",
8454
9705
  "import",
@@ -8536,6 +9787,7 @@ function includeLinkedSharedEntries(optimizeDeps, shared, projectRoot, exposes,
8536
9787
  function createEarlyVirtualModulesPlugin(options) {
8537
9788
  const { shared, remotes } = options;
8538
9789
  const isLitShare = (pkg) => pkg === "lit" || pkg.startsWith("lit/");
9790
+ const shouldGuardReactMixedMode = Object.keys(remotes ?? {}).length > 0 && shared?.react?.shareConfig.singleton === true;
8539
9791
  return {
8540
9792
  name: "vite:module-federation-early-init",
8541
9793
  enforce: "pre",
@@ -8563,6 +9815,7 @@ function createEarlyVirtualModulesPlugin(options) {
8563
9815
  if (isRolldown) {
8564
9816
  optimizeDeps.rolldownOptions ??= {};
8565
9817
  optimizeDeps.rolldownOptions.plugins ??= [];
9818
+ if (shouldGuardReactMixedMode) optimizeDeps.rolldownOptions.plugins.push(createRolldownReactMixedModeGuard());
8566
9819
  optimizeDeps.rolldownOptions.plugins.push({
8567
9820
  name: "module-federation:optimize-shared-resolver",
8568
9821
  load(id) {
@@ -8607,6 +9860,7 @@ function createEarlyVirtualModulesPlugin(options) {
8607
9860
  } else {
8608
9861
  optimizeDeps.esbuildOptions ??= {};
8609
9862
  optimizeDeps.esbuildOptions.plugins ??= [];
9863
+ if (shouldGuardReactMixedMode) optimizeDeps.esbuildOptions.plugins.push(createEsbuildReactMixedModeGuard());
8610
9864
  optimizeDeps.esbuildOptions.plugins.push({
8611
9865
  name: "module-federation:optimize-shared-proxy",
8612
9866
  setup(build) {
@@ -8738,7 +9992,7 @@ export default __mfShared.default ?? __mfShared;`
8738
9992
  }
8739
9993
  };
8740
9994
  }
8741
- const SSR_ONLY_PLUGINS = new Set(["@module-federation/vite/ssrEntryLoader"]);
9995
+ const SSR_ONLY_PLUGINS = /* @__PURE__ */ new Set(["@module-federation/vite/ssrEntryLoader"]);
8742
9996
  function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaultDisableSnapshot }) {
8743
9997
  const envTargetDefineValue = !options.target && isAstro ? "undefined" : JSON.stringify(target);
8744
9998
  if (!("ENV_TARGET" in define)) define.ENV_TARGET = envTargetDefineValue;
@@ -8750,7 +10004,7 @@ function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaul
8750
10004
  }
8751
10005
  function loadPluginDts(options) {
8752
10006
  if (options.dts === false) return [];
8753
- return [import("./pluginDts-Dbbi4cnh.js").then((n) => n.n).then(({ default: pluginDts }) => pluginDts(options))];
10007
+ return [Promise.resolve().then(() => pluginDts_exports).then(({ default: pluginDts }) => pluginDts(options))];
8754
10008
  }
8755
10009
  const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
8756
10010
  function isInjectExternalRuntimeCorePlugin(specifier) {
@@ -8789,6 +10043,14 @@ function federation(mfUserOptions) {
8789
10043
  if (!name) throw createModuleFederationError("name is required");
8790
10044
  const remoteEntryId = getRemoteEntryId(options);
8791
10045
  const virtualExposesId = getVirtualExposesId(options);
10046
+ const moduleParseController = createModuleParseController();
10047
+ const moduleParsePlugins = pluginModuleParseEnd_default((id) => {
10048
+ return id.includes(getHostAutoInitImportId(options)) || id.includes(remoteEntryId) || id.includes(virtualExposesId) || id.includes("virtual:mf-localSharedImportMap") || id.includes("__loadShare__") || id.includes("__prebuild__") || id.includes("__treeShakingProvider__") || id.includes("__mf_tree_shaking_graph__");
10049
+ }, {
10050
+ moduleParseTimeout: options.moduleParseTimeout,
10051
+ moduleParseIdleTimeout: options.moduleParseIdleTimeout,
10052
+ exposedModuleImports: Object.values(options.exposes).map((expose) => expose.import)
10053
+ }, moduleParseController);
8792
10054
  let command;
8793
10055
  let desiredRolldownOutput;
8794
10056
  let isSsrBuild = false;
@@ -8820,7 +10082,7 @@ function federation(mfUserOptions) {
8820
10082
  writePreBuildLibPath(pkg, shared[key], options, getLoadHookExportConditions(context, loadOptions));
8821
10083
  return "refreshed";
8822
10084
  };
8823
- const refreshLoadShareModuleForEnvironment = (id, context, loadOptions) => {
10085
+ const refreshLoadShareModuleForEnvironment = (id, context, loadOptions, importFalseExportUsage) => {
8824
10086
  const pkg = getCachedLoadSharePkg(id);
8825
10087
  if (!pkg) return "not-applicable";
8826
10088
  const key = findSharedKey(pkg, shared);
@@ -8828,9 +10090,26 @@ function federation(mfUserOptions) {
8828
10090
  const requestedModule = VirtualModule.findById(id);
8829
10091
  const ownedModule = VirtualModule.findById(getLoadShareModulePath(pkg, false, options));
8830
10092
  if (!requestedModule || requestedModule !== ownedModule) return "not-owned";
8831
- writeLoadShareModule(pkg, shared[key], command, getIsRolldown(context), options, getLoadHookExportConditions(context, loadOptions));
10093
+ writeLoadShareModule(pkg, shared[key], command, getIsRolldown(context), options, getLoadHookExportConditions(context, loadOptions), importFalseExportUsage);
8832
10094
  return "refreshed";
8833
10095
  };
10096
+ const getCompleteImportFalseExportUsage = (id) => {
10097
+ if (command !== "build") return void 0;
10098
+ const pkg = getCachedLoadSharePkg(id);
10099
+ if (!pkg) return void 0;
10100
+ const key = findSharedKey(pkg, shared);
10101
+ if (!key || shared[key].shareConfig.import !== false) return void 0;
10102
+ return moduleParseController.parsePromise.then((completion) => {
10103
+ if (!completion.complete) {
10104
+ if (!moduleParseController.discardWarned) {
10105
+ moduleParseController.discardWarned = true;
10106
+ mfWarn(`import: false shared export analysis was discarded (reason: ${completion.reason}) — falling back to the complete export surface, so shared consumers keep every detected named export.` + (completion.reason === "idle-timeout" || completion.reason === "timeout" ? " If the build is simply slow, increasing moduleParseIdleTimeout may let the analysis finish." : ""));
10107
+ }
10108
+ return;
10109
+ }
10110
+ return getSharedExportUsage(pkg, shared[key], key, options);
10111
+ });
10112
+ };
8834
10113
  return [
8835
10114
  {
8836
10115
  name: "vite:module-federation-virtual-modules",
@@ -8936,20 +10215,16 @@ function federation(mfUserOptions) {
8936
10215
  pluginProxyRemoteEntry_default({
8937
10216
  options,
8938
10217
  remoteEntryId,
8939
- virtualExposesId
10218
+ virtualExposesId,
10219
+ getParsePromise: () => moduleParseController.parsePromise
8940
10220
  }),
8941
10221
  pluginProxyRemotes_default(options),
8942
10222
  pluginRemoteNamedExports(options),
8943
- ...pluginModuleParseEnd_default((id) => {
8944
- return id.includes(getHostAutoInitImportId(options)) || id.includes(remoteEntryId) || id.includes(virtualExposesId) || id.includes(getLocalSharedImportMapPath(options)) || id.includes("__loadShare__") || id.includes("__prebuild__") || id.includes("__treeShakingProvider__") || id.includes("__mf_tree_shaking_graph__");
8945
- }, {
8946
- moduleParseTimeout: options.moduleParseTimeout,
8947
- moduleParseIdleTimeout: options.moduleParseIdleTimeout,
8948
- exposedModuleImports: Object.values(options.exposes).map((expose) => expose.import)
8949
- }),
10223
+ ...moduleParsePlugins,
8950
10224
  ...proxySharedModule({
8951
10225
  shared,
8952
- federationOptions: options
10226
+ federationOptions: options,
10227
+ getParsePromise: () => moduleParseController.parsePromise
8953
10228
  }),
8954
10229
  {
8955
10230
  name: "module-federation-esm-shims",
@@ -9077,8 +10352,9 @@ function federation(mfUserOptions) {
9077
10352
  }
9078
10353
  },
9079
10354
  load(id, loadOptions) {
9080
- if (id.includes("__loadShare__") || id.includes("__loadRemote__")) {
9081
- if (id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
10355
+ const loadVirtualModule = (importFalseExportUsage) => {
10356
+ if (!id.includes("__loadShare__") && !id.includes("__loadRemote__")) return;
10357
+ if (id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions, importFalseExportUsage) === "not-owned") return;
9082
10358
  const virtualModule = VirtualModule.findById(id);
9083
10359
  if (!virtualModule?.code) return null;
9084
10360
  let code = virtualModule.code;
@@ -9095,7 +10371,10 @@ function federation(mfUserOptions) {
9095
10371
  code,
9096
10372
  syntheticNamedExports: "__moduleExports"
9097
10373
  };
9098
- }
10374
+ };
10375
+ const pendingImportFalseExportUsage = id.includes("__loadShare__") ? getCompleteImportFalseExportUsage(id) : void 0;
10376
+ if (pendingImportFalseExportUsage) return pendingImportFalseExportUsage.then(loadVirtualModule);
10377
+ return loadVirtualModule();
9099
10378
  },
9100
10379
  generateBundle(_outputOptions, bundle, _isWrite) {
9101
10380
  for (const [fileName, chunk] of Object.entries(bundle)) {
@@ -9230,7 +10509,8 @@ function federation(mfUserOptions) {
9230
10509
  };
9231
10510
  res.end = (chunk, ...args) => {
9232
10511
  if (chunk) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
9233
- return end(normalizeVinextRscPreloadHints(Buffer.concat(chunks).toString()), ...args);
10512
+ const body = normalizeVinextRscPreloadHints(Buffer.concat(chunks).toString());
10513
+ return end(body, ...args);
9234
10514
  };
9235
10515
  next();
9236
10516
  });