@module-federation/vite 1.15.0 → 1.15.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.cjs +583 -240
- package/lib/index.d.cts +13 -1
- package/lib/index.d.mts +13 -1
- package/lib/index.mjs +584 -239
- package/package.json +6 -8
package/lib/index.mjs
CHANGED
|
@@ -1,28 +1,151 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import defu from "defu";
|
|
3
2
|
import * as fs$1 from "fs";
|
|
4
|
-
import fs, { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFile, writeFileSync } from "fs";
|
|
3
|
+
import fs, { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFile, writeFileSync } from "fs";
|
|
5
4
|
import { createRequire as createRequire$1 } from "module";
|
|
6
5
|
import * as path$1 from "pathe";
|
|
7
6
|
import path, { basename, dirname, join, parse, resolve } from "pathe";
|
|
8
|
-
import MagicString from "magic-string";
|
|
9
7
|
import { normalizeOptions } from "@module-federation/sdk";
|
|
10
8
|
import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
|
|
11
9
|
import { rpc } from "@module-federation/dts-plugin/core";
|
|
12
|
-
import { createFilter } from "@rollup/pluginutils";
|
|
13
10
|
import { fileURLToPath } from "url";
|
|
14
11
|
import { init, parse as parse$1 } from "es-module-lexer";
|
|
15
12
|
//#region \0rolldown/runtime.js
|
|
16
13
|
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
17
14
|
//#endregion
|
|
15
|
+
//#region src/utils/codeRewriter.ts
|
|
16
|
+
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
17
|
+
var CodeRewriter = class {
|
|
18
|
+
replacements = [];
|
|
19
|
+
constructor(original) {
|
|
20
|
+
this.original = original;
|
|
21
|
+
}
|
|
22
|
+
overwrite(start, end, content) {
|
|
23
|
+
if (start < 0 || end < start || end > this.original.length) throw new Error(`Invalid overwrite range: ${start}-${end}`);
|
|
24
|
+
this.replacements.push({
|
|
25
|
+
start,
|
|
26
|
+
end,
|
|
27
|
+
content
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
toString() {
|
|
31
|
+
return applyReplacements(this.original, this.getSortedReplacements()).code;
|
|
32
|
+
}
|
|
33
|
+
generateMap(source = "") {
|
|
34
|
+
const { code, replacements } = applyReplacements(this.original, this.getSortedReplacements());
|
|
35
|
+
return {
|
|
36
|
+
version: 3,
|
|
37
|
+
sources: [source],
|
|
38
|
+
sourcesContent: [this.original],
|
|
39
|
+
names: [],
|
|
40
|
+
mappings: generateLineMappings(code, this.original, replacements)
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
getSortedReplacements() {
|
|
44
|
+
return [...this.replacements].sort((a, b) => a.start - b.start || a.end - b.end);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
function createSourceMap(code, source = "") {
|
|
48
|
+
return {
|
|
49
|
+
version: 3,
|
|
50
|
+
sources: [source],
|
|
51
|
+
sourcesContent: [code],
|
|
52
|
+
names: [],
|
|
53
|
+
mappings: generateLineMappings(code, code, [])
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function applyReplacements(original, replacements) {
|
|
57
|
+
let code = "";
|
|
58
|
+
let cursor = 0;
|
|
59
|
+
let delta = 0;
|
|
60
|
+
const applied = [];
|
|
61
|
+
for (const replacement of replacements) {
|
|
62
|
+
if (replacement.start < cursor) throw new Error("Overlapping overwrite ranges are not supported");
|
|
63
|
+
code += original.slice(cursor, replacement.start);
|
|
64
|
+
const generatedStart = replacement.start + delta;
|
|
65
|
+
code += replacement.content;
|
|
66
|
+
const generatedEnd = generatedStart + replacement.content.length;
|
|
67
|
+
applied.push({
|
|
68
|
+
...replacement,
|
|
69
|
+
generatedStart,
|
|
70
|
+
generatedEnd
|
|
71
|
+
});
|
|
72
|
+
cursor = replacement.end;
|
|
73
|
+
delta += replacement.content.length - (replacement.end - replacement.start);
|
|
74
|
+
}
|
|
75
|
+
code += original.slice(cursor);
|
|
76
|
+
return {
|
|
77
|
+
code,
|
|
78
|
+
replacements: applied
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function generateLineMappings(generated, original, replacements) {
|
|
82
|
+
const generatedLineStarts = getLineStarts(generated);
|
|
83
|
+
const originalLineStarts = getLineStarts(original);
|
|
84
|
+
let previousOriginalLine = 0;
|
|
85
|
+
let previousOriginalColumn = 0;
|
|
86
|
+
let mappings = "";
|
|
87
|
+
generatedLineStarts.forEach((generatedOffset, lineIndex) => {
|
|
88
|
+
if (lineIndex > 0) mappings += ";";
|
|
89
|
+
const originalOffset = generatedOffsetToOriginalOffset(generatedOffset, replacements);
|
|
90
|
+
const originalLine = findLine(originalLineStarts, originalOffset);
|
|
91
|
+
const originalColumn = originalOffset - originalLineStarts[originalLine];
|
|
92
|
+
mappings += encodeSegment([
|
|
93
|
+
0,
|
|
94
|
+
0,
|
|
95
|
+
originalLine - previousOriginalLine,
|
|
96
|
+
originalColumn - previousOriginalColumn
|
|
97
|
+
]);
|
|
98
|
+
previousOriginalLine = originalLine;
|
|
99
|
+
previousOriginalColumn = originalColumn;
|
|
100
|
+
});
|
|
101
|
+
return mappings;
|
|
102
|
+
}
|
|
103
|
+
function generatedOffsetToOriginalOffset(offset, replacements) {
|
|
104
|
+
let delta = 0;
|
|
105
|
+
for (const replacement of replacements) {
|
|
106
|
+
if (offset < replacement.generatedStart) break;
|
|
107
|
+
if (offset < replacement.generatedEnd) return replacement.start;
|
|
108
|
+
delta += replacement.content.length - (replacement.end - replacement.start);
|
|
109
|
+
}
|
|
110
|
+
return offset - delta;
|
|
111
|
+
}
|
|
112
|
+
function getLineStarts(code) {
|
|
113
|
+
const starts = [0];
|
|
114
|
+
for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) starts.push(i + 1);
|
|
115
|
+
return starts;
|
|
116
|
+
}
|
|
117
|
+
function findLine(lineStarts, offset) {
|
|
118
|
+
let low = 0;
|
|
119
|
+
let high = lineStarts.length - 1;
|
|
120
|
+
while (low <= high) {
|
|
121
|
+
const mid = low + high >> 1;
|
|
122
|
+
if (lineStarts[mid] <= offset) low = mid + 1;
|
|
123
|
+
else high = mid - 1;
|
|
124
|
+
}
|
|
125
|
+
return Math.max(0, high);
|
|
126
|
+
}
|
|
127
|
+
function encodeSegment(values) {
|
|
128
|
+
return values.map(encodeVlq).join("");
|
|
129
|
+
}
|
|
130
|
+
function encodeVlq(value) {
|
|
131
|
+
let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
|
|
132
|
+
let encoded = "";
|
|
133
|
+
do {
|
|
134
|
+
let digit = vlq & 31;
|
|
135
|
+
vlq >>>= 5;
|
|
136
|
+
if (vlq > 0) digit |= 32;
|
|
137
|
+
encoded += BASE64_CHARS[digit];
|
|
138
|
+
} while (vlq > 0);
|
|
139
|
+
return encoded;
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
18
142
|
//#region src/utils/mapCodeToCodeWithSourcemap.ts
|
|
19
143
|
async function mapCodeToCodeWithSourcemap(code) {
|
|
20
144
|
const resolvedCode = await code;
|
|
21
145
|
if (resolvedCode === void 0) return;
|
|
22
|
-
const s = new MagicString(resolvedCode);
|
|
23
146
|
return {
|
|
24
|
-
code:
|
|
25
|
-
map:
|
|
147
|
+
code: resolvedCode,
|
|
148
|
+
map: createSourceMap(resolvedCode)
|
|
26
149
|
};
|
|
27
150
|
}
|
|
28
151
|
//#endregion
|
|
@@ -623,107 +746,6 @@ var VirtualModule = class {
|
|
|
623
746
|
}
|
|
624
747
|
};
|
|
625
748
|
//#endregion
|
|
626
|
-
//#region src/virtualModules/virtualRuntimeInitStatus.ts
|
|
627
|
-
const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
|
|
628
|
-
const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
|
|
629
|
-
function getRuntimeInitGlobalKey() {
|
|
630
|
-
return `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
|
|
631
|
-
}
|
|
632
|
-
function getDeferredInitPromiseCode() {
|
|
633
|
-
return `let initResolve, initReject;
|
|
634
|
-
const initPromise = new Promise((re, rj) => {
|
|
635
|
-
initResolve = re;
|
|
636
|
-
initReject = rj;
|
|
637
|
-
});`;
|
|
638
|
-
}
|
|
639
|
-
function getSsrNoopResolveCode() {
|
|
640
|
-
return `if (typeof window === 'undefined') {
|
|
641
|
-
initResolve({
|
|
642
|
-
loadRemote: function() { return Promise.resolve(undefined); },
|
|
643
|
-
loadShare: function() { return Promise.resolve(undefined); },
|
|
644
|
-
});
|
|
645
|
-
}`;
|
|
646
|
-
}
|
|
647
|
-
function getRuntimeInitStateBootstrapCode(options) {
|
|
648
|
-
return `
|
|
649
|
-
const ${options.globalKeyVar} = ${JSON.stringify(getRuntimeInitGlobalKey())};
|
|
650
|
-
let ${options.stateVar} = globalThis[${options.globalKeyVar}];
|
|
651
|
-
if (!${options.stateVar}) {
|
|
652
|
-
${getDeferredInitPromiseCode()}
|
|
653
|
-
${options.stateVar} = globalThis[${options.globalKeyVar}] = {
|
|
654
|
-
initPromise,
|
|
655
|
-
initResolve,
|
|
656
|
-
initReject,
|
|
657
|
-
};
|
|
658
|
-
${getSsrNoopResolveCode()}
|
|
659
|
-
}
|
|
660
|
-
const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
|
|
661
|
-
`;
|
|
662
|
-
}
|
|
663
|
-
function getRuntimeInitBootstrapCode() {
|
|
664
|
-
return `
|
|
665
|
-
const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
|
|
666
|
-
const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
|
|
667
|
-
globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
668
|
-
globalThis[moduleCacheGlobalKey].share ||= {};
|
|
669
|
-
globalThis[moduleCacheGlobalKey].remote ||= {};
|
|
670
|
-
if (!globalThis[globalKey]) {
|
|
671
|
-
${getDeferredInitPromiseCode()}
|
|
672
|
-
globalThis[globalKey] = {
|
|
673
|
-
initPromise,
|
|
674
|
-
initResolve,
|
|
675
|
-
initReject,
|
|
676
|
-
moduleCache: globalThis[moduleCacheGlobalKey],
|
|
677
|
-
};
|
|
678
|
-
${getSsrNoopResolveCode()}
|
|
679
|
-
}
|
|
680
|
-
globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
|
|
681
|
-
globalThis[globalKey].moduleCache.share ||= {};
|
|
682
|
-
globalThis[globalKey].moduleCache.remote ||= {};
|
|
683
|
-
`;
|
|
684
|
-
}
|
|
685
|
-
function getRuntimeModuleCacheBootstrapCode() {
|
|
686
|
-
return `
|
|
687
|
-
const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
|
|
688
|
-
globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
689
|
-
globalThis[__mfCacheGlobalKey].share ||= {};
|
|
690
|
-
globalThis[__mfCacheGlobalKey].remote ||= {};
|
|
691
|
-
const __mfModuleCache = globalThis[__mfCacheGlobalKey];
|
|
692
|
-
`;
|
|
693
|
-
}
|
|
694
|
-
function getRuntimeInitResolveBootstrapCode() {
|
|
695
|
-
return getRuntimeInitStateBootstrapCode({
|
|
696
|
-
globalKeyVar: "__mfResolveGlobalKey",
|
|
697
|
-
stateVar: "__mfResolveState",
|
|
698
|
-
exposedConst: "initResolve",
|
|
699
|
-
exposedProperty: "initResolve"
|
|
700
|
-
});
|
|
701
|
-
}
|
|
702
|
-
function writeRuntimeInitStatus(command) {
|
|
703
|
-
const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
|
|
704
|
-
export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
|
|
705
|
-
virtualRuntimeInitStatus.writeSync(`
|
|
706
|
-
${getRuntimeInitBootstrapCode()}
|
|
707
|
-
${exportStatement}
|
|
708
|
-
`);
|
|
709
|
-
}
|
|
710
|
-
//#endregion
|
|
711
|
-
//#region src/utils/localSharedImportMap_temp.ts
|
|
712
|
-
/**
|
|
713
|
-
* https://github.com/module-federation/vite/issues/68
|
|
714
|
-
*/
|
|
715
|
-
function getLocalSharedImportMapPath_temp() {
|
|
716
|
-
const { name } = getNormalizeModuleFederationOptions();
|
|
717
|
-
return path.resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
|
|
718
|
-
}
|
|
719
|
-
function writeLocalSharedImportMap_temp(content) {
|
|
720
|
-
createFile(getLocalSharedImportMapPath_temp() + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
|
|
721
|
-
}
|
|
722
|
-
function createFile(filePath, content) {
|
|
723
|
-
mkdirSync(path.dirname(filePath), { recursive: true });
|
|
724
|
-
writeFileSync(filePath, content);
|
|
725
|
-
}
|
|
726
|
-
//#endregion
|
|
727
749
|
//#region src/utils/serializeRuntimeOptions.ts
|
|
728
750
|
/**
|
|
729
751
|
* Serializes a JavaScript object into a string of source code that can be evaluated.
|
|
@@ -854,6 +876,91 @@ function generateExposes(options) {
|
|
|
854
876
|
`;
|
|
855
877
|
}
|
|
856
878
|
//#endregion
|
|
879
|
+
//#region src/virtualModules/virtualRuntimeInitStatus.ts
|
|
880
|
+
const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
|
|
881
|
+
const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
|
|
882
|
+
function getRuntimeInitGlobalKey() {
|
|
883
|
+
return `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
|
|
884
|
+
}
|
|
885
|
+
function getDeferredInitPromiseCode() {
|
|
886
|
+
return `let initResolve, initReject;
|
|
887
|
+
const initPromise = new Promise((re, rj) => {
|
|
888
|
+
initResolve = re;
|
|
889
|
+
initReject = rj;
|
|
890
|
+
});`;
|
|
891
|
+
}
|
|
892
|
+
function getSsrNoopResolveCode() {
|
|
893
|
+
return `if (typeof window === 'undefined') {
|
|
894
|
+
initResolve({
|
|
895
|
+
loadRemote: function() { return Promise.resolve(undefined); },
|
|
896
|
+
loadShare: function() { return Promise.resolve(undefined); },
|
|
897
|
+
});
|
|
898
|
+
}`;
|
|
899
|
+
}
|
|
900
|
+
function getRuntimeInitStateBootstrapCode(options) {
|
|
901
|
+
return `
|
|
902
|
+
const ${options.globalKeyVar} = ${JSON.stringify(getRuntimeInitGlobalKey())};
|
|
903
|
+
let ${options.stateVar} = globalThis[${options.globalKeyVar}];
|
|
904
|
+
if (!${options.stateVar}) {
|
|
905
|
+
${getDeferredInitPromiseCode()}
|
|
906
|
+
${options.stateVar} = globalThis[${options.globalKeyVar}] = {
|
|
907
|
+
initPromise,
|
|
908
|
+
initResolve,
|
|
909
|
+
initReject,
|
|
910
|
+
};
|
|
911
|
+
${getSsrNoopResolveCode()}
|
|
912
|
+
}
|
|
913
|
+
const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
|
|
914
|
+
`;
|
|
915
|
+
}
|
|
916
|
+
function getRuntimeInitBootstrapCode() {
|
|
917
|
+
return `
|
|
918
|
+
const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
|
|
919
|
+
const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
|
|
920
|
+
globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
921
|
+
globalThis[moduleCacheGlobalKey].share ||= {};
|
|
922
|
+
globalThis[moduleCacheGlobalKey].remote ||= {};
|
|
923
|
+
if (!globalThis[globalKey]) {
|
|
924
|
+
${getDeferredInitPromiseCode()}
|
|
925
|
+
globalThis[globalKey] = {
|
|
926
|
+
initPromise,
|
|
927
|
+
initResolve,
|
|
928
|
+
initReject,
|
|
929
|
+
moduleCache: globalThis[moduleCacheGlobalKey],
|
|
930
|
+
};
|
|
931
|
+
${getSsrNoopResolveCode()}
|
|
932
|
+
}
|
|
933
|
+
globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
|
|
934
|
+
globalThis[globalKey].moduleCache.share ||= {};
|
|
935
|
+
globalThis[globalKey].moduleCache.remote ||= {};
|
|
936
|
+
`;
|
|
937
|
+
}
|
|
938
|
+
function getRuntimeModuleCacheBootstrapCode() {
|
|
939
|
+
return `
|
|
940
|
+
const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
|
|
941
|
+
globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
942
|
+
globalThis[__mfCacheGlobalKey].share ||= {};
|
|
943
|
+
globalThis[__mfCacheGlobalKey].remote ||= {};
|
|
944
|
+
const __mfModuleCache = globalThis[__mfCacheGlobalKey];
|
|
945
|
+
`;
|
|
946
|
+
}
|
|
947
|
+
function getRuntimeInitResolveBootstrapCode() {
|
|
948
|
+
return getRuntimeInitStateBootstrapCode({
|
|
949
|
+
globalKeyVar: "__mfResolveGlobalKey",
|
|
950
|
+
stateVar: "__mfResolveState",
|
|
951
|
+
exposedConst: "initResolve",
|
|
952
|
+
exposedProperty: "initResolve"
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
function writeRuntimeInitStatus(command) {
|
|
956
|
+
const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
|
|
957
|
+
export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
|
|
958
|
+
virtualRuntimeInitStatus.writeSync(`
|
|
959
|
+
${getRuntimeInitBootstrapCode()}
|
|
960
|
+
${exportStatement}
|
|
961
|
+
`);
|
|
962
|
+
}
|
|
963
|
+
//#endregion
|
|
857
964
|
//#region src/virtualModules/virtualShared_preBuild.ts
|
|
858
965
|
/**
|
|
859
966
|
* Even the resolveId hook cannot interfere with vite pre-build,
|
|
@@ -996,7 +1103,16 @@ function getLocalProviderImportPath(pkg) {
|
|
|
996
1103
|
const resolved = createRequire$1(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
|
|
997
1104
|
return isWorkspaceFilePath(resolved) ? resolved : void 0;
|
|
998
1105
|
} catch {
|
|
999
|
-
|
|
1106
|
+
const resolved = getInstalledPackageEntry(pkg, {
|
|
1107
|
+
conditions: [
|
|
1108
|
+
"browser",
|
|
1109
|
+
"import",
|
|
1110
|
+
"module",
|
|
1111
|
+
"default"
|
|
1112
|
+
],
|
|
1113
|
+
resolveSubpathWithRequire: false
|
|
1114
|
+
});
|
|
1115
|
+
return isWorkspaceFilePath(resolved) ? resolved : void 0;
|
|
1000
1116
|
}
|
|
1001
1117
|
}
|
|
1002
1118
|
function getProjectResolvedImportPath(pkg) {
|
|
@@ -1011,7 +1127,12 @@ function getProjectResolvedImportPath(pkg) {
|
|
|
1011
1127
|
}
|
|
1012
1128
|
}
|
|
1013
1129
|
function isWorkspaceFilePath(resolved) {
|
|
1014
|
-
|
|
1130
|
+
if (!resolved) return false;
|
|
1131
|
+
let realResolved = resolved;
|
|
1132
|
+
try {
|
|
1133
|
+
realResolved = realpathSync.native(resolved);
|
|
1134
|
+
} catch {}
|
|
1135
|
+
return !realResolved.includes("/node_modules/") && !realResolved.includes("\\node_modules\\");
|
|
1015
1136
|
}
|
|
1016
1137
|
function isWorkspacePackageEntry(pkg, resolved) {
|
|
1017
1138
|
if (!resolved || !path.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
|
|
@@ -1124,11 +1245,12 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
|
1124
1245
|
const isWorkspacePackage = isWorkspacePackageEntry(pkg, localProviderPath) || isWorkspacePackageEntry(pkg, concreteSharedImportSource);
|
|
1125
1246
|
const lazyLocalFallbackSource = concreteSharedImportSource || localProviderPath || sharedImportSource;
|
|
1126
1247
|
const skipServePrebuildWarmup = command !== "build" && (pkg === "lit" || pkg.startsWith("lit/"));
|
|
1248
|
+
const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
|
|
1127
1249
|
const namedExports = getPackageNamedExports(pkg);
|
|
1128
1250
|
let exportLine;
|
|
1129
1251
|
if (namedExports.length > 0) exportLine = `export default exportModule.default ?? exportModule;\n ${`const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`}\n ${`export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`}`;
|
|
1252
|
+
else if (usesLazyLocalFallback) exportLine = `export default exportModule.default ?? exportModule`;
|
|
1130
1253
|
else exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
|
|
1131
|
-
const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
|
|
1132
1254
|
const prebuildImportLine = usesLazyLocalFallback || isWorkspacePackage && command !== "build" ? "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
|
|
1133
1255
|
const devDynamicImportLine = isWorkspacePackage ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
|
|
1134
1256
|
loadShareCacheMap[pkg].writeSync(`
|
|
@@ -1153,15 +1275,24 @@ function getUsedShares() {
|
|
|
1153
1275
|
function addUsedShares(pkg) {
|
|
1154
1276
|
usedShares.add(pkg);
|
|
1155
1277
|
}
|
|
1278
|
+
const LOCAL_SHARED_IMPORT_MAP_ID = "virtual:mf-localSharedImportMap";
|
|
1156
1279
|
function getLocalSharedImportMapPath() {
|
|
1157
|
-
|
|
1280
|
+
const { internalName, name } = getNormalizeModuleFederationOptions();
|
|
1281
|
+
return `${LOCAL_SHARED_IMPORT_MAP_ID}:${packageNameEncode(internalName || name)}`;
|
|
1282
|
+
}
|
|
1283
|
+
function getResolvedLocalSharedImportMapId() {
|
|
1284
|
+
return `\0${getLocalSharedImportMapPath()}`;
|
|
1285
|
+
}
|
|
1286
|
+
let invalidateLocalSharedImportMap;
|
|
1287
|
+
function setLocalSharedImportMapInvalidator(invalidator) {
|
|
1288
|
+
invalidateLocalSharedImportMap = invalidator;
|
|
1158
1289
|
}
|
|
1159
1290
|
let prevLocalSharedImportMapContent;
|
|
1160
1291
|
function writeLocalSharedImportMap() {
|
|
1161
1292
|
const nextContent = generateLocalSharedImportMap();
|
|
1162
1293
|
if (prevLocalSharedImportMapContent !== nextContent) {
|
|
1163
1294
|
prevLocalSharedImportMapContent = nextContent;
|
|
1164
|
-
|
|
1295
|
+
invalidateLocalSharedImportMap?.();
|
|
1165
1296
|
}
|
|
1166
1297
|
}
|
|
1167
1298
|
function shouldUseDirectReactImport() {
|
|
@@ -1270,7 +1401,7 @@ function getOrderedUsedShares() {
|
|
|
1270
1401
|
const shares = new Set(getUsedShares());
|
|
1271
1402
|
try {
|
|
1272
1403
|
Object.keys(getNormalizeModuleFederationOptions().shared).forEach((pkg) => {
|
|
1273
|
-
|
|
1404
|
+
if (!pkg.endsWith("/")) shares.add(pkg);
|
|
1274
1405
|
});
|
|
1275
1406
|
} catch {}
|
|
1276
1407
|
return Array.from(shares).sort((a, b) => {
|
|
@@ -1284,12 +1415,8 @@ function getShareItemForPreload(pkg) {
|
|
|
1284
1415
|
if (isExplicitSharedKey(pkg)) return shared[pkg];
|
|
1285
1416
|
if (isExplicitSharedKey(wildcardKey)) return shared[wildcardKey];
|
|
1286
1417
|
}
|
|
1287
|
-
function
|
|
1288
|
-
return
|
|
1289
|
-
const shareItem = getShareItemForPreload(pkg);
|
|
1290
|
-
if (!shareItem || shareItem.shareConfig.import === false) return null;
|
|
1291
|
-
const importPath = command === "serve" ? getLocalSharedPackagePath(pkg, shareItem) : getDirectSharedCacheSeedImportPath(pkg, shareItem);
|
|
1292
|
-
return `if (__mfModuleCache.share[${JSON.stringify(pkg)}] === undefined) {
|
|
1418
|
+
function generateSharedCacheSeedItem(pkg, importPath) {
|
|
1419
|
+
return `if (__mfModuleCache.share[${JSON.stringify(pkg)}] === undefined) {
|
|
1293
1420
|
const mod = await import(${JSON.stringify(importPath)});
|
|
1294
1421
|
const exportModule = ${JSON.stringify(shouldUseDirectReactImport())} && ${JSON.stringify(pkg)} === "react"
|
|
1295
1422
|
? (mod?.default ?? mod)
|
|
@@ -1300,6 +1427,33 @@ function generateDirectSharedCacheSeedCode(command = "build") {
|
|
|
1300
1427
|
});
|
|
1301
1428
|
__mfModuleCache.share[${JSON.stringify(pkg)}] = exportModule;
|
|
1302
1429
|
}`;
|
|
1430
|
+
}
|
|
1431
|
+
function generateDirectSharedCacheSeedCode(command = "build") {
|
|
1432
|
+
return getOrderedUsedShares().map((pkg) => {
|
|
1433
|
+
const shareItem = getShareItemForPreload(pkg);
|
|
1434
|
+
if (!shareItem || shareItem.shareConfig.import === false) return null;
|
|
1435
|
+
return generateSharedCacheSeedItem(pkg, command === "serve" ? getLocalSharedPackagePath(pkg, shareItem) : getDirectSharedCacheSeedImportPath(pkg, shareItem));
|
|
1436
|
+
}).filter((item) => item !== null).join("\n");
|
|
1437
|
+
}
|
|
1438
|
+
function getBrowserImportPath(importPath) {
|
|
1439
|
+
if (/^(?:[a-zA-Z]:[\\/]|\/)/.test(importPath) && !importPath.startsWith("/@")) return `/@fs/${importPath}`;
|
|
1440
|
+
return importPath;
|
|
1441
|
+
}
|
|
1442
|
+
function getHostAutoInitSharedSeedItems() {
|
|
1443
|
+
return getOrderedUsedShares().map((pkg) => ({
|
|
1444
|
+
pkg,
|
|
1445
|
+
shareItem: getShareItemForPreload(pkg)
|
|
1446
|
+
})).filter(({ shareItem }) => shareItem?.shareConfig.import === false).sort((a, b) => {
|
|
1447
|
+
const priority = (pkg) => pkg === "vue" ? 0 : pkg === "pinia" ? 1 : 2;
|
|
1448
|
+
const aIsLocal = !!getLocalProviderImportPath(a.pkg);
|
|
1449
|
+
const bIsLocal = !!getLocalProviderImportPath(b.pkg);
|
|
1450
|
+
return priority(a.pkg) - priority(b.pkg) || Number(aIsLocal) - Number(bIsLocal) || a.pkg.localeCompare(b.pkg);
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
function generateHostAutoInitSharedCacheSeedCode() {
|
|
1454
|
+
return getHostAutoInitSharedSeedItems().map(({ pkg, shareItem }) => {
|
|
1455
|
+
if (!shareItem) return null;
|
|
1456
|
+
return generateSharedCacheSeedItem(pkg, getBrowserImportPath(getDirectSharedCacheSeedImportPath(pkg, shareItem)));
|
|
1303
1457
|
}).filter((item) => item !== null).join("\n");
|
|
1304
1458
|
}
|
|
1305
1459
|
const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
|
|
@@ -1338,14 +1492,40 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
1338
1492
|
let runtimeInstance
|
|
1339
1493
|
let localSharedImportMapPromise
|
|
1340
1494
|
let exposesMapPromise
|
|
1495
|
+
const shouldRetrySharedInitError = ${command !== "build"} && ((error) => {
|
|
1496
|
+
const message = String((error && error.message) || error || '');
|
|
1497
|
+
return message.includes('Importing a module script failed') ||
|
|
1498
|
+
message.includes('Failed to fetch') ||
|
|
1499
|
+
message.includes('Load failed') ||
|
|
1500
|
+
message.includes('Outdated Optimize Dep');
|
|
1501
|
+
});
|
|
1502
|
+
const waitSharedInitRetry = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1503
|
+
async function retrySharedInit(fn) {
|
|
1504
|
+
for (let attempt = 0; ; attempt++) {
|
|
1505
|
+
try {
|
|
1506
|
+
return await fn();
|
|
1507
|
+
} catch (e) {
|
|
1508
|
+
const canRetry = typeof shouldRetrySharedInitError === 'function' && shouldRetrySharedInitError(e);
|
|
1509
|
+
if (!canRetry || attempt >= 19) throw e;
|
|
1510
|
+
await waitSharedInitRetry(250);
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1341
1514
|
|
|
1342
1515
|
async function getLocalSharedImportMap() {
|
|
1343
|
-
localSharedImportMapPromise
|
|
1516
|
+
if (!localSharedImportMapPromise) {
|
|
1517
|
+
localSharedImportMapPromise = retrySharedInit(() => import("${getLocalSharedImportMapPath()}"))
|
|
1518
|
+
.catch((e) => { localSharedImportMapPromise = undefined; throw e; });
|
|
1519
|
+
}
|
|
1344
1520
|
return localSharedImportMapPromise
|
|
1345
1521
|
}
|
|
1346
1522
|
|
|
1347
1523
|
async function getExposesMap() {
|
|
1348
|
-
|
|
1524
|
+
if (!exposesMapPromise) {
|
|
1525
|
+
exposesMapPromise = retrySharedInit(() => import("${virtualExposesId}"))
|
|
1526
|
+
.then((mod) => mod.default ?? mod)
|
|
1527
|
+
.catch((e) => { exposesMapPromise = undefined; throw e; });
|
|
1528
|
+
}
|
|
1349
1529
|
return exposesMapPromise
|
|
1350
1530
|
}
|
|
1351
1531
|
|
|
@@ -1374,11 +1554,13 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
1374
1554
|
initRes.initShareScopeMap('${options.shareScope}', shared);
|
|
1375
1555
|
initResolve(initRes)
|
|
1376
1556
|
try {
|
|
1377
|
-
await
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1557
|
+
await retrySharedInit(async () => {
|
|
1558
|
+
await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
|
|
1559
|
+
strategy: '${options.shareStrategy}',
|
|
1560
|
+
from: "build",
|
|
1561
|
+
initScope
|
|
1562
|
+
}));
|
|
1563
|
+
});
|
|
1382
1564
|
} catch (e) {
|
|
1383
1565
|
console.error('[Module Federation]', e)
|
|
1384
1566
|
}
|
|
@@ -1406,6 +1588,7 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build") {
|
|
|
1406
1588
|
async function initHost() {
|
|
1407
1589
|
if (!hostInitPromise) {
|
|
1408
1590
|
hostInitPromise = (async () => {
|
|
1591
|
+
${generateHostAutoInitSharedCacheSeedCode()}
|
|
1409
1592
|
const remoteEntry = await import(${remoteEntryImport});
|
|
1410
1593
|
const runtime = await remoteEntry.init();
|
|
1411
1594
|
const usedShared = ${generateUsedSharedPreloadConfig()};
|
|
@@ -1659,17 +1842,26 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1659
1842
|
}
|
|
1660
1843
|
return patched;
|
|
1661
1844
|
}
|
|
1662
|
-
function getBootstrapSource(initSrc, entrySrc) {
|
|
1663
|
-
const remotePreloads = Object.
|
|
1845
|
+
function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false) {
|
|
1846
|
+
const remotePreloads = Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `runtime.loadRemote(${JSON.stringify(remote)})`).join(",");
|
|
1847
|
+
const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
|
|
1848
|
+
globalThis.System && typeof globalThis.System.import === 'function'
|
|
1849
|
+
? globalThis.System.import(src)
|
|
1850
|
+
: import(src);
|
|
1851
|
+
` : "";
|
|
1852
|
+
const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
|
|
1664
1853
|
return `${getRuntimeModuleCacheBootstrapCode()}
|
|
1665
|
-
(async () => {
|
|
1666
|
-
const { initHost } = await
|
|
1854
|
+
${importHelper}(async () => {
|
|
1855
|
+
const { initHost } = await ${importExpression(initSrc)};
|
|
1667
1856
|
const runtime = await initHost();
|
|
1668
1857
|
const __mfRemotePreloads = [${remotePreloads}];
|
|
1669
1858
|
await Promise.all(__mfRemotePreloads);
|
|
1670
|
-
})().then(() =>
|
|
1859
|
+
})().then(() => ${importExpression(entrySrc)});
|
|
1671
1860
|
`;
|
|
1672
1861
|
}
|
|
1862
|
+
function getSystemBootstrapSource(initSrc, entrySrc) {
|
|
1863
|
+
return getBootstrapSource(initSrc, entrySrc, true);
|
|
1864
|
+
}
|
|
1673
1865
|
function injectHtml() {
|
|
1674
1866
|
return inject === "html" && (htmlFilePath || hasPackageDependency("@sveltejs/kit"));
|
|
1675
1867
|
}
|
|
@@ -1809,7 +2001,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1809
2001
|
const bootstrapRef = this.emitFile({
|
|
1810
2002
|
type: "asset",
|
|
1811
2003
|
fileName: bootstrapFileName,
|
|
1812
|
-
source:
|
|
2004
|
+
source: getSystemBootstrapSource(initPath, entrySrc)
|
|
1813
2005
|
});
|
|
1814
2006
|
const bootstrapPath = viteConfig.base + this.getFileName(bootstrapRef);
|
|
1815
2007
|
return scriptTag.replace(entrySrc, bootstrapPath);
|
|
@@ -1954,7 +2146,7 @@ function getHmrWsPath(base, hmrPath) {
|
|
|
1954
2146
|
return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
|
|
1955
2147
|
}
|
|
1956
2148
|
function shouldIgnoreFile(file, options) {
|
|
1957
|
-
return file.includes("/node_modules/") || file.includes("\\node_modules\\") || file.includes(`/${options.virtualModuleDir}/`) || file.includes(`\\${options.virtualModuleDir}\\`) || file.includes("/.vite/") || file.includes("\\.vite\\") || file.includes("/.
|
|
2149
|
+
return file.includes("/node_modules/") || file.includes("\\node_modules\\") || file.includes(`/${options.virtualModuleDir}/`) || file.includes(`\\${options.virtualModuleDir}\\`) || file.includes("/.vite/") || file.includes("\\.vite\\") || file.includes("/.mf/") || file.includes("\\.mf\\") || file.includes("/mf-manifest.json") || file.includes("\\mf-manifest.json") || file.includes("/mf-stats.json") || file.includes("\\mf-stats.json");
|
|
1958
2150
|
}
|
|
1959
2151
|
function getRemoteHmrWsUrl(server) {
|
|
1960
2152
|
const hmr = server.config.server.hmr;
|
|
@@ -1995,7 +2187,22 @@ function getStringPreview(value, max = 180) {
|
|
|
1995
2187
|
return rawValue.slice(0, max);
|
|
1996
2188
|
}
|
|
1997
2189
|
function isRemoteHmrEnabled(dev) {
|
|
1998
|
-
return typeof dev === "object" && dev !== null && dev.remoteHmr
|
|
2190
|
+
return typeof dev === "object" && dev !== null && !!dev.remoteHmr;
|
|
2191
|
+
}
|
|
2192
|
+
/**
|
|
2193
|
+
* Detects whether the Vite plugin pipeline includes a framework with
|
|
2194
|
+
* cross-federation HMR support (a shared runtime proxy that works
|
|
2195
|
+
* across module federation boundaries).
|
|
2196
|
+
*
|
|
2197
|
+
* Currently only React is supported via the shared /@react-refresh proxy.
|
|
2198
|
+
*/
|
|
2199
|
+
function hasCrossFederationHmr(plugins) {
|
|
2200
|
+
const supportedPlugins = ["vite:react-refresh", "vite:react-swc:refresh"];
|
|
2201
|
+
return plugins.some((p) => supportedPlugins.includes(p.name));
|
|
2202
|
+
}
|
|
2203
|
+
function resolveHmrStrategy(dev, plugins) {
|
|
2204
|
+
if (typeof dev === "object" && dev !== null && dev.remoteHmr === "full-reload") return "full-reload";
|
|
2205
|
+
return hasCrossFederationHmr(plugins) ? "native" : "full-reload";
|
|
1999
2206
|
}
|
|
2000
2207
|
function pluginDevRemoteHmr(options) {
|
|
2001
2208
|
return {
|
|
@@ -2005,6 +2212,7 @@ function pluginDevRemoteHmr(options) {
|
|
|
2005
2212
|
if (!isRemoteHmrEnabled(options.dev)) return;
|
|
2006
2213
|
const isRemote = Object.keys(options.exposes).length > 0;
|
|
2007
2214
|
const isHost = Object.keys(options.remotes).length > 0;
|
|
2215
|
+
const strategy = resolveHmrStrategy(options.dev, server.config.plugins);
|
|
2008
2216
|
if (isRemote) {
|
|
2009
2217
|
const endpointPath = getRemoteHmrPath(server.config.base);
|
|
2010
2218
|
const wsUrl = getRemoteHmrWsUrl(server);
|
|
@@ -2028,6 +2236,7 @@ function pluginDevRemoteHmr(options) {
|
|
|
2028
2236
|
}));
|
|
2029
2237
|
});
|
|
2030
2238
|
const broadcast = (file) => {
|
|
2239
|
+
if (strategy === "native") return;
|
|
2031
2240
|
if (shouldIgnoreFile(file, options)) return;
|
|
2032
2241
|
server.ws.send({
|
|
2033
2242
|
type: "custom",
|
|
@@ -2092,6 +2301,7 @@ function pluginDevRemoteHmr(options) {
|
|
|
2092
2301
|
}
|
|
2093
2302
|
const ws = new WebSocket(metadata.wsUrl, "vite-hmr");
|
|
2094
2303
|
ws.onmessage = (rawEvent) => {
|
|
2304
|
+
if (strategy === "native") return;
|
|
2095
2305
|
const message = parseRemoteHmrMessage(rawEvent.data);
|
|
2096
2306
|
if (!message || message.event !== REMOTE_HMR_EVENT) return;
|
|
2097
2307
|
server.ws.send({ type: "full-reload" });
|
|
@@ -2116,6 +2326,7 @@ function pluginDevRemoteHmr(options) {
|
|
|
2116
2326
|
};
|
|
2117
2327
|
for (const [remoteName, remote] of Object.entries(options.remotes)) connectRemote(remoteName, remote);
|
|
2118
2328
|
const triggerHostReload = (file) => {
|
|
2329
|
+
if (strategy === "native") return;
|
|
2119
2330
|
if (shouldIgnoreFile(file, options)) return;
|
|
2120
2331
|
server.ws.send({ type: "full-reload" });
|
|
2121
2332
|
};
|
|
@@ -2438,6 +2649,26 @@ function initVirtualModules(command, remoteEntryId) {
|
|
|
2438
2649
|
}
|
|
2439
2650
|
//#endregion
|
|
2440
2651
|
//#region src/utils/bundleHelpers.ts
|
|
2652
|
+
function isOutputChunk$1(chunk) {
|
|
2653
|
+
return chunk.type === "chunk";
|
|
2654
|
+
}
|
|
2655
|
+
function escapeRegExp(value) {
|
|
2656
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2657
|
+
}
|
|
2658
|
+
function getProxyBaseName(fileName) {
|
|
2659
|
+
return fileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
|
|
2660
|
+
}
|
|
2661
|
+
function extractFunctionDeclaration(code, functionName) {
|
|
2662
|
+
const funcRe = new RegExp(`function\\s+${functionName}\\s*\\([^)]*\\)\\s*\\{`);
|
|
2663
|
+
const funcStart = code.search(funcRe);
|
|
2664
|
+
if (funcStart < 0) return;
|
|
2665
|
+
let depth = 0;
|
|
2666
|
+
for (let i = code.indexOf("{", funcStart); i < code.length; i++) if (code[i] === "{") depth++;
|
|
2667
|
+
else if (code[i] === "}") {
|
|
2668
|
+
depth--;
|
|
2669
|
+
if (depth === 0) return code.slice(funcStart, i + 1);
|
|
2670
|
+
}
|
|
2671
|
+
}
|
|
2441
2672
|
/**
|
|
2442
2673
|
* Resolve the local alias for a non-inlineable proxy binding.
|
|
2443
2674
|
* If Rollup's deconflict renamed the alias but didn't update references
|
|
@@ -2460,6 +2691,147 @@ function resolveProxyAlias(binding, proxyLocal, code, fullImport, claimedLocals
|
|
|
2460
2691
|
local
|
|
2461
2692
|
};
|
|
2462
2693
|
}
|
|
2694
|
+
function collectLoadShareProxyChunks(bundle, loadShareTag) {
|
|
2695
|
+
const proxyChunks = /* @__PURE__ */ new Map();
|
|
2696
|
+
for (const [fileName, chunk] of Object.entries(bundle)) {
|
|
2697
|
+
if (!isOutputChunk$1(chunk)) continue;
|
|
2698
|
+
if (fileName.includes(loadShareTag) && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
|
|
2699
|
+
code: chunk.code,
|
|
2700
|
+
fileName
|
|
2701
|
+
});
|
|
2702
|
+
}
|
|
2703
|
+
return proxyChunks;
|
|
2704
|
+
}
|
|
2705
|
+
function collectSystemProxyInfos(proxyChunks, loadShareTag) {
|
|
2706
|
+
const systemProxyInfo = /* @__PURE__ */ new Map();
|
|
2707
|
+
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
2708
|
+
const depsMatch = proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);
|
|
2709
|
+
if (!depsMatch) continue;
|
|
2710
|
+
const loadShareDep = Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).find((dep) => dep.includes(loadShareTag) && !dep.includes("commonjs-proxy"));
|
|
2711
|
+
if (!loadShareDep) continue;
|
|
2712
|
+
const loadShareBindings = {};
|
|
2713
|
+
for (const m of proxyInfo.code.matchAll(/([A-Za-z_$][\w$]*)\s*=\s*module\d+\.([A-Za-z_$][\w$]*)/g)) loadShareBindings[m[1]] = m[2];
|
|
2714
|
+
const exportMap = {};
|
|
2715
|
+
const objectExportMatch = proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);
|
|
2716
|
+
if (objectExportMatch) for (const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)) {
|
|
2717
|
+
const [, exported, local] = m;
|
|
2718
|
+
const funcBody = extractFunctionDeclaration(proxyInfo.code, local);
|
|
2719
|
+
if (funcBody) exportMap[exported] = {
|
|
2720
|
+
type: "helper",
|
|
2721
|
+
code: funcBody
|
|
2722
|
+
};
|
|
2723
|
+
}
|
|
2724
|
+
for (const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)) {
|
|
2725
|
+
const exported = m[1];
|
|
2726
|
+
const expression = m[2];
|
|
2727
|
+
for (const [local, exportName] of Object.entries(loadShareBindings)) if (new RegExp(`\\b${local}\\b`).test(expression)) {
|
|
2728
|
+
exportMap[exported] = {
|
|
2729
|
+
type: "reexport",
|
|
2730
|
+
exportName
|
|
2731
|
+
};
|
|
2732
|
+
break;
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
if (Object.keys(exportMap).length > 0) systemProxyInfo.set(proxyFileName, {
|
|
2736
|
+
loadShareDep,
|
|
2737
|
+
exportMap
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2740
|
+
return systemProxyInfo;
|
|
2741
|
+
}
|
|
2742
|
+
function rewriteEsmProxyConsumers(code, proxyChunks) {
|
|
2743
|
+
let nextCode = code;
|
|
2744
|
+
const claimedLocals = /* @__PURE__ */ new Set();
|
|
2745
|
+
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
2746
|
+
const proxyBaseName = getProxyBaseName(proxyFileName);
|
|
2747
|
+
const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);
|
|
2748
|
+
if (!importMatch) continue;
|
|
2749
|
+
const fullImport = importMatch[0];
|
|
2750
|
+
const bindings = importMatch[1].split(",").map((s) => {
|
|
2751
|
+
const parts = s.trim().split(/\s+as\s+/);
|
|
2752
|
+
return {
|
|
2753
|
+
imported: parts[0].trim(),
|
|
2754
|
+
local: (parts[1] || parts[0]).trim()
|
|
2755
|
+
};
|
|
2756
|
+
});
|
|
2757
|
+
const exportMapMatch = proxyInfo.code.match(/export\s*\{([^}]+)\}/);
|
|
2758
|
+
if (!exportMapMatch) continue;
|
|
2759
|
+
const exportMap = {};
|
|
2760
|
+
for (const entry of exportMapMatch[1].split(",")) {
|
|
2761
|
+
const parts = entry.trim().split(/\s+as\s+/);
|
|
2762
|
+
if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
|
|
2763
|
+
}
|
|
2764
|
+
const inlineable = [];
|
|
2765
|
+
const nonInlineable = [];
|
|
2766
|
+
const pendingLocals = new Set(bindings.map((binding) => binding.local));
|
|
2767
|
+
for (const b of bindings) {
|
|
2768
|
+
pendingLocals.delete(b.local);
|
|
2769
|
+
const proxyLocal = exportMap[b.imported];
|
|
2770
|
+
if (!proxyLocal) {
|
|
2771
|
+
claimedLocals.add(b.local);
|
|
2772
|
+
nonInlineable.push(b);
|
|
2773
|
+
continue;
|
|
2774
|
+
}
|
|
2775
|
+
const funcBody = extractFunctionDeclaration(proxyInfo.code, proxyLocal);
|
|
2776
|
+
if (funcBody) {
|
|
2777
|
+
inlineable.push({
|
|
2778
|
+
local: b.local,
|
|
2779
|
+
funcBody: funcBody.replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`)
|
|
2780
|
+
});
|
|
2781
|
+
claimedLocals.add(b.local);
|
|
2782
|
+
} else {
|
|
2783
|
+
const unavailableLocals = new Set(claimedLocals);
|
|
2784
|
+
pendingLocals.forEach((local) => unavailableLocals.add(local));
|
|
2785
|
+
const resolvedBinding = resolveProxyAlias(b, proxyLocal, nextCode, fullImport, unavailableLocals);
|
|
2786
|
+
claimedLocals.add(resolvedBinding.local);
|
|
2787
|
+
nonInlineable.push(resolvedBinding);
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
|
|
2791
|
+
if (inlineable.length === 0 && !hasRenamedAlias) continue;
|
|
2792
|
+
let replacement = "";
|
|
2793
|
+
if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
|
|
2794
|
+
replacement += inlineable.map((f) => f.funcBody).join("");
|
|
2795
|
+
nextCode = nextCode.replace(fullImport, () => replacement);
|
|
2796
|
+
}
|
|
2797
|
+
return nextCode;
|
|
2798
|
+
}
|
|
2799
|
+
function rewriteSystemProxyConsumers(code, systemProxyInfo) {
|
|
2800
|
+
if (!code.includes("System.register(")) return code;
|
|
2801
|
+
let nextCode = code;
|
|
2802
|
+
for (const [proxyFileName, proxyInfo] of Array.from(systemProxyInfo.entries())) {
|
|
2803
|
+
const proxyBaseName = getProxyBaseName(proxyFileName);
|
|
2804
|
+
const depMatch = new RegExp(`["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']`).exec(nextCode);
|
|
2805
|
+
if (!depMatch) continue;
|
|
2806
|
+
let setterIndex = 0;
|
|
2807
|
+
const depListMatch = nextCode.match(/System\.register\(\[([\s\S]*?)\]/);
|
|
2808
|
+
if (depListMatch) setterIndex = Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).findIndex((dep) => dep.includes(proxyBaseName));
|
|
2809
|
+
if (setterIndex < 0) continue;
|
|
2810
|
+
const settersStart = nextCode.indexOf("setters: [");
|
|
2811
|
+
if (settersStart < 0) continue;
|
|
2812
|
+
const setterMatch = Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];
|
|
2813
|
+
if (!setterMatch) continue;
|
|
2814
|
+
const [fullSetter, moduleLocal, setterBody] = setterMatch;
|
|
2815
|
+
const helpersToInline = [];
|
|
2816
|
+
const nextSetterBody = setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`, "g"), (assignment, local, imported) => {
|
|
2817
|
+
const mapped = proxyInfo.exportMap[imported];
|
|
2818
|
+
if (!mapped) return assignment;
|
|
2819
|
+
if (mapped.type === "helper") {
|
|
2820
|
+
helpersToInline.push(mapped.code.replace(new RegExp(`function\\s+${imported}\\s*\\(`), `function ${local}(`));
|
|
2821
|
+
return "";
|
|
2822
|
+
}
|
|
2823
|
+
return `${local} = ${moduleLocal}.${mapped.exportName};`;
|
|
2824
|
+
});
|
|
2825
|
+
if (nextSetterBody === setterBody && helpersToInline.length === 0) continue;
|
|
2826
|
+
const nextSetter = fullSetter.replace(setterBody, () => nextSetterBody);
|
|
2827
|
+
nextCode = nextCode.replace(fullSetter, () => nextSetter);
|
|
2828
|
+
nextCode = nextCode.replace(depMatch[0], JSON.stringify(proxyInfo.loadShareDep));
|
|
2829
|
+
if (helpersToInline.length > 0) nextCode = nextCode.replace("execute: (function() {", () => {
|
|
2830
|
+
return `execute: (function() {${helpersToInline.join("")}`;
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
return nextCode;
|
|
2834
|
+
}
|
|
2463
2835
|
function findRemoteEntryFile(filename, bundle) {
|
|
2464
2836
|
for (const [_, fileData] of Object.entries(bundle)) if (filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "") === fileData.name || fileData.name === "remoteEntry") return fileData.fileName;
|
|
2465
2837
|
}
|
|
@@ -2609,6 +2981,12 @@ const COMMON_SHARED_SUBPATHS = {
|
|
|
2609
2981
|
"react-dom/client",
|
|
2610
2982
|
"react-dom/server",
|
|
2611
2983
|
"react-dom/server.browser"
|
|
2984
|
+
],
|
|
2985
|
+
"solid-js": [
|
|
2986
|
+
"solid-js/web",
|
|
2987
|
+
"solid-js/store",
|
|
2988
|
+
"solid-js/html",
|
|
2989
|
+
"solid-js/h"
|
|
2612
2990
|
]
|
|
2613
2991
|
};
|
|
2614
2992
|
function removeTrailingSlash(value) {
|
|
@@ -2623,6 +3001,9 @@ function normalizeNodeModulePath(source) {
|
|
|
2623
3001
|
function isNodeModulePath(source) {
|
|
2624
3002
|
return source.includes("/node_modules/") || source.includes("\\node_modules\\");
|
|
2625
3003
|
}
|
|
3004
|
+
function filterId(id) {
|
|
3005
|
+
return typeof id === "string" && !id.includes("\0");
|
|
3006
|
+
}
|
|
2626
3007
|
function getMatchingNodeModuleSubpath(source, candidates) {
|
|
2627
3008
|
const normalized = normalizeNodeModulePath(source);
|
|
2628
3009
|
return [...candidates].sort((a, b) => b.length - a.length).find((candidate) => normalized.includes(`/node_modules/${candidate}/`) || normalized.includes(`/node_modules/${candidate}.`));
|
|
@@ -2807,10 +3188,11 @@ const Manifest = () => {
|
|
|
2807
3188
|
alias: remoteKey,
|
|
2808
3189
|
entry: "*"
|
|
2809
3190
|
})));
|
|
2810
|
-
const shared = Array.from(getUsedShares()).
|
|
3191
|
+
const shared = Array.from(getUsedShares()).flatMap((shareKey) => {
|
|
2811
3192
|
const shareItem = getNormalizeShareItem(shareKey);
|
|
3193
|
+
if (!shareItem) return [];
|
|
2812
3194
|
const assets = preloadMap[shareKey] || createEmptyAssetMap();
|
|
2813
|
-
return {
|
|
3195
|
+
return [{
|
|
2814
3196
|
id: `${name}:${shareKey}`,
|
|
2815
3197
|
name: shareKey,
|
|
2816
3198
|
version: shareItem.version,
|
|
@@ -2826,7 +3208,7 @@ const Manifest = () => {
|
|
|
2826
3208
|
sync: assets.css.sync
|
|
2827
3209
|
}
|
|
2828
3210
|
}
|
|
2829
|
-
};
|
|
3211
|
+
}];
|
|
2830
3212
|
});
|
|
2831
3213
|
const exposes = Object.entries(options.exposes).map(([key, value]) => {
|
|
2832
3214
|
const formatKey = key.replace("./", "");
|
|
@@ -2978,7 +3360,6 @@ function pluginModuleParseEnd_default(excludeFn, options) {
|
|
|
2978
3360
|
}
|
|
2979
3361
|
//#endregion
|
|
2980
3362
|
//#region src/plugins/pluginProxyRemoteEntry.ts
|
|
2981
|
-
const filter$1 = createFilter();
|
|
2982
3363
|
function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId }) {
|
|
2983
3364
|
let viteConfig, _command, root;
|
|
2984
3365
|
return {
|
|
@@ -3018,14 +3399,14 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
3018
3399
|
},
|
|
3019
3400
|
transform(code, id) {
|
|
3020
3401
|
return mapCodeToCodeWithSourcemap((() => {
|
|
3021
|
-
if (!
|
|
3402
|
+
if (!filterId(id)) return;
|
|
3022
3403
|
if (id.includes(remoteEntryId)) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId, _command));
|
|
3023
3404
|
if (id === virtualExposesId) return generateExposes(options);
|
|
3024
3405
|
if (id.includes(getHostAutoInitPath())) {
|
|
3025
3406
|
if (_command === "serve") {
|
|
3026
3407
|
const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
|
|
3027
3408
|
const publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
|
|
3028
|
-
const fallbackOrigin =
|
|
3409
|
+
const fallbackOrigin = `//${host}:${viteConfig.server?.port}`;
|
|
3029
3410
|
const ssrRemoteEntry = "data:text/javascript," + encodeURIComponent("export async function init(){return {loadRemote:async()=>({}),loadShare:async()=>({})}}");
|
|
3030
3411
|
return `
|
|
3031
3412
|
const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
|
|
@@ -3076,10 +3457,25 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
3076
3457
|
}
|
|
3077
3458
|
//#endregion
|
|
3078
3459
|
//#region src/plugins/pluginProxyRemotes.ts
|
|
3079
|
-
const filter = createFilter();
|
|
3080
3460
|
function isNodeModulesImporter(importer) {
|
|
3081
3461
|
return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
|
|
3082
3462
|
}
|
|
3463
|
+
function appendAlias(config, alias) {
|
|
3464
|
+
config.resolve ??= {};
|
|
3465
|
+
const existingAlias = config.resolve.alias;
|
|
3466
|
+
if (!existingAlias) {
|
|
3467
|
+
config.resolve.alias = [alias];
|
|
3468
|
+
return;
|
|
3469
|
+
}
|
|
3470
|
+
if (Array.isArray(existingAlias)) {
|
|
3471
|
+
existingAlias.push(alias);
|
|
3472
|
+
return;
|
|
3473
|
+
}
|
|
3474
|
+
config.resolve.alias = [...Object.entries(existingAlias).map(([find, replacement]) => ({
|
|
3475
|
+
find,
|
|
3476
|
+
replacement
|
|
3477
|
+
})), alias];
|
|
3478
|
+
}
|
|
3083
3479
|
function pluginProxyRemotes_default(options) {
|
|
3084
3480
|
let command;
|
|
3085
3481
|
let root = process.cwd();
|
|
@@ -3096,19 +3492,20 @@ function pluginProxyRemotes_default(options) {
|
|
|
3096
3492
|
}
|
|
3097
3493
|
return {
|
|
3098
3494
|
name: "proxyRemotes",
|
|
3495
|
+
enforce: "pre",
|
|
3099
3496
|
config(config, { command: _command }) {
|
|
3100
3497
|
command = _command;
|
|
3101
3498
|
root = config.root || process.cwd();
|
|
3102
3499
|
Object.keys(remotes).forEach((key) => {
|
|
3103
3500
|
const remote = remotes[key];
|
|
3104
|
-
config
|
|
3501
|
+
appendAlias(config, {
|
|
3105
3502
|
find: new RegExp(`^(${remote.name}(\/.*|$))`),
|
|
3106
3503
|
replacement: "$1"
|
|
3107
3504
|
});
|
|
3108
3505
|
});
|
|
3109
3506
|
},
|
|
3110
3507
|
resolveId(source, importer) {
|
|
3111
|
-
if (!
|
|
3508
|
+
if (!filterId(source)) return;
|
|
3112
3509
|
for (const remote of Object.values(remotes)) {
|
|
3113
3510
|
if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
|
|
3114
3511
|
return resolveRemoteId(source, importer, remote.name);
|
|
@@ -3209,7 +3606,7 @@ function excludeSharedSubDependencies(shared) {
|
|
|
3209
3606
|
for (const dep of deps) {
|
|
3210
3607
|
const depKey = sharedKeyByBase.get(dep);
|
|
3211
3608
|
if (depKey && depKey !== parentKey) {
|
|
3212
|
-
if (shared[depKey]?.shareConfig.import === false) continue;
|
|
3609
|
+
if (shared[depKey]?.shareConfig.singleton === true || shared[depKey]?.shareConfig.import === false) continue;
|
|
3213
3610
|
mfWarn(`"${dep}" is a dependency of shared package "${parentKey}" and is also shared separately. This may cause initialization order issues in dev mode. Consider sharing only "${parentKey}".\n Auto-excluding "${dep}" from shared modules for dev mode.`);
|
|
3214
3611
|
delete shared[depKey];
|
|
3215
3612
|
sharedKeys.delete(depKey);
|
|
@@ -3225,15 +3622,27 @@ function proxySharedModule(options) {
|
|
|
3225
3622
|
let useDirectReactImport = false;
|
|
3226
3623
|
let useRolldown = false;
|
|
3227
3624
|
const savePrebuild = new PromiseStore();
|
|
3625
|
+
let devServer;
|
|
3228
3626
|
return [
|
|
3229
3627
|
{
|
|
3230
3628
|
name: "generateLocalSharedImportMap",
|
|
3231
3629
|
enforce: "post",
|
|
3630
|
+
configureServer(server) {
|
|
3631
|
+
devServer = server;
|
|
3632
|
+
setLocalSharedImportMapInvalidator(() => {
|
|
3633
|
+
const module = server.moduleGraph.getModuleById(getResolvedLocalSharedImportMapId());
|
|
3634
|
+
if (module) server.moduleGraph.invalidateModule(module);
|
|
3635
|
+
});
|
|
3636
|
+
},
|
|
3637
|
+
resolveId(source) {
|
|
3638
|
+
if (source === getLocalSharedImportMapPath()) return getResolvedLocalSharedImportMapId();
|
|
3639
|
+
},
|
|
3232
3640
|
load(id) {
|
|
3233
|
-
if (id
|
|
3641
|
+
if (id === getResolvedLocalSharedImportMapId()) return parsePromise.then((_) => generateLocalSharedImportMap());
|
|
3234
3642
|
},
|
|
3235
|
-
|
|
3236
|
-
if (
|
|
3643
|
+
closeBundle() {
|
|
3644
|
+
if (devServer) return;
|
|
3645
|
+
setLocalSharedImportMapInvalidator(void 0);
|
|
3237
3646
|
}
|
|
3238
3647
|
},
|
|
3239
3648
|
{
|
|
@@ -3280,7 +3689,6 @@ function proxySharedModule(options) {
|
|
|
3280
3689
|
if (importer && (importer.includes("hostAutoInit") || importer.includes("__H_A_I__"))) return;
|
|
3281
3690
|
if (importer && importer.includes("__loadShare__")) return;
|
|
3282
3691
|
if (importer && importer.includes("__prebuild__")) return;
|
|
3283
|
-
if (key.endsWith("/") && source !== key.slice(0, -1)) return;
|
|
3284
3692
|
const shareSource = isNodeModulePath(source) ? getCommonSharedSubpathFromNodeModulePath(source, key) || key : source;
|
|
3285
3693
|
const loadSharePath = getLoadShareModulePath(shareSource, useRolldown);
|
|
3286
3694
|
writeLoadShareModule(shareSource, shared[key], _command, useRolldown);
|
|
@@ -3365,7 +3773,7 @@ function wrapDynamicImport(original) {
|
|
|
3365
3773
|
}
|
|
3366
3774
|
function applyRewrites(code, imports, id) {
|
|
3367
3775
|
if (imports.length === 0) return;
|
|
3368
|
-
const ms = new
|
|
3776
|
+
const ms = new CodeRewriter(code);
|
|
3369
3777
|
let changed = false;
|
|
3370
3778
|
let counter = 0;
|
|
3371
3779
|
for (const imp of imports) switch (imp.kind) {
|
|
@@ -3413,7 +3821,7 @@ function applyRewrites(code, imports, id) {
|
|
|
3413
3821
|
if (!changed) return;
|
|
3414
3822
|
return {
|
|
3415
3823
|
code: ms.toString(),
|
|
3416
|
-
map: ms.generateMap(
|
|
3824
|
+
map: ms.generateMap(id)
|
|
3417
3825
|
};
|
|
3418
3826
|
}
|
|
3419
3827
|
async function collectFromAST(ast, code, isRemoteImport) {
|
|
@@ -3855,6 +4263,9 @@ function ignoreFederationGeneratedFiles(config, options) {
|
|
|
3855
4263
|
function isSharedResolverInternalImporter(importer) {
|
|
3856
4264
|
return !!importer && (importer.includes("__loadShare__") || importer.includes("__prebuild__"));
|
|
3857
4265
|
}
|
|
4266
|
+
function isCommonJsImporter(importer) {
|
|
4267
|
+
return !!importer && (importer.endsWith(".cjs") || importer.includes("/cjs/"));
|
|
4268
|
+
}
|
|
3858
4269
|
function isOutputChunk(chunk) {
|
|
3859
4270
|
return chunk.type === "chunk";
|
|
3860
4271
|
}
|
|
@@ -3938,9 +4349,10 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
3938
4349
|
optimizeDeps.rolldownOptions.plugins ??= [];
|
|
3939
4350
|
optimizeDeps.rolldownOptions.plugins.push({
|
|
3940
4351
|
name: "module-federation:optimize-shared-resolver",
|
|
3941
|
-
resolveId(source, importer) {
|
|
4352
|
+
resolveId(source, importer, options) {
|
|
4353
|
+
if (options?.kind?.startsWith("require")) return;
|
|
3942
4354
|
if (isSharedResolverInternalImporter(importer)) return;
|
|
3943
|
-
if (
|
|
4355
|
+
if (isCommonJsImporter(importer)) return;
|
|
3944
4356
|
const key = findSharedKey(source, shared);
|
|
3945
4357
|
if (!key) return;
|
|
3946
4358
|
if (source.endsWith(".css")) return;
|
|
@@ -4021,7 +4433,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4021
4433
|
optimizeDeps.include ??= [];
|
|
4022
4434
|
optimizeDeps.exclude ??= [];
|
|
4023
4435
|
const shouldBypassOptimizeDep = isLitShare(key);
|
|
4024
|
-
if (
|
|
4436
|
+
if (shouldBypassOptimizeDep) optimizeDeps.exclude.push(key);
|
|
4025
4437
|
if (!isRolldown && !shouldBypassOptimizeDep) optimizeDeps.include.push(getLoadShareImportId(key, isRolldown));
|
|
4026
4438
|
optimizeDeps.include.push(getPreBuildLibImportId(key));
|
|
4027
4439
|
for (const subpath of getCommonSharedSubpaths(key)) {
|
|
@@ -4251,87 +4663,17 @@ function federation(mfUserOptions) {
|
|
|
4251
4663
|
if (!isFederationControlChunk(fileName, filename)) continue;
|
|
4252
4664
|
chunk.code = sanitizeFederationControlChunk(chunk.code, fileName, filename);
|
|
4253
4665
|
}
|
|
4254
|
-
const proxyChunks =
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
fileName
|
|
4260
|
-
|
|
4261
|
-
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
if (fileName.includes("__loadShare__")) continue;
|
|
4265
|
-
let code = chunk.code;
|
|
4266
|
-
let modified = false;
|
|
4267
|
-
const claimedLocals = /* @__PURE__ */ new Set();
|
|
4268
|
-
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
4269
|
-
const proxyBaseName = proxyFileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
|
|
4270
|
-
const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${proxyBaseName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^"']*)["']\\s*;?`).exec(code);
|
|
4271
|
-
if (!importMatch) continue;
|
|
4272
|
-
const fullImport = importMatch[0];
|
|
4273
|
-
const bindings = importMatch[1].split(",").map((s) => {
|
|
4274
|
-
const parts = s.trim().split(/\s+as\s+/);
|
|
4275
|
-
return {
|
|
4276
|
-
imported: parts[0].trim(),
|
|
4277
|
-
local: (parts[1] || parts[0]).trim()
|
|
4278
|
-
};
|
|
4279
|
-
});
|
|
4280
|
-
const proxyCode = proxyInfo.code;
|
|
4281
|
-
const exportMapMatch = proxyCode.match(/export\s*\{([^}]+)\}/);
|
|
4282
|
-
if (!exportMapMatch) continue;
|
|
4283
|
-
const exportMap = {};
|
|
4284
|
-
for (const entry of exportMapMatch[1].split(",")) {
|
|
4285
|
-
const parts = entry.trim().split(/\s+as\s+/);
|
|
4286
|
-
if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
|
|
4287
|
-
}
|
|
4288
|
-
const inlineable = [];
|
|
4289
|
-
const nonInlineable = [];
|
|
4290
|
-
const pendingLocals = new Set(bindings.map((binding) => binding.local));
|
|
4291
|
-
for (const b of bindings) {
|
|
4292
|
-
pendingLocals.delete(b.local);
|
|
4293
|
-
const proxyLocal = exportMap[b.imported];
|
|
4294
|
-
if (!proxyLocal) {
|
|
4295
|
-
claimedLocals.add(b.local);
|
|
4296
|
-
nonInlineable.push(b);
|
|
4297
|
-
continue;
|
|
4298
|
-
}
|
|
4299
|
-
const funcRe = new RegExp(`function\\s+${proxyLocal}\\s*\\([^)]*\\)\\s*\\{`);
|
|
4300
|
-
if (funcRe.test(proxyCode)) {
|
|
4301
|
-
const funcStart = proxyCode.search(funcRe);
|
|
4302
|
-
let depth = 0;
|
|
4303
|
-
let funcEnd = funcStart;
|
|
4304
|
-
for (let i = proxyCode.indexOf("{", funcStart); i < proxyCode.length; i++) if (proxyCode[i] === "{") depth++;
|
|
4305
|
-
else if (proxyCode[i] === "}") {
|
|
4306
|
-
depth--;
|
|
4307
|
-
if (depth === 0) {
|
|
4308
|
-
funcEnd = i + 1;
|
|
4309
|
-
break;
|
|
4310
|
-
}
|
|
4311
|
-
}
|
|
4312
|
-
const renamedFunc = proxyCode.slice(funcStart, funcEnd).replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`);
|
|
4313
|
-
inlineable.push({
|
|
4314
|
-
local: b.local,
|
|
4315
|
-
funcBody: renamedFunc
|
|
4316
|
-
});
|
|
4317
|
-
claimedLocals.add(b.local);
|
|
4318
|
-
} else {
|
|
4319
|
-
const unavailableLocals = new Set(claimedLocals);
|
|
4320
|
-
pendingLocals.forEach((local) => unavailableLocals.add(local));
|
|
4321
|
-
const resolvedBinding = resolveProxyAlias(b, proxyLocal, code, fullImport, unavailableLocals);
|
|
4322
|
-
claimedLocals.add(resolvedBinding.local);
|
|
4323
|
-
nonInlineable.push(resolvedBinding);
|
|
4324
|
-
}
|
|
4325
|
-
}
|
|
4326
|
-
const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
|
|
4327
|
-
if (inlineable.length === 0 && !hasRenamedAlias) continue;
|
|
4328
|
-
let replacement = "";
|
|
4329
|
-
if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
|
|
4330
|
-
replacement += inlineable.map((f) => f.funcBody).join("");
|
|
4331
|
-
code = code.replace(fullImport, () => replacement);
|
|
4332
|
-
modified = true;
|
|
4666
|
+
const proxyChunks = collectLoadShareProxyChunks(bundle, LOAD_SHARE_TAG);
|
|
4667
|
+
if (proxyChunks.size > 0) {
|
|
4668
|
+
const systemProxyInfo = collectSystemProxyInfos(proxyChunks, LOAD_SHARE_TAG);
|
|
4669
|
+
for (const [fileName, chunk] of Object.entries(bundle)) {
|
|
4670
|
+
if (!isOutputChunk(chunk)) continue;
|
|
4671
|
+
if (proxyChunks.has(fileName)) continue;
|
|
4672
|
+
let code = chunk.code;
|
|
4673
|
+
if (!fileName.includes("__loadShare__")) code = rewriteEsmProxyConsumers(code, proxyChunks);
|
|
4674
|
+
code = rewriteSystemProxyConsumers(code, systemProxyInfo);
|
|
4675
|
+
if (code !== chunk.code) chunk.code = code;
|
|
4333
4676
|
}
|
|
4334
|
-
if (modified) chunk.code = code;
|
|
4335
4677
|
}
|
|
4336
4678
|
}
|
|
4337
4679
|
},
|
|
@@ -4369,12 +4711,14 @@ function federation(mfUserOptions) {
|
|
|
4369
4711
|
find: "@module-federation/runtime",
|
|
4370
4712
|
replacement: implementation
|
|
4371
4713
|
});
|
|
4372
|
-
config.build
|
|
4714
|
+
config.build ||= {};
|
|
4715
|
+
config.build.commonjsOptions ||= {};
|
|
4716
|
+
config.build.commonjsOptions.strictRequires ??= "auto";
|
|
4373
4717
|
const virtualDir = options.virtualModuleDir;
|
|
4374
4718
|
config.optimizeDeps ||= {};
|
|
4375
4719
|
config.optimizeDeps.include ||= [];
|
|
4376
4720
|
config.optimizeDeps.include.push("@module-federation/runtime");
|
|
4377
|
-
config.optimizeDeps.include.push(virtualDir);
|
|
4721
|
+
if (!isRolldown) config.optimizeDeps.include.push(virtualDir);
|
|
4378
4722
|
config.ssr ||= {};
|
|
4379
4723
|
config.ssr.noExternal ||= [];
|
|
4380
4724
|
if (Array.isArray(config.ssr.noExternal)) config.ssr.noExternal.push(virtualDir);
|
|
@@ -4382,11 +4726,12 @@ function federation(mfUserOptions) {
|
|
|
4382
4726
|
const pluginPath = typeof p === "string" ? p : p[0];
|
|
4383
4727
|
if (pluginPath && !pluginPath.startsWith(".") && !pluginPath.startsWith("/") && !pluginPath.startsWith("\0") && !pluginPath.startsWith("virtual:")) config.optimizeDeps.include.push(pluginPath);
|
|
4384
4728
|
});
|
|
4385
|
-
if (isRolldown)
|
|
4386
|
-
|
|
4729
|
+
if (isRolldown) {
|
|
4730
|
+
config.build ??= {};
|
|
4731
|
+
config.build.target ??= "esnext";
|
|
4732
|
+
} else {
|
|
4387
4733
|
config.optimizeDeps.needsInterop ||= [];
|
|
4388
4734
|
config.optimizeDeps.needsInterop.push(virtualDir);
|
|
4389
|
-
config.optimizeDeps.needsInterop.push(getLocalSharedImportMapPath());
|
|
4390
4735
|
}
|
|
4391
4736
|
const isAstro = hasPackageDependency("astro");
|
|
4392
4737
|
const resolvedTarget = options.target ?? (config.build?.ssr ? "node" : "web");
|