@module-federation/vite 1.20.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.d.ts +4 -3
- package/lib/index.js +1140 -51
- package/lib/{ssrEntryLoader-BUD1-3Z2.js → ssrEntryLoader-Bw423jj_.js} +5 -1
- package/lib/{ssrVmStrategy-C_cJtu5V.js → ssrVmStrategy-7HAPa-Vc.js} +1 -1
- package/lib/utils/ssrEntryLoader.d.ts +1 -4
- package/lib/utils/ssrEntryLoader.js +1 -1
- package/package.json +11 -11
- package/lib/pluginDts-Dbbi4cnh.js +0 -845
package/lib/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { _ as createModuleFederationError, a as getIsRolldown, b as rebaseImport, c as getPackageNameFromNodeModulePath, d as isNuxtProjectRoot, f as packageNameDecode, g as sharedCacheHelperCode, h as setPackageDetectionCwd, i as getInstalledPackageJson, l as getSharedCacheDescriptor, m as resolveImportPath, o as getPackageDetectionCwd, p as packageNameEncode, r as getInstalledPackageEntry, s as getPackageName, u as hasPackageDependency, v as mfWarn, y as normalizePathForImport } from "./pluginDts-Dbbi4cnh.js";
|
|
2
1
|
import { createRequire } from "node:module";
|
|
3
2
|
import * as fs$2 from "fs";
|
|
4
|
-
import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
|
|
3
|
+
import fs, { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "fs";
|
|
5
4
|
import { createRequire as createRequire$1 } from "module";
|
|
6
5
|
import * as path$1 from "node:path";
|
|
7
6
|
import path, { basename } from "node:path";
|
|
@@ -11,9 +10,71 @@ import { createHash } from "node:crypto";
|
|
|
11
10
|
import * as fs$1 from "node:fs";
|
|
12
11
|
import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
|
|
13
12
|
import { pathToFileURL as pathToFileURL$1 } from "node:url";
|
|
13
|
+
import { normalizeOptions } from "@module-federation/sdk";
|
|
14
|
+
import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
|
|
15
|
+
import { rpc } from "@module-federation/dts-plugin/core";
|
|
16
|
+
//#region \0rolldown/runtime.js
|
|
17
|
+
var __defProp = Object.defineProperty;
|
|
18
|
+
var __exportAll = (all, no_symbols) => {
|
|
19
|
+
let target = {};
|
|
20
|
+
for (var name in all) __defProp(target, name, {
|
|
21
|
+
get: all[name],
|
|
22
|
+
enumerable: true
|
|
23
|
+
});
|
|
24
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
25
|
+
return target;
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/utils/buildPaths.ts
|
|
29
|
+
/**
|
|
30
|
+
* Rebase an import path for a bootstrap file that moved from root into `dir`.
|
|
31
|
+
*
|
|
32
|
+
* When entryFileNames places entries in a subdirectory (e.g. `static/js/`),
|
|
33
|
+
* the bootstrap file moves there too. Paths that resolved from the HTML root
|
|
34
|
+
* must resolve from the new directory instead.
|
|
35
|
+
*
|
|
36
|
+
* Cases: `/static/js/hostInit.js` → `./hostInit.js` (strip dir prefix)
|
|
37
|
+
* `./src/main.tsx` → `../../src/main.tsx` (climb back up for each dir level)
|
|
38
|
+
* `https://cdn.example.com` → unchanged (absolute URL)
|
|
39
|
+
*/
|
|
40
|
+
function rebaseImport(importSrc, dir) {
|
|
41
|
+
if (!dir) return importSrc;
|
|
42
|
+
if (isAbsoluteUrl(importSrc)) return importSrc;
|
|
43
|
+
const normalizedDir = dir.replace(/^\/+|\/+$/g, "");
|
|
44
|
+
if (!normalizedDir) return importSrc;
|
|
45
|
+
const stripDirPrefix = (src, prefix) => {
|
|
46
|
+
if (src === prefix) return "";
|
|
47
|
+
if (src.startsWith(prefix + "/")) return src.slice(prefix.length);
|
|
48
|
+
};
|
|
49
|
+
const absoluteRemainder = stripDirPrefix(importSrc, "/" + normalizedDir);
|
|
50
|
+
if (absoluteRemainder !== void 0) {
|
|
51
|
+
const remainder = absoluteRemainder.replace(/^\/+/, "");
|
|
52
|
+
return remainder ? "./" + remainder : "./";
|
|
53
|
+
}
|
|
54
|
+
const relativeRemainder = stripDirPrefix(importSrc, normalizedDir);
|
|
55
|
+
if (relativeRemainder !== void 0) {
|
|
56
|
+
const remainder = relativeRemainder.replace(/^\/+/, "");
|
|
57
|
+
return remainder ? "./" + remainder : "./";
|
|
58
|
+
}
|
|
59
|
+
const upLevels = normalizedDir.split("/").filter(Boolean).length;
|
|
60
|
+
const prefix = upLevels > 0 ? "../".repeat(upLevels) : "./";
|
|
61
|
+
if (importSrc.startsWith("./")) return prefix + importSrc.slice(2);
|
|
62
|
+
if (importSrc.startsWith("/")) return prefix + importSrc.slice(1);
|
|
63
|
+
return prefix + importSrc;
|
|
64
|
+
}
|
|
65
|
+
function normalizePathForImport(path) {
|
|
66
|
+
return path.replace(/\\/g, "/");
|
|
67
|
+
}
|
|
68
|
+
const EXTERNAL_URL_RE = /^(?:[a-z]+:|\/\/)/i;
|
|
69
|
+
function isAbsoluteUrl(src) {
|
|
70
|
+
if (/^[a-z]:[\\/]/i.test(src)) return false;
|
|
71
|
+
return EXTERNAL_URL_RE.test(src);
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
14
74
|
//#region src/utils/codeRewriter.ts
|
|
15
75
|
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
16
76
|
var CodeRewriter = class {
|
|
77
|
+
original;
|
|
17
78
|
replacements = [];
|
|
18
79
|
constructor(original) {
|
|
19
80
|
this.original = original;
|
|
@@ -149,7 +210,7 @@ async function mapCodeToCodeWithSourcemap(code) {
|
|
|
149
210
|
}
|
|
150
211
|
//#endregion
|
|
151
212
|
//#region src/utils/codePositionMap.ts
|
|
152
|
-
const REGEX_PREFIX_KEYWORDS = new Set([
|
|
213
|
+
const REGEX_PREFIX_KEYWORDS = /* @__PURE__ */ new Set([
|
|
153
214
|
"await",
|
|
154
215
|
"case",
|
|
155
216
|
"delete",
|
|
@@ -321,6 +382,475 @@ function injectEntryScript(html, initSrc) {
|
|
|
321
382
|
return html.replace("<head>", `<head><script type="module" src=${JSON.stringify(src)}><\/script>`);
|
|
322
383
|
}
|
|
323
384
|
//#endregion
|
|
385
|
+
//#region src/utils/logger.ts
|
|
386
|
+
const MODULE_FEDERATION_LOG_PREFIX = "[Module Federation]";
|
|
387
|
+
function formatModuleFederationMessage(message) {
|
|
388
|
+
return `${MODULE_FEDERATION_LOG_PREFIX} ${message}`;
|
|
389
|
+
}
|
|
390
|
+
function createModuleFederationError(message) {
|
|
391
|
+
return new Error(formatModuleFederationMessage(message));
|
|
392
|
+
}
|
|
393
|
+
function toConsoleArgs(message, rest = []) {
|
|
394
|
+
if (typeof message === "string") return [formatModuleFederationMessage(message), ...rest];
|
|
395
|
+
if (message === void 0) return [MODULE_FEDERATION_LOG_PREFIX, ...rest];
|
|
396
|
+
return [
|
|
397
|
+
MODULE_FEDERATION_LOG_PREFIX,
|
|
398
|
+
message,
|
|
399
|
+
...rest
|
|
400
|
+
];
|
|
401
|
+
}
|
|
402
|
+
const moduleFederationConsole = {
|
|
403
|
+
log(message, ...rest) {
|
|
404
|
+
console.log(...toConsoleArgs(message, rest));
|
|
405
|
+
},
|
|
406
|
+
warn(message, ...rest) {
|
|
407
|
+
console.warn(...toConsoleArgs(message, rest));
|
|
408
|
+
},
|
|
409
|
+
error(message, ...rest) {
|
|
410
|
+
console.error(...toConsoleArgs(message, rest));
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
moduleFederationConsole.log;
|
|
414
|
+
const mfWarn = moduleFederationConsole.warn;
|
|
415
|
+
const mfError = moduleFederationConsole.error;
|
|
416
|
+
//#endregion
|
|
417
|
+
//#region src/utils/packageUtils.ts
|
|
418
|
+
const dependencyPresenceCache = /* @__PURE__ */ new Map();
|
|
419
|
+
let packageDetectionCwd;
|
|
420
|
+
function getDependencyCacheKey(cwd, dependencyName) {
|
|
421
|
+
return `${cwd}:${dependencyName}`;
|
|
422
|
+
}
|
|
423
|
+
const installedPackageJsonCache = /* @__PURE__ */ new Map();
|
|
424
|
+
function setPackageDetectionCwd(cwd) {
|
|
425
|
+
packageDetectionCwd = cwd;
|
|
426
|
+
}
|
|
427
|
+
function getPackageDetectionCwd() {
|
|
428
|
+
return packageDetectionCwd || process.cwd();
|
|
429
|
+
}
|
|
430
|
+
function resolveImportPath(specifier) {
|
|
431
|
+
const resolved = import.meta.resolve(specifier);
|
|
432
|
+
if (!resolved.startsWith("file:")) return resolved;
|
|
433
|
+
const filePath = fileURLToPath(resolved);
|
|
434
|
+
if (!existsSync(filePath)) {
|
|
435
|
+
const error = /* @__PURE__ */ new Error(`Cannot find module '${specifier}'`);
|
|
436
|
+
error.code = "MODULE_NOT_FOUND";
|
|
437
|
+
throw error;
|
|
438
|
+
}
|
|
439
|
+
return filePath;
|
|
440
|
+
}
|
|
441
|
+
const DEFAULT_EXPORT_CONDITIONS = [
|
|
442
|
+
"browser",
|
|
443
|
+
"import",
|
|
444
|
+
"module",
|
|
445
|
+
"default"
|
|
446
|
+
];
|
|
447
|
+
function resolveExportsEntry(exportsField, conditions = DEFAULT_EXPORT_CONDITIONS) {
|
|
448
|
+
return resolveExportsEntryWithConditions(exportsField, new Set(conditions));
|
|
449
|
+
}
|
|
450
|
+
function resolveExportsEntryWithConditions(exportsField, conditions) {
|
|
451
|
+
if (typeof exportsField === "string") return exportsField;
|
|
452
|
+
if (!exportsField || typeof exportsField !== "object") return void 0;
|
|
453
|
+
if (Array.isArray(exportsField)) {
|
|
454
|
+
for (const target of exportsField) {
|
|
455
|
+
const resolved = resolveExportsEntryWithConditions(target, conditions);
|
|
456
|
+
if (resolved) return resolved;
|
|
457
|
+
}
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
const record = exportsField;
|
|
461
|
+
const rootExport = record["."];
|
|
462
|
+
if (rootExport) return resolveExportsEntryWithConditions(rootExport, conditions);
|
|
463
|
+
for (const [condition, value] of Object.entries(record)) {
|
|
464
|
+
if (condition !== "default" && !conditions.has(condition)) continue;
|
|
465
|
+
const target = resolveExportsEntryWithConditions(value, conditions);
|
|
466
|
+
if (target) return target;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
function substituteExportsWildcard(target, patternMatch) {
|
|
470
|
+
if (typeof target === "string") return target.split("*").join(patternMatch);
|
|
471
|
+
if (Array.isArray(target)) return target.map((entry) => substituteExportsWildcard(entry, patternMatch));
|
|
472
|
+
if (target && typeof target === "object") {
|
|
473
|
+
const source = target;
|
|
474
|
+
const out = {};
|
|
475
|
+
for (const key of Object.keys(source)) out[key] = substituteExportsWildcard(source[key], patternMatch);
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
return target;
|
|
479
|
+
}
|
|
480
|
+
function matchExportsSubpath(record, subpath) {
|
|
481
|
+
if (subpath in record) return record[subpath];
|
|
482
|
+
let bestKey;
|
|
483
|
+
let bestBaseLength = -1;
|
|
484
|
+
let bestKeyLength = -1;
|
|
485
|
+
for (const key of Object.keys(record)) {
|
|
486
|
+
const wildcardIndex = key.indexOf("*");
|
|
487
|
+
if (wildcardIndex === -1) continue;
|
|
488
|
+
const patternBase = key.slice(0, wildcardIndex);
|
|
489
|
+
const patternTrailer = key.slice(wildcardIndex + 1);
|
|
490
|
+
if (patternTrailer.includes("*")) continue;
|
|
491
|
+
if (!subpath.startsWith(patternBase) || !subpath.endsWith(patternTrailer)) continue;
|
|
492
|
+
if (subpath.length <= patternBase.length + patternTrailer.length) continue;
|
|
493
|
+
if (patternBase.length > bestBaseLength || patternBase.length === bestBaseLength && key.length > bestKeyLength) {
|
|
494
|
+
bestKey = key;
|
|
495
|
+
bestBaseLength = patternBase.length;
|
|
496
|
+
bestKeyLength = key.length;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (bestKey === void 0) return void 0;
|
|
500
|
+
const patternTrailer = bestKey.slice(bestKey.indexOf("*") + 1);
|
|
501
|
+
const patternMatch = subpath.slice(bestBaseLength, subpath.length - patternTrailer.length);
|
|
502
|
+
return substituteExportsWildcard(record[bestKey], patternMatch);
|
|
503
|
+
}
|
|
504
|
+
function getPackageExportsTarget(pkg, packageName, exportsField) {
|
|
505
|
+
if (typeof exportsField === "string") return pkg === packageName ? exportsField : void 0;
|
|
506
|
+
if (!exportsField || typeof exportsField !== "object") return void 0;
|
|
507
|
+
const record = exportsField;
|
|
508
|
+
const subpath = pkg === packageName ? "." : `.${pkg.slice(packageName.length)}`;
|
|
509
|
+
if (subpath !== ".") return matchExportsSubpath(record, subpath);
|
|
510
|
+
return record["."] ?? (!Object.keys(record).some((key) => key.startsWith(".")) ? record : void 0);
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Escaping rules:
|
|
514
|
+
* Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
|
|
515
|
+
* @ => 1
|
|
516
|
+
* / => 2
|
|
517
|
+
* - => 3
|
|
518
|
+
* . => 4
|
|
519
|
+
*/
|
|
520
|
+
/**
|
|
521
|
+
* Encodes a package name into a valid file name.
|
|
522
|
+
* @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
|
|
523
|
+
* @returns {string} - The encoded file name.
|
|
524
|
+
*/
|
|
525
|
+
function packageNameEncode(name) {
|
|
526
|
+
if (typeof name !== "string") throw createModuleFederationError("A string package name is required");
|
|
527
|
+
return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Decodes an encoded file name back to the original package name.
|
|
531
|
+
* @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
|
|
532
|
+
* @returns {string} - The decoded package name.
|
|
533
|
+
*/
|
|
534
|
+
function packageNameDecode(encoded) {
|
|
535
|
+
if (typeof encoded !== "string") throw createModuleFederationError("A string encoded file name is required");
|
|
536
|
+
return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Removes any subpath from an npm package specifier and returns the package name only.
|
|
540
|
+
* @param {string} packageString - The package specifier, e.g., "@scope/pkg/runtime" or "react/jsx-runtime".
|
|
541
|
+
* @returns {string} - The base npm package name.
|
|
542
|
+
*/
|
|
543
|
+
function getPackageName(packageString) {
|
|
544
|
+
const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
|
|
545
|
+
return match ? match[0] : packageString;
|
|
546
|
+
}
|
|
547
|
+
function getPackageNameFromNodeModulePath(source) {
|
|
548
|
+
const normalized = source.replace(/\\/g, "/");
|
|
549
|
+
const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
|
|
550
|
+
if (nodeModulesIndex < 0) return;
|
|
551
|
+
const parts = normalized.slice(nodeModulesIndex + 14).split("/");
|
|
552
|
+
if (!parts[0]) return;
|
|
553
|
+
if (parts[0].startsWith("@")) return parts[1] ? `${parts[0]}/${parts[1]}` : void 0;
|
|
554
|
+
return parts[0];
|
|
555
|
+
}
|
|
556
|
+
function getSharedCacheKeyParts(input) {
|
|
557
|
+
const scope = (Array.isArray(input.scope) ? input.scope[0] : input.scope) || "default";
|
|
558
|
+
const id = input.singleton || !input.version ? input.pkg : `${input.pkg}@${input.version}`;
|
|
559
|
+
return {
|
|
560
|
+
scope,
|
|
561
|
+
id,
|
|
562
|
+
key: `${scope}:${id}`
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
function getSharedCacheDescriptor(pkg, shareItem) {
|
|
566
|
+
const parts = getSharedCacheKeyParts({
|
|
567
|
+
pkg,
|
|
568
|
+
singleton: shareItem.shareConfig.singleton,
|
|
569
|
+
version: shareItem.version,
|
|
570
|
+
scope: shareItem.scope
|
|
571
|
+
});
|
|
572
|
+
return {
|
|
573
|
+
canonical: parts.key,
|
|
574
|
+
...parts.scope === "default" ? { aliases: [parts.id] } : {}
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
const sharedCacheHelperCode = `const __mfGetSharedCacheDescriptor = (pkg, singleton, version, scope) => {
|
|
578
|
+
const normalizedScope = Array.isArray(scope) ? scope[0] : scope;
|
|
579
|
+
const scopeName = normalizedScope || "default";
|
|
580
|
+
const id = singleton || !version ? pkg : pkg + "@" + version;
|
|
581
|
+
const descriptor = { canonical: scopeName + ":" + id };
|
|
582
|
+
if (scopeName === "default") descriptor.aliases = [id];
|
|
583
|
+
return descriptor;
|
|
584
|
+
};
|
|
585
|
+
const __mfReadSharedCache = (cache, descriptor) => {
|
|
586
|
+
const value = cache[descriptor.canonical];
|
|
587
|
+
if (value !== undefined) return value;
|
|
588
|
+
const aliases = descriptor.aliases || [];
|
|
589
|
+
for (const alias of aliases) {
|
|
590
|
+
if (!Object.prototype.hasOwnProperty.call(cache, alias)) continue;
|
|
591
|
+
const aliasValue = cache[alias];
|
|
592
|
+
if (aliasValue !== undefined) {
|
|
593
|
+
cache[descriptor.canonical] = aliasValue;
|
|
594
|
+
return aliasValue;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return undefined;
|
|
598
|
+
};
|
|
599
|
+
const __mfSharedCacheListenersKey = Symbol.for("module-federation.shared-cache-listeners");
|
|
600
|
+
const __mfGetSharedCacheListeners = (cache) => {
|
|
601
|
+
let listeners = cache[__mfSharedCacheListenersKey];
|
|
602
|
+
if (listeners === undefined) {
|
|
603
|
+
listeners = Object.create(null);
|
|
604
|
+
Object.defineProperty(cache, __mfSharedCacheListenersKey, {
|
|
605
|
+
value: listeners,
|
|
606
|
+
enumerable: false,
|
|
607
|
+
configurable: false,
|
|
608
|
+
writable: false
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
return listeners;
|
|
612
|
+
};
|
|
613
|
+
const __mfSubscribeSharedCache = (cache, descriptor, listener) => {
|
|
614
|
+
const listeners = __mfGetSharedCacheListeners(cache);
|
|
615
|
+
(listeners[descriptor.canonical] ||= new Set()).add(listener);
|
|
616
|
+
};
|
|
617
|
+
const __mfSharedCacheOwnersKey = Symbol.for("module-federation.shared-cache-owners");
|
|
618
|
+
const __mfGetSharedCacheOwners = (cache) => {
|
|
619
|
+
let owners = cache[__mfSharedCacheOwnersKey];
|
|
620
|
+
if (owners === undefined) {
|
|
621
|
+
owners = Object.create(null);
|
|
622
|
+
Object.defineProperty(cache, __mfSharedCacheOwnersKey, {
|
|
623
|
+
value: owners,
|
|
624
|
+
enumerable: false,
|
|
625
|
+
configurable: false,
|
|
626
|
+
writable: false
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
return owners;
|
|
630
|
+
};
|
|
631
|
+
const __mfReadSharedCacheOwner = (cache, descriptor) =>
|
|
632
|
+
cache[__mfSharedCacheOwnersKey]?.[descriptor.canonical];
|
|
633
|
+
const __mfWriteSharedCache = (cache, descriptor, value, owner) => {
|
|
634
|
+
cache[descriptor.canonical] = value;
|
|
635
|
+
const aliases = descriptor.aliases || [];
|
|
636
|
+
for (const alias of aliases) {
|
|
637
|
+
Object.defineProperty(cache, alias, {
|
|
638
|
+
value,
|
|
639
|
+
enumerable: true,
|
|
640
|
+
configurable: true,
|
|
641
|
+
writable: true
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
const owners = cache[__mfSharedCacheOwnersKey];
|
|
645
|
+
if (owner === undefined) {
|
|
646
|
+
if (owners) delete owners[descriptor.canonical];
|
|
647
|
+
} else {
|
|
648
|
+
__mfGetSharedCacheOwners(cache)[descriptor.canonical] = owner;
|
|
649
|
+
}
|
|
650
|
+
const listeners = cache[__mfSharedCacheListenersKey]?.[descriptor.canonical];
|
|
651
|
+
if (listeners) {
|
|
652
|
+
for (const listener of listeners) listener(value);
|
|
653
|
+
}
|
|
654
|
+
return value;
|
|
655
|
+
};
|
|
656
|
+
const __mfTreeShakingSharedCacheKey = Symbol.for("module-federation.tree-shaking-shared-cache");
|
|
657
|
+
const __mfGetTreeShakingSharedCache = (cache) => {
|
|
658
|
+
let metadata = cache[__mfTreeShakingSharedCacheKey];
|
|
659
|
+
if (metadata === undefined) {
|
|
660
|
+
metadata = Object.create(null);
|
|
661
|
+
Object.defineProperty(cache, __mfTreeShakingSharedCacheKey, {
|
|
662
|
+
value: metadata,
|
|
663
|
+
enumerable: false,
|
|
664
|
+
configurable: false,
|
|
665
|
+
writable: false
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
return metadata;
|
|
669
|
+
};
|
|
670
|
+
const __mfReadTreeShakingSharedCache = (cache, descriptor, requiredExports) => {
|
|
671
|
+
const fullModule = __mfReadSharedCache(cache, descriptor);
|
|
672
|
+
if (fullModule !== undefined) return fullModule;
|
|
673
|
+
if (!Array.isArray(requiredExports)) return undefined;
|
|
674
|
+
const metadata = cache[__mfTreeShakingSharedCacheKey];
|
|
675
|
+
const entries = metadata?.[descriptor.canonical] || [];
|
|
676
|
+
let compatibleEntry;
|
|
677
|
+
for (const entry of entries) {
|
|
678
|
+
if (!requiredExports.every((name) => entry.providedExports.includes(name))) continue;
|
|
679
|
+
if (!compatibleEntry || entry.providedExports.length < compatibleEntry.providedExports.length) {
|
|
680
|
+
compatibleEntry = entry;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return compatibleEntry?.value;
|
|
684
|
+
};
|
|
685
|
+
const __mfWriteTreeShakingSharedCache = (cache, descriptor, providedExports, value) => {
|
|
686
|
+
if (!Array.isArray(providedExports)) return value;
|
|
687
|
+
const normalizedExports = [...new Set(providedExports)].sort();
|
|
688
|
+
const metadata = __mfGetTreeShakingSharedCache(cache);
|
|
689
|
+
const entries = (metadata[descriptor.canonical] ||= []);
|
|
690
|
+
const existing = entries.find((entry) =>
|
|
691
|
+
entry.providedExports.length === normalizedExports.length &&
|
|
692
|
+
entry.providedExports.every((name, index) => name === normalizedExports[index])
|
|
693
|
+
);
|
|
694
|
+
if (existing) existing.value = value;
|
|
695
|
+
else entries.push({ providedExports: normalizedExports, value });
|
|
696
|
+
return value;
|
|
697
|
+
};
|
|
698
|
+
const __mfTreeShakingSelectionCacheKey = Symbol.for("module-federation.tree-shaking-shared-selection-cache");
|
|
699
|
+
const __mfGetTreeShakingSelectionCache = (cache) => {
|
|
700
|
+
let selections = cache[__mfTreeShakingSelectionCacheKey];
|
|
701
|
+
if (selections === undefined) {
|
|
702
|
+
selections = Object.create(null);
|
|
703
|
+
Object.defineProperty(cache, __mfTreeShakingSelectionCacheKey, {
|
|
704
|
+
value: selections,
|
|
705
|
+
enumerable: false,
|
|
706
|
+
configurable: false,
|
|
707
|
+
writable: false
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
return selections;
|
|
711
|
+
};
|
|
712
|
+
const __mfReadTreeShakingSharedSelection = (cache, descriptor, consumer) => {
|
|
713
|
+
const fullModule = __mfReadSharedCache(cache, descriptor);
|
|
714
|
+
if (fullModule !== undefined) return fullModule;
|
|
715
|
+
return cache[__mfTreeShakingSelectionCacheKey]?.[descriptor.canonical]?.[consumer];
|
|
716
|
+
};
|
|
717
|
+
const __mfWriteTreeShakingSharedSelection = (cache, descriptor, consumer, value) => {
|
|
718
|
+
const selections = __mfGetTreeShakingSelectionCache(cache);
|
|
719
|
+
const byConsumer = (selections[descriptor.canonical] ||= Object.create(null));
|
|
720
|
+
byConsumer[consumer] = value;
|
|
721
|
+
return value;
|
|
722
|
+
};`;
|
|
723
|
+
function getInstalledPackageJson(pkg, opts) {
|
|
724
|
+
const cwd = opts?.cwd || getPackageDetectionCwd();
|
|
725
|
+
const packageName = opts?.packageName || getPackageName(pkg);
|
|
726
|
+
const cacheKey = `${cwd}\0${pkg}\0${packageName}\0${opts?.fromResolvedEntry ?? ""}`;
|
|
727
|
+
if (installedPackageJsonCache.has(cacheKey)) return installedPackageJsonCache.get(cacheKey);
|
|
728
|
+
const result = resolveInstalledPackageJson(pkg, cwd, packageName, opts);
|
|
729
|
+
installedPackageJsonCache.set(cacheKey, result);
|
|
730
|
+
return result;
|
|
731
|
+
}
|
|
732
|
+
function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
|
|
733
|
+
const tryReadPackageJson = (packageJsonPath) => {
|
|
734
|
+
if (!existsSync(packageJsonPath)) return void 0;
|
|
735
|
+
try {
|
|
736
|
+
return {
|
|
737
|
+
path: packageJsonPath,
|
|
738
|
+
dir: path$1.dirname(packageJsonPath),
|
|
739
|
+
packageJson: JSON.parse(readFileSync(packageJsonPath, "utf-8"))
|
|
740
|
+
};
|
|
741
|
+
} catch {
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
const findPackageInPnpmStore = (startDir) => {
|
|
746
|
+
let currentDir = startDir;
|
|
747
|
+
const rootDir = path$1.parse(currentDir).root;
|
|
748
|
+
while (true) {
|
|
749
|
+
const pnpmStoreDir = path$1.join(currentDir, "node_modules", ".pnpm");
|
|
750
|
+
if (existsSync(pnpmStoreDir)) try {
|
|
751
|
+
for (const entry of readdirSync(pnpmStoreDir, { withFileTypes: true })) {
|
|
752
|
+
if (!entry.isDirectory()) continue;
|
|
753
|
+
const candidate = tryReadPackageJson(path$1.join(pnpmStoreDir, entry.name, "node_modules", packageName, "package.json"));
|
|
754
|
+
if (candidate?.packageJson.name === packageName) return candidate;
|
|
755
|
+
}
|
|
756
|
+
} catch {}
|
|
757
|
+
if (currentDir === rootDir) break;
|
|
758
|
+
currentDir = path$1.dirname(currentDir);
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
try {
|
|
762
|
+
const projectRequire = createRequire$1(pathToFileURL(path$1.join(cwd, "package.json")));
|
|
763
|
+
let resolvedPath;
|
|
764
|
+
if (opts?.fromResolvedEntry) resolvedPath = opts.fromResolvedEntry;
|
|
765
|
+
else try {
|
|
766
|
+
resolvedPath = projectRequire.resolve(pkg);
|
|
767
|
+
} catch {
|
|
768
|
+
resolvedPath = projectRequire.resolve(packageName);
|
|
769
|
+
}
|
|
770
|
+
let currentDir = path$1.dirname(resolvedPath);
|
|
771
|
+
const rootDir = path$1.parse(currentDir).root;
|
|
772
|
+
while (true) {
|
|
773
|
+
const packageJsonPath = path$1.join(currentDir, "package.json");
|
|
774
|
+
if (existsSync(packageJsonPath)) {
|
|
775
|
+
const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
|
|
776
|
+
try {
|
|
777
|
+
const packageJson = JSON.parse(packageJsonContent);
|
|
778
|
+
if (packageJson.name === packageName) return {
|
|
779
|
+
path: packageJsonPath,
|
|
780
|
+
dir: currentDir,
|
|
781
|
+
packageJson
|
|
782
|
+
};
|
|
783
|
+
} catch (error) {
|
|
784
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
if (currentDir === rootDir) break;
|
|
788
|
+
currentDir = path$1.dirname(currentDir);
|
|
789
|
+
}
|
|
790
|
+
} catch {
|
|
791
|
+
let currentDir = cwd;
|
|
792
|
+
const rootDir = path$1.parse(currentDir).root;
|
|
793
|
+
while (true) {
|
|
794
|
+
const directCandidate = tryReadPackageJson(path$1.join(currentDir, "node_modules", packageName, "package.json"));
|
|
795
|
+
if (directCandidate?.packageJson.name === packageName) return directCandidate;
|
|
796
|
+
if (currentDir === rootDir) break;
|
|
797
|
+
currentDir = path$1.dirname(currentDir);
|
|
798
|
+
}
|
|
799
|
+
return findPackageInPnpmStore(cwd);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
function getInstalledPackageEntry(pkg, opts) {
|
|
803
|
+
const installed = getInstalledPackageJson(pkg, opts);
|
|
804
|
+
if (!installed) return void 0;
|
|
805
|
+
const cwd = opts?.cwd || getPackageDetectionCwd();
|
|
806
|
+
const packageName = opts?.packageName || getPackageName(pkg);
|
|
807
|
+
const packageJson = installed.packageJson;
|
|
808
|
+
if (pkg !== packageName && (opts?.resolveSubpathWithRequire !== false || packageJson.exports === void 0)) try {
|
|
809
|
+
return createRequire$1(pathToFileURL(path$1.join(cwd, "package.json"))).resolve(pkg);
|
|
810
|
+
} catch {}
|
|
811
|
+
const explicitEntry = resolveExportsEntry(getPackageExportsTarget(pkg, packageName, packageJson.exports), opts?.conditions) || (typeof packageJson.module === "string" ? packageJson.module : void 0) || (typeof packageJson.main === "string" ? packageJson.main : void 0) || "index.js";
|
|
812
|
+
return path$1.join(installed.dir, explicitEntry);
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Detect whether the current runtime is Vite 8+ by checking for a Vite version flag
|
|
816
|
+
* on the plugin hook context, with Rolldown metadata kept as a compatibility fallback.
|
|
817
|
+
*/
|
|
818
|
+
function getIsRolldown(ctx) {
|
|
819
|
+
const viteVersion = ctx?.meta?.viteVersion;
|
|
820
|
+
const viteMajor = Number(String(viteVersion ?? "").split(".")[0]);
|
|
821
|
+
return Number.isFinite(viteMajor) && viteMajor >= 8 || !!ctx?.meta?.rolldownVersion;
|
|
822
|
+
}
|
|
823
|
+
/** Walk up from Vite `config.root` (Nuxt may point at `.nuxt` cache dirs). */
|
|
824
|
+
function isNuxtProjectRoot(root) {
|
|
825
|
+
let dir = root;
|
|
826
|
+
for (let i = 0; i < 8; i++) {
|
|
827
|
+
if (hasPackageDependency("nuxt", dir) || hasPackageDependency("nuxt-nightly", dir)) return true;
|
|
828
|
+
const parent = path$1.dirname(dir);
|
|
829
|
+
if (parent === dir) break;
|
|
830
|
+
dir = parent;
|
|
831
|
+
}
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
function hasPackageDependency(dependencyName, cwd = packageDetectionCwd || process.cwd()) {
|
|
835
|
+
const cacheKey = getDependencyCacheKey(cwd, dependencyName);
|
|
836
|
+
const cached = dependencyPresenceCache.get(cacheKey);
|
|
837
|
+
if (cached !== void 0) return cached;
|
|
838
|
+
try {
|
|
839
|
+
const packageJson = JSON.parse(readFileSync(path$1.join(cwd, "package.json"), "utf8"));
|
|
840
|
+
const hasDependency = [
|
|
841
|
+
packageJson.dependencies,
|
|
842
|
+
packageJson.devDependencies,
|
|
843
|
+
packageJson.peerDependencies,
|
|
844
|
+
packageJson.optionalDependencies
|
|
845
|
+
].some((deps) => !!deps?.[dependencyName]);
|
|
846
|
+
dependencyPresenceCache.set(cacheKey, hasDependency);
|
|
847
|
+
return hasDependency;
|
|
848
|
+
} catch {
|
|
849
|
+
dependencyPresenceCache.set(cacheKey, false);
|
|
850
|
+
return false;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
//#endregion
|
|
324
854
|
//#region src/utils/pathNormalization.ts
|
|
325
855
|
const COMMON_SHARED_SUBPATHS = {
|
|
326
856
|
react: [
|
|
@@ -396,11 +926,11 @@ function removeTrailingSlash(value) {
|
|
|
396
926
|
function ensureTrailingSlash(value) {
|
|
397
927
|
return `${removeTrailingSlash(value)}/`;
|
|
398
928
|
}
|
|
399
|
-
function getBasePath$
|
|
929
|
+
function getBasePath$2(base) {
|
|
400
930
|
return removeTrailingSlash(base || "/");
|
|
401
931
|
}
|
|
402
932
|
function isNuxtClientBase(base) {
|
|
403
|
-
return getBasePath$
|
|
933
|
+
return getBasePath$2(base).endsWith("/_nuxt");
|
|
404
934
|
}
|
|
405
935
|
function normalizeNodeModulePath(source) {
|
|
406
936
|
return source.replace(/\\/g, "/").replace(/\?.*$/, "");
|
|
@@ -1016,6 +1546,104 @@ function generateReactIslandSSRDefinition(enabled) {
|
|
|
1016
1546
|
}
|
|
1017
1547
|
}`;
|
|
1018
1548
|
}
|
|
1549
|
+
const REACT_ISLAND_CLIENT_ID_PREFIX = "virtual:mf-react-island-client:";
|
|
1550
|
+
const REACT_ISLAND_SERVER_ID_PREFIX = "virtual:mf-react-island-server:";
|
|
1551
|
+
const RESOLVED_REACT_ISLAND_CLIENT_ID_PREFIX = `\0${REACT_ISLAND_CLIENT_ID_PREFIX}`;
|
|
1552
|
+
const RESOLVED_REACT_ISLAND_SERVER_ID_PREFIX = `\0${REACT_ISLAND_SERVER_ID_PREFIX}`;
|
|
1553
|
+
function encodeIslandRemoteId(remoteId) {
|
|
1554
|
+
return encodeURIComponent(remoteId);
|
|
1555
|
+
}
|
|
1556
|
+
function decodeIslandRemoteId(encodedRemoteId) {
|
|
1557
|
+
return decodeURIComponent(encodedRemoteId);
|
|
1558
|
+
}
|
|
1559
|
+
function getReactIslandImportRemoteId(source) {
|
|
1560
|
+
const queryIndex = source.indexOf("?");
|
|
1561
|
+
if (queryIndex === -1) return;
|
|
1562
|
+
if (!new URLSearchParams(source.slice(queryIndex + 1)).has("mf-island")) return;
|
|
1563
|
+
return source.slice(0, queryIndex);
|
|
1564
|
+
}
|
|
1565
|
+
function getReactIslandServerImportId(remoteId) {
|
|
1566
|
+
return `${REACT_ISLAND_SERVER_ID_PREFIX}${encodeIslandRemoteId(remoteId)}`;
|
|
1567
|
+
}
|
|
1568
|
+
function getReactIslandClientImportId(remoteId) {
|
|
1569
|
+
return `${REACT_ISLAND_CLIENT_ID_PREFIX}${encodeIslandRemoteId(remoteId)}`;
|
|
1570
|
+
}
|
|
1571
|
+
function resolveReactIslandConsumerId(id) {
|
|
1572
|
+
if (id.startsWith("virtual:mf-react-island-server:")) return `\0${id}`;
|
|
1573
|
+
if (id.startsWith("virtual:mf-react-island-client:")) return `\0${id}`;
|
|
1574
|
+
}
|
|
1575
|
+
function remoteIdFromResolvedIslandId(id, prefix) {
|
|
1576
|
+
if (!id.startsWith(prefix)) return;
|
|
1577
|
+
return decodeIslandRemoteId(id.slice(prefix.length));
|
|
1578
|
+
}
|
|
1579
|
+
/** Generates the server half of the opt-in `?mf-island` consumer component. */
|
|
1580
|
+
function generateReactIslandConsumerServer(remoteId) {
|
|
1581
|
+
const source = JSON.stringify(remoteId);
|
|
1582
|
+
return `import * as React from "react";
|
|
1583
|
+
import IslandClient from ${JSON.stringify(getReactIslandClientImportId(remoteId))};
|
|
1584
|
+
|
|
1585
|
+
const islandModulePromise = import(${source});
|
|
1586
|
+
|
|
1587
|
+
async function loadIslandModule() {
|
|
1588
|
+
const namespace = await islandModulePromise;
|
|
1589
|
+
const pending = namespace && namespace.__mf_remote_pending;
|
|
1590
|
+
if (pending && typeof pending.then === "function") return pending;
|
|
1591
|
+
return namespace && namespace.__moduleExports || namespace;
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
export default async function ModuleFederationIsland(props) {
|
|
1595
|
+
const remoteModule = await loadIslandModule();
|
|
1596
|
+
const shell = remoteModule && remoteModule.__mf_island;
|
|
1597
|
+
if (!shell || typeof shell.renderToHtml !== "function") {
|
|
1598
|
+
throw new Error(${JSON.stringify(`[Module Federation] ${remoteId} does not expose an SSR island capability`)});
|
|
1599
|
+
}
|
|
1600
|
+
const html = await shell.renderToHtml(props);
|
|
1601
|
+
return React.createElement(IslandClient, { html, islandProps: props });
|
|
1602
|
+
}`;
|
|
1603
|
+
}
|
|
1604
|
+
/** Generates the client boundary which hydrates with the remote-owned React. */
|
|
1605
|
+
function generateReactIslandConsumerClient(remoteId) {
|
|
1606
|
+
return `"use client";
|
|
1607
|
+
|
|
1608
|
+
import * as React from "react";
|
|
1609
|
+
|
|
1610
|
+
const islandModulePromise = import(${JSON.stringify(remoteId)});
|
|
1611
|
+
|
|
1612
|
+
async function loadIslandModule() {
|
|
1613
|
+
const namespace = await islandModulePromise;
|
|
1614
|
+
const pending = namespace && namespace.__mf_remote_pending;
|
|
1615
|
+
if (pending && typeof pending.then === "function") return pending;
|
|
1616
|
+
return namespace && namespace.__moduleExports || namespace;
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
export default function ModuleFederationIslandClient({ html, islandProps }) {
|
|
1620
|
+
const ref = React.useRef(null);
|
|
1621
|
+
|
|
1622
|
+
React.useEffect(() => {
|
|
1623
|
+
const element = ref.current;
|
|
1624
|
+
if (!element) return;
|
|
1625
|
+
void loadIslandModule().then((remoteModule) => {
|
|
1626
|
+
const shell = remoteModule && remoteModule.__mf_island;
|
|
1627
|
+
if (!shell || typeof shell.hydrate !== "function") {
|
|
1628
|
+
throw new Error(${JSON.stringify(`[Module Federation] ${remoteId} does not expose a client island capability`)});
|
|
1629
|
+
}
|
|
1630
|
+
return shell.hydrate(element, islandProps);
|
|
1631
|
+
});
|
|
1632
|
+
}, []);
|
|
1633
|
+
|
|
1634
|
+
return React.createElement("div", {
|
|
1635
|
+
ref,
|
|
1636
|
+
suppressHydrationWarning: true,
|
|
1637
|
+
dangerouslySetInnerHTML: { __html: html },
|
|
1638
|
+
});
|
|
1639
|
+
}`;
|
|
1640
|
+
}
|
|
1641
|
+
function loadReactIslandConsumerModule(id) {
|
|
1642
|
+
const serverRemoteId = remoteIdFromResolvedIslandId(id, RESOLVED_REACT_ISLAND_SERVER_ID_PREFIX);
|
|
1643
|
+
if (serverRemoteId !== void 0) return generateReactIslandConsumerServer(serverRemoteId);
|
|
1644
|
+
const clientRemoteId = remoteIdFromResolvedIslandId(id, RESOLVED_REACT_ISLAND_CLIENT_ID_PREFIX);
|
|
1645
|
+
if (clientRemoteId !== void 0) return generateReactIslandConsumerClient(clientRemoteId);
|
|
1646
|
+
}
|
|
1019
1647
|
//#endregion
|
|
1020
1648
|
//#region src/virtualModules/virtualExposes.ts
|
|
1021
1649
|
const EXPOSES_CSS_MAP_PLACEHOLDER = "__MF_EXPOSES_CSS_MAP__";
|
|
@@ -1684,7 +2312,18 @@ function hasCodeMatch(source, regex, codePositions) {
|
|
|
1684
2312
|
return false;
|
|
1685
2313
|
}
|
|
1686
2314
|
function hasCommonJsExports(source) {
|
|
1687
|
-
|
|
2315
|
+
const codePositions = createCodePositionMap(source);
|
|
2316
|
+
if (hasCodeMatch(source, /\bmodule\s*(?:\.exports|\[\s*['"]exports['"]\s*\])/g, codePositions)) return true;
|
|
2317
|
+
const exportsRegex = /\bexports\s*(?:\.|\[|[,)]|=(?!=|>))/g;
|
|
2318
|
+
let match;
|
|
2319
|
+
while ((match = exportsRegex.exec(source)) !== null) {
|
|
2320
|
+
if (!codePositions[match.index]) continue;
|
|
2321
|
+
let previousCodeIndex = match.index - 1;
|
|
2322
|
+
while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
|
|
2323
|
+
if (source[previousCodeIndex] === ".") continue;
|
|
2324
|
+
return true;
|
|
2325
|
+
}
|
|
2326
|
+
return false;
|
|
1688
2327
|
}
|
|
1689
2328
|
function inspectSharedExportsFromFile(entryPath, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
|
|
1690
2329
|
try {
|
|
@@ -1701,6 +2340,64 @@ function inspectSharedExportsFromFile(entryPath, exportConditions = DEFAULT_SHAR
|
|
|
1701
2340
|
return;
|
|
1702
2341
|
}
|
|
1703
2342
|
}
|
|
2343
|
+
function getMutableExportsFromFile(entryPath, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS, visited = /* @__PURE__ */ new Set()) {
|
|
2344
|
+
if (!entryPath || visited.has(entryPath)) return [];
|
|
2345
|
+
visited.add(entryPath);
|
|
2346
|
+
try {
|
|
2347
|
+
const source = readFileSync(entryPath, "utf-8");
|
|
2348
|
+
const codePositions = createCodePositionMap(source);
|
|
2349
|
+
const mutableBindings = /* @__PURE__ */ new Set();
|
|
2350
|
+
const mutableExports = /* @__PURE__ */ new Set();
|
|
2351
|
+
let match;
|
|
2352
|
+
const declarationRegex = new RegExp(`\\b(?:export\\s+)?(?:let|var)\\s+(${JS_IDENTIFIER_PATTERN})`, "gu");
|
|
2353
|
+
let declarationScanIndex = 0;
|
|
2354
|
+
let braceDepth = 0;
|
|
2355
|
+
while ((match = declarationRegex.exec(source)) !== null) {
|
|
2356
|
+
if (!codePositions[match.index]) continue;
|
|
2357
|
+
for (let index = declarationScanIndex; index < match.index; index++) {
|
|
2358
|
+
if (!codePositions[index]) continue;
|
|
2359
|
+
if (source[index] === "{") braceDepth++;
|
|
2360
|
+
else if (source[index] === "}") braceDepth--;
|
|
2361
|
+
}
|
|
2362
|
+
declarationScanIndex = match.index;
|
|
2363
|
+
if (braceDepth !== 0) continue;
|
|
2364
|
+
mutableBindings.add(match[1]);
|
|
2365
|
+
if (match[0].trimStart().startsWith("export")) mutableExports.add(match[1]);
|
|
2366
|
+
}
|
|
2367
|
+
const listRegex = /export\s*\{([^}]+)\}(?:\s*from\s*['"]([^'"]+)['"])?/g;
|
|
2368
|
+
while ((match = listRegex.exec(source)) !== null) {
|
|
2369
|
+
if (!codePositions[match.index]) continue;
|
|
2370
|
+
const reExportPath = match[2] ? resolveReExportModule(entryPath, match[2], exportConditions) : void 0;
|
|
2371
|
+
const reExportedMutable = new Set(reExportPath ? getMutableExportsFromFile(reExportPath, exportConditions, visited) : []);
|
|
2372
|
+
for (const rawSpecifier of match[1].split(",")) {
|
|
2373
|
+
const specifier = rawSpecifier.trim();
|
|
2374
|
+
if (!specifier || specifier.startsWith("type ")) continue;
|
|
2375
|
+
const parts = specifier.split(/\s+as\s+/);
|
|
2376
|
+
const local = parts[0].trim();
|
|
2377
|
+
const exported = (parts[1] || local).trim();
|
|
2378
|
+
if (isValidEsmExportName(exported) && (mutableBindings.has(local) || reExportedMutable.has(local))) mutableExports.add(exported);
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
const starExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g;
|
|
2382
|
+
while ((match = starExportRegex.exec(source)) !== null) {
|
|
2383
|
+
if (!codePositions[match.index]) continue;
|
|
2384
|
+
const resolved = resolveReExportModule(entryPath, match[1], exportConditions);
|
|
2385
|
+
for (const name of getMutableExportsFromFile(resolved, exportConditions, visited)) mutableExports.add(name);
|
|
2386
|
+
}
|
|
2387
|
+
visited.delete(entryPath);
|
|
2388
|
+
return Array.from(mutableExports);
|
|
2389
|
+
} catch {
|
|
2390
|
+
visited.delete(entryPath);
|
|
2391
|
+
return [];
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
function getSharedMutableExports(pkg, shareItem, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
|
|
2395
|
+
const configuredImport = shareItem?.shareConfig.import;
|
|
2396
|
+
return getMutableExportsFromFile(typeof configuredImport === "string" ? resolveConfiguredImportPath(configuredImport, exportConditions) : getInstalledPackageEntry(pkg, {
|
|
2397
|
+
conditions: exportConditions,
|
|
2398
|
+
resolveSubpathWithRequire: false
|
|
2399
|
+
}), exportConditions);
|
|
2400
|
+
}
|
|
1704
2401
|
function resolveConfiguredImportPath(importSource, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
|
|
1705
2402
|
if (path$1.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
|
|
1706
2403
|
const projectRoot = getPackageDetectionCwd();
|
|
@@ -1948,6 +2645,7 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
|
|
|
1948
2645
|
const specifiers = match[1].split(",");
|
|
1949
2646
|
for (const specifier of specifiers) {
|
|
1950
2647
|
const trimmed = specifier.trim();
|
|
2648
|
+
if (!trimmed) continue;
|
|
1951
2649
|
if (typeOnlySpecifierRegex.test(trimmed)) continue;
|
|
1952
2650
|
const asMatch = trimmed.match(exportSpecifierRegex);
|
|
1953
2651
|
if (!asMatch) {
|
|
@@ -2163,11 +2861,14 @@ function isSharedSingletonConsumedByPeer(pkg, options = getNormalizeModuleFedera
|
|
|
2163
2861
|
}
|
|
2164
2862
|
return false;
|
|
2165
2863
|
};
|
|
2166
|
-
return Array.from(sharedKeyByPackageName.values()).some((sharedPkg) => sharedPkg !== pkg && reachesPkg(sharedPkg, new Set([sharedPkg])));
|
|
2864
|
+
return Array.from(sharedKeyByPackageName.values()).some((sharedPkg) => sharedPkg !== pkg && reachesPkg(sharedPkg, /* @__PURE__ */ new Set([sharedPkg])));
|
|
2167
2865
|
}
|
|
2168
2866
|
function isRemoteOnlyContainer(options = getNormalizeModuleFederationOptions()) {
|
|
2169
2867
|
return Object.keys(options.exposes || {}).length > 0 && Object.keys(options.remotes || {}).length === 0;
|
|
2170
2868
|
}
|
|
2869
|
+
function isLocalOnlyContainer(options = getNormalizeModuleFederationOptions()) {
|
|
2870
|
+
return Object.keys(options.exposes || {}).length === 0 && Object.keys(options.remotes || {}).length === 0;
|
|
2871
|
+
}
|
|
2171
2872
|
function tryResolveImportFromPackageRoot(pkg, root) {
|
|
2172
2873
|
try {
|
|
2173
2874
|
return resolveWorkspaceEsmEntry(pkg, createRequire$1(pathToFileURL(path$1.join(root, "package.json"))).resolve(pkg), root);
|
|
@@ -2317,6 +3018,7 @@ export default { get, init };
|
|
|
2317
3018
|
materializedTreeShakingProviders.add(pkg);
|
|
2318
3019
|
}
|
|
2319
3020
|
function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
|
|
3021
|
+
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
2320
3022
|
const { preBuildCacheMap, preBuildShareItemMap } = getSharedVirtualModuleState(options);
|
|
2321
3023
|
if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = createScopedSharedVirtualModule(pkg, PREBUILD_TAG, options);
|
|
2322
3024
|
preBuildShareItemMap[pkg] = shareItem;
|
|
@@ -2368,14 +3070,19 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
|
|
|
2368
3070
|
}
|
|
2369
3071
|
const namedExports = getSharedNamedExports(pkg, shareItem, exportConditions) ?? [];
|
|
2370
3072
|
if (namedExports.length > 0) {
|
|
2371
|
-
const
|
|
2372
|
-
const
|
|
2373
|
-
const
|
|
3073
|
+
const mutableExports = new Set(isLocalOnlyContainer(resolvedOptions) ? getSharedMutableExports(pkg, shareItem, exportConditions) : []);
|
|
3074
|
+
const copiedExports = namedExports.filter((name) => !mutableExports.has(name));
|
|
3075
|
+
const liveExports = namedExports.filter((name) => mutableExports.has(name));
|
|
3076
|
+
const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
|
|
3077
|
+
const declarations = copiedExports.map((name, i) => `const ${namedExportVars[i]} = __mfPrebuildExports[${escapeGeneratedStringLiteral(name)}];`).join("\n ");
|
|
3078
|
+
const namedExportLine = copiedExports.length ? `export { ${copiedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
|
|
3079
|
+
const liveExportLine = liveExports.length ? `export { ${liveExports.join(", ")} } from ${escapeGeneratedStringLiteral(importSource)};` : "";
|
|
2374
3080
|
preBuildCacheMap[pkg].writeSync(`
|
|
2375
3081
|
import * as __mfPrebuildNamespace from ${escapeGeneratedStringLiteral(importSource)};
|
|
2376
3082
|
const __mfPrebuildExports = __mfPrebuildNamespace;
|
|
2377
3083
|
${declarations}
|
|
2378
3084
|
${namedExportLine}
|
|
3085
|
+
${liveExportLine}
|
|
2379
3086
|
export default Reflect.get(__mfPrebuildNamespace, "default") ?? __mfPrebuildNamespace;
|
|
2380
3087
|
`, true);
|
|
2381
3088
|
return;
|
|
@@ -2463,11 +3170,13 @@ function findCurrentLoadShareForStaleOwnerId(id, shared, findSharedKey, options)
|
|
|
2463
3170
|
function getSharedCacheReadExpression(cacheDescriptor, treeShakingConsumer) {
|
|
2464
3171
|
return treeShakingConsumer ? `__mfReadTreeShakingSharedSelection(__mfModuleCache.share, ${cacheDescriptor}, ${JSON.stringify(treeShakingConsumer)})` : `__mfReadSharedCache(__mfModuleCache.share, ${cacheDescriptor})`;
|
|
2465
3172
|
}
|
|
2466
|
-
function generateEagerWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer) {
|
|
2467
|
-
const
|
|
3173
|
+
function generateEagerWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, mutableExports = []) {
|
|
3174
|
+
const copiedExports = namedExports.filter((name) => !mutableExports.includes(name));
|
|
3175
|
+
const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
|
|
2468
3176
|
const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
|
|
2469
|
-
const assignments = [...
|
|
2470
|
-
const namedExportLine =
|
|
3177
|
+
const assignments = [...copiedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ");
|
|
3178
|
+
const namedExportLine = copiedExports.length > 0 ? `\n export { ${copiedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
|
|
3179
|
+
const mutableExportLine = mutableExports.length ? `\n export { ${mutableExports.join(", ")} } from ${escapeGeneratedStringLiteral(importSource)};` : "";
|
|
2471
3180
|
return `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(importSource)};
|
|
2472
3181
|
let exportModule = ${getSharedCacheReadExpression(cacheDescriptor, treeShakingConsumer)};
|
|
2473
3182
|
if (exportModule === undefined) {
|
|
@@ -2484,13 +3193,15 @@ function generateEagerWorkspaceSingletonExports(namedExports, importSource, cach
|
|
|
2484
3193
|
};
|
|
2485
3194
|
__mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplyEagerShareExports);
|
|
2486
3195
|
__mfApplyEagerShareExports(exportModule);
|
|
2487
|
-
export { __mf_default as default };${namedExportLine}`;
|
|
3196
|
+
export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
|
|
2488
3197
|
}
|
|
2489
|
-
function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false) {
|
|
2490
|
-
const
|
|
3198
|
+
function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false, mutableExports = []) {
|
|
3199
|
+
const copiedExports = namedExports.filter((name) => !mutableExports.includes(name));
|
|
3200
|
+
const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
|
|
2491
3201
|
const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
|
|
2492
|
-
const assignments =
|
|
2493
|
-
const namedExportLine =
|
|
3202
|
+
const assignments = copiedExports.length > 0 ? [...copiedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ") : "__mf_default = mod.default ?? mod;";
|
|
3203
|
+
const namedExportLine = copiedExports.length > 0 ? `\n export { ${copiedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
|
|
3204
|
+
const mutableExportLine = mutableExports.length ? `\n export { ${mutableExports.join(", ")} } from ${escapeGeneratedStringLiteral(importSource)};` : "";
|
|
2494
3205
|
const applyLocalFallback = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
2495
3206
|
__mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});
|
|
2496
3207
|
__mfApplyLazyShareExports(exportModule);`;
|
|
@@ -2519,7 +3230,7 @@ function generateLazyWorkspaceSingletonExports(namedExports, importSource, cache
|
|
|
2519
3230
|
} else {
|
|
2520
3231
|
__mfApplyLazyShareExports(exportModule);
|
|
2521
3232
|
}
|
|
2522
|
-
export { __mf_default as default };${namedExportLine}`;
|
|
3233
|
+
export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
|
|
2523
3234
|
}
|
|
2524
3235
|
const WORKSPACE_SINGLETON_SSR_LOCAL_SHARE = "__mfNormalizeShareModule(__mfLocalShare)";
|
|
2525
3236
|
function prependWorkspaceSingletonSsrImport(code) {
|
|
@@ -2619,6 +3330,10 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2619
3330
|
const skipServePrebuildWarmup = command !== "build" && (pkg === "lit" || pkg.startsWith("lit/"));
|
|
2620
3331
|
const detectedNamedExports = getSharedNamedExports(pkg, shareItem, exportConditions);
|
|
2621
3332
|
const namedExports = detectedNamedExports ?? [];
|
|
3333
|
+
const mutableExports = new Set(isLocalOnlyContainer(resolvedOptions) ? getSharedMutableExports(pkg, shareItem, exportConditions) : []);
|
|
3334
|
+
const copiedNamedExports = namedExports.filter((name) => !mutableExports.has(name));
|
|
3335
|
+
const liveNamedExports = namedExports.filter((name) => mutableExports.has(name));
|
|
3336
|
+
const liveNamedExportLine = liveNamedExports.length ? `export { ${liveNamedExports.join(", ")} } from ${escapeGeneratedStringLiteral(sharedImportSource)};` : "";
|
|
2622
3337
|
const hasCompleteExportCoverage = detectedNamedExports !== void 0;
|
|
2623
3338
|
const isWorkspaceSingleton = isWorkspacePackage && shareItem.shareConfig.singleton === true;
|
|
2624
3339
|
const isDefaultShareScope = shareItem.scope === void 0 || shareItem.scope === "default" || Array.isArray(shareItem.scope) && shareItem.scope[0] === "default";
|
|
@@ -2632,11 +3347,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2632
3347
|
let initBlock = "";
|
|
2633
3348
|
if (usesDeferredTreeShakingFallback) {
|
|
2634
3349
|
importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
|
|
2635
|
-
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback));
|
|
2636
|
-
} else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer);
|
|
3350
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback), liveNamedExports);
|
|
3351
|
+
} else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
|
|
2637
3352
|
else if (usesDeferredSingletonFallback) {
|
|
2638
3353
|
importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
|
|
2639
|
-
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback));
|
|
3354
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback), liveNamedExports);
|
|
2640
3355
|
} else if (detectedNamedExports === void 0) {
|
|
2641
3356
|
exportLine = `const __mfDefaultExport = (() => {
|
|
2642
3357
|
${generateShareModuleUnwrapCode({
|
|
@@ -2650,10 +3365,10 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2650
3365
|
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
2651
3366
|
__mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
|
|
2652
3367
|
} else if (namedExports.length > 0 && shareItem.shareConfig.singleton === true) {
|
|
2653
|
-
const namedExportVars =
|
|
3368
|
+
const namedExportVars = copiedNamedExports.map((_name, i) => `__mf_${i}`);
|
|
2654
3369
|
exportLine = `${["let __mfDefaultExport;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ")}
|
|
2655
3370
|
const __mfApplySharedExports = (mod) => {
|
|
2656
|
-
${[...
|
|
3371
|
+
${[...copiedNamedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), `__mfDefaultExport = (() => {
|
|
2657
3372
|
${generateShareModuleUnwrapCode({
|
|
2658
3373
|
source: "mod",
|
|
2659
3374
|
preserveNamedExports: false,
|
|
@@ -2664,12 +3379,13 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2664
3379
|
__mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplySharedExports);
|
|
2665
3380
|
__mfApplySharedExports(exportModule);
|
|
2666
3381
|
export { __mfDefaultExport as default };
|
|
2667
|
-
${`export { ${
|
|
3382
|
+
${copiedNamedExports.length ? `export { ${copiedNamedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };` : ""}
|
|
3383
|
+
${liveNamedExportLine}`;
|
|
2668
3384
|
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
2669
3385
|
__mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
|
|
2670
3386
|
} else if (namedExports.length > 0) {
|
|
2671
|
-
const destructure = `const { ${
|
|
2672
|
-
const namedExportLine = `export { ${
|
|
3387
|
+
const destructure = copiedNamedExports.length ? `const { ${copiedNamedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;` : "";
|
|
3388
|
+
const namedExportLine = copiedNamedExports.length ? `export { ${copiedNamedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };` : "";
|
|
2673
3389
|
exportLine = `const __mfDefaultExport = (() => {
|
|
2674
3390
|
${generateShareModuleUnwrapCode({
|
|
2675
3391
|
source: "exportModule",
|
|
@@ -2679,7 +3395,8 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
2679
3395
|
})();
|
|
2680
3396
|
export default __mfDefaultExport;
|
|
2681
3397
|
${destructure}
|
|
2682
|
-
${namedExportLine}
|
|
3398
|
+
${namedExportLine}
|
|
3399
|
+
${liveNamedExportLine}`;
|
|
2683
3400
|
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
2684
3401
|
__mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
|
|
2685
3402
|
} else if (shareItem.shareConfig.singleton === true) {
|
|
@@ -2754,7 +3471,8 @@ function getLocalOwnerKey(options) {
|
|
|
2754
3471
|
}
|
|
2755
3472
|
function getLocalSharedImportMapPath(options) {
|
|
2756
3473
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
2757
|
-
|
|
3474
|
+
const ownerName = options ? getLocalOwnerKey(resolvedOptions) : resolvedOptions.internalName || resolvedOptions.name;
|
|
3475
|
+
return `${LOCAL_SHARED_IMPORT_MAP_ID}:${packageNameEncode(ownerName)}`;
|
|
2758
3476
|
}
|
|
2759
3477
|
function getResolvedLocalSharedImportMapId(options) {
|
|
2760
3478
|
return `\0${getLocalSharedImportMapPath(options)}`;
|
|
@@ -3272,9 +3990,10 @@ function generateHostAutoInitSharedCacheSeedCode(command = "build", options) {
|
|
|
3272
3990
|
}
|
|
3273
3991
|
const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
|
|
3274
3992
|
function getRemoteEntryId(options) {
|
|
3275
|
-
|
|
3993
|
+
const scopedKey = `${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
3994
|
+
return `${REMOTE_ENTRY_ID}:${scopedKey}`;
|
|
3276
3995
|
}
|
|
3277
|
-
const SSR_ONLY_PLUGIN_SPECIFIERS = new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
3996
|
+
const SSR_ONLY_PLUGIN_SPECIFIERS = /* @__PURE__ */ new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
3278
3997
|
const isSsrOnlyPlugin = (importStatement) => [...SSR_ONLY_PLUGIN_SPECIFIERS].some((s) => importStatement.includes(s));
|
|
3279
3998
|
const getSsrOnlyPluginSpecifier = (importStatement) => [...SSR_ONLY_PLUGIN_SPECIFIERS].find((s) => importStatement.includes(s));
|
|
3280
3999
|
function generateTreeShakingSharedResolutionCode(enabled) {
|
|
@@ -4240,8 +4959,9 @@ function getHostAutoInitState(options) {
|
|
|
4240
4959
|
if (!options) return legacyHostAutoInitState;
|
|
4241
4960
|
let state = hostAutoInitStates.get(options);
|
|
4242
4961
|
if (!state) {
|
|
4962
|
+
const ownerKey = getLocalOwnerKey(options);
|
|
4243
4963
|
state = {
|
|
4244
|
-
module: new VirtualModule("hostAutoInit", HOST_AUTO_INIT_TAG, "",
|
|
4964
|
+
module: new VirtualModule("hostAutoInit", HOST_AUTO_INIT_TAG, "", ownerKey),
|
|
4245
4965
|
remoteEntryId: REMOTE_ENTRY_ID,
|
|
4246
4966
|
command: "build"
|
|
4247
4967
|
};
|
|
@@ -4943,10 +5663,11 @@ const __mfCurrentScript = document.currentScript;
|
|
|
4943
5663
|
const entrySrc = stripBase(originalSrc);
|
|
4944
5664
|
addEntryRemoteImports(entrySrc);
|
|
4945
5665
|
const resolvedEntrySrc = entrySrc.startsWith("virtual:") ? toViteEncodedId(entrySrc) : entrySrc;
|
|
4946
|
-
|
|
5666
|
+
const query = new URLSearchParams({
|
|
4947
5667
|
init: sanitizeDevEntryPath(stripBase(devEntryPath)),
|
|
4948
5668
|
entry: sanitizeDevEntryPath(resolvedEntrySrc)
|
|
4949
|
-
}).toString()
|
|
5669
|
+
}).toString();
|
|
5670
|
+
return toViteEncodedId(`${DEV_HTML_PROXY_PREFIX}${query}`);
|
|
4950
5671
|
});
|
|
4951
5672
|
return html === c ? injectEntryScript(c, stripBase(devEntryPath)) : html;
|
|
4952
5673
|
}
|
|
@@ -5332,7 +6053,7 @@ const REMOTE_HMR_ENDPOINT = "__mf_hmr";
|
|
|
5332
6053
|
const REMOTE_HMR_EVENT = "mf:remote-update";
|
|
5333
6054
|
const REMOTE_HMR_CONNECT_RETRY_DELAY_MS = 1e3;
|
|
5334
6055
|
const REMOTE_HMR_CONNECT_MAX_RETRIES = 10;
|
|
5335
|
-
function getBasePath(base) {
|
|
6056
|
+
function getBasePath$1(base) {
|
|
5336
6057
|
if (!base) return "/";
|
|
5337
6058
|
if (base.startsWith("http://") || base.startsWith("https://")) try {
|
|
5338
6059
|
return new URL(base).pathname || "/";
|
|
@@ -5342,11 +6063,11 @@ function getBasePath(base) {
|
|
|
5342
6063
|
return base;
|
|
5343
6064
|
}
|
|
5344
6065
|
function getRemoteHmrPath(base) {
|
|
5345
|
-
return `${getBasePath(base).replace(/\/?$/, "/")}${REMOTE_HMR_ENDPOINT}`.replace(/\/{2,}/g, "/");
|
|
6066
|
+
return `${getBasePath$1(base).replace(/\/?$/, "/")}${REMOTE_HMR_ENDPOINT}`.replace(/\/{2,}/g, "/");
|
|
5346
6067
|
}
|
|
5347
6068
|
function getHmrWsPath(base, hmrPath) {
|
|
5348
|
-
const normalizedBase = getBasePath(base);
|
|
5349
|
-
const normalizedPath = getBasePath(hmrPath || "");
|
|
6069
|
+
const normalizedBase = getBasePath$1(base);
|
|
6070
|
+
const normalizedPath = getBasePath$1(hmrPath || "");
|
|
5350
6071
|
if (!normalizedPath || normalizedPath === "/") return normalizedBase;
|
|
5351
6072
|
return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
|
|
5352
6073
|
}
|
|
@@ -6267,7 +6988,8 @@ function generateExposesSSR(options, reactIslandExposes = /* @__PURE__ */ new Se
|
|
|
6267
6988
|
//#region src/virtualModules/virtualRemoteEntrySSR.ts
|
|
6268
6989
|
const REMOTE_ENTRY_SSR_ID = "virtual:mf-REMOTE_ENTRY_SSR_ID";
|
|
6269
6990
|
function getRemoteEntrySSRId(options) {
|
|
6270
|
-
|
|
6991
|
+
const scopedKey = `${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
6992
|
+
return `${REMOTE_ENTRY_SSR_ID}:${scopedKey}`;
|
|
6271
6993
|
}
|
|
6272
6994
|
function getSsrRemoteEntryFileName(browserFilename) {
|
|
6273
6995
|
const ext = browserFilename.match(/\.[^.]+$/)?.[0] || ".js";
|
|
@@ -6345,6 +7067,318 @@ function generateRemoteEntrySSR(options) {
|
|
|
6345
7067
|
`;
|
|
6346
7068
|
}
|
|
6347
7069
|
//#endregion
|
|
7070
|
+
//#region src/plugins/pluginDts.ts
|
|
7071
|
+
var pluginDts_exports = /* @__PURE__ */ __exportAll({
|
|
7072
|
+
DEFAULT_PUBLIC_TYPES_FOLDER: () => DEFAULT_PUBLIC_TYPES_FOLDER,
|
|
7073
|
+
createDevDtsAssetMiddleware: () => createDevDtsAssetMiddleware,
|
|
7074
|
+
default: () => pluginDts,
|
|
7075
|
+
getDevDtsAssetPaths: () => getDevDtsAssetPaths,
|
|
7076
|
+
resolveDtsPluginOptions: () => resolveDtsPluginOptions
|
|
7077
|
+
});
|
|
7078
|
+
const DEFAULT_DEV_OPTIONS = {
|
|
7079
|
+
disableLiveReload: true,
|
|
7080
|
+
disableHotTypesReload: false,
|
|
7081
|
+
disableDynamicRemoteTypeHints: false
|
|
7082
|
+
};
|
|
7083
|
+
const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
|
|
7084
|
+
const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
|
|
7085
|
+
const DEV_TYPES_FOLDER = ".dev-server";
|
|
7086
|
+
const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
|
|
7087
|
+
const forkDevWorkerPath = (() => {
|
|
7088
|
+
return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
|
|
7089
|
+
})();
|
|
7090
|
+
var DevWorker = class {
|
|
7091
|
+
worker = rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
|
|
7092
|
+
constructor(options) {
|
|
7093
|
+
this.worker.connect(options);
|
|
7094
|
+
}
|
|
7095
|
+
update() {
|
|
7096
|
+
this.worker.process?.send?.({
|
|
7097
|
+
type: rpc.RpcGMCallTypes.CALL,
|
|
7098
|
+
id: this.worker.id,
|
|
7099
|
+
args: [void 0, "update"]
|
|
7100
|
+
});
|
|
7101
|
+
}
|
|
7102
|
+
exit() {
|
|
7103
|
+
this.worker.terminate();
|
|
7104
|
+
}
|
|
7105
|
+
};
|
|
7106
|
+
const normalizeDevOptions = (dev) => {
|
|
7107
|
+
if (dev === false) return false;
|
|
7108
|
+
if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
|
|
7109
|
+
return {
|
|
7110
|
+
...DEFAULT_DEV_OPTIONS,
|
|
7111
|
+
...dev
|
|
7112
|
+
};
|
|
7113
|
+
};
|
|
7114
|
+
const buildDtsModuleFederationConfig = (options) => {
|
|
7115
|
+
const exposes = {};
|
|
7116
|
+
Object.entries(options.exposes).forEach(([key, value]) => {
|
|
7117
|
+
if (value.import) exposes[key] = value.import;
|
|
7118
|
+
});
|
|
7119
|
+
const remotes = {};
|
|
7120
|
+
Object.entries(options.remotes).forEach(([key, remote]) => {
|
|
7121
|
+
if (!remote.entry) return;
|
|
7122
|
+
const entryGlobalName = remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key;
|
|
7123
|
+
remotes[key] = `${entryGlobalName}@${remote.entry}`;
|
|
7124
|
+
});
|
|
7125
|
+
return {
|
|
7126
|
+
...options,
|
|
7127
|
+
exposes,
|
|
7128
|
+
remotes
|
|
7129
|
+
};
|
|
7130
|
+
};
|
|
7131
|
+
const resolveOutputDir = (config) => {
|
|
7132
|
+
const { outDir } = config.build;
|
|
7133
|
+
if (path$1.isAbsolute(outDir)) return normalizePathForImport(path$1.relative(config.root, outDir));
|
|
7134
|
+
return outDir;
|
|
7135
|
+
};
|
|
7136
|
+
const ensureRuntimePlugin = (options, pluginId) => {
|
|
7137
|
+
if (!options.runtimePlugins.some((plugin) => {
|
|
7138
|
+
if (typeof plugin === "string") return plugin === pluginId;
|
|
7139
|
+
return plugin[0] === pluginId;
|
|
7140
|
+
})) options.runtimePlugins.push(pluginId);
|
|
7141
|
+
};
|
|
7142
|
+
const getExposeImportPaths = (options) => {
|
|
7143
|
+
return Object.values(options.exposes).map((value) => {
|
|
7144
|
+
return value.import;
|
|
7145
|
+
}).filter((value) => Boolean(value));
|
|
7146
|
+
};
|
|
7147
|
+
const usesVueSfcExposes = (options) => {
|
|
7148
|
+
return getExposeImportPaths(options).some((value) => value.endsWith(".vue"));
|
|
7149
|
+
};
|
|
7150
|
+
const resolveDtsPluginOptions = (dts, options, context) => {
|
|
7151
|
+
if (dts === false) return false;
|
|
7152
|
+
const inferredGenerateTypesDefaults = { generateAPITypes: true };
|
|
7153
|
+
if (usesVueSfcExposes(options) && hasPackageDependency("vue-tsc", context)) inferredGenerateTypesDefaults.compilerInstance = "vue-tsc";
|
|
7154
|
+
if (dts === true || typeof dts === "undefined") return { generateTypes: inferredGenerateTypesDefaults };
|
|
7155
|
+
const generateTypes = dts.generateTypes;
|
|
7156
|
+
return {
|
|
7157
|
+
...dts,
|
|
7158
|
+
generateTypes: generateTypes === false ? false : {
|
|
7159
|
+
...inferredGenerateTypesDefaults,
|
|
7160
|
+
...generateTypes === true || typeof generateTypes === "undefined" ? {} : generateTypes
|
|
7161
|
+
}
|
|
7162
|
+
};
|
|
7163
|
+
};
|
|
7164
|
+
const getBasePath = (base) => {
|
|
7165
|
+
if (base.startsWith("http://") || base.startsWith("https://")) return new URL(base).pathname.replace(/\/$/, "") || "/";
|
|
7166
|
+
return base.replace(/\/$/, "") || "/";
|
|
7167
|
+
};
|
|
7168
|
+
const joinBaseAndAsset = (base, assetFileName) => {
|
|
7169
|
+
const basePath = getBasePath(base);
|
|
7170
|
+
return `${basePath === "/" ? "" : basePath}/${assetFileName}`.replace(/\/{2,}/g, "/");
|
|
7171
|
+
};
|
|
7172
|
+
const getDevDtsAssetPaths = (options) => {
|
|
7173
|
+
const { outputDir, publicTypesFolder, root, base } = options;
|
|
7174
|
+
return {
|
|
7175
|
+
apiFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.d.ts`),
|
|
7176
|
+
apiRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.d.ts`),
|
|
7177
|
+
zipFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.zip`),
|
|
7178
|
+
zipRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.zip`)
|
|
7179
|
+
};
|
|
7180
|
+
};
|
|
7181
|
+
const createDevDtsAssetMiddleware = (assetPaths) => {
|
|
7182
|
+
return (req, res, next) => {
|
|
7183
|
+
const requestPath = req.url?.split("?")[0];
|
|
7184
|
+
const isZipRequest = requestPath === assetPaths.zipRequestPath;
|
|
7185
|
+
const isApiRequest = requestPath === assetPaths.apiRequestPath;
|
|
7186
|
+
if (!isZipRequest && !isApiRequest) {
|
|
7187
|
+
next();
|
|
7188
|
+
return;
|
|
7189
|
+
}
|
|
7190
|
+
const filePath = isZipRequest ? assetPaths.zipFilePath : assetPaths.apiFilePath;
|
|
7191
|
+
if (!fs.existsSync(filePath)) {
|
|
7192
|
+
res.statusCode = 404;
|
|
7193
|
+
res.end();
|
|
7194
|
+
return;
|
|
7195
|
+
}
|
|
7196
|
+
res.statusCode = 200;
|
|
7197
|
+
res.setHeader("Content-Type", isZipRequest ? "application/x-gzip" : "application/typescript");
|
|
7198
|
+
if (req.method === "HEAD") {
|
|
7199
|
+
res.end();
|
|
7200
|
+
return;
|
|
7201
|
+
}
|
|
7202
|
+
const stream = fs.createReadStream(filePath);
|
|
7203
|
+
stream.on("error", () => {
|
|
7204
|
+
if (!res.headersSent) res.statusCode = 500;
|
|
7205
|
+
res.end();
|
|
7206
|
+
});
|
|
7207
|
+
res.on("close", () => {
|
|
7208
|
+
stream.destroy();
|
|
7209
|
+
});
|
|
7210
|
+
stream.pipe(res);
|
|
7211
|
+
};
|
|
7212
|
+
};
|
|
7213
|
+
const normalizeDevDtsOptions = (dts, context) => {
|
|
7214
|
+
return normalizeOptions(isTSProject(dts, context), {
|
|
7215
|
+
generateTypes: { compileInChildProcess: true },
|
|
7216
|
+
consumeTypes: { consumeAPITypes: true },
|
|
7217
|
+
extraOptions: {},
|
|
7218
|
+
displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
|
|
7219
|
+
}, "mfOptions.dts")(dts);
|
|
7220
|
+
};
|
|
7221
|
+
const logDtsError = (error, dtsOptions) => {
|
|
7222
|
+
if (dtsOptions === false) return;
|
|
7223
|
+
if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
|
|
7224
|
+
mfError(error);
|
|
7225
|
+
};
|
|
7226
|
+
function pluginDts(options) {
|
|
7227
|
+
if (options.dts === false) return [];
|
|
7228
|
+
const baseDtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
|
|
7229
|
+
const getDtsModuleFederationConfig = (context) => ({
|
|
7230
|
+
...baseDtsModuleFederationConfig,
|
|
7231
|
+
dts: resolveDtsPluginOptions(options.dts, options, context)
|
|
7232
|
+
});
|
|
7233
|
+
let resolvedConfig;
|
|
7234
|
+
let devWorker;
|
|
7235
|
+
let normalizedDevOptions;
|
|
7236
|
+
let hasGeneratedBundle = false;
|
|
7237
|
+
return [{
|
|
7238
|
+
name: "module-federation-dts-dev",
|
|
7239
|
+
apply: "serve",
|
|
7240
|
+
config(config) {
|
|
7241
|
+
normalizedDevOptions = normalizeDevOptions(options.dev);
|
|
7242
|
+
if (!normalizedDevOptions) return;
|
|
7243
|
+
if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
|
|
7244
|
+
ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
|
|
7245
|
+
const define = config.define ? { ...config.define } : {};
|
|
7246
|
+
if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
|
|
7247
|
+
config.define = define;
|
|
7248
|
+
},
|
|
7249
|
+
configResolved(config) {
|
|
7250
|
+
resolvedConfig = config;
|
|
7251
|
+
},
|
|
7252
|
+
configureServer(server) {
|
|
7253
|
+
if (!normalizedDevOptions || !resolvedConfig) return;
|
|
7254
|
+
const devOptions = normalizedDevOptions;
|
|
7255
|
+
if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
|
|
7256
|
+
if (!options.name) throw createModuleFederationError("name is required if you want to enable dev server!");
|
|
7257
|
+
const outputDir = resolveOutputDir(resolvedConfig);
|
|
7258
|
+
const dtsModuleFederationConfig = getDtsModuleFederationConfig(resolvedConfig.root);
|
|
7259
|
+
const normalizedDtsOptions = normalizeDevDtsOptions(dtsModuleFederationConfig.dts, resolvedConfig.root);
|
|
7260
|
+
if (typeof normalizedDtsOptions !== "object") return;
|
|
7261
|
+
const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
|
|
7262
|
+
const remote = normalizedGenerateTypes === false ? void 0 : {
|
|
7263
|
+
implementation: normalizedDtsOptions.implementation,
|
|
7264
|
+
context: resolvedConfig.root,
|
|
7265
|
+
outputDir,
|
|
7266
|
+
moduleFederationConfig: { ...dtsModuleFederationConfig },
|
|
7267
|
+
hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
|
|
7268
|
+
...normalizedGenerateTypes,
|
|
7269
|
+
typesFolder: DEV_TYPES_FOLDER
|
|
7270
|
+
};
|
|
7271
|
+
if (remote) server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({
|
|
7272
|
+
outputDir,
|
|
7273
|
+
publicTypesFolder: remote.hostRemoteTypesFolder || "@mf-types",
|
|
7274
|
+
root: resolvedConfig.root,
|
|
7275
|
+
base: resolvedConfig.base
|
|
7276
|
+
})));
|
|
7277
|
+
if (remote && !remote.tsConfigPath && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
|
|
7278
|
+
const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
|
|
7279
|
+
const host = normalizedConsumeTypes === false ? void 0 : {
|
|
7280
|
+
implementation: normalizedDtsOptions.implementation,
|
|
7281
|
+
context: resolvedConfig.root,
|
|
7282
|
+
moduleFederationConfig: dtsModuleFederationConfig,
|
|
7283
|
+
typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
|
|
7284
|
+
abortOnError: false,
|
|
7285
|
+
...normalizedConsumeTypes
|
|
7286
|
+
};
|
|
7287
|
+
const extraOptions = normalizedDtsOptions.extraOptions || {};
|
|
7288
|
+
if (!remote && !host && devOptions.disableLiveReload) return;
|
|
7289
|
+
const startDevWorker = async () => {
|
|
7290
|
+
let remoteTypeUrls;
|
|
7291
|
+
if (host) remoteTypeUrls = await new Promise((resolve) => {
|
|
7292
|
+
consumeTypesAPI({
|
|
7293
|
+
host,
|
|
7294
|
+
extraOptions,
|
|
7295
|
+
displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
|
|
7296
|
+
}, resolve);
|
|
7297
|
+
});
|
|
7298
|
+
devWorker = new DevWorker({
|
|
7299
|
+
name: options.name,
|
|
7300
|
+
remote,
|
|
7301
|
+
host: host ? {
|
|
7302
|
+
...host,
|
|
7303
|
+
remoteTypeUrls
|
|
7304
|
+
} : void 0,
|
|
7305
|
+
extraOptions,
|
|
7306
|
+
disableLiveReload: devOptions.disableLiveReload,
|
|
7307
|
+
disableHotTypesReload: devOptions.disableHotTypesReload
|
|
7308
|
+
});
|
|
7309
|
+
const update = () => devWorker?.update();
|
|
7310
|
+
server.watcher.on("change", update);
|
|
7311
|
+
server.watcher.on("add", update);
|
|
7312
|
+
server.watcher.on("unlink", update);
|
|
7313
|
+
server.httpServer?.once("close", () => {
|
|
7314
|
+
devWorker?.exit();
|
|
7315
|
+
server.watcher.off("change", update);
|
|
7316
|
+
server.watcher.off("add", update);
|
|
7317
|
+
server.watcher.off("unlink", update);
|
|
7318
|
+
});
|
|
7319
|
+
};
|
|
7320
|
+
startDevWorker().catch((error) => {
|
|
7321
|
+
logDtsError(error, normalizedDtsOptions);
|
|
7322
|
+
});
|
|
7323
|
+
}
|
|
7324
|
+
}, {
|
|
7325
|
+
name: "module-federation-dts-build",
|
|
7326
|
+
apply: "build",
|
|
7327
|
+
configResolved(config) {
|
|
7328
|
+
resolvedConfig = config;
|
|
7329
|
+
},
|
|
7330
|
+
async generateBundle() {
|
|
7331
|
+
if (hasGeneratedBundle) return;
|
|
7332
|
+
hasGeneratedBundle = true;
|
|
7333
|
+
if (!resolvedConfig) return;
|
|
7334
|
+
let normalizedDtsOptions;
|
|
7335
|
+
try {
|
|
7336
|
+
normalizedDtsOptions = normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root), resolvedConfig.root);
|
|
7337
|
+
} catch (error) {
|
|
7338
|
+
logDtsError(error, options.dts);
|
|
7339
|
+
return;
|
|
7340
|
+
}
|
|
7341
|
+
if (typeof normalizedDtsOptions !== "object") return;
|
|
7342
|
+
const context = resolvedConfig.root;
|
|
7343
|
+
const outputDir = resolveOutputDir(resolvedConfig);
|
|
7344
|
+
let consumeOptions;
|
|
7345
|
+
try {
|
|
7346
|
+
consumeOptions = normalizeConsumeTypesOptions({
|
|
7347
|
+
context,
|
|
7348
|
+
dtsOptions: normalizedDtsOptions,
|
|
7349
|
+
pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
|
|
7350
|
+
});
|
|
7351
|
+
} catch (error) {
|
|
7352
|
+
logDtsError(error, normalizedDtsOptions);
|
|
7353
|
+
return;
|
|
7354
|
+
}
|
|
7355
|
+
if (consumeOptions?.host?.typesOnBuild) try {
|
|
7356
|
+
await consumeTypesAPI(consumeOptions);
|
|
7357
|
+
} catch (error) {
|
|
7358
|
+
logDtsError(error, normalizedDtsOptions);
|
|
7359
|
+
}
|
|
7360
|
+
let generateOptions;
|
|
7361
|
+
try {
|
|
7362
|
+
generateOptions = normalizeGenerateTypesOptions({
|
|
7363
|
+
context,
|
|
7364
|
+
outputDir,
|
|
7365
|
+
dtsOptions: normalizedDtsOptions,
|
|
7366
|
+
pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
|
|
7367
|
+
});
|
|
7368
|
+
} catch (error) {
|
|
7369
|
+
logDtsError(error, normalizedDtsOptions);
|
|
7370
|
+
return;
|
|
7371
|
+
}
|
|
7372
|
+
if (!generateOptions) return;
|
|
7373
|
+
try {
|
|
7374
|
+
await generateTypesAPI({ dtsManagerOptions: generateOptions });
|
|
7375
|
+
} catch (error) {
|
|
7376
|
+
logDtsError(error, normalizedDtsOptions);
|
|
7377
|
+
}
|
|
7378
|
+
}
|
|
7379
|
+
}];
|
|
7380
|
+
}
|
|
7381
|
+
//#endregion
|
|
6348
7382
|
//#region src/plugins/pluginMFManifest.ts
|
|
6349
7383
|
/**
|
|
6350
7384
|
* Resolves the build version for the module federation manifest.
|
|
@@ -6447,9 +7481,20 @@ const Manifest = (providedOptions) => {
|
|
|
6447
7481
|
return [{
|
|
6448
7482
|
name: "module-federation-manifest",
|
|
6449
7483
|
apply: "serve",
|
|
7484
|
+
/**
|
|
7485
|
+
* Stores resolved Vite config for later use
|
|
7486
|
+
*/
|
|
7487
|
+
/**
|
|
7488
|
+
* Finalizes configuration after all plugins are resolved
|
|
7489
|
+
* @param config - Fully resolved Vite config
|
|
7490
|
+
*/
|
|
6450
7491
|
configResolved(config) {
|
|
6451
7492
|
viteConfig = config;
|
|
6452
7493
|
},
|
|
7494
|
+
/**
|
|
7495
|
+
* Configures dev server middleware to handle manifest requests
|
|
7496
|
+
* @param server - Vite dev server instance
|
|
7497
|
+
*/
|
|
6453
7498
|
configureServer(server) {
|
|
6454
7499
|
server.middlewares.use((req, res, next) => {
|
|
6455
7500
|
const devRemoteEntryFile = resolveDevRemoteEntryFileName(filename);
|
|
@@ -6507,6 +7552,11 @@ const Manifest = (providedOptions) => {
|
|
|
6507
7552
|
}, {
|
|
6508
7553
|
name: "module-federation-manifest",
|
|
6509
7554
|
enforce: "post",
|
|
7555
|
+
/**
|
|
7556
|
+
* Initial plugin configuration
|
|
7557
|
+
* @param config - Vite config object
|
|
7558
|
+
* @param command - Current Vite command (serve/build)
|
|
7559
|
+
*/
|
|
6510
7560
|
config(config, { command }) {
|
|
6511
7561
|
_command = command;
|
|
6512
7562
|
if (!config.build) config.build = {};
|
|
@@ -6521,6 +7571,11 @@ const Manifest = (providedOptions) => {
|
|
|
6521
7571
|
if (_command === "serve") base = (config.server.origin || "") + config.base;
|
|
6522
7572
|
publicPath = mfOptions.publicPath === "auto" ? "auto" : resolvePublicPath(mfOptions, base, _originalConfigBase);
|
|
6523
7573
|
},
|
|
7574
|
+
/**
|
|
7575
|
+
* Generates the module federation manifest file
|
|
7576
|
+
* @param options - Rollup output options
|
|
7577
|
+
* @param bundle - Generated bundle assets
|
|
7578
|
+
*/
|
|
6524
7579
|
async generateBundle(_options, bundle) {
|
|
6525
7580
|
if (!mfManifestName) return;
|
|
6526
7581
|
if (this.environment?.name === "ssr") return;
|
|
@@ -7091,11 +8146,23 @@ function pluginProxyRemotes_default(options) {
|
|
|
7091
8146
|
enableSsrInit = getSsrCapabilities(parseInt(version, 10), command, Object.keys(remotes).length > 0).enableSsrInitBootstrap;
|
|
7092
8147
|
},
|
|
7093
8148
|
resolveId(source, importer) {
|
|
8149
|
+
const resolvedIslandConsumerId = resolveReactIslandConsumerId(source);
|
|
8150
|
+
if (resolvedIslandConsumerId) return resolvedIslandConsumerId;
|
|
8151
|
+
const islandRemoteId = getReactIslandImportRemoteId(source);
|
|
8152
|
+
if (islandRemoteId) for (const remoteAlias of Object.keys(remotes)) {
|
|
8153
|
+
if (islandRemoteId !== remoteAlias && !islandRemoteId.startsWith(`${remoteAlias}/`)) continue;
|
|
8154
|
+
addUsedRemote(remoteAlias, islandRemoteId, options);
|
|
8155
|
+
refreshHostAutoInit(options);
|
|
8156
|
+
return `\0${getReactIslandServerImportId(islandRemoteId)}`;
|
|
8157
|
+
}
|
|
7094
8158
|
if (!filterId(source)) return;
|
|
7095
8159
|
for (const remoteAlias of Object.keys(remotes)) {
|
|
7096
8160
|
if (source !== remoteAlias && !source.startsWith(`${remoteAlias}/`)) continue;
|
|
7097
8161
|
return resolveRemoteId(this, source, importer, remoteAlias);
|
|
7098
8162
|
}
|
|
8163
|
+
},
|
|
8164
|
+
load(id) {
|
|
8165
|
+
return loadReactIslandConsumerModule(id);
|
|
7099
8166
|
}
|
|
7100
8167
|
};
|
|
7101
8168
|
}
|
|
@@ -7299,7 +8366,7 @@ function proxySharedModule(options) {
|
|
|
7299
8366
|
load(id) {
|
|
7300
8367
|
if (id === getResolvedLocalSharedImportMapId(federationOptions)) return parsePromise.then((_) => {
|
|
7301
8368
|
refreshTreeShakingModules(federationOptions);
|
|
7302
|
-
const providerPackages = new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
|
|
8369
|
+
const providerPackages = /* @__PURE__ */ new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
|
|
7303
8370
|
for (const pkg of providerPackages) {
|
|
7304
8371
|
const sharedKey = findSharedKeyForSource(pkg, shared);
|
|
7305
8372
|
const shareItem = shared[pkg] || (sharedKey ? shared[sharedKey] : void 0);
|
|
@@ -7731,14 +8798,14 @@ function pluginRemoteNamedExports(options) {
|
|
|
7731
8798
|
//#region src/plugins/pluginSSRRemoteEntry.ts
|
|
7732
8799
|
const MAX_RUNNER_BODY_BYTES = 1024 * 1024;
|
|
7733
8800
|
const MAX_RUNNER_START_OFFSET = 1024 * 1024;
|
|
7734
|
-
const ALLOWED_RUNNER_INVOKE_NAMES = new Set(["fetchModule", "getBuiltins"]);
|
|
8801
|
+
const ALLOWED_RUNNER_INVOKE_NAMES = /* @__PURE__ */ new Set(["fetchModule", "getBuiltins"]);
|
|
7735
8802
|
const VITE_FS_PREFIX = "/@fs/";
|
|
7736
8803
|
function isPlainObject(value) {
|
|
7737
8804
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
7738
8805
|
}
|
|
7739
8806
|
function isSafeRunnerFetchModuleOptions(value) {
|
|
7740
8807
|
if (!isPlainObject(value)) return false;
|
|
7741
|
-
const allowedKeys = new Set([
|
|
8808
|
+
const allowedKeys = /* @__PURE__ */ new Set([
|
|
7742
8809
|
"cached",
|
|
7743
8810
|
"startOffset",
|
|
7744
8811
|
"inlineSourceMap"
|
|
@@ -7876,7 +8943,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
7876
8943
|
...options.ssrExternals ?? []
|
|
7877
8944
|
];
|
|
7878
8945
|
const ssrOnlyExternalPattern = new RegExp(`^(${ssrOnlyExternals.map((e) => e.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&")).join("|")})(\\/.*)?$`);
|
|
7879
|
-
const ssrModuleIds = new Set([remoteEntrySSRId, virtualExposesSSRId]);
|
|
8946
|
+
const ssrModuleIds = /* @__PURE__ */ new Set([remoteEntrySSRId, virtualExposesSSRId]);
|
|
7880
8947
|
const resolvedAbsToPackage = /* @__PURE__ */ new Map();
|
|
7881
8948
|
let isServe = false;
|
|
7882
8949
|
let viteConfig;
|
|
@@ -7929,7 +8996,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
7929
8996
|
},
|
|
7930
8997
|
configureServer(server) {
|
|
7931
8998
|
const base = "/__mf_ssr__";
|
|
7932
|
-
const basePath = getBasePath$
|
|
8999
|
+
const basePath = getBasePath$2(viteConfig?.base);
|
|
7933
9000
|
const ssrEntryFileName = getSsrRemoteEntryFileName(options.filename);
|
|
7934
9001
|
if (isNuxtProject || isNuxtClientBase(basePath)) server.middlewares.use((req, _res, next) => {
|
|
7935
9002
|
if (req.url?.replace(/\?.*/, "") === `${basePath}/${ssrEntryFileName}`) req.url = `${basePath}/__mf_ssr__/${ssrEntryFileName}`;
|
|
@@ -8073,7 +9140,7 @@ function collectEntryOutputFiles(bundle, entryFileName) {
|
|
|
8073
9140
|
const file = bundle[fileName];
|
|
8074
9141
|
if (!file) return;
|
|
8075
9142
|
files.add(fileName);
|
|
8076
|
-
const dependencies = new Set([
|
|
9143
|
+
const dependencies = /* @__PURE__ */ new Set([
|
|
8077
9144
|
...file.imports || [],
|
|
8078
9145
|
...file.dynamicImports || [],
|
|
8079
9146
|
...file.implicitlyLoadedBefore || [],
|
|
@@ -8102,9 +9169,20 @@ const VarRemoteEntry = (providedOptions) => {
|
|
|
8102
9169
|
return [{
|
|
8103
9170
|
name: "module-federation-var-remote-entry",
|
|
8104
9171
|
apply: "serve",
|
|
9172
|
+
/**
|
|
9173
|
+
* Stores resolved Vite config for later use
|
|
9174
|
+
*/
|
|
9175
|
+
/**
|
|
9176
|
+
* Finalizes configuration after all plugins are resolved
|
|
9177
|
+
* @param config - Fully resolved Vite config
|
|
9178
|
+
*/
|
|
8105
9179
|
configResolved(config) {
|
|
8106
9180
|
viteConfig = config;
|
|
8107
9181
|
},
|
|
9182
|
+
/**
|
|
9183
|
+
* Configures dev server middleware to handle varRemoteEntry requests
|
|
9184
|
+
* @param server - Vite dev server instance
|
|
9185
|
+
*/
|
|
8108
9186
|
configureServer(server) {
|
|
8109
9187
|
server.middlewares.use((req, res, next) => {
|
|
8110
9188
|
if (!varFilename) {
|
|
@@ -8121,12 +9199,22 @@ const VarRemoteEntry = (providedOptions) => {
|
|
|
8121
9199
|
}, {
|
|
8122
9200
|
name: "module-federation-var-remote-entry",
|
|
8123
9201
|
enforce: "post",
|
|
9202
|
+
/**
|
|
9203
|
+
* Initial plugin configuration
|
|
9204
|
+
* @param config - Vite config object
|
|
9205
|
+
* @param command - Current Vite command (serve/build)
|
|
9206
|
+
*/
|
|
8124
9207
|
config(config) {
|
|
8125
9208
|
if (!config.build) config.build = {};
|
|
8126
9209
|
},
|
|
8127
9210
|
configResolved(config) {
|
|
8128
9211
|
viteConfig = config;
|
|
8129
9212
|
},
|
|
9213
|
+
/**
|
|
9214
|
+
* Generates the module federation "var" remote entry file
|
|
9215
|
+
* @param options - Rollup output options
|
|
9216
|
+
* @param bundle - Generated bundle assets
|
|
9217
|
+
*/
|
|
8130
9218
|
async generateBundle(_options, bundle) {
|
|
8131
9219
|
if (!varFilename) return;
|
|
8132
9220
|
if (!isValidVarName(name)) mfWarn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);
|
|
@@ -8278,7 +9366,7 @@ const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
|
|
|
8278
9366
|
];
|
|
8279
9367
|
const VITE_DEV_PROD_CONDITION = "development|production";
|
|
8280
9368
|
function appendConditions(conditions, fallbackConditions) {
|
|
8281
|
-
return [
|
|
9369
|
+
return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
|
|
8282
9370
|
}
|
|
8283
9371
|
function resolveViteModeCondition(conditions, isProduction) {
|
|
8284
9372
|
const modeCondition = isProduction ? "production" : "development";
|
|
@@ -8448,7 +9536,7 @@ function canResolveSharedSubpath(subpath, projectRoot) {
|
|
|
8448
9536
|
return false;
|
|
8449
9537
|
}
|
|
8450
9538
|
}
|
|
8451
|
-
const VITE_DEV_IMPORT_CONDITIONS = new Set([
|
|
9539
|
+
const VITE_DEV_IMPORT_CONDITIONS = /* @__PURE__ */ new Set([
|
|
8452
9540
|
"browser",
|
|
8453
9541
|
"development",
|
|
8454
9542
|
"import",
|
|
@@ -8738,7 +9826,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
8738
9826
|
}
|
|
8739
9827
|
};
|
|
8740
9828
|
}
|
|
8741
|
-
const SSR_ONLY_PLUGINS = new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
9829
|
+
const SSR_ONLY_PLUGINS = /* @__PURE__ */ new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
8742
9830
|
function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaultDisableSnapshot }) {
|
|
8743
9831
|
const envTargetDefineValue = !options.target && isAstro ? "undefined" : JSON.stringify(target);
|
|
8744
9832
|
if (!("ENV_TARGET" in define)) define.ENV_TARGET = envTargetDefineValue;
|
|
@@ -8750,7 +9838,7 @@ function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaul
|
|
|
8750
9838
|
}
|
|
8751
9839
|
function loadPluginDts(options) {
|
|
8752
9840
|
if (options.dts === false) return [];
|
|
8753
|
-
return [
|
|
9841
|
+
return [Promise.resolve().then(() => pluginDts_exports).then(({ default: pluginDts }) => pluginDts(options))];
|
|
8754
9842
|
}
|
|
8755
9843
|
const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
|
|
8756
9844
|
function isInjectExternalRuntimeCorePlugin(specifier) {
|
|
@@ -9230,7 +10318,8 @@ function federation(mfUserOptions) {
|
|
|
9230
10318
|
};
|
|
9231
10319
|
res.end = (chunk, ...args) => {
|
|
9232
10320
|
if (chunk) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
9233
|
-
|
|
10321
|
+
const body = normalizeVinextRscPreloadHints(Buffer.concat(chunks).toString());
|
|
10322
|
+
return end(body, ...args);
|
|
9234
10323
|
};
|
|
9235
10324
|
next();
|
|
9236
10325
|
});
|