@module-federation/vite 1.20.6 → 1.20.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +792 -439
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -13,6 +13,217 @@ import { createHash } from "node:crypto";
|
|
|
13
13
|
import * as fs$1 from "node:fs";
|
|
14
14
|
import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
|
|
15
15
|
import { pathToFileURL as pathToFileURL$1 } from "node:url";
|
|
16
|
+
//#region src/utils/bundleHelpers.ts
|
|
17
|
+
function isOutputChunk$1(chunk) {
|
|
18
|
+
return chunk.type === "chunk";
|
|
19
|
+
}
|
|
20
|
+
function escapeRegExp$2(value) {
|
|
21
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Whether `code` references `name` as a whole identifier.
|
|
25
|
+
*
|
|
26
|
+
* Not `\b`: a word boundary needs a `\w` on one side, and `$` is not one, so
|
|
27
|
+
* `\b$8\b` matches nothing at all. Minifiers assign `$`-prefixed names to any
|
|
28
|
+
* chunk with more than ~54 module-scope bindings, and a missed match here reads
|
|
29
|
+
* as "unused", which orphans a still-referenced import.
|
|
30
|
+
*/
|
|
31
|
+
function isIdentifierReferenced(name, code) {
|
|
32
|
+
return new RegExp(`(?<![$\\w])${escapeRegExp$2(name)}(?![$\\w])`).test(code);
|
|
33
|
+
}
|
|
34
|
+
function getProxyBaseName(fileName) {
|
|
35
|
+
return fileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Matches `function <name>(`. Escaped because an unescaped leading `$` is a
|
|
39
|
+
* regex end-anchor, so the pattern would silently match nothing.
|
|
40
|
+
*/
|
|
41
|
+
function functionDeclarationRegExp(name) {
|
|
42
|
+
return new RegExp(`function\\s+${escapeRegExp$2(name)}\\s*\\(`);
|
|
43
|
+
}
|
|
44
|
+
function extractFunctionDeclaration(code, functionName) {
|
|
45
|
+
const funcRe = new RegExp(`function\\s+${escapeRegExp$2(functionName)}\\s*\\([^)]*\\)\\s*\\{`);
|
|
46
|
+
const funcStart = code.search(funcRe);
|
|
47
|
+
if (funcStart < 0) return;
|
|
48
|
+
let depth = 0;
|
|
49
|
+
for (let i = code.indexOf("{", funcStart); i < code.length; i++) if (code[i] === "{") depth++;
|
|
50
|
+
else if (code[i] === "}") {
|
|
51
|
+
depth--;
|
|
52
|
+
if (depth === 0) return code.slice(funcStart, i + 1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Resolve the local alias for a non-inlineable proxy binding.
|
|
57
|
+
* If Rollup's deconflict renamed the alias but didn't update references
|
|
58
|
+
* in the code body, fall back to proxyLocal so they stay in sync.
|
|
59
|
+
*/
|
|
60
|
+
function resolveProxyAlias(binding, proxyLocal, code, fullImport, claimedLocals = /* @__PURE__ */ new Set()) {
|
|
61
|
+
const codeWithoutImport = code.replace(fullImport, "");
|
|
62
|
+
const localUsedInCode = isIdentifierReferenced(binding.local, codeWithoutImport);
|
|
63
|
+
const claimedImportLocals = /* @__PURE__ */ new Set();
|
|
64
|
+
const importRe = /import\s*\{([^}]+)\}\s*from\s*["'][^"']+["']\s*;?/g;
|
|
65
|
+
let match;
|
|
66
|
+
while ((match = importRe.exec(codeWithoutImport)) !== null) for (const spec of match[1].split(",")) {
|
|
67
|
+
const parts = spec.trim().split(/\s+as\s+/);
|
|
68
|
+
claimedImportLocals.add((parts[1] || parts[0]).trim());
|
|
69
|
+
}
|
|
70
|
+
const local = !localUsedInCode && !claimedLocals.has(proxyLocal) && !claimedImportLocals.has(proxyLocal) ? proxyLocal : binding.local;
|
|
71
|
+
return {
|
|
72
|
+
imported: binding.imported,
|
|
73
|
+
local
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function collectLoadShareProxyChunks(bundle, loadShareTag) {
|
|
77
|
+
const proxyChunks = /* @__PURE__ */ new Map();
|
|
78
|
+
for (const [fileName, chunk] of Object.entries(bundle)) {
|
|
79
|
+
if (!isOutputChunk$1(chunk)) continue;
|
|
80
|
+
if (fileName.includes(loadShareTag) && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
|
|
81
|
+
code: chunk.code,
|
|
82
|
+
fileName
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return proxyChunks;
|
|
86
|
+
}
|
|
87
|
+
function collectSystemProxyInfos(proxyChunks, loadShareTag) {
|
|
88
|
+
const systemProxyInfo = /* @__PURE__ */ new Map();
|
|
89
|
+
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
90
|
+
const depsMatch = proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);
|
|
91
|
+
if (!depsMatch) continue;
|
|
92
|
+
const loadShareDep = Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).find((dep) => dep.includes(loadShareTag) && !dep.includes("commonjs-proxy"));
|
|
93
|
+
if (!loadShareDep) continue;
|
|
94
|
+
const loadShareBindings = {};
|
|
95
|
+
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];
|
|
96
|
+
const exportMap = {};
|
|
97
|
+
const objectExportMatch = proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);
|
|
98
|
+
if (objectExportMatch) for (const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)) {
|
|
99
|
+
const [, exported, local] = m;
|
|
100
|
+
const funcBody = extractFunctionDeclaration(proxyInfo.code, local);
|
|
101
|
+
if (funcBody) exportMap[exported] = {
|
|
102
|
+
type: "helper",
|
|
103
|
+
code: funcBody
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
for (const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)) {
|
|
107
|
+
const exported = m[1];
|
|
108
|
+
const expression = m[2];
|
|
109
|
+
for (const [local, exportName] of Object.entries(loadShareBindings).reverse()) if (isIdentifierReferenced(local, expression)) {
|
|
110
|
+
exportMap[exported] = {
|
|
111
|
+
type: "reexport",
|
|
112
|
+
exportName
|
|
113
|
+
};
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (Object.keys(exportMap).length > 0) systemProxyInfo.set(proxyFileName, {
|
|
118
|
+
loadShareDep,
|
|
119
|
+
exportMap
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return systemProxyInfo;
|
|
123
|
+
}
|
|
124
|
+
function rewriteEsmProxyConsumers(code, proxyChunks) {
|
|
125
|
+
let nextCode = code;
|
|
126
|
+
const claimedLocals = /* @__PURE__ */ new Set();
|
|
127
|
+
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
128
|
+
const proxyBaseName = getProxyBaseName(proxyFileName);
|
|
129
|
+
const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp$2(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);
|
|
130
|
+
if (!importMatch) continue;
|
|
131
|
+
const fullImport = importMatch[0];
|
|
132
|
+
const bindings = importMatch[1].split(",").map((s) => {
|
|
133
|
+
const parts = s.trim().split(/\s+as\s+/);
|
|
134
|
+
return {
|
|
135
|
+
imported: parts[0].trim(),
|
|
136
|
+
local: (parts[1] || parts[0]).trim()
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
const exportMapMatch = proxyInfo.code.match(/export\s*\{([^}]+)\}/);
|
|
140
|
+
if (!exportMapMatch) continue;
|
|
141
|
+
const exportMap = {};
|
|
142
|
+
for (const entry of exportMapMatch[1].split(",")) {
|
|
143
|
+
const parts = entry.trim().split(/\s+as\s+/);
|
|
144
|
+
if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
|
|
145
|
+
}
|
|
146
|
+
const inlineable = [];
|
|
147
|
+
const nonInlineable = [];
|
|
148
|
+
const pendingLocals = new Set(bindings.map((binding) => binding.local));
|
|
149
|
+
for (const b of bindings) {
|
|
150
|
+
pendingLocals.delete(b.local);
|
|
151
|
+
const proxyLocal = exportMap[b.imported];
|
|
152
|
+
if (!proxyLocal) {
|
|
153
|
+
claimedLocals.add(b.local);
|
|
154
|
+
nonInlineable.push(b);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const funcBody = extractFunctionDeclaration(proxyInfo.code, proxyLocal);
|
|
158
|
+
if (funcBody) {
|
|
159
|
+
inlineable.push({
|
|
160
|
+
local: b.local,
|
|
161
|
+
funcBody: funcBody.replace(functionDeclarationRegExp(proxyLocal), () => `function ${b.local}(`)
|
|
162
|
+
});
|
|
163
|
+
claimedLocals.add(b.local);
|
|
164
|
+
} else {
|
|
165
|
+
const unavailableLocals = new Set(claimedLocals);
|
|
166
|
+
pendingLocals.forEach((local) => unavailableLocals.add(local));
|
|
167
|
+
const resolvedBinding = resolveProxyAlias(b, proxyLocal, nextCode, fullImport, unavailableLocals);
|
|
168
|
+
claimedLocals.add(resolvedBinding.local);
|
|
169
|
+
nonInlineable.push(resolvedBinding);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
|
|
173
|
+
if (inlineable.length === 0 && !hasRenamedAlias) continue;
|
|
174
|
+
let replacement = "";
|
|
175
|
+
if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
|
|
176
|
+
replacement += inlineable.map((f) => f.funcBody).join("");
|
|
177
|
+
nextCode = nextCode.replace(fullImport, () => replacement);
|
|
178
|
+
}
|
|
179
|
+
return nextCode;
|
|
180
|
+
}
|
|
181
|
+
function rewriteSystemProxyConsumers(code, systemProxyInfo) {
|
|
182
|
+
if (!code.includes("System.register(")) return code;
|
|
183
|
+
let nextCode = code;
|
|
184
|
+
for (const [proxyFileName, proxyInfo] of Array.from(systemProxyInfo.entries())) {
|
|
185
|
+
const proxyBaseName = getProxyBaseName(proxyFileName);
|
|
186
|
+
const depMatch = new RegExp(`["']([^"']*${escapeRegExp$2(proxyBaseName)}[^"']*)["']`).exec(nextCode);
|
|
187
|
+
if (!depMatch) continue;
|
|
188
|
+
let setterIndex = 0;
|
|
189
|
+
const depListMatch = nextCode.match(/System\.register\(\[([\s\S]*?)\]/);
|
|
190
|
+
if (depListMatch) setterIndex = Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).findIndex((dep) => dep.includes(proxyBaseName));
|
|
191
|
+
if (setterIndex < 0) continue;
|
|
192
|
+
const settersStart = nextCode.indexOf("setters: [");
|
|
193
|
+
if (settersStart < 0) continue;
|
|
194
|
+
const setterMatch = Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];
|
|
195
|
+
if (!setterMatch) continue;
|
|
196
|
+
const [fullSetter, moduleLocal, setterBody] = setterMatch;
|
|
197
|
+
const helpersToInline = [];
|
|
198
|
+
const nextSetterBody = setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`, "g"), (assignment, local, imported) => {
|
|
199
|
+
const mapped = proxyInfo.exportMap[imported];
|
|
200
|
+
if (!mapped) return assignment;
|
|
201
|
+
if (mapped.type === "helper") {
|
|
202
|
+
helpersToInline.push(mapped.code.replace(functionDeclarationRegExp(imported), () => `function ${local}(`));
|
|
203
|
+
return "";
|
|
204
|
+
}
|
|
205
|
+
return `${local} = ${moduleLocal}.${mapped.exportName};`;
|
|
206
|
+
});
|
|
207
|
+
if (nextSetterBody === setterBody && helpersToInline.length === 0) continue;
|
|
208
|
+
const nextSetter = fullSetter.replace(setterBody, () => nextSetterBody);
|
|
209
|
+
nextCode = nextCode.replace(fullSetter, () => nextSetter);
|
|
210
|
+
nextCode = nextCode.replace(depMatch[0], JSON.stringify(proxyInfo.loadShareDep));
|
|
211
|
+
if (helpersToInline.length > 0) nextCode = nextCode.replace("execute: (function() {", () => {
|
|
212
|
+
return `execute: (function() {${helpersToInline.join("")}`;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return nextCode;
|
|
216
|
+
}
|
|
217
|
+
function findRemoteEntryFile(filename, bundle) {
|
|
218
|
+
const strippedName = filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "");
|
|
219
|
+
let fallback;
|
|
220
|
+
for (const fileData of Object.values(bundle)) {
|
|
221
|
+
if (fileData.fileName === filename) return fileData.fileName;
|
|
222
|
+
if (fallback === void 0 && (strippedName === fileData.name || fileData.name === "remoteEntry")) fallback = fileData.fileName;
|
|
223
|
+
}
|
|
224
|
+
return fallback;
|
|
225
|
+
}
|
|
226
|
+
//#endregion
|
|
16
227
|
//#region src/utils/codeRewriter.ts
|
|
17
228
|
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
18
229
|
var CodeRewriter = class {
|
|
@@ -291,15 +502,66 @@ function createCodePositionMap(code) {
|
|
|
291
502
|
}
|
|
292
503
|
//#endregion
|
|
293
504
|
//#region src/utils/htmlEntryUtils.ts
|
|
294
|
-
function
|
|
505
|
+
function isTypeOnlyClause(clause) {
|
|
506
|
+
const normalized = clause.trim();
|
|
507
|
+
if (/^type\b/.test(normalized)) return true;
|
|
508
|
+
const namedSpecifiers = normalized.match(/^\{([\s\S]*)\}$/)?.[1];
|
|
509
|
+
if (!namedSpecifiers) return false;
|
|
510
|
+
const specifiers = namedSpecifiers.split(",").map((specifier) => specifier.trim()).filter(Boolean);
|
|
511
|
+
return specifiers.length > 0 && specifiers.every((specifier) => /^type\s+\S/.test(specifier));
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Finds module imports while ignoring comments, strings, and regular expressions.
|
|
515
|
+
* The descriptor keeps enough information for callers to distinguish runtime
|
|
516
|
+
* static imports from type-only imports without introducing a parser dependency.
|
|
517
|
+
*/
|
|
518
|
+
function findModuleImportDescriptors(code) {
|
|
295
519
|
const codePositions = createCodePositionMap(code);
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
520
|
+
const descriptors = [];
|
|
521
|
+
const staticFromPattern = /\b(?:import|export)\s+([\s\S]*?)\s+from\s*(["'])([^"']+)\2/g;
|
|
522
|
+
const dynamicPattern = /\bimport\s*\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(["'])([^"']+)\1\s*\)/g;
|
|
523
|
+
const requirePattern = /\brequire\s*\(\s*(["'])([^"']+)\1\s*\)/g;
|
|
524
|
+
const sideEffectPattern = /\bimport\s*(["'])([^"']+)\1/g;
|
|
525
|
+
for (const match of code.matchAll(staticFromPattern)) {
|
|
526
|
+
if (!codePositions[match.index]) continue;
|
|
527
|
+
descriptors.push({
|
|
528
|
+
kind: "static",
|
|
529
|
+
syntax: "import",
|
|
530
|
+
source: match[3],
|
|
531
|
+
typeOnly: isTypeOnlyClause(match[1])
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
for (const match of code.matchAll(dynamicPattern)) {
|
|
535
|
+
if (!codePositions[match.index]) continue;
|
|
536
|
+
descriptors.push({
|
|
537
|
+
kind: "dynamic",
|
|
538
|
+
syntax: "import",
|
|
539
|
+
source: match[2],
|
|
540
|
+
typeOnly: false
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
for (const match of code.matchAll(requirePattern)) {
|
|
544
|
+
if (!codePositions[match.index]) continue;
|
|
545
|
+
descriptors.push({
|
|
546
|
+
kind: "dynamic",
|
|
547
|
+
syntax: "require",
|
|
548
|
+
source: match[2],
|
|
549
|
+
typeOnly: false
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
for (const match of code.matchAll(sideEffectPattern)) {
|
|
553
|
+
if (!codePositions[match.index]) continue;
|
|
554
|
+
descriptors.push({
|
|
555
|
+
kind: "static",
|
|
556
|
+
syntax: "import",
|
|
557
|
+
source: match[2],
|
|
558
|
+
typeOnly: false
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
return descriptors;
|
|
562
|
+
}
|
|
563
|
+
function findModuleImportSources(code) {
|
|
564
|
+
return Array.from(new Set(findModuleImportDescriptors(code).filter(({ syntax, typeOnly }) => syntax === "import" && !typeOnly).map(({ source }) => source)));
|
|
303
565
|
}
|
|
304
566
|
function sanitizeDevEntryPath(devEntryPath) {
|
|
305
567
|
return devEntryPath.replace(/\\\\?/g, "/");
|
|
@@ -440,6 +702,7 @@ function normalizeShareItem(key, shareItem) {
|
|
|
440
702
|
eager: shareItem.eager || false,
|
|
441
703
|
requiredVersion: shareItem.requiredVersion !== void 0 ? shareItem.requiredVersion : isImportFalse || shareItem.version ? "*" : version ? `^${version}` : "*",
|
|
442
704
|
strictVersion: !!shareItem.strictVersion,
|
|
705
|
+
...shareItem.suppressMissingImportWarning ? { suppressMissingImportWarning: true } : {},
|
|
443
706
|
...treeShaking ? { treeShaking: { ...treeShaking } } : {}
|
|
444
707
|
}
|
|
445
708
|
};
|
|
@@ -584,11 +847,11 @@ const idCacheMap = {};
|
|
|
584
847
|
const VITE_ID_PREFIX = "/@id/";
|
|
585
848
|
const VITE_ENCODED_NULL_BYTE_PREFIX = `${VITE_ID_PREFIX}__x00__`;
|
|
586
849
|
const MF_OWNER_INFIX = "__mf_owner__";
|
|
587
|
-
function escapeRegExp$
|
|
850
|
+
function escapeRegExp$1(value) {
|
|
588
851
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
589
852
|
}
|
|
590
853
|
function createViteEncodedIdPrefixRegExp(sourcePrefix = "") {
|
|
591
|
-
return new RegExp(`^(?:${escapeRegExp$
|
|
854
|
+
return new RegExp(`^(?:${escapeRegExp$1(VITE_ENCODED_NULL_BYTE_PREFIX)})?${sourcePrefix}`);
|
|
592
855
|
}
|
|
593
856
|
function toViteEncodedId(id) {
|
|
594
857
|
return `${VITE_ENCODED_NULL_BYTE_PREFIX}${id}`;
|
|
@@ -686,6 +949,17 @@ function getSsrCapabilities(viteMajor, command, hasRemotes) {
|
|
|
686
949
|
}
|
|
687
950
|
//#endregion
|
|
688
951
|
//#region src/utils/serializeRuntimeOptions.ts
|
|
952
|
+
const UNSAFE_JS_CHAR_MAP = {
|
|
953
|
+
"<": "\\u003C",
|
|
954
|
+
"\u2028": "\\u2028",
|
|
955
|
+
"\u2029": "\\u2029"
|
|
956
|
+
};
|
|
957
|
+
const UNSAFE_JS_CHAR_PATTERN = /[<\u2028\u2029]/g;
|
|
958
|
+
function toSafeJsLiteral(value) {
|
|
959
|
+
const json = JSON.stringify(value);
|
|
960
|
+
if (json === void 0) return "undefined";
|
|
961
|
+
return json.replace(UNSAFE_JS_CHAR_PATTERN, (char) => UNSAFE_JS_CHAR_MAP[char]);
|
|
962
|
+
}
|
|
689
963
|
/**
|
|
690
964
|
* Serializes a JavaScript object into a string of source code that can be evaluated.
|
|
691
965
|
* This function is used to create runtime plugin options without relying solely on JSON.stringify,
|
|
@@ -703,16 +977,13 @@ function serializeRuntimeOptions(options) {
|
|
|
703
977
|
function valueToCode(val) {
|
|
704
978
|
if (val === null) return "null";
|
|
705
979
|
const type = typeof val;
|
|
706
|
-
if (type === "string") return
|
|
980
|
+
if (type === "string") return toSafeJsLiteral(val);
|
|
707
981
|
if (type === "number" || type === "boolean") return String(val);
|
|
708
982
|
if (type === "undefined") return "undefined";
|
|
709
|
-
if (type === "symbol") {
|
|
710
|
-
const desc = val.description ?? "";
|
|
711
|
-
return `Symbol(${JSON.stringify(desc)})`;
|
|
712
|
-
}
|
|
983
|
+
if (type === "symbol") return `Symbol(${toSafeJsLiteral(val.description ?? "")})`;
|
|
713
984
|
if (type === "function") return val.toString();
|
|
714
|
-
if (val instanceof Date) return `new Date(${
|
|
715
|
-
if (val instanceof RegExp) return `new RegExp(${
|
|
985
|
+
if (val instanceof Date) return `new Date(${toSafeJsLiteral(val.toISOString())})`;
|
|
986
|
+
if (val instanceof RegExp) return `new RegExp(${toSafeJsLiteral(val.source)}, ${toSafeJsLiteral(val.flags)})`;
|
|
716
987
|
if (type === "object") {
|
|
717
988
|
if (ancestors.has(val)) return `"__circular__"`;
|
|
718
989
|
ancestors.add(val);
|
|
@@ -721,16 +992,16 @@ function serializeRuntimeOptions(options) {
|
|
|
721
992
|
if (val instanceof Map) return `new Map([${Array.from(val.entries()).map(([k, v]) => `[${valueToCode(k)}, ${valueToCode(v)}]`).join(", ")}])`;
|
|
722
993
|
if (val instanceof Set) return `new Set([${Array.from(val.values()).map(valueToCode).join(", ")}])`;
|
|
723
994
|
const properties = [];
|
|
724
|
-
for (const key in val) if (Object.prototype.hasOwnProperty.call(val, key)) properties.push(`${
|
|
995
|
+
for (const key in val) if (Object.prototype.hasOwnProperty.call(val, key)) properties.push(`${toSafeJsLiteral(key)}: ${valueToCode(val[key])}`);
|
|
725
996
|
return `{${properties.join(", ")}}`;
|
|
726
997
|
} finally {
|
|
727
998
|
ancestors.delete(val);
|
|
728
999
|
}
|
|
729
1000
|
}
|
|
730
|
-
return
|
|
1001
|
+
return toSafeJsLiteral(String(val));
|
|
731
1002
|
}
|
|
732
1003
|
const topLevelProps = [];
|
|
733
|
-
for (const key in options) if (Object.prototype.hasOwnProperty.call(options, key)) topLevelProps.push(`${
|
|
1004
|
+
for (const key in options) if (Object.prototype.hasOwnProperty.call(options, key)) topLevelProps.push(`${toSafeJsLiteral(key)}: ${valueToCode(options[key])}`);
|
|
734
1005
|
return `{${topLevelProps.join(", ")}}`;
|
|
735
1006
|
}
|
|
736
1007
|
//#endregion
|
|
@@ -1084,12 +1355,56 @@ function generateExposes(options, remoteDependencyMap = {}, command = "build", r
|
|
|
1084
1355
|
`;
|
|
1085
1356
|
}
|
|
1086
1357
|
//#endregion
|
|
1358
|
+
//#region src/utils/sharedExportConditions.ts
|
|
1359
|
+
const DEFAULT_CLIENT_EXPORT_CONDITIONS = [
|
|
1360
|
+
"browser",
|
|
1361
|
+
"import",
|
|
1362
|
+
"module",
|
|
1363
|
+
"default"
|
|
1364
|
+
];
|
|
1365
|
+
const DEFAULT_NODE_SSR_EXPORT_CONDITIONS = [
|
|
1366
|
+
"node",
|
|
1367
|
+
"import",
|
|
1368
|
+
"module",
|
|
1369
|
+
"default"
|
|
1370
|
+
];
|
|
1371
|
+
const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
|
|
1372
|
+
"worker",
|
|
1373
|
+
"browser",
|
|
1374
|
+
"import",
|
|
1375
|
+
"module",
|
|
1376
|
+
"default"
|
|
1377
|
+
];
|
|
1378
|
+
const VITE_DEV_PROD_CONDITION = "development|production";
|
|
1379
|
+
function appendConditions(conditions, fallbackConditions) {
|
|
1380
|
+
return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
|
|
1381
|
+
}
|
|
1382
|
+
function resolveViteModeCondition(conditions, isProduction) {
|
|
1383
|
+
const modeCondition = isProduction ? "production" : "development";
|
|
1384
|
+
return [...new Set(conditions.map((condition) => condition === VITE_DEV_PROD_CONDITION ? modeCondition : condition))];
|
|
1385
|
+
}
|
|
1386
|
+
function getSharedExportConditions({ environmentConditions, isProduction, isSsr, rootConditions, ssrConditions, ssrTarget = "node" }) {
|
|
1387
|
+
if (environmentConditions !== void 0) return resolveViteModeCondition(appendConditions(environmentConditions, ["import", "default"]), isProduction);
|
|
1388
|
+
const defaultConditions = isSsr ? ssrTarget === "webworker" ? DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS : DEFAULT_NODE_SSR_EXPORT_CONDITIONS : DEFAULT_CLIENT_EXPORT_CONDITIONS;
|
|
1389
|
+
const configuredConditions = isSsr ? ssrConditions ?? rootConditions : rootConditions;
|
|
1390
|
+
if (configuredConditions !== void 0) return resolveViteModeCondition(appendConditions(configuredConditions, defaultConditions), isProduction);
|
|
1391
|
+
return [...defaultConditions];
|
|
1392
|
+
}
|
|
1393
|
+
function isReactServerConditions(conditions) {
|
|
1394
|
+
return Boolean(conditions?.includes("react-server"));
|
|
1395
|
+
}
|
|
1396
|
+
//#endregion
|
|
1087
1397
|
//#region src/virtualModules/virtualRuntimeInitStatus.ts
|
|
1088
1398
|
const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
|
|
1089
1399
|
const runtimeInitModules = /* @__PURE__ */ new WeakMap();
|
|
1090
1400
|
const runtimeInitOwnerIds = /* @__PURE__ */ new WeakMap();
|
|
1091
1401
|
let nextRuntimeInitOwnerId = 1;
|
|
1092
1402
|
const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
|
|
1403
|
+
const REACT_SERVER_MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache_react_server__";
|
|
1404
|
+
const MODULE_CACHE_SHARE_SCOPE_KEY = "module-federation.vite-module-cache";
|
|
1405
|
+
function getModuleCacheGlobalKey(exportConditions) {
|
|
1406
|
+
return isReactServerConditions(exportConditions) ? REACT_SERVER_MODULE_CACHE_GLOBAL_KEY : MODULE_CACHE_GLOBAL_KEY;
|
|
1407
|
+
}
|
|
1093
1408
|
function getRuntimeInitOwnerId(options) {
|
|
1094
1409
|
let ownerId = runtimeInitOwnerIds.get(options);
|
|
1095
1410
|
if (!ownerId) {
|
|
@@ -1133,7 +1448,7 @@ function getSsrNoopResolveCode(enableSsrInit, hostInitImportId, initResolveExpre
|
|
|
1133
1448
|
if (!enableSsrInit) return "";
|
|
1134
1449
|
return `if (${SERVER_ENV_GUARD}) {
|
|
1135
1450
|
var _noop = { loadRemote: function() { return Promise.resolve(undefined); }, loadShare: function() { return Promise.resolve(undefined); } };
|
|
1136
|
-
${hostInitImportId ? `import(${
|
|
1451
|
+
${hostInitImportId ? `import(${toSafeJsLiteral(hostInitImportId)})
|
|
1137
1452
|
.then(function(mod) { return mod.hostInitPromise; })
|
|
1138
1453
|
.then(function(runtime) {
|
|
1139
1454
|
${initResolveExpression}(runtime);
|
|
@@ -1149,7 +1464,7 @@ function getSsrNoopResolveCode(enableSsrInit, hostInitImportId, initResolveExpre
|
|
|
1149
1464
|
function() { return [runtimeMod, []]; }
|
|
1150
1465
|
);
|
|
1151
1466
|
}).then(function(pair) {
|
|
1152
|
-
var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${
|
|
1467
|
+
var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${toSafeJsLiteral(ssrRemotes)}, shared: {}, plugins: pair[1] });
|
|
1153
1468
|
${initResolveExpression}(runtime);
|
|
1154
1469
|
}, function() {
|
|
1155
1470
|
${initResolveExpression}(_noop);
|
|
@@ -1159,7 +1474,7 @@ function getSsrNoopResolveCode(enableSsrInit, hostInitImportId, initResolveExpre
|
|
|
1159
1474
|
}
|
|
1160
1475
|
function getRuntimeInitStateBootstrapCode(options) {
|
|
1161
1476
|
return `
|
|
1162
|
-
const ${options.globalKeyVar} = ${
|
|
1477
|
+
const ${options.globalKeyVar} = ${toSafeJsLiteral(getRuntimeInitGlobalKey(options.ownerImportId))};
|
|
1163
1478
|
let ${options.stateVar} = globalThis[${options.globalKeyVar}];
|
|
1164
1479
|
if (!${options.stateVar}) {
|
|
1165
1480
|
${getDeferredInitPromiseCode()}
|
|
@@ -1173,10 +1488,10 @@ if (!${options.stateVar}) {
|
|
|
1173
1488
|
const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
|
|
1174
1489
|
`;
|
|
1175
1490
|
}
|
|
1176
|
-
function getRuntimeInitBootstrapCode(enableSsrInit = false, ownerImportId, ssrRemotes, hostInitImportId = ownerImportId) {
|
|
1491
|
+
function getRuntimeInitBootstrapCode(enableSsrInit = false, ownerImportId, ssrRemotes, hostInitImportId = ownerImportId, exportConditions) {
|
|
1177
1492
|
return `
|
|
1178
|
-
const globalKey = ${
|
|
1179
|
-
const moduleCacheGlobalKey = ${
|
|
1493
|
+
const globalKey = ${toSafeJsLiteral(getRuntimeInitGlobalKey(ownerImportId))};
|
|
1494
|
+
const moduleCacheGlobalKey = ${toSafeJsLiteral(getModuleCacheGlobalKey(exportConditions))};
|
|
1180
1495
|
globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
1181
1496
|
globalThis[moduleCacheGlobalKey].share ||= {};
|
|
1182
1497
|
globalThis[moduleCacheGlobalKey].remote ||= {};
|
|
@@ -1194,14 +1509,14 @@ if (${SERVER_ENV_GUARD} && !globalThis[globalKey].ssrInitStarted) {
|
|
|
1194
1509
|
globalThis[globalKey].ssrInitStarted = true;
|
|
1195
1510
|
${getSsrNoopResolveCode(enableSsrInit, hostInitImportId, "globalThis[globalKey].initResolve", ssrRemotes)}
|
|
1196
1511
|
}` : ""}
|
|
1197
|
-
globalThis[globalKey].moduleCache
|
|
1512
|
+
globalThis[globalKey].moduleCache = globalThis[moduleCacheGlobalKey];
|
|
1198
1513
|
globalThis[globalKey].moduleCache.share ||= {};
|
|
1199
1514
|
globalThis[globalKey].moduleCache.remote ||= {};
|
|
1200
1515
|
`;
|
|
1201
1516
|
}
|
|
1202
|
-
function getRuntimeModuleCacheBootstrapCode() {
|
|
1517
|
+
function getRuntimeModuleCacheBootstrapCode(exportConditions) {
|
|
1203
1518
|
return `
|
|
1204
|
-
const __mfCacheGlobalKey = ${
|
|
1519
|
+
const __mfCacheGlobalKey = ${toSafeJsLiteral(getModuleCacheGlobalKey(exportConditions))};
|
|
1205
1520
|
globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
1206
1521
|
globalThis[__mfCacheGlobalKey].share ||= {};
|
|
1207
1522
|
globalThis[__mfCacheGlobalKey].remote ||= {};
|
|
@@ -2109,10 +2424,12 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
|
|
|
2109
2424
|
const exportKeywordRegex = /\bexport\b/g;
|
|
2110
2425
|
while ((match = exportKeywordRegex.exec(source)) !== null) {
|
|
2111
2426
|
if (!codePositions[match.index]) continue;
|
|
2112
|
-
if (
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2427
|
+
if (recognizedExportStarts.has(match.index)) continue;
|
|
2428
|
+
let previousCodeIndex = match.index - 1;
|
|
2429
|
+
while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
|
|
2430
|
+
if (source[previousCodeIndex] === ".") continue;
|
|
2431
|
+
scanState.complete = false;
|
|
2432
|
+
break;
|
|
2116
2433
|
}
|
|
2117
2434
|
return Array.from(names);
|
|
2118
2435
|
}
|
|
@@ -2345,7 +2662,8 @@ const legacySharedVirtualModuleState = {
|
|
|
2345
2662
|
preBuildShareItemMap: {},
|
|
2346
2663
|
treeShakingProviderCacheMap: {},
|
|
2347
2664
|
materializedTreeShakingProviders: /* @__PURE__ */ new Set(),
|
|
2348
|
-
loadShareCacheMap: {}
|
|
2665
|
+
loadShareCacheMap: {},
|
|
2666
|
+
warnedMissingImportFalse: /* @__PURE__ */ new Set()
|
|
2349
2667
|
};
|
|
2350
2668
|
const sharedVirtualModuleStates = /* @__PURE__ */ new WeakMap();
|
|
2351
2669
|
let nextSharedVirtualModuleOwnerId = 1;
|
|
@@ -2364,6 +2682,7 @@ function getSharedVirtualModuleState(options) {
|
|
|
2364
2682
|
treeShakingProviderCacheMap: {},
|
|
2365
2683
|
materializedTreeShakingProviders: /* @__PURE__ */ new Set(),
|
|
2366
2684
|
loadShareCacheMap: {},
|
|
2685
|
+
warnedMissingImportFalse: /* @__PURE__ */ new Set(),
|
|
2367
2686
|
ownerKey: `${options.internalName}${MF_OWNER_INFIX}${nextSharedVirtualModuleOwnerId++}`
|
|
2368
2687
|
};
|
|
2369
2688
|
sharedVirtualModuleStates.set(options, state);
|
|
@@ -2481,7 +2800,7 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
|
|
|
2481
2800
|
});
|
|
2482
2801
|
preBuildCacheMap[pkg].writeSync(`
|
|
2483
2802
|
${sharedCacheHelperCode}
|
|
2484
|
-
const __mfCacheGlobalKey =
|
|
2803
|
+
const __mfCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
|
|
2485
2804
|
export const c = function(size) {
|
|
2486
2805
|
const cache = globalThis[__mfCacheGlobalKey]?.share;
|
|
2487
2806
|
const sharedReact = cache && __mfReadSharedCache(cache, ${reactCacheDescriptor});
|
|
@@ -2545,12 +2864,12 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
|
|
|
2545
2864
|
`, true);
|
|
2546
2865
|
}
|
|
2547
2866
|
/** Re-render already materialized wrappers after import analysis discovers exports. */
|
|
2548
|
-
function refreshTreeShakingModules(options) {
|
|
2867
|
+
function refreshTreeShakingModules(options, command = "build", isRolldown = false, exportConditions) {
|
|
2549
2868
|
const { preBuildShareItemMap } = getSharedVirtualModuleState(options);
|
|
2550
2869
|
for (const [pkg, shareItem] of Object.entries(preBuildShareItemMap)) {
|
|
2551
2870
|
if (!shareItem?.shareConfig.treeShaking) continue;
|
|
2552
|
-
writePreBuildLibPath(pkg, shareItem, options);
|
|
2553
|
-
writeLoadShareModule(pkg, shareItem,
|
|
2871
|
+
writePreBuildLibPath(pkg, shareItem, options, exportConditions);
|
|
2872
|
+
writeLoadShareModule(pkg, shareItem, command, isRolldown, options, exportConditions);
|
|
2554
2873
|
}
|
|
2555
2874
|
}
|
|
2556
2875
|
function getPreBuildLibImportId(pkg, options) {
|
|
@@ -2752,7 +3071,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2752
3071
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
2753
3072
|
const { loadShareCacheMap } = getSharedVirtualModuleState(options);
|
|
2754
3073
|
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = createScopedSharedVirtualModule(pkg, LOAD_SHARE_TAG, options);
|
|
2755
|
-
let importLine = getRuntimeModuleCacheBootstrapCode();
|
|
3074
|
+
let importLine = getRuntimeModuleCacheBootstrapCode(exportConditions);
|
|
2756
3075
|
const cacheDescriptor = getSharedCacheDescriptorLiteral(pkg, shareItem);
|
|
2757
3076
|
const cacheOwner = JSON.stringify(resolvedOptions.name);
|
|
2758
3077
|
const runtimeInitOwnerImportId = options ? getRuntimeInitStatusImportId(options) : void 0;
|
|
@@ -2763,7 +3082,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2763
3082
|
let exportLine;
|
|
2764
3083
|
if (namedExports.length > 0) exportLine = generateDeferredHostProvidedExports(namedExports, pkg, cacheDescriptor, treeShakingConsumer);
|
|
2765
3084
|
else {
|
|
2766
|
-
|
|
3085
|
+
const { warnedMissingImportFalse } = getSharedVirtualModuleState(resolvedOptions);
|
|
3086
|
+
if (detectedNamedExports === void 0 && !shareItem.shareConfig.suppressMissingImportWarning && !warnedMissingImportFalse.has(pkg)) {
|
|
3087
|
+
warnedMissingImportFalse.add(pkg);
|
|
3088
|
+
mfWarn(`Shared dependency "${pkg}" has import: false but is not installed locally.\n Named imports (e.g. import { ... } from '${pkg}') will not work in production builds.\n Install it as a devDependency to enable named export detection.`);
|
|
3089
|
+
}
|
|
2767
3090
|
exportLine = generateDeferredHostProvidedExports([], pkg, cacheDescriptor, treeShakingConsumer);
|
|
2768
3091
|
}
|
|
2769
3092
|
loadShareCacheMap[pkg].writeSync(`
|
|
@@ -2795,18 +3118,18 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2795
3118
|
const servesRemoteSingletonFallback = command !== "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true;
|
|
2796
3119
|
const isConsumedByPeerSingleton = isSharedSingletonConsumedByPeer(pkg, resolvedOptions);
|
|
2797
3120
|
const usesEntryInjectedRemoteFallback = hasCompleteExportCoverage && command !== "build" && !isWorkspaceSingleton && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true && resolvedOptions.hostInitInjectLocation === "entry" && isConsumedByPeerSingleton;
|
|
2798
|
-
const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
|
|
3121
|
+
const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && !servesRemoteSingletonFallback && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
|
|
2799
3122
|
const usesDeferredTreeShakingFallback = hasCompleteExportCoverage && Boolean(treeShakingConsumer);
|
|
2800
3123
|
const reactMixedModeGuard = pkg === "react" ? createReactMixedModeRuntimeGuard() : "";
|
|
2801
3124
|
let exportLine;
|
|
2802
3125
|
let initBlock = "";
|
|
2803
3126
|
if (usesDeferredTreeShakingFallback) {
|
|
2804
3127
|
importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
|
|
2805
|
-
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage
|
|
3128
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
|
|
2806
3129
|
} else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
|
|
2807
3130
|
else if (usesDeferredSingletonFallback) {
|
|
2808
3131
|
importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
|
|
2809
|
-
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage
|
|
3132
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
|
|
2810
3133
|
} else if (detectedNamedExports === void 0) {
|
|
2811
3134
|
exportLine = `const __mfDefaultExport = (() => {
|
|
2812
3135
|
${generateShareModuleUnwrapCode({
|
|
@@ -2875,7 +3198,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2875
3198
|
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
2876
3199
|
__mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
|
|
2877
3200
|
}
|
|
2878
|
-
const prebuildImportLine = usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? servesRemoteSingletonFallback
|
|
3201
|
+
const prebuildImportLine = usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? !servesRemoteSingletonFallback && usesDeferredSingletonFallback && command !== "build" && (isWorkspaceSingleton || isWorkspacePackage) ? `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(lazyLocalFallbackSource)};` : "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(detectedNamedExports === void 0 ? coherentLocalSource : skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
|
|
2879
3202
|
const devDynamicImportLine = isWorkspacePackage ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
|
|
2880
3203
|
const moduleBody = usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? `
|
|
2881
3204
|
${prebuildImportLine}
|
|
@@ -2982,15 +3305,15 @@ function generateLocalSharedImportMap(options) {
|
|
|
2982
3305
|
${orderedShares.map((pkg, index) => {
|
|
2983
3306
|
const shareItem = getNormalizeShareItem(pkg, resolvedOptions);
|
|
2984
3307
|
if (!shareItem?.shareConfig.eager || shareItem.shareConfig.import === false) return "";
|
|
2985
|
-
return `import * as __mfEagerShare_${index} from ${
|
|
3308
|
+
return `import * as __mfEagerShare_${index} from ${toSafeJsLiteral(getLocalSharedPackagePath(pkg, shareItem, options))};`;
|
|
2986
3309
|
}).filter(Boolean).join("\n")}
|
|
2987
3310
|
const importMap = {
|
|
2988
3311
|
${orderedShares.map((pkg, index) => {
|
|
2989
3312
|
const shareItem = getNormalizeShareItem(pkg, resolvedOptions);
|
|
2990
3313
|
return `
|
|
2991
|
-
${
|
|
2992
|
-
${shareItem?.shareConfig.import === false ? `throw new Error(\`[Module Federation] Shared module '\${${
|
|
2993
|
-
return pkg;` : `let pkg = await import(${
|
|
3314
|
+
${toSafeJsLiteral(pkg)}: async () => {
|
|
3315
|
+
${shareItem?.shareConfig.import === false ? `throw new Error(\`[Module Federation] Shared module '\${${toSafeJsLiteral(pkg)}}' must be provided by host\`);` : shareItem?.shareConfig.eager ? `let pkg = __mfEagerShare_${index};
|
|
3316
|
+
return pkg;` : `let pkg = await import(${toSafeJsLiteral(getLocalSharedPackagePath(pkg, shareItem, options))});
|
|
2994
3317
|
return pkg;`}
|
|
2995
3318
|
}
|
|
2996
3319
|
`;
|
|
@@ -3010,23 +3333,23 @@ function generateLocalSharedImportMap(options) {
|
|
|
3010
3333
|
const treeShakingProviderImportId = treeShakingConfig && !disableRuntimeInference && hasTreeShakingSharedProvider(key, shareItem, options) ? getTreeShakingSharedProviderImportId(key, options) : void 0;
|
|
3011
3334
|
const treeShakingStatus = treeShakingUsage?.kind === "full" || disableRuntimeInference || treeShakingConfig?.mode === "runtime-infer" && !treeShakingProviderImportId && shareItem.shareConfig.import !== false ? 0 : 1;
|
|
3012
3335
|
return `
|
|
3013
|
-
${
|
|
3014
|
-
name: ${
|
|
3015
|
-
version: ${
|
|
3016
|
-
scope: [${
|
|
3336
|
+
${toSafeJsLiteral(key)}: {
|
|
3337
|
+
name: ${toSafeJsLiteral(key)},
|
|
3338
|
+
version: ${toSafeJsLiteral(shareItem.version)},
|
|
3339
|
+
scope: [${toSafeJsLiteral(shareItem.scope)}],
|
|
3017
3340
|
loaded: false,
|
|
3018
3341
|
materialize: ${sharesToMaterialize.has(key)},
|
|
3019
3342
|
eager: ${Boolean(shareItem.shareConfig.eager)},
|
|
3020
|
-
from: ${
|
|
3343
|
+
from: ${toSafeJsLiteral(resolvedOptions.name)},
|
|
3021
3344
|
canLiveRebind: ${canLiveRebind},
|
|
3022
3345
|
async get () {
|
|
3023
3346
|
if (${shareItem.shareConfig.import === false}) {
|
|
3024
|
-
throw new Error(\`[Module Federation] Shared module '\${${
|
|
3347
|
+
throw new Error(\`[Module Federation] Shared module '\${${toSafeJsLiteral(key)}}' must be provided by host\`);
|
|
3025
3348
|
}
|
|
3026
|
-
usedShared[${
|
|
3027
|
-
const {${
|
|
3349
|
+
usedShared[${toSafeJsLiteral(key)}].loaded = true
|
|
3350
|
+
const {${toSafeJsLiteral(key)}: pkgDynamicImport} = importMap
|
|
3028
3351
|
const res = await pkgDynamicImport()
|
|
3029
|
-
const exportModule = ${
|
|
3352
|
+
const exportModule = ${toSafeJsLiteral(useDirectReactImport)} && ${toSafeJsLiteral(key)} === "react"
|
|
3030
3353
|
? (res?.default ?? res)
|
|
3031
3354
|
: {...res}
|
|
3032
3355
|
// All npm packages pre-built by vite will be converted to esm
|
|
@@ -3042,18 +3365,18 @@ function generateLocalSharedImportMap(options) {
|
|
|
3042
3365
|
},
|
|
3043
3366
|
shareConfig: {
|
|
3044
3367
|
singleton: ${shareItem.shareConfig.singleton},
|
|
3045
|
-
requiredVersion: ${
|
|
3368
|
+
requiredVersion: ${toSafeJsLiteral(shareItem.shareConfig.requiredVersion)},
|
|
3046
3369
|
strictVersion: ${shareItem.shareConfig.strictVersion},
|
|
3047
3370
|
eager: ${Boolean(shareItem.shareConfig.eager)},
|
|
3048
3371
|
${shareItem.shareConfig.import === false ? "import: false," : ""}
|
|
3049
3372
|
},
|
|
3050
3373
|
${treeShakingConfig ? `treeShaking: {
|
|
3051
|
-
mode: ${
|
|
3052
|
-
usedExports: ${
|
|
3053
|
-
providedExports: ${
|
|
3374
|
+
mode: ${toSafeJsLiteral(treeShakingConfig.mode)},
|
|
3375
|
+
usedExports: ${toSafeJsLiteral(treeShakingUsedExports)},
|
|
3376
|
+
providedExports: ${toSafeJsLiteral(treeShakingProviderExports)},
|
|
3054
3377
|
status: ${treeShakingStatus},
|
|
3055
3378
|
${treeShakingProviderImportId ? `async get() {
|
|
3056
|
-
const container = await import(${
|
|
3379
|
+
const container = await import(${toSafeJsLiteral(treeShakingProviderImportId)});
|
|
3057
3380
|
if (typeof container.init === "function") await container.init();
|
|
3058
3381
|
return container.get();
|
|
3059
3382
|
},` : ""}
|
|
@@ -3067,12 +3390,12 @@ function generateLocalSharedImportMap(options) {
|
|
|
3067
3390
|
if (!remote) return null;
|
|
3068
3391
|
return `
|
|
3069
3392
|
{
|
|
3070
|
-
alias: ${
|
|
3071
|
-
entryGlobalName: ${
|
|
3072
|
-
name: ${
|
|
3073
|
-
type: ${
|
|
3074
|
-
entry: ${
|
|
3075
|
-
shareScope: ${
|
|
3393
|
+
alias: ${toSafeJsLiteral(key)},
|
|
3394
|
+
entryGlobalName: ${toSafeJsLiteral(remote.entryGlobalName)},
|
|
3395
|
+
name: ${toSafeJsLiteral(options ? getRuntimeRemoteAlias(key, options) : remote.name)},
|
|
3396
|
+
type: ${toSafeJsLiteral(remote.type)},
|
|
3397
|
+
entry: ${toSafeJsLiteral(remote.entry)},
|
|
3398
|
+
shareScope: ${toSafeJsLiteral(remote.shareScope ?? "default")},
|
|
3076
3399
|
}
|
|
3077
3400
|
`;
|
|
3078
3401
|
}).filter((x) => x !== null).join(",")}
|
|
@@ -3122,7 +3445,6 @@ function getMaterializedShares(options) {
|
|
|
3122
3445
|
}
|
|
3123
3446
|
}
|
|
3124
3447
|
}
|
|
3125
|
-
if (hasPackageDependency("vinext")) shares.delete("react");
|
|
3126
3448
|
return orderSharedDependenciesFirst([...shares].sort((a, b) => {
|
|
3127
3449
|
const priority = (pkg) => pkg === "react" ? 0 : pkg === "react-dom" ? 1 : pkg.startsWith("react/") ? 2 : 3;
|
|
3128
3450
|
return priority(a) - priority(b) || a.localeCompare(b);
|
|
@@ -3214,8 +3536,8 @@ function getShareItemForPreload(pkg, options = getNormalizeModuleFederationOptio
|
|
|
3214
3536
|
function generateSharedCacheSeedItem(pkg, shareItem, importPath, options = getNormalizeModuleFederationOptions()) {
|
|
3215
3537
|
const cacheDescriptor = getSharedCacheDescriptor(pkg, shareItem);
|
|
3216
3538
|
const cacheOwner = options.name;
|
|
3217
|
-
return `if (__mfReadSharedCache(__mfModuleCache.share, ${
|
|
3218
|
-
const mod = await import(${
|
|
3539
|
+
return `if (__mfReadSharedCache(__mfModuleCache.share, ${toSafeJsLiteral(cacheDescriptor)}) === undefined) {
|
|
3540
|
+
const mod = await import(${toSafeJsLiteral(importPath)});
|
|
3219
3541
|
${normalizeRuntimeShareCode}
|
|
3220
3542
|
const normalizedModule = __mfNormalizeRuntimeShare(mod);
|
|
3221
3543
|
const exportModule = normalizedModule === mod ? {...mod} : normalizedModule;
|
|
@@ -3223,7 +3545,7 @@ function generateSharedCacheSeedItem(pkg, shareItem, importPath, options = getNo
|
|
|
3223
3545
|
value: true,
|
|
3224
3546
|
enumerable: false
|
|
3225
3547
|
});
|
|
3226
|
-
__mfWriteSharedCache(__mfModuleCache.share, ${
|
|
3548
|
+
__mfWriteSharedCache(__mfModuleCache.share, ${toSafeJsLiteral(cacheDescriptor)}, exportModule, ${toSafeJsLiteral(cacheOwner)});
|
|
3227
3549
|
}`;
|
|
3228
3550
|
}
|
|
3229
3551
|
const normalizeRuntimeShareCode = `const __mfNormalizeRuntimeShare = (mod) => {
|
|
@@ -3385,9 +3707,13 @@ const externalSharedProviderSelectionHelperCode = `const __mfSelectExternalShare
|
|
|
3385
3707
|
function generateRuntimeSharedCacheSeedCode(shareStrategy, options) {
|
|
3386
3708
|
const seedBatches = getShareBatches(options, false);
|
|
3387
3709
|
return `
|
|
3388
|
-
const __mfSeedOrder = ${
|
|
3389
|
-
const __mfSeedBatches = ${
|
|
3390
|
-
|
|
3710
|
+
const __mfSeedOrder = ${toSafeJsLiteral(seedBatches.flat())};
|
|
3711
|
+
const __mfSeedBatches = ${toSafeJsLiteral(seedBatches)};
|
|
3712
|
+
// A share is normally skipped here until the dev scanner has observed a real
|
|
3713
|
+
// import and set materialize. An import:false share has no local fallback
|
|
3714
|
+
// though, so on a cold request (materialize not set yet) it must still be
|
|
3715
|
+
// attempted here, or it is never seeded and its consumer reads it undefined.
|
|
3716
|
+
const __mfSeedKeys = __mfSeedOrder.filter((pkg) => usedShared[pkg] && (usedShared[pkg].materialize !== false || usedShared[pkg].shareConfig?.import === false));
|
|
3391
3717
|
__mfModuleCache.providerInit ||= new Map();
|
|
3392
3718
|
const __mfInitializeProviderOnce = (key, initialize) => {
|
|
3393
3719
|
const existing = __mfModuleCache.providerInit.get(key);
|
|
@@ -3486,7 +3812,7 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy, options) {
|
|
|
3486
3812
|
initialShared[pkg],
|
|
3487
3813
|
pkg,
|
|
3488
3814
|
share,
|
|
3489
|
-
${
|
|
3815
|
+
${toSafeJsLiteral(shareStrategy)}
|
|
3490
3816
|
));
|
|
3491
3817
|
};
|
|
3492
3818
|
const __mfFirstRuntimeSeedBarrierIndex = __mfSeedKeys.findIndex(
|
|
@@ -3689,11 +4015,11 @@ function generateTreeShakingSnapshotPluginCode(enabled) {
|
|
|
3689
4015
|
},
|
|
3690
4016
|
});`;
|
|
3691
4017
|
}
|
|
3692
|
-
function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options), command = "build") {
|
|
4018
|
+
function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options), command = "build", exportConditions) {
|
|
3693
4019
|
const needsSharedProviderSelectionHelper = Object.keys(options.shared ?? {}).length > 0;
|
|
3694
4020
|
const hasTreeShakingShared = Object.values(options.shared ?? {}).some((share) => !!share?.shareConfig.treeShaking);
|
|
3695
4021
|
const hasMultipleShareScopes = Array.isArray(options.shareScope);
|
|
3696
|
-
const materializedShareBatches =
|
|
4022
|
+
const materializedShareBatches = toSafeJsLiteral(getShareBatches(options, false));
|
|
3697
4023
|
const runtimeImports = [
|
|
3698
4024
|
"init as runtimeInit",
|
|
3699
4025
|
"loadRemote",
|
|
@@ -3747,12 +4073,12 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
3747
4073
|
import {${runtimeImports}} from "@module-federation/runtime";
|
|
3748
4074
|
${runtimeHelperImports.length ? `import {${runtimeHelperImports.join(", ")}} from "@module-federation/runtime/helpers";` : ""}
|
|
3749
4075
|
${pluginImportNames.filter((item) => !isSsrOnlyPlugin(item[1])).map((item) => item[1]).join("\n")}
|
|
3750
|
-
${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options)) + "\n const { initResolve } = globalThis[globalKey];"}
|
|
3751
|
-
${getRuntimeModuleCacheBootstrapCode()}
|
|
4076
|
+
${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options), void 0, void 0, exportConditions) + "\n const { initResolve } = globalThis[globalKey];"}
|
|
4077
|
+
${getRuntimeModuleCacheBootstrapCode(exportConditions)}
|
|
3752
4078
|
const initTokens = {}
|
|
3753
|
-
const shareScopeNames = Array.isArray(${
|
|
3754
|
-
const shareScopeName = ${
|
|
3755
|
-
const mfName = ${
|
|
4079
|
+
const shareScopeNames = Array.isArray(${toSafeJsLiteral(options.shareScope)}) ? ${toSafeJsLiteral(options.shareScope)} : [${toSafeJsLiteral(options.shareScope)}]
|
|
4080
|
+
const shareScopeName = ${toSafeJsLiteral(hasMultipleShareScopes ? options.shareScope[0] : options.shareScope)}
|
|
4081
|
+
const mfName = ${toSafeJsLiteral(options.name)}
|
|
3756
4082
|
const __mfMaterializedShareBatches = ${materializedShareBatches}
|
|
3757
4083
|
let localSharedImportMapPromise
|
|
3758
4084
|
let exposesMapPromise
|
|
@@ -3882,7 +4208,12 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
3882
4208
|
function isWebpackProvider(provider) {
|
|
3883
4209
|
if (typeof provider?.get !== 'function') return false;
|
|
3884
4210
|
const source = Function.prototype.toString.call(provider.get);
|
|
3885
|
-
|
|
4211
|
+
// Production minification renames __webpack_require__, but preserves
|
|
4212
|
+
// Webpack's lazy chunk-loading .e(...).then(...) shape.
|
|
4213
|
+
return (
|
|
4214
|
+
source.includes('__webpack_require__') ||
|
|
4215
|
+
/\\.\\s*e\\s*\\([^)]*\\)\\s*\\.then\\s*\\(/.test(source)
|
|
4216
|
+
);
|
|
3886
4217
|
}
|
|
3887
4218
|
const __mfUsesWebpackShareScope = Object.values(initialShared).some((versions) =>
|
|
3888
4219
|
Object.values(versions || {}).some(isWebpackProvider)
|
|
@@ -3934,7 +4265,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
3934
4265
|
? await Promise.all([${pluginImportNames.filter((item) => isSsrOnlyPlugin(item[1])).map((item) => {
|
|
3935
4266
|
const specifier = getSsrOnlyPluginSpecifier(item[1]);
|
|
3936
4267
|
const opts = item[2];
|
|
3937
|
-
return `import(${
|
|
4268
|
+
return `import(${toSafeJsLiteral(specifier)}).then(m => (m.default ?? m)(${opts}))`;
|
|
3938
4269
|
}).join(", ")}])
|
|
3939
4270
|
: [];
|
|
3940
4271
|
const __mfRuntimeShareLoadIdKey = "__mf_vite_runtime_share_load_id__";
|
|
@@ -3945,7 +4276,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
3945
4276
|
name: mfName,
|
|
3946
4277
|
remotes: ${options.shareStrategy === "loaded-first" ? "[]" : "usedRemotes"},
|
|
3947
4278
|
shared: usedShared,
|
|
3948
|
-
plugins: [__mfSharePinLifecyclePlugin(), ${hasTreeShakingShared ? "__mfTreeShakingSnapshotPlugin()," : ""} ...__browserPlugins, ...__ssrPlugins],
|
|
4279
|
+
plugins: [__mfSharePinLifecyclePlugin(), __mfRealNameSnapshotPlugin(), ${hasTreeShakingShared ? "__mfTreeShakingSnapshotPlugin()," : ""} ...__browserPlugins, ...__ssrPlugins],
|
|
3949
4280
|
${options.shareStrategy ? `shareStrategy: '${options.shareStrategy}'` : ""}
|
|
3950
4281
|
});
|
|
3951
4282
|
${hasMultipleShareScopes ? `for (const shareScopeName of shareScopeNamesToInitialize) {
|
|
@@ -3977,6 +4308,33 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
3977
4308
|
}
|
|
3978
4309
|
};
|
|
3979
4310
|
}
|
|
4311
|
+
function __mfRealNameSnapshotPlugin() {
|
|
4312
|
+
return {
|
|
4313
|
+
name: "vite-real-name-snapshot-plugin",
|
|
4314
|
+
afterLoadSnapshot(args) {
|
|
4315
|
+
// Remotes are registered under an owner-scoped runtime name, so the
|
|
4316
|
+
// global snapshot only ever holds that name. Containers built by other
|
|
4317
|
+
// bundlers ask for the same remote by its real container name, miss, and
|
|
4318
|
+
// fall back to that container's own entry, whose remoteEntry is empty
|
|
4319
|
+
// (RUNTIME-011). Mirroring the resolved snapshot under the real name
|
|
4320
|
+
// keeps the primary lookup off that fallback.
|
|
4321
|
+
const snapshot = args && args.remoteSnapshot;
|
|
4322
|
+
const globalName = snapshot && snapshot.globalName;
|
|
4323
|
+
const version = snapshot && snapshot.version;
|
|
4324
|
+
if (!globalName || !version || !snapshot.remoteEntry) return args;
|
|
4325
|
+
const moduleInfo = globalThis.__FEDERATION__ && globalThis.__FEDERATION__.moduleInfo;
|
|
4326
|
+
const realNameKey = globalName + ":" + version;
|
|
4327
|
+
// Stores the same object, not a copy, so a later mutation (e.g. runtime-core
|
|
4328
|
+
// normalizing fields) stays consistent across both keys. Never overwrites an
|
|
4329
|
+
// existing entry: a different owner may have already resolved this real name
|
|
4330
|
+
// to its own snapshot, and this mirror must not shadow that one.
|
|
4331
|
+
if (moduleInfo && !moduleInfo[realNameKey]) {
|
|
4332
|
+
moduleInfo[realNameKey] = snapshot;
|
|
4333
|
+
}
|
|
4334
|
+
return args;
|
|
4335
|
+
}
|
|
4336
|
+
};
|
|
4337
|
+
}
|
|
3980
4338
|
const runtimeResolveShareHook = initRes.sharedHandler.hooks.lifecycle.resolveShare;
|
|
3981
4339
|
const __mfRuntimeProviderOrigins = new WeakMap();
|
|
3982
4340
|
runtimeResolveShareHook.on((args) => {
|
|
@@ -4005,7 +4363,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4005
4363
|
if (!versionMap || versionMap[version] !== currentProvider) return undefined;
|
|
4006
4364
|
const pinnedProvider = Object.assign({}, provider, {
|
|
4007
4365
|
version: provider.version ?? version,
|
|
4008
|
-
scope: provider.scope ?? currentProvider?.scope ?? ${
|
|
4366
|
+
scope: provider.scope ?? currentProvider?.scope ?? ${toSafeJsLiteral(hasMultipleShareScopes ? options.shareScope : [options.shareScope])},
|
|
4009
4367
|
strategy: 'loaded-first'
|
|
4010
4368
|
});
|
|
4011
4369
|
const providerFrom = provider.from;
|
|
@@ -4277,7 +4635,6 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4277
4635
|
expectedSelection
|
|
4278
4636
|
) => {
|
|
4279
4637
|
try {
|
|
4280
|
-
if (__mfGetPendingExternalSharedProvider(pkg, usedShare)) return;
|
|
4281
4638
|
const usedCacheDescriptor = __mfGetSharedCacheDescriptor(pkg, usedShare.shareConfig?.singleton, usedShare.version, usedShare.scope);
|
|
4282
4639
|
const cachedShare = __mfReadSharedCache(__mfModuleCache.share, usedCacheDescriptor);
|
|
4283
4640
|
const cachedShareOwner = __mfReadSharedCacheOwner(__mfModuleCache.share, usedCacheDescriptor);
|
|
@@ -4325,12 +4682,6 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4325
4682
|
!scopeRootProvider &&
|
|
4326
4683
|
!__mfMatchesSharedProvider(liveProvider, provider)
|
|
4327
4684
|
) return;
|
|
4328
|
-
if (
|
|
4329
|
-
!selectedLocalProvider &&
|
|
4330
|
-
isWebpackProvider(provider) &&
|
|
4331
|
-
!provider.lib &&
|
|
4332
|
-
!provider.loaded
|
|
4333
|
-
) return;
|
|
4334
4685
|
const loadedShare = await __mfLoadPinnedRuntimeShare(
|
|
4335
4686
|
pkg,
|
|
4336
4687
|
usedShare.shareConfig,
|
|
@@ -4605,13 +4956,14 @@ function getHostAutoInitState(options) {
|
|
|
4605
4956
|
}
|
|
4606
4957
|
return state;
|
|
4607
4958
|
}
|
|
4608
|
-
function generateHostAutoInitCode(remoteEntryImport, _command = "build", options) {
|
|
4959
|
+
function generateHostAutoInitCode(remoteEntryImport, _command = "build", options, exportConditions) {
|
|
4609
4960
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
4610
4961
|
const shouldPreloadShares = resolvedOptions.shareStrategy !== "loaded-first";
|
|
4611
|
-
const
|
|
4612
|
-
const cacheOwner =
|
|
4962
|
+
const hostInitShareBatches = toSafeJsLiteral(getShareBatches(options, false));
|
|
4963
|
+
const cacheOwner = toSafeJsLiteral(resolvedOptions.name);
|
|
4964
|
+
const preferLocalVinextReact = hasPackageDependency("vinext") && (!exportConditions?.includes("browser") || exportConditions.includes("worker"));
|
|
4613
4965
|
return `
|
|
4614
|
-
${getRuntimeModuleCacheBootstrapCode()}
|
|
4966
|
+
${getRuntimeModuleCacheBootstrapCode(exportConditions)}
|
|
4615
4967
|
let hostInitPromise;
|
|
4616
4968
|
async function initHost() {
|
|
4617
4969
|
if (!hostInitPromise) {
|
|
@@ -4623,31 +4975,44 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
|
|
|
4623
4975
|
const {usedShared} = await import("${getLocalSharedImportMapPath(options)}");
|
|
4624
4976
|
${normalizeRuntimeShareCode}
|
|
4625
4977
|
${shouldPreloadShares ? `
|
|
4626
|
-
const
|
|
4627
|
-
for (const
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4978
|
+
const __mfHostInitShareBatches = ${hostInitShareBatches};
|
|
4979
|
+
for (const __mfHostInitShareBatch of __mfHostInitShareBatches) {
|
|
4980
|
+
await Promise.all(__mfHostInitShareBatch.map(async (pkg) => {
|
|
4981
|
+
const share = usedShared[pkg];
|
|
4982
|
+
if (!share || share.materialize === false) return;
|
|
4983
|
+
// remoteEntry.init resolves tree-enabled shares into the
|
|
4984
|
+
// coverage-aware cache. Never republish that selected partial under
|
|
4985
|
+
// a generic full-module key here.
|
|
4986
|
+
if (share.treeShaking) return;
|
|
4987
|
+
const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
|
|
4988
|
+
if (
|
|
4989
|
+
__mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined &&
|
|
4990
|
+
__mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) ${_command === "serve" ? "!== undefined" : `=== ${cacheOwner}`}
|
|
4991
|
+
) return;
|
|
4992
|
+
await runtime.loadShare(pkg, {
|
|
4993
|
+
customShareInfo: { shareConfig: share.shareConfig }
|
|
4994
|
+
}).then(async (factory) => {
|
|
4995
|
+
const mod = typeof factory === "function" ? factory() : factory;
|
|
4996
|
+
let resolved = __mfNormalizeRuntimeShare(await Promise.resolve(mod));
|
|
4997
|
+
${preferLocalVinextReact ? `if (
|
|
4998
|
+
(pkg === "react" || pkg === "react-dom") &&
|
|
4999
|
+
typeof share.get === "function" &&
|
|
5000
|
+
share.shareConfig?.import !== false
|
|
5001
|
+
) {
|
|
5002
|
+
try {
|
|
5003
|
+
const localFactory = await share.get();
|
|
5004
|
+
const localModule = typeof localFactory === "function" ? localFactory() : localFactory;
|
|
5005
|
+
resolved = __mfNormalizeRuntimeShare(await Promise.resolve(localModule));
|
|
5006
|
+
} catch {}
|
|
5007
|
+
}` : ""}
|
|
4643
5008
|
__mfWriteSharedCache(
|
|
4644
5009
|
__mfModuleCache.share,
|
|
4645
5010
|
cacheDescriptor,
|
|
4646
|
-
|
|
5011
|
+
resolved,
|
|
4647
5012
|
${cacheOwner}
|
|
4648
5013
|
);
|
|
4649
5014
|
});
|
|
4650
|
-
});
|
|
5015
|
+
}));
|
|
4651
5016
|
}
|
|
4652
5017
|
` : ""}
|
|
4653
5018
|
return runtime;
|
|
@@ -4659,24 +5024,29 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
|
|
|
4659
5024
|
export { initHost, hostInitPromise };
|
|
4660
5025
|
`;
|
|
4661
5026
|
}
|
|
4662
|
-
function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID, command = "build", options) {
|
|
5027
|
+
function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID, command = "build", options, exportConditions) {
|
|
4663
5028
|
const state = getHostAutoInitState(options);
|
|
4664
5029
|
state.remoteEntryId = remoteEntryId;
|
|
4665
5030
|
state.command = command;
|
|
4666
|
-
|
|
5031
|
+
if (exportConditions !== void 0) state.exportConditions = exportConditions;
|
|
5032
|
+
state.module.writeSync(generateHostAutoInitCode(toSafeJsLiteral(remoteEntryId), command, options, state.exportConditions), true);
|
|
4667
5033
|
}
|
|
4668
|
-
function refreshHostAutoInit(options) {
|
|
5034
|
+
function refreshHostAutoInit(options, exportConditions) {
|
|
4669
5035
|
try {
|
|
4670
5036
|
const state = getHostAutoInitState(options);
|
|
4671
|
-
writeHostAutoInit(state.remoteEntryId, state.command, options);
|
|
5037
|
+
writeHostAutoInit(state.remoteEntryId, state.command, options, exportConditions);
|
|
4672
5038
|
} catch {}
|
|
4673
5039
|
}
|
|
4674
5040
|
function getHostAutoInitPath(options) {
|
|
4675
5041
|
return getHostAutoInitState(options).module.getImportId();
|
|
4676
5042
|
}
|
|
5043
|
+
function isOwnedHostAutoInitId(id, options) {
|
|
5044
|
+
return VirtualModule.findById(id) === getHostAutoInitState(options).module;
|
|
5045
|
+
}
|
|
4677
5046
|
//#endregion
|
|
4678
5047
|
//#region src/virtualModules/virtualRemotes.ts
|
|
4679
5048
|
const cacheRemoteMap = /* @__PURE__ */ new WeakMap();
|
|
5049
|
+
const remoteModuleMetadata = /* @__PURE__ */ new WeakMap();
|
|
4680
5050
|
const remoteOptionsIds = /* @__PURE__ */ new WeakMap();
|
|
4681
5051
|
let nextRemoteOptionsId = 1;
|
|
4682
5052
|
function getRemoteOptionsId(options) {
|
|
@@ -4698,14 +5068,29 @@ function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer
|
|
|
4698
5068
|
if (!instanceCache.has(cacheKey)) {
|
|
4699
5069
|
const virtual = new VirtualModule(`${consumer === "unified" ? remote : `${remote}__mf_consumer__${consumer}`}${MF_OWNER_INFIX}${getRemoteOptionsId(options)}`, LOAD_REMOTE_TAG, ".js", options.internalName);
|
|
4700
5070
|
virtual.writeSync(generateRemotes(remote, command, enableSsrInit, consumer, options));
|
|
5071
|
+
remoteModuleMetadata.set(virtual, {
|
|
5072
|
+
remote,
|
|
5073
|
+
command,
|
|
5074
|
+
enableSsrInit,
|
|
5075
|
+
consumer,
|
|
5076
|
+
options
|
|
5077
|
+
});
|
|
4701
5078
|
instanceCache.set(cacheKey, virtual);
|
|
4702
5079
|
}
|
|
4703
5080
|
return instanceCache.get(cacheKey);
|
|
4704
5081
|
}
|
|
5082
|
+
function refreshRemoteModuleForEnvironment(id, options, exportConditions) {
|
|
5083
|
+
const virtual = VirtualModule.findById(id);
|
|
5084
|
+
const metadata = virtual && remoteModuleMetadata.get(virtual);
|
|
5085
|
+
if (!virtual || !metadata || metadata.options !== options) return false;
|
|
5086
|
+
virtual.write(generateRemotes(metadata.remote, metadata.command, metadata.enableSsrInit, metadata.consumer, options, exportConditions));
|
|
5087
|
+
return true;
|
|
5088
|
+
}
|
|
4705
5089
|
const usedRemotesMap = {};
|
|
4706
5090
|
const usedRemotesByOptions = /* @__PURE__ */ new WeakMap();
|
|
4707
5091
|
const dynamicRemotesByOptions = /* @__PURE__ */ new WeakMap();
|
|
4708
5092
|
const staticRemotesByOptions = /* @__PURE__ */ new WeakMap();
|
|
5093
|
+
const EMPTY_STATIC_REMOTES = /* @__PURE__ */ new Set();
|
|
4709
5094
|
function getScopedUsedRemotesMap(options) {
|
|
4710
5095
|
let scoped = usedRemotesByOptions.get(options);
|
|
4711
5096
|
if (!scoped) {
|
|
@@ -4742,12 +5127,28 @@ function markStaticRemote(remote, options) {
|
|
|
4742
5127
|
}
|
|
4743
5128
|
remotes.add(remote);
|
|
4744
5129
|
}
|
|
5130
|
+
function getStaticRemotes(options) {
|
|
5131
|
+
return staticRemotesByOptions.get(options) ?? EMPTY_STATIC_REMOTES;
|
|
5132
|
+
}
|
|
4745
5133
|
function isDynamicOnlyRemote(remote, options) {
|
|
4746
5134
|
return (dynamicRemotesByOptions.get(options)?.has(remote) ?? false) && !(staticRemotesByOptions.get(options)?.has(remote) ?? false);
|
|
4747
5135
|
}
|
|
4748
5136
|
function getRemoteAliasFromId(id, remotes) {
|
|
4749
5137
|
return Object.keys(remotes).filter((name) => id === name || id.startsWith(name + "/")).sort((a, b) => b.length - a.length)[0];
|
|
4750
5138
|
}
|
|
5139
|
+
function getRemoteRegistration(id, remotes, options) {
|
|
5140
|
+
const alias = getRemoteAliasFromId(id, remotes);
|
|
5141
|
+
if (!alias) return void 0;
|
|
5142
|
+
const remote = remotes[alias];
|
|
5143
|
+
return {
|
|
5144
|
+
entryGlobalName: remote.entryGlobalName,
|
|
5145
|
+
name: options ? getRuntimeRemoteAlias(alias, options) : remote.name,
|
|
5146
|
+
alias,
|
|
5147
|
+
type: remote.type,
|
|
5148
|
+
entry: remote.entry,
|
|
5149
|
+
shareScope: remote.shareScope ?? "default"
|
|
5150
|
+
};
|
|
5151
|
+
}
|
|
4751
5152
|
function getRuntimeRemoteId(id, remotes, options) {
|
|
4752
5153
|
const alias = getRemoteAliasFromId(id, remotes);
|
|
4753
5154
|
if (!alias) return id;
|
|
@@ -4917,23 +5318,14 @@ ${deferRemoteLoad ? getLazyRemotePendingExport() : getEagerRemotePendingExport()
|
|
|
4917
5318
|
${command === "serve" && consumer === "server" ? getServerThenExport() : ""}
|
|
4918
5319
|
export { __mfDefaultExport as default };`;
|
|
4919
5320
|
}
|
|
4920
|
-
function generateRemotes(id, command, enableSsrInit = false, consumer = "unified", options) {
|
|
5321
|
+
function generateRemotes(id, command, enableSsrInit = false, consumer = "unified", options, exportConditions) {
|
|
4921
5322
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
4922
5323
|
const isLoadedFirst = resolvedOptions.shareStrategy === "loaded-first";
|
|
4923
5324
|
const initMode = resolveRemoteInitMode(resolvedOptions.shareStrategy, consumer);
|
|
4924
5325
|
const deferRemoteLoad = shouldDeferRemoteLoad(initMode);
|
|
4925
|
-
const remoteAlias = getRemoteAliasFromId(id, resolvedOptions.remotes);
|
|
4926
|
-
const remote = remoteAlias ? resolvedOptions.remotes[remoteAlias] : void 0;
|
|
4927
|
-
const runtimeRemoteAlias = remoteAlias ? getRuntimeRemoteAlias(remoteAlias, options) : void 0;
|
|
4928
5326
|
const runtimeRemoteId = getRuntimeRemoteId(id, resolvedOptions.remotes, options);
|
|
4929
|
-
const
|
|
4930
|
-
|
|
4931
|
-
name: options ? runtimeRemoteAlias : remote.name,
|
|
4932
|
-
alias: remoteAlias,
|
|
4933
|
-
type: remote.type,
|
|
4934
|
-
entry: remote.entry,
|
|
4935
|
-
shareScope: remote.shareScope ?? "default"
|
|
4936
|
-
})}]);` : "";
|
|
5327
|
+
const remoteRegistration = getRemoteRegistration(id, resolvedOptions.remotes, options);
|
|
5328
|
+
const registerRemoteCode = isLoadedFirst && remoteRegistration ? `runtime.registerRemotes([${JSON.stringify(remoteRegistration)}]);` : "";
|
|
4937
5329
|
const hostAutoInitPath = getHostAutoInitPath(options);
|
|
4938
5330
|
const ssrRemotes = Object.entries(resolvedOptions.remotes).map(([name, item]) => ({
|
|
4939
5331
|
name: getRuntimeRemoteAlias(name, options),
|
|
@@ -4943,9 +5335,9 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
|
|
|
4943
5335
|
const browserHostInitCode = `import(${JSON.stringify(hostAutoInitPath)})
|
|
4944
5336
|
.then((mod) => mod.hostInitPromise)
|
|
4945
5337
|
.then(initResolve, initReject);`;
|
|
4946
|
-
const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getRuntimeInitStatusImportId(options), ssrRemotes, hostAutoInitPath)}
|
|
5338
|
+
const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getRuntimeInitStatusImportId(options), ssrRemotes, hostAutoInitPath, exportConditions)}
|
|
4947
5339
|
const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];`;
|
|
4948
|
-
const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
|
|
5340
|
+
const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode(exportConditions)}
|
|
4949
5341
|
import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(hostAutoInitPath)};` : `${devRuntimeBootstrap}
|
|
4950
5342
|
${command === "serve" && consumer !== "server" ? browserHostInitCode : ""}`;
|
|
4951
5343
|
const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
|
|
@@ -4966,6 +5358,12 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
|
|
|
4966
5358
|
__mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
|
|
4967
5359
|
.then((runtime) => {
|
|
4968
5360
|
${registerRemoteCode}
|
|
5361
|
+
const moduleCacheKey = Symbol.for(${JSON.stringify(MODULE_CACHE_SHARE_SCOPE_KEY)});
|
|
5362
|
+
const shareScopes = runtime.shareScopeMap || {};
|
|
5363
|
+
for (const scope of Object.values(shareScopes)) {
|
|
5364
|
+
if (scope && typeof scope === "object") scope[moduleCacheKey] = __mfModuleCache;
|
|
5365
|
+
}
|
|
5366
|
+
shareScopes[moduleCacheKey] = __mfModuleCache;
|
|
4969
5367
|
return runtime.loadRemote(${JSON.stringify(runtimeRemoteId)});
|
|
4970
5368
|
})
|
|
4971
5369
|
.then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
|
|
@@ -5006,28 +5404,57 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
|
|
|
5006
5404
|
}
|
|
5007
5405
|
//#endregion
|
|
5008
5406
|
//#region src/plugins/pluginAddEntry.ts
|
|
5407
|
+
const isPreloadableVirtualMfChunk = (name) => name.includes("virtual_mf") && !name.includes("__prebuild__");
|
|
5009
5408
|
const HOST_INIT_PRELOAD_CHUNKS = [
|
|
5010
5409
|
(name) => name === "hostInit",
|
|
5011
5410
|
(name) => name === "remoteEntry",
|
|
5012
|
-
(name) => name
|
|
5411
|
+
(name) => name === "virtualExposes",
|
|
5412
|
+
isPreloadableVirtualMfChunk,
|
|
5013
5413
|
(name) => name === "index"
|
|
5014
5414
|
];
|
|
5415
|
+
const isRemoteWarmupExcluded = (name) => name.includes("__prebuild__") || name.includes("__loadShare__");
|
|
5416
|
+
const REMOTE_ENTRY_WARMUP_CHUNKS = [
|
|
5417
|
+
(name) => name === "hostInit",
|
|
5418
|
+
(name) => name === "virtualExposes",
|
|
5419
|
+
(name) => isPreloadableVirtualMfChunk(name) && !isRemoteWarmupExcluded(name)
|
|
5420
|
+
];
|
|
5421
|
+
function getChunksByFileName(bundle) {
|
|
5422
|
+
return new Map(Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.fileName, chunk]));
|
|
5423
|
+
}
|
|
5424
|
+
function collectPreloadChunkFiles(chunksByFileName, seeds, excludeFromClosure = (name) => name.includes("__prebuild__")) {
|
|
5425
|
+
const seenFiles = /* @__PURE__ */ new Set();
|
|
5426
|
+
const files = [];
|
|
5427
|
+
const queue = [...seeds];
|
|
5428
|
+
while (queue.length > 0) {
|
|
5429
|
+
const chunk = queue.shift();
|
|
5430
|
+
if (seenFiles.has(chunk.fileName)) continue;
|
|
5431
|
+
seenFiles.add(chunk.fileName);
|
|
5432
|
+
for (const imported of chunk.imports ?? []) {
|
|
5433
|
+
const importedChunk = chunksByFileName.get(imported);
|
|
5434
|
+
if (importedChunk && !excludeFromClosure(importedChunk.name)) queue.push(importedChunk);
|
|
5435
|
+
}
|
|
5436
|
+
files.push(chunk.fileName);
|
|
5437
|
+
}
|
|
5438
|
+
return files;
|
|
5439
|
+
}
|
|
5015
5440
|
function escapeHtmlAttr(value) {
|
|
5016
5441
|
return value.replace(/&/g, "&").replace(/"/g, """);
|
|
5017
5442
|
}
|
|
5018
5443
|
function getExistingHrefSet(html) {
|
|
5019
5444
|
return new Set(Array.from(html.matchAll(/\bhref\s*=\s*["']([^"']+)["']/gi), (match) => match[1]));
|
|
5020
5445
|
}
|
|
5021
|
-
function injectHostInitPreloads(html, bundle, resolvePath) {
|
|
5446
|
+
function injectHostInitPreloads(html, bundle, resolvePath, externalHrefs = []) {
|
|
5022
5447
|
const existingHrefs = getExistingHrefSet(html);
|
|
5023
|
-
const seenFiles = /* @__PURE__ */ new Set();
|
|
5024
5448
|
const hrefs = [];
|
|
5025
|
-
for (const
|
|
5026
|
-
if (
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5030
|
-
|
|
5449
|
+
for (const href of externalHrefs) {
|
|
5450
|
+
if (existingHrefs.has(href)) continue;
|
|
5451
|
+
existingHrefs.add(href);
|
|
5452
|
+
hrefs.push(href);
|
|
5453
|
+
}
|
|
5454
|
+
const chunksByFileName = getChunksByFileName(bundle);
|
|
5455
|
+
const seeds = Array.from(chunksByFileName.values()).filter((chunk) => HOST_INIT_PRELOAD_CHUNKS.some((match) => match(chunk.name)));
|
|
5456
|
+
for (const fileName of collectPreloadChunkFiles(chunksByFileName, seeds)) {
|
|
5457
|
+
const href = resolvePath(fileName);
|
|
5031
5458
|
if (existingHrefs.has(href)) continue;
|
|
5032
5459
|
existingHrefs.add(href);
|
|
5033
5460
|
hrefs.push(href);
|
|
@@ -5036,6 +5463,40 @@ function injectHostInitPreloads(html, bundle, resolvePath) {
|
|
|
5036
5463
|
const tags = hrefs.map((href) => `<link rel="modulepreload" crossorigin href="${escapeHtmlAttr(href)}">`).join("");
|
|
5037
5464
|
return html.includes("</head>") ? html.replace("</head>", `${tags}</head>`) : `${tags}${html}`;
|
|
5038
5465
|
}
|
|
5466
|
+
function appendRemoteEntryWarmup(bundle, entryFileName) {
|
|
5467
|
+
const chunksByFileName = getChunksByFileName(bundle);
|
|
5468
|
+
const entryChunk = chunksByFileName.get(entryFileName);
|
|
5469
|
+
if (!entryChunk || entryChunk.code.includes("__mfWarmupPath")) return;
|
|
5470
|
+
const reachable = /* @__PURE__ */ new Set();
|
|
5471
|
+
const walk = [entryChunk];
|
|
5472
|
+
while (walk.length > 0) {
|
|
5473
|
+
const chunk = walk.pop();
|
|
5474
|
+
if (reachable.has(chunk.fileName)) continue;
|
|
5475
|
+
reachable.add(chunk.fileName);
|
|
5476
|
+
for (const imported of [...chunk.imports ?? [], ...chunk.dynamicImports ?? []]) {
|
|
5477
|
+
const importedChunk = chunksByFileName.get(imported);
|
|
5478
|
+
if (importedChunk) walk.push(importedChunk);
|
|
5479
|
+
}
|
|
5480
|
+
}
|
|
5481
|
+
const seeds = Array.from(reachable).map((file) => chunksByFileName.get(file)).filter((chunk) => chunk.fileName !== entryFileName && REMOTE_ENTRY_WARMUP_CHUNKS.some((match) => match(chunk.name)));
|
|
5482
|
+
const lastSlash = entryFileName.lastIndexOf("/");
|
|
5483
|
+
const entryDir = lastSlash !== -1 ? entryFileName.slice(0, lastSlash + 1) : "";
|
|
5484
|
+
const files = collectPreloadChunkFiles(chunksByFileName, seeds, isRemoteWarmupExcluded).filter((file) => file !== entryFileName).map((file) => rebaseImport(file, entryDir));
|
|
5485
|
+
if (files.length === 0) return;
|
|
5486
|
+
entryChunk.code += `
|
|
5487
|
+
if (typeof document !== 'undefined' && document.head) {
|
|
5488
|
+
try {
|
|
5489
|
+
for (const __mfWarmupPath of ${JSON.stringify(files)}) {
|
|
5490
|
+
const __mfWarmupLink = document.createElement('link');
|
|
5491
|
+
__mfWarmupLink.rel = 'modulepreload';
|
|
5492
|
+
__mfWarmupLink.crossOrigin = '';
|
|
5493
|
+
__mfWarmupLink.href = new URL(__mfWarmupPath, import.meta.url).href;
|
|
5494
|
+
document.head.appendChild(__mfWarmupLink);
|
|
5495
|
+
}
|
|
5496
|
+
} catch (__mfWarmupError) {}
|
|
5497
|
+
}
|
|
5498
|
+
`;
|
|
5499
|
+
}
|
|
5039
5500
|
function getFirstHtmlEntryFile(entryFiles) {
|
|
5040
5501
|
return entryFiles.find((file) => file.endsWith(".html"));
|
|
5041
5502
|
}
|
|
@@ -5156,6 +5617,16 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5156
5617
|
}
|
|
5157
5618
|
return patched;
|
|
5158
5619
|
}
|
|
5620
|
+
function getRemoteEntryPreloadUrls() {
|
|
5621
|
+
const normalizedOptions = federationOptions ?? getNormalizeModuleFederationOptions();
|
|
5622
|
+
const isLoadedFirstClientBuild = (_command === "build" || viteConfig?.command === "build") && waitsForInit && !viteConfig?.build?.ssr && normalizedOptions.shareStrategy === "loaded-first";
|
|
5623
|
+
if (normalizedOptions.shareStrategy === "loaded-first" && !isLoadedFirstClientBuild) return [];
|
|
5624
|
+
const remoteSources = isLoadedFirstClientBuild ? Array.from(getStaticRemotes(normalizedOptions)) : Object.entries(getUsedRemotesMap(federationOptions)).flatMap(([, remotes]) => Array.from(remotes)).filter((remote) => !federationOptions || !isDynamicOnlyRemote(remote, federationOptions));
|
|
5625
|
+
return Array.from(new Set(remoteSources.flatMap((remote) => {
|
|
5626
|
+
const registration = getRemoteRegistration(remote, normalizedOptions.remotes, federationOptions);
|
|
5627
|
+
return registration && (registration.type === "module" || registration.type === "esm") && /^(?:https?:)?\/\//.test(registration.entry) ? [registration.entry] : [];
|
|
5628
|
+
})));
|
|
5629
|
+
}
|
|
5159
5630
|
function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false, options) {
|
|
5160
5631
|
const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
|
|
5161
5632
|
globalThis.System && typeof globalThis.System.import === 'function'
|
|
@@ -5167,11 +5638,35 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5167
5638
|
const entryImportDeclaration = isEncodedVirtualEntry ? `const __mfEntryUrl = ${JSON.stringify(entrySrc)};
|
|
5168
5639
|
` : "";
|
|
5169
5640
|
const entryImportExpression = isEncodedVirtualEntry ? "import(/* @vite-ignore */ __mfEntryUrl)" : importExpression(entrySrc);
|
|
5170
|
-
const
|
|
5641
|
+
const normalizedOptions = federationOptions ?? getNormalizeModuleFederationOptions();
|
|
5642
|
+
const isLoadedFirstClientBuild = (_command === "build" || viteConfig?.command === "build") && waitsForInit && !viteConfig?.build?.ssr && normalizedOptions.shareStrategy === "loaded-first";
|
|
5643
|
+
const shouldPreloadRemotes = !options?.skipRemotePreload && (normalizedOptions.shareStrategy !== "loaded-first" || isLoadedFirstClientBuild);
|
|
5644
|
+
const remoteSources = isLoadedFirstClientBuild ? Array.from(getStaticRemotes(normalizedOptions)) : Object.entries(getUsedRemotesMap(federationOptions)).flatMap(([, remotes]) => Array.from(remotes)).filter((remote) => !federationOptions || !isDynamicOnlyRemote(remote, federationOptions));
|
|
5645
|
+
const remotePreloads = shouldPreloadRemotes ? remoteSources.sort().map((remote) => {
|
|
5646
|
+
const registration = isLoadedFirstClientBuild ? getRemoteRegistration(remote, normalizedOptions.remotes, federationOptions) : void 0;
|
|
5647
|
+
return `__mfPreloadRemote(${JSON.stringify(getRuntimeRemoteId(remote, normalizedOptions.remotes, federationOptions))}, ${JSON.stringify(remote)}${registration ? `, ${JSON.stringify(registration)}` : ""})`;
|
|
5648
|
+
}).join(",") : "";
|
|
5649
|
+
const remoteEntryPrefetchUrls = shouldPreloadRemotes ? getRemoteEntryPreloadUrls() : [];
|
|
5650
|
+
const remoteEntryPrefetchBlock = remoteEntryPrefetchUrls.length > 0 ? `const __mfRemoteEntryPrefetchUrls = ${JSON.stringify(remoteEntryPrefetchUrls)};
|
|
5651
|
+
for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
|
|
5652
|
+
import(/* @vite-ignore */ __mfRemoteEntryPrefetchUrl).catch(() => {});
|
|
5653
|
+
}
|
|
5654
|
+
` : "";
|
|
5655
|
+
const sharedPreloadSources = _command === "serve" && waitsForInit && Object.keys(normalizedOptions.exposes || {}).length > 0 && Object.keys(normalizedOptions.remotes || {}).length === 0 && federationOptions ? Array.from(getUsedShares(federationOptions)).filter((pkg) => !pkg.endsWith("/")).filter((pkg) => {
|
|
5656
|
+
const shareItem = federationOptions.shared[pkg] || Object.entries(federationOptions.shared).find(([key]) => key.endsWith("/") && pkg.startsWith(key))?.[1];
|
|
5657
|
+
const isExplicitShare = Object.prototype.hasOwnProperty.call(federationOptions.shared, pkg);
|
|
5658
|
+
return shareItem?.shareConfig?.singleton === true && shareItem?.shareConfig?.import !== false && !shareItem?.shareConfig?.treeShaking && (isExplicitShare || typeof shareItem?.shareConfig?.import === "string" || Boolean(getProjectResolvedImportPath(pkg)));
|
|
5659
|
+
}).map((pkg) => toViteEncodedId(getLoadShareModulePath(pkg, false, federationOptions))) : [];
|
|
5660
|
+
const sharedPreloadBlock = sharedPreloadSources.length > 0 ? `
|
|
5661
|
+
const __mfSharedPreloadUrls = ${JSON.stringify(sharedPreloadSources)};
|
|
5662
|
+
await Promise.all(__mfSharedPreloadUrls.map((src) => import(/* @vite-ignore */ src).catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));` : "";
|
|
5171
5663
|
const remoteCachePrefix = getRuntimeRemoteCachePrefix(federationOptions);
|
|
5172
5664
|
const preloadBlock = remotePreloads ? `
|
|
5173
5665
|
const runtime = await initHost();
|
|
5174
|
-
const __mfPreloadRemote = (runtimeRemote, remote) => {
|
|
5666
|
+
const __mfPreloadRemote = (runtimeRemote, remote${isLoadedFirstClientBuild ? ", registration" : ""}) => {
|
|
5667
|
+
${isLoadedFirstClientBuild ? `if (registration && typeof runtime.registerRemotes === "function") {
|
|
5668
|
+
runtime.registerRemotes([registration]);
|
|
5669
|
+
}` : ""}
|
|
5175
5670
|
const remoteCacheKey = ${JSON.stringify(remoteCachePrefix)} + remote;
|
|
5176
5671
|
const pendingKey = "__mf_pending__" + remoteCacheKey;
|
|
5177
5672
|
if (!__mfModuleCache.remote[pendingKey]) {
|
|
@@ -5189,22 +5684,28 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5189
5684
|
return __mfModuleCache.remote[pendingKey];
|
|
5190
5685
|
};
|
|
5191
5686
|
const __mfRemotePreloads = [${remotePreloads}];
|
|
5192
|
-
await Promise.allSettled(__mfRemotePreloads);` : `await initHost();`;
|
|
5687
|
+
await ${isLoadedFirstClientBuild ? "Promise.all" : "Promise.allSettled"}(__mfRemotePreloads);` : `await initHost();`;
|
|
5688
|
+
const pendingShareLoadsAwait = `
|
|
5689
|
+
if (__mfModuleCache.pendingShareLoads) {
|
|
5690
|
+
await Promise.all(__mfModuleCache.pendingShareLoads);
|
|
5691
|
+
}
|
|
5692
|
+
const __mfReactServerModuleCache = globalThis[${JSON.stringify(getModuleCacheGlobalKey(["react-server"]))}];
|
|
5693
|
+
if (__mfReactServerModuleCache?.pendingShareLoads) {
|
|
5694
|
+
await Promise.all(__mfReactServerModuleCache.pendingShareLoads);
|
|
5695
|
+
}`;
|
|
5193
5696
|
const importCode = `
|
|
5194
5697
|
(async () => {
|
|
5195
5698
|
const __mfHostInit = await ${importExpression(initSrc)};
|
|
5196
5699
|
await __mfHostInit.__tla;
|
|
5197
5700
|
const { initHost } = __mfHostInit;
|
|
5198
|
-
${preloadBlock}
|
|
5199
|
-
if (__mfModuleCache.pendingShareLoads) {
|
|
5200
|
-
await Promise.all(__mfModuleCache.pendingShareLoads);
|
|
5201
|
-
}
|
|
5701
|
+
${preloadBlock}${sharedPreloadBlock}${pendingShareLoadsAwait}
|
|
5202
5702
|
})().then(() => ${entryImportExpression});
|
|
5203
5703
|
`;
|
|
5204
5704
|
return [
|
|
5205
5705
|
getRuntimeModuleCacheBootstrapCode(),
|
|
5206
5706
|
importHelper,
|
|
5207
5707
|
entryImportDeclaration,
|
|
5708
|
+
remoteEntryPrefetchBlock,
|
|
5208
5709
|
importCode
|
|
5209
5710
|
].join("\n");
|
|
5210
5711
|
}
|
|
@@ -5236,6 +5737,17 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5236
5737
|
const normalized = decodeViteId(id).replace(/^\0+/, "");
|
|
5237
5738
|
return normalized.includes("virtual:mf:") || /__(?:loadShare|prebuild|loadRemote)__/.test(normalized);
|
|
5238
5739
|
}
|
|
5740
|
+
function isWorkspaceSourceId(id) {
|
|
5741
|
+
const normalized = normalizeModuleId(decodeViteId(id));
|
|
5742
|
+
if (normalized.startsWith("\0") || normalized.startsWith("virtual:")) return false;
|
|
5743
|
+
const filePath = stripQueryAndHash$1(normalized);
|
|
5744
|
+
if (filePath.startsWith("/@fs/")) return true;
|
|
5745
|
+
if (!path$1.isAbsolute(filePath)) return false;
|
|
5746
|
+
const root = normalizePathForImport(path$1.resolve(viteConfig.root));
|
|
5747
|
+
const absolutePath = normalizePathForImport(path$1.resolve(filePath));
|
|
5748
|
+
const relativePath = normalizePathForImport(path$1.relative(root, absolutePath));
|
|
5749
|
+
return (relativePath === ".." || relativePath.startsWith("../") || path$1.isAbsolute(relativePath)) && fs$2.existsSync(absolutePath);
|
|
5750
|
+
}
|
|
5239
5751
|
function addEntryFile(file) {
|
|
5240
5752
|
const normalized = normalizeModuleId(file);
|
|
5241
5753
|
if (!entryFiles.includes(normalized)) entryFiles.push(normalized);
|
|
@@ -5302,7 +5814,10 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5302
5814
|
}
|
|
5303
5815
|
const devFileName = resolveDevHashEntryFileName$1(fileName);
|
|
5304
5816
|
if (devFileName !== fileName && req.url?.startsWith((viteConfig.base + devFileName).replace(/^\/?/, "/"))) req.url = req.url.replace(devFileName, fileName);
|
|
5305
|
-
if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, "/")))
|
|
5817
|
+
if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, "/"))) {
|
|
5818
|
+
req.url = devEntryPath;
|
|
5819
|
+
req.headers["sec-fetch-dest"] = "script";
|
|
5820
|
+
}
|
|
5306
5821
|
next();
|
|
5307
5822
|
});
|
|
5308
5823
|
},
|
|
@@ -5383,6 +5898,10 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5383
5898
|
},
|
|
5384
5899
|
generateBundle(_options, bundle) {
|
|
5385
5900
|
if (skipSvelteKitSsrBuild()) return;
|
|
5901
|
+
if (entryName === "remoteEntry" && emitFileId && fileName && !viteConfig?.build?.ssr && _options?.format === "es" && viteConfig?.build?.modulePreload !== false) {
|
|
5902
|
+
const remoteEntryFile = findRemoteEntryFile(fileName, bundle);
|
|
5903
|
+
if (remoteEntryFile) appendRemoteEntryWarmup(bundle, remoteEntryFile);
|
|
5904
|
+
}
|
|
5386
5905
|
if (!injectHtml()) return;
|
|
5387
5906
|
if (!emitFileId) return;
|
|
5388
5907
|
const htmlFileNames = Object.keys(bundle).filter((fileName) => fileName.endsWith(".html"));
|
|
@@ -5444,12 +5963,12 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5444
5963
|
htmlContent = htmlContent.replace("<head>", `<head>${scriptContent}`);
|
|
5445
5964
|
}
|
|
5446
5965
|
}
|
|
5447
|
-
if (waitsForInit && viteConfig.build.modulePreload !== false) htmlContent = injectHostInitPreloads(htmlContent, bundle, (builtFileName) => resolvePath(builtFileName, fileName));
|
|
5966
|
+
if (waitsForInit && viteConfig.build.modulePreload !== false) htmlContent = injectHostInitPreloads(htmlContent, bundle, (builtFileName) => resolvePath(builtFileName, fileName), getRemoteEntryPreloadUrls());
|
|
5448
5967
|
htmlAsset.source = htmlContent;
|
|
5449
5968
|
}
|
|
5450
5969
|
},
|
|
5451
5970
|
closeBundle() {
|
|
5452
|
-
if (_command === "serve" || skipSvelteKitSsrBuild()) return;
|
|
5971
|
+
if (_command === "serve" || !hasPackageDependency("@sveltejs/kit") || skipSvelteKitSsrBuild()) return;
|
|
5453
5972
|
let attempts = 0;
|
|
5454
5973
|
const retry = () => {
|
|
5455
5974
|
attempts += 1;
|
|
@@ -5489,7 +6008,7 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5489
6008
|
return mapCodeToCodeWithSourcemap(code.replace("vueApp.mount(vueAppRootContainer);", `${injection}vueApp.mount(vueAppRootContainer);`));
|
|
5490
6009
|
}
|
|
5491
6010
|
const isReactRouterEntry = isReactRouterClientEntry(id);
|
|
5492
|
-
const isHydrationEntryFallback = inject === "entry" && entryFiles.length === 0 && (!htmlFilePath || !fs$2.existsSync(htmlFilePath)) && !clientInjected && !isFederationInternalVirtualId(id) && !id.includes("node_modules") && (!code.includes("HydratedRouter") || isReactRouterEntry) && (id.startsWith("\0") || /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id)) && (/hydrateRoot|createRoot|ReactDOM\.render/.test(code) || /\.mount\s*\(\s*['"#]/.test(code) || /\.mount\s*\(/.test(code) && /createSSRApp|createApp/.test(code));
|
|
6011
|
+
const isHydrationEntryFallback = inject === "entry" && entryFiles.length === 0 && (!htmlFilePath || !fs$2.existsSync(htmlFilePath)) && !clientInjected && !isFederationInternalVirtualId(id) && !id.includes("node_modules") && (!code.includes("HydratedRouter") || isReactRouterEntry) && (id.startsWith("\0") || /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id)) && (/hydrateRoot|createRoot|ReactDOM\.render/.test(code) || /\.mount\s*\(\s*['"#]/.test(code) || /\.mount\s*\(/.test(code) && /createSSRApp|createApp/.test(code)) && !isWorkspaceSourceId(id);
|
|
5493
6012
|
const isNuxtEntryAsyncModule = /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
|
|
5494
6013
|
const isNuxtClientEntryFallback = _command === "serve" && inject === "entry" && (!htmlFilePath || !fs$2.existsSync(htmlFilePath)) && !clientInjected && !hasEntryBootstrapParam(id) && !id.includes("node_modules/.vite") && isNuxtEntryAsyncModule && !entryFiles.some((file) => projectId === file);
|
|
5495
6014
|
if (!(_command === "serve" && isNuxtEntryAsyncModule) && (injectedTransformIds.has(projectId) || injectEntry() && entryFiles.some((file) => projectId === file) || _command === "serve" && inject === "html" && !isVinext && !clientInjected && !skipHtmlDevFallback && !id.startsWith("\0") && !id.includes("node_modules") && /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id) || isHydrationEntryFallback || inject === "entry" && waitsForInit && isReactRouterEntry || isNuxtClientEntryFallback)) {
|
|
@@ -6243,200 +6762,6 @@ function initVirtualModules(command, remoteEntryId, enableSsrInit = false, optio
|
|
|
6243
6762
|
})) : void 0);
|
|
6244
6763
|
}
|
|
6245
6764
|
//#endregion
|
|
6246
|
-
//#region src/utils/bundleHelpers.ts
|
|
6247
|
-
function isOutputChunk$1(chunk) {
|
|
6248
|
-
return chunk.type === "chunk";
|
|
6249
|
-
}
|
|
6250
|
-
function escapeRegExp$1(value) {
|
|
6251
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6252
|
-
}
|
|
6253
|
-
function getProxyBaseName(fileName) {
|
|
6254
|
-
return fileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
|
|
6255
|
-
}
|
|
6256
|
-
function extractFunctionDeclaration(code, functionName) {
|
|
6257
|
-
const funcRe = new RegExp(`function\\s+${functionName}\\s*\\([^)]*\\)\\s*\\{`);
|
|
6258
|
-
const funcStart = code.search(funcRe);
|
|
6259
|
-
if (funcStart < 0) return;
|
|
6260
|
-
let depth = 0;
|
|
6261
|
-
for (let i = code.indexOf("{", funcStart); i < code.length; i++) if (code[i] === "{") depth++;
|
|
6262
|
-
else if (code[i] === "}") {
|
|
6263
|
-
depth--;
|
|
6264
|
-
if (depth === 0) return code.slice(funcStart, i + 1);
|
|
6265
|
-
}
|
|
6266
|
-
}
|
|
6267
|
-
/**
|
|
6268
|
-
* Resolve the local alias for a non-inlineable proxy binding.
|
|
6269
|
-
* If Rollup's deconflict renamed the alias but didn't update references
|
|
6270
|
-
* in the code body, fall back to proxyLocal so they stay in sync.
|
|
6271
|
-
*/
|
|
6272
|
-
function resolveProxyAlias(binding, proxyLocal, code, fullImport, claimedLocals = /* @__PURE__ */ new Set()) {
|
|
6273
|
-
const codeWithoutImport = code.replace(fullImport, "");
|
|
6274
|
-
const escapedLocal = binding.local.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6275
|
-
const localUsedInCode = new RegExp(`\\b${escapedLocal}\\b`).test(codeWithoutImport);
|
|
6276
|
-
const claimedImportLocals = /* @__PURE__ */ new Set();
|
|
6277
|
-
const importRe = /import\s*\{([^}]+)\}\s*from\s*["'][^"']+["']\s*;?/g;
|
|
6278
|
-
let match;
|
|
6279
|
-
while ((match = importRe.exec(codeWithoutImport)) !== null) for (const spec of match[1].split(",")) {
|
|
6280
|
-
const parts = spec.trim().split(/\s+as\s+/);
|
|
6281
|
-
claimedImportLocals.add((parts[1] || parts[0]).trim());
|
|
6282
|
-
}
|
|
6283
|
-
const local = !localUsedInCode && !claimedLocals.has(proxyLocal) && !claimedImportLocals.has(proxyLocal) ? proxyLocal : binding.local;
|
|
6284
|
-
return {
|
|
6285
|
-
imported: binding.imported,
|
|
6286
|
-
local
|
|
6287
|
-
};
|
|
6288
|
-
}
|
|
6289
|
-
function collectLoadShareProxyChunks(bundle, loadShareTag) {
|
|
6290
|
-
const proxyChunks = /* @__PURE__ */ new Map();
|
|
6291
|
-
for (const [fileName, chunk] of Object.entries(bundle)) {
|
|
6292
|
-
if (!isOutputChunk$1(chunk)) continue;
|
|
6293
|
-
if (fileName.includes(loadShareTag) && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
|
|
6294
|
-
code: chunk.code,
|
|
6295
|
-
fileName
|
|
6296
|
-
});
|
|
6297
|
-
}
|
|
6298
|
-
return proxyChunks;
|
|
6299
|
-
}
|
|
6300
|
-
function collectSystemProxyInfos(proxyChunks, loadShareTag) {
|
|
6301
|
-
const systemProxyInfo = /* @__PURE__ */ new Map();
|
|
6302
|
-
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
6303
|
-
const depsMatch = proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);
|
|
6304
|
-
if (!depsMatch) continue;
|
|
6305
|
-
const loadShareDep = Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).find((dep) => dep.includes(loadShareTag) && !dep.includes("commonjs-proxy"));
|
|
6306
|
-
if (!loadShareDep) continue;
|
|
6307
|
-
const loadShareBindings = {};
|
|
6308
|
-
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];
|
|
6309
|
-
const exportMap = {};
|
|
6310
|
-
const objectExportMatch = proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);
|
|
6311
|
-
if (objectExportMatch) for (const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)) {
|
|
6312
|
-
const [, exported, local] = m;
|
|
6313
|
-
const funcBody = extractFunctionDeclaration(proxyInfo.code, local);
|
|
6314
|
-
if (funcBody) exportMap[exported] = {
|
|
6315
|
-
type: "helper",
|
|
6316
|
-
code: funcBody
|
|
6317
|
-
};
|
|
6318
|
-
}
|
|
6319
|
-
for (const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)) {
|
|
6320
|
-
const exported = m[1];
|
|
6321
|
-
const expression = m[2];
|
|
6322
|
-
for (const [local, exportName] of Object.entries(loadShareBindings).reverse()) if (new RegExp(`\\b${local}\\b`).test(expression)) {
|
|
6323
|
-
exportMap[exported] = {
|
|
6324
|
-
type: "reexport",
|
|
6325
|
-
exportName
|
|
6326
|
-
};
|
|
6327
|
-
break;
|
|
6328
|
-
}
|
|
6329
|
-
}
|
|
6330
|
-
if (Object.keys(exportMap).length > 0) systemProxyInfo.set(proxyFileName, {
|
|
6331
|
-
loadShareDep,
|
|
6332
|
-
exportMap
|
|
6333
|
-
});
|
|
6334
|
-
}
|
|
6335
|
-
return systemProxyInfo;
|
|
6336
|
-
}
|
|
6337
|
-
function rewriteEsmProxyConsumers(code, proxyChunks) {
|
|
6338
|
-
let nextCode = code;
|
|
6339
|
-
const claimedLocals = /* @__PURE__ */ new Set();
|
|
6340
|
-
for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
|
|
6341
|
-
const proxyBaseName = getProxyBaseName(proxyFileName);
|
|
6342
|
-
const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp$1(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);
|
|
6343
|
-
if (!importMatch) continue;
|
|
6344
|
-
const fullImport = importMatch[0];
|
|
6345
|
-
const bindings = importMatch[1].split(",").map((s) => {
|
|
6346
|
-
const parts = s.trim().split(/\s+as\s+/);
|
|
6347
|
-
return {
|
|
6348
|
-
imported: parts[0].trim(),
|
|
6349
|
-
local: (parts[1] || parts[0]).trim()
|
|
6350
|
-
};
|
|
6351
|
-
});
|
|
6352
|
-
const exportMapMatch = proxyInfo.code.match(/export\s*\{([^}]+)\}/);
|
|
6353
|
-
if (!exportMapMatch) continue;
|
|
6354
|
-
const exportMap = {};
|
|
6355
|
-
for (const entry of exportMapMatch[1].split(",")) {
|
|
6356
|
-
const parts = entry.trim().split(/\s+as\s+/);
|
|
6357
|
-
if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
|
|
6358
|
-
}
|
|
6359
|
-
const inlineable = [];
|
|
6360
|
-
const nonInlineable = [];
|
|
6361
|
-
const pendingLocals = new Set(bindings.map((binding) => binding.local));
|
|
6362
|
-
for (const b of bindings) {
|
|
6363
|
-
pendingLocals.delete(b.local);
|
|
6364
|
-
const proxyLocal = exportMap[b.imported];
|
|
6365
|
-
if (!proxyLocal) {
|
|
6366
|
-
claimedLocals.add(b.local);
|
|
6367
|
-
nonInlineable.push(b);
|
|
6368
|
-
continue;
|
|
6369
|
-
}
|
|
6370
|
-
const funcBody = extractFunctionDeclaration(proxyInfo.code, proxyLocal);
|
|
6371
|
-
if (funcBody) {
|
|
6372
|
-
inlineable.push({
|
|
6373
|
-
local: b.local,
|
|
6374
|
-
funcBody: funcBody.replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`)
|
|
6375
|
-
});
|
|
6376
|
-
claimedLocals.add(b.local);
|
|
6377
|
-
} else {
|
|
6378
|
-
const unavailableLocals = new Set(claimedLocals);
|
|
6379
|
-
pendingLocals.forEach((local) => unavailableLocals.add(local));
|
|
6380
|
-
const resolvedBinding = resolveProxyAlias(b, proxyLocal, nextCode, fullImport, unavailableLocals);
|
|
6381
|
-
claimedLocals.add(resolvedBinding.local);
|
|
6382
|
-
nonInlineable.push(resolvedBinding);
|
|
6383
|
-
}
|
|
6384
|
-
}
|
|
6385
|
-
const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
|
|
6386
|
-
if (inlineable.length === 0 && !hasRenamedAlias) continue;
|
|
6387
|
-
let replacement = "";
|
|
6388
|
-
if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
|
|
6389
|
-
replacement += inlineable.map((f) => f.funcBody).join("");
|
|
6390
|
-
nextCode = nextCode.replace(fullImport, () => replacement);
|
|
6391
|
-
}
|
|
6392
|
-
return nextCode;
|
|
6393
|
-
}
|
|
6394
|
-
function rewriteSystemProxyConsumers(code, systemProxyInfo) {
|
|
6395
|
-
if (!code.includes("System.register(")) return code;
|
|
6396
|
-
let nextCode = code;
|
|
6397
|
-
for (const [proxyFileName, proxyInfo] of Array.from(systemProxyInfo.entries())) {
|
|
6398
|
-
const proxyBaseName = getProxyBaseName(proxyFileName);
|
|
6399
|
-
const depMatch = new RegExp(`["']([^"']*${escapeRegExp$1(proxyBaseName)}[^"']*)["']`).exec(nextCode);
|
|
6400
|
-
if (!depMatch) continue;
|
|
6401
|
-
let setterIndex = 0;
|
|
6402
|
-
const depListMatch = nextCode.match(/System\.register\(\[([\s\S]*?)\]/);
|
|
6403
|
-
if (depListMatch) setterIndex = Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).findIndex((dep) => dep.includes(proxyBaseName));
|
|
6404
|
-
if (setterIndex < 0) continue;
|
|
6405
|
-
const settersStart = nextCode.indexOf("setters: [");
|
|
6406
|
-
if (settersStart < 0) continue;
|
|
6407
|
-
const setterMatch = Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];
|
|
6408
|
-
if (!setterMatch) continue;
|
|
6409
|
-
const [fullSetter, moduleLocal, setterBody] = setterMatch;
|
|
6410
|
-
const helpersToInline = [];
|
|
6411
|
-
const nextSetterBody = setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`, "g"), (assignment, local, imported) => {
|
|
6412
|
-
const mapped = proxyInfo.exportMap[imported];
|
|
6413
|
-
if (!mapped) return assignment;
|
|
6414
|
-
if (mapped.type === "helper") {
|
|
6415
|
-
helpersToInline.push(mapped.code.replace(new RegExp(`function\\s+${imported}\\s*\\(`), `function ${local}(`));
|
|
6416
|
-
return "";
|
|
6417
|
-
}
|
|
6418
|
-
return `${local} = ${moduleLocal}.${mapped.exportName};`;
|
|
6419
|
-
});
|
|
6420
|
-
if (nextSetterBody === setterBody && helpersToInline.length === 0) continue;
|
|
6421
|
-
const nextSetter = fullSetter.replace(setterBody, () => nextSetterBody);
|
|
6422
|
-
nextCode = nextCode.replace(fullSetter, () => nextSetter);
|
|
6423
|
-
nextCode = nextCode.replace(depMatch[0], JSON.stringify(proxyInfo.loadShareDep));
|
|
6424
|
-
if (helpersToInline.length > 0) nextCode = nextCode.replace("execute: (function() {", () => {
|
|
6425
|
-
return `execute: (function() {${helpersToInline.join("")}`;
|
|
6426
|
-
});
|
|
6427
|
-
}
|
|
6428
|
-
return nextCode;
|
|
6429
|
-
}
|
|
6430
|
-
function findRemoteEntryFile(filename, bundle) {
|
|
6431
|
-
const strippedName = filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "");
|
|
6432
|
-
let fallback;
|
|
6433
|
-
for (const fileData of Object.values(bundle)) {
|
|
6434
|
-
if (fileData.fileName === filename) return fileData.fileName;
|
|
6435
|
-
if (fallback === void 0 && (strippedName === fileData.name || fileData.name === "remoteEntry")) fallback = fileData.fileName;
|
|
6436
|
-
}
|
|
6437
|
-
return fallback;
|
|
6438
|
-
}
|
|
6439
|
-
//#endregion
|
|
6440
6765
|
//#region src/utils/cssModuleHelpers.ts
|
|
6441
6766
|
const ASSET_TYPES = ["js", "css"];
|
|
6442
6767
|
const LOAD_TIMINGS = ["sync", "async"];
|
|
@@ -6500,28 +6825,33 @@ const chunkContainsCssModules = (modules) => {
|
|
|
6500
6825
|
for (const modulePath of Object.keys(modules)) if (isCSSFile(modulePath)) return true;
|
|
6501
6826
|
return false;
|
|
6502
6827
|
};
|
|
6828
|
+
const collectStaticChunks = (bundle, roots) => {
|
|
6829
|
+
const chunks = [];
|
|
6830
|
+
const visited = /* @__PURE__ */ new Set();
|
|
6831
|
+
const queue = [...roots];
|
|
6832
|
+
for (let queueIndex = 0; queueIndex < queue.length; queueIndex++) {
|
|
6833
|
+
const fileName = queue[queueIndex];
|
|
6834
|
+
if (visited.has(fileName)) continue;
|
|
6835
|
+
visited.add(fileName);
|
|
6836
|
+
const chunk = bundle[fileName];
|
|
6837
|
+
if (!chunk || chunk.type !== "chunk") continue;
|
|
6838
|
+
chunks.push(chunk);
|
|
6839
|
+
queue.push(...chunk.imports ?? []);
|
|
6840
|
+
}
|
|
6841
|
+
return chunks;
|
|
6842
|
+
};
|
|
6503
6843
|
/**
|
|
6504
6844
|
* Analyzes assets associated with a chunk without mutating the output map.
|
|
6505
6845
|
* The static-import traversal is cycle-safe and ignores missing bundle entries.
|
|
6506
6846
|
*/
|
|
6507
6847
|
const analyzeChunkAssets = (bundle, fileName, chunk) => {
|
|
6508
6848
|
const dynamicAssets = [];
|
|
6509
|
-
const
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
|
|
6513
|
-
|
|
6514
|
-
|
|
6515
|
-
const currentChunk = bundle[currentFileName];
|
|
6516
|
-
if (!currentChunk || currentChunk.type !== "chunk") continue;
|
|
6517
|
-
for (const dynamicImport of currentChunk.dynamicImports ?? []) {
|
|
6518
|
-
if (!bundle[dynamicImport]) continue;
|
|
6519
|
-
dynamicAssets.push({
|
|
6520
|
-
fileName: dynamicImport,
|
|
6521
|
-
type: isCSSFile(dynamicImport) ? "css" : "js"
|
|
6522
|
-
});
|
|
6523
|
-
}
|
|
6524
|
-
for (const staticImport of currentChunk.imports ?? []) queue.push(staticImport);
|
|
6849
|
+
for (const currentChunk of collectStaticChunks(bundle, [fileName])) for (const dynamicImport of currentChunk.dynamicImports ?? []) {
|
|
6850
|
+
if (!bundle[dynamicImport]) continue;
|
|
6851
|
+
dynamicAssets.push({
|
|
6852
|
+
fileName: dynamicImport,
|
|
6853
|
+
type: isCSSFile(dynamicImport) ? "css" : "js"
|
|
6854
|
+
});
|
|
6525
6855
|
}
|
|
6526
6856
|
return {
|
|
6527
6857
|
importedCss: Array.from(chunk.viteMetadata?.importedCss ?? []),
|
|
@@ -6673,6 +7003,7 @@ function generateRemoteEntrySSR(options) {
|
|
|
6673
7003
|
import { init as runtimeInit } from "@module-federation/runtime";
|
|
6674
7004
|
|
|
6675
7005
|
const sharedSingletons = ${JSON.stringify(sharedSingletons)};
|
|
7006
|
+
const moduleCacheKey = Symbol.for(${JSON.stringify(MODULE_CACHE_SHARE_SCOPE_KEY)});
|
|
6676
7007
|
let exposesMapPromise;
|
|
6677
7008
|
|
|
6678
7009
|
function createShareInitError(errors) {
|
|
@@ -6750,7 +7081,8 @@ function generateRemoteEntrySSR(options) {
|
|
|
6750
7081
|
throw createShareInitError(shareInitErrors);
|
|
6751
7082
|
}
|
|
6752
7083
|
if (cacheEntries.length > 0) {
|
|
6753
|
-
const moduleCache =
|
|
7084
|
+
const moduleCache = shared?.[moduleCacheKey] ||
|
|
7085
|
+
(globalThis.__mf_module_cache__ ||= { share: {}, remote: {} });
|
|
6754
7086
|
const cache = (moduleCache.share ||= {});
|
|
6755
7087
|
for (const { scopeName, pkg, module } of cacheEntries) {
|
|
6756
7088
|
cache[scopeName + ':' + pkg] ??= module;
|
|
@@ -6836,6 +7168,54 @@ function isTreeShakingProviderChunk(file) {
|
|
|
6836
7168
|
if (file.facadeModuleId?.includes("__treeShakingProvider__")) return true;
|
|
6837
7169
|
return Object.keys(file.modules || {}).some((id) => id.includes("__treeShakingProvider__") || id.includes("__mf_tree_shaking_graph__"));
|
|
6838
7170
|
}
|
|
7171
|
+
function isContainerBootstrapChunk(chunk, moduleIds) {
|
|
7172
|
+
return [chunk.facadeModuleId, ...chunk.moduleIds ?? []].some((id) => typeof id === "string" && moduleIds.has(normalizeVirtualModuleId(id)));
|
|
7173
|
+
}
|
|
7174
|
+
function collectImportedCss(chunks) {
|
|
7175
|
+
const css = /* @__PURE__ */ new Set();
|
|
7176
|
+
for (const chunk of chunks) for (const cssFile of chunk.viteMetadata?.importedCss ?? []) css.add(cssFile);
|
|
7177
|
+
return Array.from(css);
|
|
7178
|
+
}
|
|
7179
|
+
function expandExposeAssets(filesMap, exposeModules, bundle, remoteEntryFileName, options) {
|
|
7180
|
+
if (exposeModules.length === 0) return;
|
|
7181
|
+
const containerChunks = remoteEntryFileName ? collectStaticChunks(bundle, [remoteEntryFileName]) : [];
|
|
7182
|
+
const bootstrapChunks = containerChunks.slice(1);
|
|
7183
|
+
const seen = new Set(containerChunks.map((chunk) => chunk.fileName));
|
|
7184
|
+
if (containerChunks.length > 0) {
|
|
7185
|
+
const bootstrapModuleIds = /* @__PURE__ */ new Set([getLocalSharedImportMapPath(options), getVirtualExposesId(options)]);
|
|
7186
|
+
for (const containerChunk of containerChunks) for (const imported of containerChunk.dynamicImports ?? []) {
|
|
7187
|
+
const importedChunk = bundle[imported];
|
|
7188
|
+
if (!importedChunk || importedChunk.type !== "chunk" || !isContainerBootstrapChunk(importedChunk, bootstrapModuleIds)) continue;
|
|
7189
|
+
for (const chunk of collectStaticChunks(bundle, [imported])) {
|
|
7190
|
+
if (seen.has(chunk.fileName)) continue;
|
|
7191
|
+
seen.add(chunk.fileName);
|
|
7192
|
+
bootstrapChunks.push(chunk);
|
|
7193
|
+
}
|
|
7194
|
+
}
|
|
7195
|
+
}
|
|
7196
|
+
const bootstrapAssets = bootstrapChunks.map((chunk) => chunk.fileName);
|
|
7197
|
+
const bootstrapCss = collectImportedCss(bootstrapChunks);
|
|
7198
|
+
for (const exposeModule of exposeModules) {
|
|
7199
|
+
const assets = filesMap[exposeModule];
|
|
7200
|
+
if (!assets) continue;
|
|
7201
|
+
const syncChunks = collectStaticChunks(bundle, assets.js.sync);
|
|
7202
|
+
const sync = Array.from(/* @__PURE__ */ new Set([...bootstrapAssets, ...syncChunks.map((chunk) => chunk.fileName)]));
|
|
7203
|
+
const syncSet = new Set(sync);
|
|
7204
|
+
const asyncChunks = collectStaticChunks(bundle, assets.js.async);
|
|
7205
|
+
const async = asyncChunks.map((chunk) => chunk.fileName).filter((fileName) => !syncSet.has(fileName));
|
|
7206
|
+
assets.js.sync = sync;
|
|
7207
|
+
assets.js.async = async;
|
|
7208
|
+
const syncCss = Array.from(/* @__PURE__ */ new Set([
|
|
7209
|
+
...assets.css.sync,
|
|
7210
|
+
...bootstrapCss,
|
|
7211
|
+
...collectImportedCss(syncChunks)
|
|
7212
|
+
]));
|
|
7213
|
+
const syncCssSet = new Set(syncCss);
|
|
7214
|
+
const asyncCss = Array.from(/* @__PURE__ */ new Set([...assets.css.async, ...collectImportedCss(asyncChunks)])).filter((fileName) => !syncCssSet.has(fileName));
|
|
7215
|
+
assets.css.sync = syncCss;
|
|
7216
|
+
assets.css.async = asyncCss;
|
|
7217
|
+
}
|
|
7218
|
+
}
|
|
6839
7219
|
function getTreeShakingBuildInfo(options) {
|
|
6840
7220
|
if (!(Object.values(options.shared || {}).some((share) => !!share.shareConfig.treeShaking) || !!options.treeShakingSharedPlugins?.length || !!options.treeShakingSharedExcludePlugins?.length)) return {};
|
|
6841
7221
|
return {
|
|
@@ -6998,6 +7378,7 @@ const Manifest = (providedOptions) => {
|
|
|
6998
7378
|
root,
|
|
6999
7379
|
stripKnownJsExtensions: true
|
|
7000
7380
|
});
|
|
7381
|
+
expandExposeAssets(filesMap, exposesModules, bundle, foundRemoteEntryFile, mfOptions);
|
|
7001
7382
|
const fileToShareKey = await buildFileToShareKeyMap(getUsedShares(mfOptions), this.resolve.bind(this), mfOptions);
|
|
7002
7383
|
processModuleAssets(Object.fromEntries(Object.entries(bundle).filter(([, file]) => !isTreeShakingProviderChunk(file))), filesMap, (modulePath) => fileToShareKey.get(modulePath));
|
|
7003
7384
|
if (mfOptions.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
|
|
@@ -7356,6 +7737,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7356
7737
|
const cleanId = id.split("?")[0];
|
|
7357
7738
|
return cleanId.includes(getHostAutoInitPath(options)) || cleanId.includes(getHostAutoInitPath());
|
|
7358
7739
|
};
|
|
7740
|
+
const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
|
|
7359
7741
|
function isRemoteImport(source) {
|
|
7360
7742
|
return Object.keys(options.remotes).some((name) => source === name || source.startsWith(name + "/"));
|
|
7361
7743
|
}
|
|
@@ -7455,7 +7837,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7455
7837
|
}
|
|
7456
7838
|
},
|
|
7457
7839
|
async load(id) {
|
|
7458
|
-
if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
|
|
7840
|
+
if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(this)));
|
|
7459
7841
|
if (id === virtualExposesId) {
|
|
7460
7842
|
await refreshExposeRemoteDependencies(this);
|
|
7461
7843
|
return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
|
|
@@ -7465,7 +7847,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7465
7847
|
async transform(code, id) {
|
|
7466
7848
|
return mapCodeToCodeWithSourcemap(await (async () => {
|
|
7467
7849
|
if (!filterId(id)) return;
|
|
7468
|
-
if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
|
|
7850
|
+
if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(this)));
|
|
7469
7851
|
if (id === virtualExposesId) {
|
|
7470
7852
|
await refreshExposeRemoteDependencies(this);
|
|
7471
7853
|
return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
|
|
@@ -7483,7 +7865,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7483
7865
|
return `
|
|
7484
7866
|
const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
|
|
7485
7867
|
const remoteEntryImport = typeof window !== 'undefined' ? ${isAbsolutePublicPath ? remoteEntryUrl : `origin + ${remoteEntryUrl}`} : ${JSON.stringify(ssrRemoteEntry)};
|
|
7486
|
-
${generateHostAutoInitCode("remoteEntryImport", "serve", options)}
|
|
7868
|
+
${generateHostAutoInitCode("remoteEntryImport", "serve", options, getEnvironmentConditions(this))}
|
|
7487
7869
|
`;
|
|
7488
7870
|
}
|
|
7489
7871
|
return code;
|
|
@@ -7767,6 +8149,7 @@ function excludeSharedSubDependencies(shared) {
|
|
|
7767
8149
|
delete shared[depKey];
|
|
7768
8150
|
sharedKeys.delete(depKey);
|
|
7769
8151
|
sharedKeyByBase.delete(dep);
|
|
8152
|
+
sharedKeyMatcherCache.delete(shared);
|
|
7770
8153
|
}
|
|
7771
8154
|
}
|
|
7772
8155
|
}
|
|
@@ -7782,6 +8165,8 @@ function proxySharedModule(options) {
|
|
|
7782
8165
|
const materializedLoadShareSources = /* @__PURE__ */ new Set();
|
|
7783
8166
|
const emittedTreeShakingProviders = /* @__PURE__ */ new Set();
|
|
7784
8167
|
const hasAnalyzableShares = Object.values(shared).some((share) => shouldAnalyzeSharedExports(share));
|
|
8168
|
+
const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
|
|
8169
|
+
const refreshTreeShakingForEnvironment = (context) => refreshTreeShakingModules(federationOptions, _command, getIsRolldown(context), getEnvironmentConditions(context));
|
|
7785
8170
|
const normalizeTreeShakingOutputPath = (value) => {
|
|
7786
8171
|
const normalized = normalizePathForImport(value);
|
|
7787
8172
|
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.`);
|
|
@@ -7827,7 +8212,7 @@ function proxySharedModule(options) {
|
|
|
7827
8212
|
},
|
|
7828
8213
|
load(id) {
|
|
7829
8214
|
if (id === getResolvedLocalSharedImportMapId(federationOptions)) return getParsePromise().then((_) => {
|
|
7830
|
-
|
|
8215
|
+
refreshTreeShakingForEnvironment(this);
|
|
7831
8216
|
const providerPackages = /* @__PURE__ */ new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
|
|
7832
8217
|
for (const pkg of providerPackages) {
|
|
7833
8218
|
const sharedKey = findSharedKeyForSource(pkg, shared);
|
|
@@ -7879,7 +8264,7 @@ function proxySharedModule(options) {
|
|
|
7879
8264
|
if (_command !== "build") return;
|
|
7880
8265
|
resetTreeShakingExports(federationOptions);
|
|
7881
8266
|
emittedTreeShakingProviders.clear();
|
|
7882
|
-
|
|
8267
|
+
refreshTreeShakingForEnvironment(this);
|
|
7883
8268
|
},
|
|
7884
8269
|
shouldTransformCachedModule() {
|
|
7885
8270
|
return _command === "build" && hasAnalyzableShares;
|
|
@@ -7887,7 +8272,7 @@ function proxySharedModule(options) {
|
|
|
7887
8272
|
transform(code, id) {
|
|
7888
8273
|
if (_command !== "build" || !hasAnalyzableShares) return;
|
|
7889
8274
|
collectTreeShakingImports(code, id, shared, findSharedKeyForSource, (sharedKey, exports, request) => recordTreeShakingExports(sharedKey, exports, request, federationOptions), (sharedKey, request) => markTreeShakingPackageUnsafe(sharedKey, request, federationOptions));
|
|
7890
|
-
|
|
8275
|
+
refreshTreeShakingForEnvironment(this);
|
|
7891
8276
|
}
|
|
7892
8277
|
},
|
|
7893
8278
|
{
|
|
@@ -7989,15 +8374,6 @@ const JS_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?|vue|svelte)(?:\?|$)/;
|
|
|
7989
8374
|
function isAstNode(value) {
|
|
7990
8375
|
return !!value && typeof value === "object" && typeof value.type === "string";
|
|
7991
8376
|
}
|
|
7992
|
-
function findStaticRemoteSources(code, isRemoteImport) {
|
|
7993
|
-
const codePositions = createCodePositionMap(code);
|
|
7994
|
-
const sources = /* @__PURE__ */ new Set();
|
|
7995
|
-
for (const pattern of [/\b(?:import|export)\s+[^;]*?\bfrom\s*["']([^"']+)["']/g, /\bimport\s*["']([^"']+)["']/g]) for (const match of code.matchAll(pattern)) {
|
|
7996
|
-
const source = match[1];
|
|
7997
|
-
if (codePositions[match.index] && isRemoteImport(source)) sources.add(source);
|
|
7998
|
-
}
|
|
7999
|
-
return sources;
|
|
8000
|
-
}
|
|
8001
8377
|
function walkAST(root, visitor) {
|
|
8002
8378
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
8003
8379
|
function visit(node) {
|
|
@@ -8256,7 +8632,7 @@ function pluginRemoteNamedExports(options) {
|
|
|
8256
8632
|
if (!JS_EXTENSIONS_RE.test(id)) return;
|
|
8257
8633
|
if (!remoteNames.some((name) => code.includes(name))) return;
|
|
8258
8634
|
const matchesRemoteImport = (source) => isRemoteImport(source, id);
|
|
8259
|
-
for (const source of
|
|
8635
|
+
for (const { kind, source, typeOnly } of findModuleImportDescriptors(code)) if (kind === "static" && !typeOnly && matchesRemoteImport(source)) markStaticRemote(source, options);
|
|
8260
8636
|
let imports;
|
|
8261
8637
|
try {
|
|
8262
8638
|
imports = await collectFromAST(this.parse(code), code, matchesRemoteImport);
|
|
@@ -8764,7 +9140,7 @@ const FEDERATION_CONTROL_CHUNK_HINTS = [
|
|
|
8764
9140
|
"localSharedImportMap"
|
|
8765
9141
|
];
|
|
8766
9142
|
function stripEmptyPreloadCalls(code) {
|
|
8767
|
-
const helperImportRegex = /import\s*\{\s*_\s*as\s*(\w
|
|
9143
|
+
const helperImportRegex = /import\s*\{\s*_\s*as\s*([A-Za-z_$][\w$]*)\s*\}\s*from\s*["'][^"']+["']\s*;?/g;
|
|
8768
9144
|
const helperAliases = [];
|
|
8769
9145
|
let helperImportMatch;
|
|
8770
9146
|
while ((helperImportMatch = helperImportRegex.exec(code)) !== null) helperAliases.push(helperImportMatch[1]);
|
|
@@ -8800,7 +9176,7 @@ function stripEmptyPreloadCalls(code) {
|
|
|
8800
9176
|
}
|
|
8801
9177
|
nextCode = nextCode.replace(/import\s*["'][^"']*__loadShare__[^"']*["']\s*;?/g, "");
|
|
8802
9178
|
nextCode = nextCode.replace(helperImportRegex, (statement, local) => {
|
|
8803
|
-
return
|
|
9179
|
+
return isIdentifierReferenced(local, nextCode.replace(statement, "")) ? statement : "";
|
|
8804
9180
|
});
|
|
8805
9181
|
return nextCode;
|
|
8806
9182
|
}
|
|
@@ -8826,42 +9202,6 @@ function isTestEnv() {
|
|
|
8826
9202
|
return process.env.NODE_ENV === "test" || process.env.VITEST != null || process.env.JEST_WORKER_ID != null;
|
|
8827
9203
|
}
|
|
8828
9204
|
//#endregion
|
|
8829
|
-
//#region src/utils/sharedExportConditions.ts
|
|
8830
|
-
const DEFAULT_CLIENT_EXPORT_CONDITIONS = [
|
|
8831
|
-
"browser",
|
|
8832
|
-
"import",
|
|
8833
|
-
"module",
|
|
8834
|
-
"default"
|
|
8835
|
-
];
|
|
8836
|
-
const DEFAULT_NODE_SSR_EXPORT_CONDITIONS = [
|
|
8837
|
-
"node",
|
|
8838
|
-
"import",
|
|
8839
|
-
"module",
|
|
8840
|
-
"default"
|
|
8841
|
-
];
|
|
8842
|
-
const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
|
|
8843
|
-
"worker",
|
|
8844
|
-
"browser",
|
|
8845
|
-
"import",
|
|
8846
|
-
"module",
|
|
8847
|
-
"default"
|
|
8848
|
-
];
|
|
8849
|
-
const VITE_DEV_PROD_CONDITION = "development|production";
|
|
8850
|
-
function appendConditions(conditions, fallbackConditions) {
|
|
8851
|
-
return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
|
|
8852
|
-
}
|
|
8853
|
-
function resolveViteModeCondition(conditions, isProduction) {
|
|
8854
|
-
const modeCondition = isProduction ? "production" : "development";
|
|
8855
|
-
return [...new Set(conditions.map((condition) => condition === VITE_DEV_PROD_CONDITION ? modeCondition : condition))];
|
|
8856
|
-
}
|
|
8857
|
-
function getSharedExportConditions({ environmentConditions, isProduction, isSsr, rootConditions, ssrConditions, ssrTarget = "node" }) {
|
|
8858
|
-
if (environmentConditions !== void 0) return resolveViteModeCondition(appendConditions(environmentConditions, ["import", "default"]), isProduction);
|
|
8859
|
-
const defaultConditions = isSsr ? ssrTarget === "webworker" ? DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS : DEFAULT_NODE_SSR_EXPORT_CONDITIONS : DEFAULT_CLIENT_EXPORT_CONDITIONS;
|
|
8860
|
-
const configuredConditions = isSsr ? ssrConditions ?? rootConditions : rootConditions;
|
|
8861
|
-
if (configuredConditions !== void 0) return resolveViteModeCondition(appendConditions(configuredConditions, defaultConditions), isProduction);
|
|
8862
|
-
return [...defaultConditions];
|
|
8863
|
-
}
|
|
8864
|
-
//#endregion
|
|
8865
9205
|
//#region src/utils/normalizeOptimizeDeps.ts
|
|
8866
9206
|
var normalizeOptimizeDeps_default = {
|
|
8867
9207
|
name: "normalizeOptimizeDeps",
|
|
@@ -9109,9 +9449,10 @@ function isFile(candidate) {
|
|
|
9109
9449
|
return false;
|
|
9110
9450
|
}
|
|
9111
9451
|
}
|
|
9112
|
-
function
|
|
9113
|
-
|
|
9114
|
-
|
|
9452
|
+
function isReactRouterBuildClientRouteInput(entry) {
|
|
9453
|
+
return /[?&]__react-router-build-client-route(?:[=&]|$)/.test(entry);
|
|
9454
|
+
}
|
|
9455
|
+
function registerEntryImports(options, projectRoot, recordShared = true, entryFiles = []) {
|
|
9115
9456
|
const sourceExtensions = [
|
|
9116
9457
|
".mjs",
|
|
9117
9458
|
".js",
|
|
@@ -9141,10 +9482,15 @@ function registerEntryImports(options, projectRoot) {
|
|
|
9141
9482
|
preloadRemotes
|
|
9142
9483
|
});
|
|
9143
9484
|
};
|
|
9144
|
-
const
|
|
9145
|
-
|
|
9485
|
+
const htmlEntries = entryFiles.filter((file) => file.endsWith(".html"));
|
|
9486
|
+
const htmlEntryPaths = htmlEntries.length ? htmlEntries : entryFiles.length === 0 ? [path$1.join(root, "index.html")] : [];
|
|
9487
|
+
for (const htmlEntry of htmlEntryPaths) if (existsSync(htmlEntry)) {
|
|
9146
9488
|
const html = readFileSync(htmlEntry, "utf8");
|
|
9147
|
-
for (const match of html.matchAll(/<script\b[^>]*\bsrc=(['"])([^'"]+)\1[^>]*>/gi)) enqueue(match[2], htmlEntry, true);
|
|
9489
|
+
for (const match of html.matchAll(/<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=(['"])([^'"]+)\1)[^>]*>/gi)) enqueue(match[2], htmlEntry, true);
|
|
9490
|
+
}
|
|
9491
|
+
for (const entry of entryFiles.filter((file) => !file.endsWith(".html"))) {
|
|
9492
|
+
const relativeEntry = path$1.relative(root, entry);
|
|
9493
|
+
enqueue(relativeEntry.startsWith(".") ? relativeEntry : `./${relativeEntry}`, path$1.join(root, "index.html"), true);
|
|
9148
9494
|
}
|
|
9149
9495
|
for (const expose of Object.values(options.exposes ?? {})) enqueue(expose.import);
|
|
9150
9496
|
while (pending.length) {
|
|
@@ -9152,17 +9498,15 @@ function registerEntryImports(options, projectRoot) {
|
|
|
9152
9498
|
if (visited.get(file) || visited.has(file) && !preloadRemotes) continue;
|
|
9153
9499
|
visited.set(file, preloadRemotes);
|
|
9154
9500
|
const code = readFileSync(file, "utf8");
|
|
9155
|
-
for (const
|
|
9156
|
-
const isStatic =
|
|
9157
|
-
|
|
9158
|
-
|
|
9159
|
-
|
|
9160
|
-
|
|
9161
|
-
|
|
9162
|
-
|
|
9163
|
-
|
|
9164
|
-
else if (request) enqueue(request, file, preloadRemotes && isStatic);
|
|
9165
|
-
}
|
|
9501
|
+
for (const { source: request, kind, typeOnly } of findModuleImportDescriptors(code)) {
|
|
9502
|
+
const isStatic = kind === "static" && !typeOnly;
|
|
9503
|
+
const remoteKey = preloadRemotes && isStatic && request ? Object.keys(options.remotes).find((name) => request === name || request.startsWith(`${name}/`)) : void 0;
|
|
9504
|
+
const sharedKey = !typeOnly && request && findSharedKey(request, options.shared);
|
|
9505
|
+
if (remoteKey) {
|
|
9506
|
+
addUsedRemote(remoteKey, request, options);
|
|
9507
|
+
markStaticRemote(request, options);
|
|
9508
|
+
} else if (sharedKey && recordShared) addUsedShares(request, options);
|
|
9509
|
+
else if (request && !typeOnly) enqueue(request, file, preloadRemotes && isStatic);
|
|
9166
9510
|
}
|
|
9167
9511
|
}
|
|
9168
9512
|
}
|
|
@@ -9180,6 +9524,8 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9180
9524
|
config(config, { command: _command }) {
|
|
9181
9525
|
if (_command === "serve") ignoreFederationGeneratedFiles(config, options);
|
|
9182
9526
|
const root = config.root || process.cwd();
|
|
9527
|
+
const buildInput = getBuildInput(config);
|
|
9528
|
+
const resolvedConfiguredEntryFiles = (typeof buildInput === "string" ? [buildInput] : Array.isArray(buildInput) ? buildInput : buildInput && typeof buildInput === "object" ? Object.values(buildInput) : []).map((entry) => String(entry)).filter((entry) => !isReactRouterBuildClientRouteInput(entry)).map((entry) => entry.split(/[?#]/)[0]).map((entry) => path$1.isAbsolute(entry) ? entry : path$1.resolve(root, entry));
|
|
9183
9529
|
resetConcreteSharedImportSourceCache();
|
|
9184
9530
|
setPackageDetectionCwd(root);
|
|
9185
9531
|
const isVinext = hasPackageDependency("vinext");
|
|
@@ -9194,7 +9540,7 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9194
9540
|
config.optimizeDeps.exclude.push(...Object.keys(remotes || {}));
|
|
9195
9541
|
}
|
|
9196
9542
|
}
|
|
9197
|
-
if (
|
|
9543
|
+
if (!config.build?.ssr && (Object.keys(shared ?? {}).length > 0 || Object.keys(remotes ?? {}).length > 0)) registerEntryImports(options, root, _command === "serve", resolvedConfiguredEntryFiles);
|
|
9198
9544
|
if (shared && Object.keys(shared).length > 0) {
|
|
9199
9545
|
if (_command === "serve") {
|
|
9200
9546
|
excludeSharedSubDependencies(shared);
|
|
@@ -9457,6 +9803,7 @@ function federation(mfUserOptions) {
|
|
|
9457
9803
|
ssrTarget
|
|
9458
9804
|
});
|
|
9459
9805
|
};
|
|
9806
|
+
const refreshLoadRemoteModuleForEnvironment = (id, context, loadOptions) => refreshRemoteModuleForEnvironment(id, options, getLoadHookExportConditions(context, loadOptions));
|
|
9460
9807
|
const refreshPreBuildModuleForEnvironment = (id, context, loadOptions) => {
|
|
9461
9808
|
const pkg = getCachedPreBuildPkg(id);
|
|
9462
9809
|
if (!pkg) return "not-applicable";
|
|
@@ -9520,8 +9867,13 @@ function federation(mfUserOptions) {
|
|
|
9520
9867
|
return virtualModule.getResolvedId();
|
|
9521
9868
|
},
|
|
9522
9869
|
load(id, loadOptions) {
|
|
9523
|
-
if (
|
|
9870
|
+
if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
|
|
9871
|
+
if (command !== "build" && id.includes("__loadShare__")) {
|
|
9872
|
+
id = findCurrentLoadShareForStaleOwnerId(id, options.shared, findSharedKey, options)?.getResolvedId() ?? id;
|
|
9873
|
+
if (refreshLoadShareModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
|
|
9874
|
+
}
|
|
9524
9875
|
if (id.includes("__prebuild__") && refreshPreBuildModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
|
|
9876
|
+
if (id.includes("__H_A_I__") && isOwnedHostAutoInitId(id, options)) refreshHostAutoInit(options, getLoadHookExportConditions(this, loadOptions));
|
|
9525
9877
|
const virtualModule = VirtualModule.findById(id);
|
|
9526
9878
|
if (!virtualModule) return;
|
|
9527
9879
|
if (command === "build" && (id.includes("__loadShare__") || id.includes("__loadRemote__"))) return;
|
|
@@ -9742,6 +10094,7 @@ function federation(mfUserOptions) {
|
|
|
9742
10094
|
load(id, loadOptions) {
|
|
9743
10095
|
const loadVirtualModule = (importFalseExportUsage) => {
|
|
9744
10096
|
if (!id.includes("__loadShare__") && !id.includes("__loadRemote__")) return;
|
|
10097
|
+
if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
|
|
9745
10098
|
if (id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions, importFalseExportUsage) === "not-owned") return;
|
|
9746
10099
|
const virtualModule = VirtualModule.findById(id);
|
|
9747
10100
|
if (!virtualModule?.code) return null;
|