@module-federation/vite 1.20.5 → 1.20.7
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/dtsConstants-DyJrx8ah.js +476 -0
- package/lib/index.js +629 -1024
- package/lib/pluginDts-BNCg4Gri.js +312 -0
- package/lib/{ssrEntryLoader-Ccr0zMrr.js → ssrEntryLoader-0NnTjWR1.js} +11 -8
- package/lib/{ssrVmStrategy-DTJITp2Z.js → ssrVmStrategy-B0fCaHs5.js} +1 -1
- package/lib/utils/ssrEntryLoader.js +1 -1
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { n as normalizePathForImport, r as rebaseImport } from "./buildPaths-BkaQHrd2.js";
|
|
2
|
-
import { a as
|
|
2
|
+
import { a as getPackageDetectionCwd, c as getSharedCacheDescriptor, d as packageNameDecode, f as packageNameEncode, g as createModuleFederationError, h as sharedCacheHelperCode, i as getIsRolldown, l as hasPackageDependency, m as setPackageDetectionCwd, n as getInstalledPackageEntry, o as getPackageName, p as resolveImportPath, r as getInstalledPackageJson, s as getPackageNameFromNodeModulePath, u as isNuxtProjectRoot, v as mfWarn } from "./dtsConstants-DyJrx8ah.js";
|
|
3
|
+
import { a as getCommonSharedSubpaths, c as isNodeModulePath, d as normalizeNodeModulePath, f as resolvePublicPath, i as getCommonSharedSubpathFromNodeModulePath, l as isNuxtClientBase, n as filterId, o as getMatchingNodeModuleSubpath, r as getBasePath$1, s as isAssetLikeImport, t as ensureTrailingSlash, u as isViteOptimizableEntry } from "./pathNormalization-DvgU8LIp.js";
|
|
3
4
|
import { createRequire } from "node:module";
|
|
4
5
|
import * as fs$2 from "fs";
|
|
5
|
-
import
|
|
6
|
+
import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
|
|
6
7
|
import { createRequire as createRequire$1 } from "module";
|
|
7
8
|
import * as path$1 from "node:path";
|
|
8
9
|
import path, { basename } from "node:path";
|
|
@@ -12,21 +13,6 @@ import { createHash } from "node:crypto";
|
|
|
12
13
|
import * as fs$1 from "node:fs";
|
|
13
14
|
import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
|
|
14
15
|
import { pathToFileURL as pathToFileURL$1 } from "node:url";
|
|
15
|
-
import { normalizeOptions } from "@module-federation/sdk";
|
|
16
|
-
import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
|
|
17
|
-
import { rpc } from "@module-federation/dts-plugin/core";
|
|
18
|
-
//#region \0rolldown/runtime.js
|
|
19
|
-
var __defProp = Object.defineProperty;
|
|
20
|
-
var __exportAll = (all, no_symbols) => {
|
|
21
|
-
let target = {};
|
|
22
|
-
for (var name in all) __defProp(target, name, {
|
|
23
|
-
get: all[name],
|
|
24
|
-
enumerable: true
|
|
25
|
-
});
|
|
26
|
-
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
27
|
-
return target;
|
|
28
|
-
};
|
|
29
|
-
//#endregion
|
|
30
16
|
//#region src/utils/codeRewriter.ts
|
|
31
17
|
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
32
18
|
var CodeRewriter = class {
|
|
@@ -338,475 +324,6 @@ function injectEntryScript(html, initSrc) {
|
|
|
338
324
|
return html.replace("<head>", `<head><script type="module" src=${JSON.stringify(src)}><\/script>`);
|
|
339
325
|
}
|
|
340
326
|
//#endregion
|
|
341
|
-
//#region src/utils/logger.ts
|
|
342
|
-
const MODULE_FEDERATION_LOG_PREFIX = "[Module Federation]";
|
|
343
|
-
function formatModuleFederationMessage(message) {
|
|
344
|
-
return `${MODULE_FEDERATION_LOG_PREFIX} ${message}`;
|
|
345
|
-
}
|
|
346
|
-
function createModuleFederationError(message) {
|
|
347
|
-
return new Error(formatModuleFederationMessage(message));
|
|
348
|
-
}
|
|
349
|
-
function toConsoleArgs(message, rest = []) {
|
|
350
|
-
if (typeof message === "string") return [formatModuleFederationMessage(message), ...rest];
|
|
351
|
-
if (message === void 0) return [MODULE_FEDERATION_LOG_PREFIX, ...rest];
|
|
352
|
-
return [
|
|
353
|
-
MODULE_FEDERATION_LOG_PREFIX,
|
|
354
|
-
message,
|
|
355
|
-
...rest
|
|
356
|
-
];
|
|
357
|
-
}
|
|
358
|
-
const moduleFederationConsole = {
|
|
359
|
-
log(message, ...rest) {
|
|
360
|
-
console.log(...toConsoleArgs(message, rest));
|
|
361
|
-
},
|
|
362
|
-
warn(message, ...rest) {
|
|
363
|
-
console.warn(...toConsoleArgs(message, rest));
|
|
364
|
-
},
|
|
365
|
-
error(message, ...rest) {
|
|
366
|
-
console.error(...toConsoleArgs(message, rest));
|
|
367
|
-
}
|
|
368
|
-
};
|
|
369
|
-
moduleFederationConsole.log;
|
|
370
|
-
const mfWarn = moduleFederationConsole.warn;
|
|
371
|
-
const mfError = moduleFederationConsole.error;
|
|
372
|
-
//#endregion
|
|
373
|
-
//#region src/utils/packageUtils.ts
|
|
374
|
-
const dependencyPresenceCache = /* @__PURE__ */ new Map();
|
|
375
|
-
let packageDetectionCwd;
|
|
376
|
-
function getDependencyCacheKey(cwd, dependencyName) {
|
|
377
|
-
return `${cwd}:${dependencyName}`;
|
|
378
|
-
}
|
|
379
|
-
const installedPackageJsonCache = /* @__PURE__ */ new Map();
|
|
380
|
-
function setPackageDetectionCwd(cwd) {
|
|
381
|
-
packageDetectionCwd = cwd;
|
|
382
|
-
}
|
|
383
|
-
function getPackageDetectionCwd() {
|
|
384
|
-
return packageDetectionCwd || process.cwd();
|
|
385
|
-
}
|
|
386
|
-
function resolveImportPath(specifier) {
|
|
387
|
-
const resolved = import.meta.resolve(specifier);
|
|
388
|
-
if (!resolved.startsWith("file:")) return resolved;
|
|
389
|
-
const filePath = fileURLToPath(resolved);
|
|
390
|
-
if (!existsSync(filePath)) {
|
|
391
|
-
const error = /* @__PURE__ */ new Error(`Cannot find module '${specifier}'`);
|
|
392
|
-
error.code = "MODULE_NOT_FOUND";
|
|
393
|
-
throw error;
|
|
394
|
-
}
|
|
395
|
-
return filePath;
|
|
396
|
-
}
|
|
397
|
-
const DEFAULT_EXPORT_CONDITIONS = [
|
|
398
|
-
"browser",
|
|
399
|
-
"import",
|
|
400
|
-
"module",
|
|
401
|
-
"default"
|
|
402
|
-
];
|
|
403
|
-
function resolveExportsEntry(exportsField, conditions = DEFAULT_EXPORT_CONDITIONS) {
|
|
404
|
-
return resolveExportsEntryWithConditions(exportsField, new Set(conditions));
|
|
405
|
-
}
|
|
406
|
-
function resolveExportsEntryWithConditions(exportsField, conditions) {
|
|
407
|
-
if (typeof exportsField === "string") return exportsField;
|
|
408
|
-
if (!exportsField || typeof exportsField !== "object") return void 0;
|
|
409
|
-
if (Array.isArray(exportsField)) {
|
|
410
|
-
for (const target of exportsField) {
|
|
411
|
-
const resolved = resolveExportsEntryWithConditions(target, conditions);
|
|
412
|
-
if (resolved) return resolved;
|
|
413
|
-
}
|
|
414
|
-
return;
|
|
415
|
-
}
|
|
416
|
-
const record = exportsField;
|
|
417
|
-
const rootExport = record["."];
|
|
418
|
-
if (rootExport) return resolveExportsEntryWithConditions(rootExport, conditions);
|
|
419
|
-
for (const [condition, value] of Object.entries(record)) {
|
|
420
|
-
if (condition !== "default" && !conditions.has(condition)) continue;
|
|
421
|
-
const target = resolveExportsEntryWithConditions(value, conditions);
|
|
422
|
-
if (target) return target;
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
function substituteExportsWildcard(target, patternMatch) {
|
|
426
|
-
if (typeof target === "string") return target.split("*").join(patternMatch);
|
|
427
|
-
if (Array.isArray(target)) return target.map((entry) => substituteExportsWildcard(entry, patternMatch));
|
|
428
|
-
if (target && typeof target === "object") {
|
|
429
|
-
const source = target;
|
|
430
|
-
const out = {};
|
|
431
|
-
for (const key of Object.keys(source)) out[key] = substituteExportsWildcard(source[key], patternMatch);
|
|
432
|
-
return out;
|
|
433
|
-
}
|
|
434
|
-
return target;
|
|
435
|
-
}
|
|
436
|
-
function matchExportsSubpath(record, subpath) {
|
|
437
|
-
if (subpath in record) return record[subpath];
|
|
438
|
-
let bestKey;
|
|
439
|
-
let bestBaseLength = -1;
|
|
440
|
-
let bestKeyLength = -1;
|
|
441
|
-
for (const key of Object.keys(record)) {
|
|
442
|
-
const wildcardIndex = key.indexOf("*");
|
|
443
|
-
if (wildcardIndex === -1) continue;
|
|
444
|
-
const patternBase = key.slice(0, wildcardIndex);
|
|
445
|
-
const patternTrailer = key.slice(wildcardIndex + 1);
|
|
446
|
-
if (patternTrailer.includes("*")) continue;
|
|
447
|
-
if (!subpath.startsWith(patternBase) || !subpath.endsWith(patternTrailer)) continue;
|
|
448
|
-
if (subpath.length <= patternBase.length + patternTrailer.length) continue;
|
|
449
|
-
if (patternBase.length > bestBaseLength || patternBase.length === bestBaseLength && key.length > bestKeyLength) {
|
|
450
|
-
bestKey = key;
|
|
451
|
-
bestBaseLength = patternBase.length;
|
|
452
|
-
bestKeyLength = key.length;
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
if (bestKey === void 0) return void 0;
|
|
456
|
-
const patternTrailer = bestKey.slice(bestKey.indexOf("*") + 1);
|
|
457
|
-
const patternMatch = subpath.slice(bestBaseLength, subpath.length - patternTrailer.length);
|
|
458
|
-
return substituteExportsWildcard(record[bestKey], patternMatch);
|
|
459
|
-
}
|
|
460
|
-
function getPackageExportsTarget(pkg, packageName, exportsField) {
|
|
461
|
-
if (typeof exportsField === "string") return pkg === packageName ? exportsField : void 0;
|
|
462
|
-
if (!exportsField || typeof exportsField !== "object") return void 0;
|
|
463
|
-
const record = exportsField;
|
|
464
|
-
const subpath = pkg === packageName ? "." : `.${pkg.slice(packageName.length)}`;
|
|
465
|
-
if (subpath !== ".") return matchExportsSubpath(record, subpath);
|
|
466
|
-
return record["."] ?? (!Object.keys(record).some((key) => key.startsWith(".")) ? record : void 0);
|
|
467
|
-
}
|
|
468
|
-
/**
|
|
469
|
-
* Escaping rules:
|
|
470
|
-
* Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
|
|
471
|
-
* @ => 1
|
|
472
|
-
* / => 2
|
|
473
|
-
* - => 3
|
|
474
|
-
* . => 4
|
|
475
|
-
*/
|
|
476
|
-
/**
|
|
477
|
-
* Encodes a package name into a valid file name.
|
|
478
|
-
* @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
|
|
479
|
-
* @returns {string} - The encoded file name.
|
|
480
|
-
*/
|
|
481
|
-
function packageNameEncode(name) {
|
|
482
|
-
if (typeof name !== "string") throw createModuleFederationError("A string package name is required");
|
|
483
|
-
return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
|
|
484
|
-
}
|
|
485
|
-
/**
|
|
486
|
-
* Decodes an encoded file name back to the original package name.
|
|
487
|
-
* @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
|
|
488
|
-
* @returns {string} - The decoded package name.
|
|
489
|
-
*/
|
|
490
|
-
function packageNameDecode(encoded) {
|
|
491
|
-
if (typeof encoded !== "string") throw createModuleFederationError("A string encoded file name is required");
|
|
492
|
-
return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
|
|
493
|
-
}
|
|
494
|
-
/**
|
|
495
|
-
* Removes any subpath from an npm package specifier and returns the package name only.
|
|
496
|
-
* @param {string} packageString - The package specifier, e.g., "@scope/pkg/runtime" or "react/jsx-runtime".
|
|
497
|
-
* @returns {string} - The base npm package name.
|
|
498
|
-
*/
|
|
499
|
-
function getPackageName(packageString) {
|
|
500
|
-
const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
|
|
501
|
-
return match ? match[0] : packageString;
|
|
502
|
-
}
|
|
503
|
-
function getPackageNameFromNodeModulePath(source) {
|
|
504
|
-
const normalized = source.replace(/\\/g, "/");
|
|
505
|
-
const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
|
|
506
|
-
if (nodeModulesIndex < 0) return;
|
|
507
|
-
const parts = normalized.slice(nodeModulesIndex + 14).split("/");
|
|
508
|
-
if (!parts[0]) return;
|
|
509
|
-
if (parts[0].startsWith("@")) return parts[1] ? `${parts[0]}/${parts[1]}` : void 0;
|
|
510
|
-
return parts[0];
|
|
511
|
-
}
|
|
512
|
-
function getSharedCacheKeyParts(input) {
|
|
513
|
-
const scope = (Array.isArray(input.scope) ? input.scope[0] : input.scope) || "default";
|
|
514
|
-
const id = input.singleton || !input.version ? input.pkg : `${input.pkg}@${input.version}`;
|
|
515
|
-
return {
|
|
516
|
-
scope,
|
|
517
|
-
id,
|
|
518
|
-
key: `${scope}:${id}`
|
|
519
|
-
};
|
|
520
|
-
}
|
|
521
|
-
function getSharedCacheDescriptor(pkg, shareItem) {
|
|
522
|
-
const parts = getSharedCacheKeyParts({
|
|
523
|
-
pkg,
|
|
524
|
-
singleton: shareItem.shareConfig.singleton,
|
|
525
|
-
version: shareItem.version,
|
|
526
|
-
scope: shareItem.scope
|
|
527
|
-
});
|
|
528
|
-
return {
|
|
529
|
-
canonical: parts.key,
|
|
530
|
-
...parts.scope === "default" ? { aliases: [parts.id] } : {}
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
const sharedCacheHelperCode = `const __mfGetSharedCacheDescriptor = (pkg, singleton, version, scope) => {
|
|
534
|
-
const normalizedScope = Array.isArray(scope) ? scope[0] : scope;
|
|
535
|
-
const scopeName = normalizedScope || "default";
|
|
536
|
-
const id = singleton || !version ? pkg : pkg + "@" + version;
|
|
537
|
-
const descriptor = { canonical: scopeName + ":" + id };
|
|
538
|
-
if (scopeName === "default") descriptor.aliases = [id];
|
|
539
|
-
return descriptor;
|
|
540
|
-
};
|
|
541
|
-
const __mfReadSharedCache = (cache, descriptor) => {
|
|
542
|
-
const value = cache[descriptor.canonical];
|
|
543
|
-
if (value !== undefined) return value;
|
|
544
|
-
const aliases = descriptor.aliases || [];
|
|
545
|
-
for (const alias of aliases) {
|
|
546
|
-
if (!Object.prototype.hasOwnProperty.call(cache, alias)) continue;
|
|
547
|
-
const aliasValue = cache[alias];
|
|
548
|
-
if (aliasValue !== undefined) {
|
|
549
|
-
cache[descriptor.canonical] = aliasValue;
|
|
550
|
-
return aliasValue;
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
return undefined;
|
|
554
|
-
};
|
|
555
|
-
const __mfSharedCacheListenersKey = Symbol.for("module-federation.shared-cache-listeners");
|
|
556
|
-
const __mfGetSharedCacheListeners = (cache) => {
|
|
557
|
-
let listeners = cache[__mfSharedCacheListenersKey];
|
|
558
|
-
if (listeners === undefined) {
|
|
559
|
-
listeners = Object.create(null);
|
|
560
|
-
Object.defineProperty(cache, __mfSharedCacheListenersKey, {
|
|
561
|
-
value: listeners,
|
|
562
|
-
enumerable: false,
|
|
563
|
-
configurable: false,
|
|
564
|
-
writable: false
|
|
565
|
-
});
|
|
566
|
-
}
|
|
567
|
-
return listeners;
|
|
568
|
-
};
|
|
569
|
-
const __mfSubscribeSharedCache = (cache, descriptor, listener) => {
|
|
570
|
-
const listeners = __mfGetSharedCacheListeners(cache);
|
|
571
|
-
(listeners[descriptor.canonical] ||= new Set()).add(listener);
|
|
572
|
-
};
|
|
573
|
-
const __mfSharedCacheOwnersKey = Symbol.for("module-federation.shared-cache-owners");
|
|
574
|
-
const __mfGetSharedCacheOwners = (cache) => {
|
|
575
|
-
let owners = cache[__mfSharedCacheOwnersKey];
|
|
576
|
-
if (owners === undefined) {
|
|
577
|
-
owners = Object.create(null);
|
|
578
|
-
Object.defineProperty(cache, __mfSharedCacheOwnersKey, {
|
|
579
|
-
value: owners,
|
|
580
|
-
enumerable: false,
|
|
581
|
-
configurable: false,
|
|
582
|
-
writable: false
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
return owners;
|
|
586
|
-
};
|
|
587
|
-
const __mfReadSharedCacheOwner = (cache, descriptor) =>
|
|
588
|
-
cache[__mfSharedCacheOwnersKey]?.[descriptor.canonical];
|
|
589
|
-
const __mfWriteSharedCache = (cache, descriptor, value, owner) => {
|
|
590
|
-
cache[descriptor.canonical] = value;
|
|
591
|
-
const aliases = descriptor.aliases || [];
|
|
592
|
-
for (const alias of aliases) {
|
|
593
|
-
Object.defineProperty(cache, alias, {
|
|
594
|
-
value,
|
|
595
|
-
enumerable: true,
|
|
596
|
-
configurable: true,
|
|
597
|
-
writable: true
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
const owners = cache[__mfSharedCacheOwnersKey];
|
|
601
|
-
if (owner === undefined) {
|
|
602
|
-
if (owners) delete owners[descriptor.canonical];
|
|
603
|
-
} else {
|
|
604
|
-
__mfGetSharedCacheOwners(cache)[descriptor.canonical] = owner;
|
|
605
|
-
}
|
|
606
|
-
const listeners = cache[__mfSharedCacheListenersKey]?.[descriptor.canonical];
|
|
607
|
-
if (listeners) {
|
|
608
|
-
for (const listener of listeners) listener(value);
|
|
609
|
-
}
|
|
610
|
-
return value;
|
|
611
|
-
};
|
|
612
|
-
const __mfTreeShakingSharedCacheKey = Symbol.for("module-federation.tree-shaking-shared-cache");
|
|
613
|
-
const __mfGetTreeShakingSharedCache = (cache) => {
|
|
614
|
-
let metadata = cache[__mfTreeShakingSharedCacheKey];
|
|
615
|
-
if (metadata === undefined) {
|
|
616
|
-
metadata = Object.create(null);
|
|
617
|
-
Object.defineProperty(cache, __mfTreeShakingSharedCacheKey, {
|
|
618
|
-
value: metadata,
|
|
619
|
-
enumerable: false,
|
|
620
|
-
configurable: false,
|
|
621
|
-
writable: false
|
|
622
|
-
});
|
|
623
|
-
}
|
|
624
|
-
return metadata;
|
|
625
|
-
};
|
|
626
|
-
const __mfReadTreeShakingSharedCache = (cache, descriptor, requiredExports) => {
|
|
627
|
-
const fullModule = __mfReadSharedCache(cache, descriptor);
|
|
628
|
-
if (fullModule !== undefined) return fullModule;
|
|
629
|
-
if (!Array.isArray(requiredExports)) return undefined;
|
|
630
|
-
const metadata = cache[__mfTreeShakingSharedCacheKey];
|
|
631
|
-
const entries = metadata?.[descriptor.canonical] || [];
|
|
632
|
-
let compatibleEntry;
|
|
633
|
-
for (const entry of entries) {
|
|
634
|
-
if (!requiredExports.every((name) => entry.providedExports.includes(name))) continue;
|
|
635
|
-
if (!compatibleEntry || entry.providedExports.length < compatibleEntry.providedExports.length) {
|
|
636
|
-
compatibleEntry = entry;
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
return compatibleEntry?.value;
|
|
640
|
-
};
|
|
641
|
-
const __mfWriteTreeShakingSharedCache = (cache, descriptor, providedExports, value) => {
|
|
642
|
-
if (!Array.isArray(providedExports)) return value;
|
|
643
|
-
const normalizedExports = [...new Set(providedExports)].sort();
|
|
644
|
-
const metadata = __mfGetTreeShakingSharedCache(cache);
|
|
645
|
-
const entries = (metadata[descriptor.canonical] ||= []);
|
|
646
|
-
const existing = entries.find((entry) =>
|
|
647
|
-
entry.providedExports.length === normalizedExports.length &&
|
|
648
|
-
entry.providedExports.every((name, index) => name === normalizedExports[index])
|
|
649
|
-
);
|
|
650
|
-
if (existing) existing.value = value;
|
|
651
|
-
else entries.push({ providedExports: normalizedExports, value });
|
|
652
|
-
return value;
|
|
653
|
-
};
|
|
654
|
-
const __mfTreeShakingSelectionCacheKey = Symbol.for("module-federation.tree-shaking-shared-selection-cache");
|
|
655
|
-
const __mfGetTreeShakingSelectionCache = (cache) => {
|
|
656
|
-
let selections = cache[__mfTreeShakingSelectionCacheKey];
|
|
657
|
-
if (selections === undefined) {
|
|
658
|
-
selections = Object.create(null);
|
|
659
|
-
Object.defineProperty(cache, __mfTreeShakingSelectionCacheKey, {
|
|
660
|
-
value: selections,
|
|
661
|
-
enumerable: false,
|
|
662
|
-
configurable: false,
|
|
663
|
-
writable: false
|
|
664
|
-
});
|
|
665
|
-
}
|
|
666
|
-
return selections;
|
|
667
|
-
};
|
|
668
|
-
const __mfReadTreeShakingSharedSelection = (cache, descriptor, consumer) => {
|
|
669
|
-
const fullModule = __mfReadSharedCache(cache, descriptor);
|
|
670
|
-
if (fullModule !== undefined) return fullModule;
|
|
671
|
-
return cache[__mfTreeShakingSelectionCacheKey]?.[descriptor.canonical]?.[consumer];
|
|
672
|
-
};
|
|
673
|
-
const __mfWriteTreeShakingSharedSelection = (cache, descriptor, consumer, value) => {
|
|
674
|
-
const selections = __mfGetTreeShakingSelectionCache(cache);
|
|
675
|
-
const byConsumer = (selections[descriptor.canonical] ||= Object.create(null));
|
|
676
|
-
byConsumer[consumer] = value;
|
|
677
|
-
return value;
|
|
678
|
-
};`;
|
|
679
|
-
function getInstalledPackageJson(pkg, opts) {
|
|
680
|
-
const cwd = opts?.cwd || getPackageDetectionCwd();
|
|
681
|
-
const packageName = opts?.packageName || getPackageName(pkg);
|
|
682
|
-
const cacheKey = `${cwd}\0${pkg}\0${packageName}\0${opts?.fromResolvedEntry ?? ""}`;
|
|
683
|
-
if (installedPackageJsonCache.has(cacheKey)) return installedPackageJsonCache.get(cacheKey);
|
|
684
|
-
const result = resolveInstalledPackageJson(pkg, cwd, packageName, opts);
|
|
685
|
-
installedPackageJsonCache.set(cacheKey, result);
|
|
686
|
-
return result;
|
|
687
|
-
}
|
|
688
|
-
function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
|
|
689
|
-
const tryReadPackageJson = (packageJsonPath) => {
|
|
690
|
-
if (!existsSync(packageJsonPath)) return void 0;
|
|
691
|
-
try {
|
|
692
|
-
return {
|
|
693
|
-
path: packageJsonPath,
|
|
694
|
-
dir: path$1.dirname(packageJsonPath),
|
|
695
|
-
packageJson: JSON.parse(readFileSync(packageJsonPath, "utf-8"))
|
|
696
|
-
};
|
|
697
|
-
} catch {
|
|
698
|
-
return;
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
const findPackageInPnpmStore = (startDir) => {
|
|
702
|
-
let currentDir = startDir;
|
|
703
|
-
const rootDir = path$1.parse(currentDir).root;
|
|
704
|
-
while (true) {
|
|
705
|
-
const pnpmStoreDir = path$1.join(currentDir, "node_modules", ".pnpm");
|
|
706
|
-
if (existsSync(pnpmStoreDir)) try {
|
|
707
|
-
for (const entry of readdirSync(pnpmStoreDir, { withFileTypes: true })) {
|
|
708
|
-
if (!entry.isDirectory()) continue;
|
|
709
|
-
const candidate = tryReadPackageJson(path$1.join(pnpmStoreDir, entry.name, "node_modules", packageName, "package.json"));
|
|
710
|
-
if (candidate?.packageJson.name === packageName) return candidate;
|
|
711
|
-
}
|
|
712
|
-
} catch {}
|
|
713
|
-
if (currentDir === rootDir) break;
|
|
714
|
-
currentDir = path$1.dirname(currentDir);
|
|
715
|
-
}
|
|
716
|
-
};
|
|
717
|
-
try {
|
|
718
|
-
const projectRequire = createRequire$1(pathToFileURL(path$1.join(cwd, "package.json")));
|
|
719
|
-
let resolvedPath;
|
|
720
|
-
if (opts?.fromResolvedEntry) resolvedPath = opts.fromResolvedEntry;
|
|
721
|
-
else try {
|
|
722
|
-
resolvedPath = projectRequire.resolve(pkg);
|
|
723
|
-
} catch {
|
|
724
|
-
resolvedPath = projectRequire.resolve(packageName);
|
|
725
|
-
}
|
|
726
|
-
let currentDir = path$1.dirname(resolvedPath);
|
|
727
|
-
const rootDir = path$1.parse(currentDir).root;
|
|
728
|
-
while (true) {
|
|
729
|
-
const packageJsonPath = path$1.join(currentDir, "package.json");
|
|
730
|
-
if (existsSync(packageJsonPath)) {
|
|
731
|
-
const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
|
|
732
|
-
try {
|
|
733
|
-
const packageJson = JSON.parse(packageJsonContent);
|
|
734
|
-
if (packageJson.name === packageName) return {
|
|
735
|
-
path: packageJsonPath,
|
|
736
|
-
dir: currentDir,
|
|
737
|
-
packageJson
|
|
738
|
-
};
|
|
739
|
-
} catch (error) {
|
|
740
|
-
if (!(error instanceof SyntaxError)) throw error;
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
if (currentDir === rootDir) break;
|
|
744
|
-
currentDir = path$1.dirname(currentDir);
|
|
745
|
-
}
|
|
746
|
-
} catch {
|
|
747
|
-
let currentDir = cwd;
|
|
748
|
-
const rootDir = path$1.parse(currentDir).root;
|
|
749
|
-
while (true) {
|
|
750
|
-
const directCandidate = tryReadPackageJson(path$1.join(currentDir, "node_modules", packageName, "package.json"));
|
|
751
|
-
if (directCandidate?.packageJson.name === packageName) return directCandidate;
|
|
752
|
-
if (currentDir === rootDir) break;
|
|
753
|
-
currentDir = path$1.dirname(currentDir);
|
|
754
|
-
}
|
|
755
|
-
return findPackageInPnpmStore(cwd);
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
function getInstalledPackageEntry(pkg, opts) {
|
|
759
|
-
const installed = getInstalledPackageJson(pkg, opts);
|
|
760
|
-
if (!installed) return void 0;
|
|
761
|
-
const cwd = opts?.cwd || getPackageDetectionCwd();
|
|
762
|
-
const packageName = opts?.packageName || getPackageName(pkg);
|
|
763
|
-
const packageJson = installed.packageJson;
|
|
764
|
-
if (pkg !== packageName && (opts?.resolveSubpathWithRequire !== false || packageJson.exports === void 0)) try {
|
|
765
|
-
return createRequire$1(pathToFileURL(path$1.join(cwd, "package.json"))).resolve(pkg);
|
|
766
|
-
} catch {}
|
|
767
|
-
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";
|
|
768
|
-
return path$1.join(installed.dir, explicitEntry);
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
|
-
* Detect whether the current runtime is Vite 8+ by checking for a Vite version flag
|
|
772
|
-
* on the plugin hook context, with Rolldown metadata kept as a compatibility fallback.
|
|
773
|
-
*/
|
|
774
|
-
function getIsRolldown(ctx) {
|
|
775
|
-
const viteVersion = ctx?.meta?.viteVersion;
|
|
776
|
-
const viteMajor = Number(String(viteVersion ?? "").split(".")[0]);
|
|
777
|
-
return Number.isFinite(viteMajor) && viteMajor >= 8 || !!ctx?.meta?.rolldownVersion;
|
|
778
|
-
}
|
|
779
|
-
/** Walk up from Vite `config.root` (Nuxt may point at `.nuxt` cache dirs). */
|
|
780
|
-
function isNuxtProjectRoot(root) {
|
|
781
|
-
let dir = root;
|
|
782
|
-
for (let i = 0; i < 8; i++) {
|
|
783
|
-
if (hasPackageDependency("nuxt", dir) || hasPackageDependency("nuxt-nightly", dir)) return true;
|
|
784
|
-
const parent = path$1.dirname(dir);
|
|
785
|
-
if (parent === dir) break;
|
|
786
|
-
dir = parent;
|
|
787
|
-
}
|
|
788
|
-
return false;
|
|
789
|
-
}
|
|
790
|
-
function hasPackageDependency(dependencyName, cwd = packageDetectionCwd || process.cwd()) {
|
|
791
|
-
const cacheKey = getDependencyCacheKey(cwd, dependencyName);
|
|
792
|
-
const cached = dependencyPresenceCache.get(cacheKey);
|
|
793
|
-
if (cached !== void 0) return cached;
|
|
794
|
-
try {
|
|
795
|
-
const packageJson = JSON.parse(readFileSync(path$1.join(cwd, "package.json"), "utf8"));
|
|
796
|
-
const hasDependency = [
|
|
797
|
-
packageJson.dependencies,
|
|
798
|
-
packageJson.devDependencies,
|
|
799
|
-
packageJson.peerDependencies,
|
|
800
|
-
packageJson.optionalDependencies
|
|
801
|
-
].some((deps) => !!deps?.[dependencyName]);
|
|
802
|
-
dependencyPresenceCache.set(cacheKey, hasDependency);
|
|
803
|
-
return hasDependency;
|
|
804
|
-
} catch {
|
|
805
|
-
dependencyPresenceCache.set(cacheKey, false);
|
|
806
|
-
return false;
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
//#endregion
|
|
810
327
|
//#region src/utils/normalizeModuleFederationOptions.ts
|
|
811
328
|
const INTERNAL_NAME_PREFIX = "__mfe_internal__";
|
|
812
329
|
function toInternalModuleFederationName(name) {
|
|
@@ -1148,6 +665,8 @@ var VirtualModule = class VirtualModule {
|
|
|
1148
665
|
//#region src/utils/ssrCapabilities.ts
|
|
1149
666
|
/** A browser-safe generated expression that is true only in Node.js. */
|
|
1150
667
|
const SERVER_ENV_GUARD = "import.meta.env.SSR";
|
|
668
|
+
const SSR_ENTRY_LOADER_SPECIFIER = "@module-federation/vite/ssrEntryLoader";
|
|
669
|
+
const SSR_ONLY_RUNTIME_PLUGINS = /* @__PURE__ */ new Set([SSR_ENTRY_LOADER_SPECIFIER]);
|
|
1151
670
|
/**
|
|
1152
671
|
* Single source of truth for SSR-related feature gates.
|
|
1153
672
|
*
|
|
@@ -1454,27 +973,40 @@ function loadReactIslandConsumerModule(id) {
|
|
|
1454
973
|
if (clientRemoteId !== void 0) return generateReactIslandConsumerClient(clientRemoteId);
|
|
1455
974
|
}
|
|
1456
975
|
//#endregion
|
|
976
|
+
//#region src/virtualModules/virtualModuleScope.ts
|
|
977
|
+
function getVirtualModuleScopeKey(options) {
|
|
978
|
+
return `${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
979
|
+
}
|
|
980
|
+
//#endregion
|
|
1457
981
|
//#region src/virtualModules/virtualExposes.ts
|
|
1458
982
|
const EXPOSES_CSS_MAP_PLACEHOLDER = "__MF_EXPOSES_CSS_MAP__";
|
|
1459
983
|
function getExposesCssMapPlaceholder() {
|
|
1460
984
|
return EXPOSES_CSS_MAP_PLACEHOLDER;
|
|
1461
985
|
}
|
|
1462
986
|
function getVirtualExposesId(options) {
|
|
1463
|
-
return `virtual:mf-exposes:${
|
|
987
|
+
return `virtual:mf-exposes:${getVirtualModuleScopeKey(options)}`;
|
|
1464
988
|
}
|
|
1465
989
|
function generateExposes(options, remoteDependencyMap = {}, command = "build", reactIslandExposes = /* @__PURE__ */ new Set()) {
|
|
1466
990
|
return `
|
|
1467
991
|
const cssAssetMap = ${JSON.stringify(options.bundleAllCSS ? EXPOSES_CSS_MAP_PLACEHOLDER : {})};
|
|
1468
992
|
const injectedCssHrefs = new Set();
|
|
1469
|
-
|
|
993
|
+
const exposeLoadPromises = new Map();
|
|
1470
994
|
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
)
|
|
1477
|
-
|
|
995
|
+
// Shared and remote readiness is handled by explicit Promise barriers below
|
|
996
|
+
// and by remoteEntry's pendingShareLoads barrier. Keep this map scoped to a
|
|
997
|
+
// single expose: unrelated exposes must stay independent and load in parallel.
|
|
998
|
+
function loadExposedModule(exposeKey, loader) {
|
|
999
|
+
let load = exposeLoadPromises.get(exposeKey);
|
|
1000
|
+
if (!load) {
|
|
1001
|
+
load = Promise.resolve()
|
|
1002
|
+
.then(loader)
|
|
1003
|
+
.catch((error) => {
|
|
1004
|
+
exposeLoadPromises.delete(exposeKey);
|
|
1005
|
+
throw error;
|
|
1006
|
+
});
|
|
1007
|
+
exposeLoadPromises.set(exposeKey, load);
|
|
1008
|
+
}
|
|
1009
|
+
return load;
|
|
1478
1010
|
}
|
|
1479
1011
|
|
|
1480
1012
|
async function injectCssAssets(exposeKey) {
|
|
@@ -1529,7 +1061,8 @@ function generateExposes(options, remoteDependencyMap = {}, command = "build", r
|
|
|
1529
1061
|
${JSON.stringify(key)}: async () => {
|
|
1530
1062
|
await injectCssAssets(${JSON.stringify(key)})
|
|
1531
1063
|
await Promise.all([${remoteDependencyPreloads}])
|
|
1532
|
-
const importModule = await
|
|
1064
|
+
const importModule = await loadExposedModule(
|
|
1065
|
+
${JSON.stringify(key)},
|
|
1533
1066
|
() => import(${JSON.stringify(options.exposes[key].import)})
|
|
1534
1067
|
)
|
|
1535
1068
|
const dependencyPending = importModule && importModule.__mf_remote_dependency_pending;
|
|
@@ -1551,12 +1084,56 @@ function generateExposes(options, remoteDependencyMap = {}, command = "build", r
|
|
|
1551
1084
|
`;
|
|
1552
1085
|
}
|
|
1553
1086
|
//#endregion
|
|
1087
|
+
//#region src/utils/sharedExportConditions.ts
|
|
1088
|
+
const DEFAULT_CLIENT_EXPORT_CONDITIONS = [
|
|
1089
|
+
"browser",
|
|
1090
|
+
"import",
|
|
1091
|
+
"module",
|
|
1092
|
+
"default"
|
|
1093
|
+
];
|
|
1094
|
+
const DEFAULT_NODE_SSR_EXPORT_CONDITIONS = [
|
|
1095
|
+
"node",
|
|
1096
|
+
"import",
|
|
1097
|
+
"module",
|
|
1098
|
+
"default"
|
|
1099
|
+
];
|
|
1100
|
+
const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
|
|
1101
|
+
"worker",
|
|
1102
|
+
"browser",
|
|
1103
|
+
"import",
|
|
1104
|
+
"module",
|
|
1105
|
+
"default"
|
|
1106
|
+
];
|
|
1107
|
+
const VITE_DEV_PROD_CONDITION = "development|production";
|
|
1108
|
+
function appendConditions(conditions, fallbackConditions) {
|
|
1109
|
+
return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
|
|
1110
|
+
}
|
|
1111
|
+
function resolveViteModeCondition(conditions, isProduction) {
|
|
1112
|
+
const modeCondition = isProduction ? "production" : "development";
|
|
1113
|
+
return [...new Set(conditions.map((condition) => condition === VITE_DEV_PROD_CONDITION ? modeCondition : condition))];
|
|
1114
|
+
}
|
|
1115
|
+
function getSharedExportConditions({ environmentConditions, isProduction, isSsr, rootConditions, ssrConditions, ssrTarget = "node" }) {
|
|
1116
|
+
if (environmentConditions !== void 0) return resolveViteModeCondition(appendConditions(environmentConditions, ["import", "default"]), isProduction);
|
|
1117
|
+
const defaultConditions = isSsr ? ssrTarget === "webworker" ? DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS : DEFAULT_NODE_SSR_EXPORT_CONDITIONS : DEFAULT_CLIENT_EXPORT_CONDITIONS;
|
|
1118
|
+
const configuredConditions = isSsr ? ssrConditions ?? rootConditions : rootConditions;
|
|
1119
|
+
if (configuredConditions !== void 0) return resolveViteModeCondition(appendConditions(configuredConditions, defaultConditions), isProduction);
|
|
1120
|
+
return [...defaultConditions];
|
|
1121
|
+
}
|
|
1122
|
+
function isReactServerConditions(conditions) {
|
|
1123
|
+
return Boolean(conditions?.includes("react-server"));
|
|
1124
|
+
}
|
|
1125
|
+
//#endregion
|
|
1554
1126
|
//#region src/virtualModules/virtualRuntimeInitStatus.ts
|
|
1555
1127
|
const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
|
|
1556
1128
|
const runtimeInitModules = /* @__PURE__ */ new WeakMap();
|
|
1557
1129
|
const runtimeInitOwnerIds = /* @__PURE__ */ new WeakMap();
|
|
1558
1130
|
let nextRuntimeInitOwnerId = 1;
|
|
1559
1131
|
const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
|
|
1132
|
+
const REACT_SERVER_MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache_react_server__";
|
|
1133
|
+
const MODULE_CACHE_SHARE_SCOPE_KEY = "module-federation.vite-module-cache";
|
|
1134
|
+
function getModuleCacheGlobalKey(exportConditions) {
|
|
1135
|
+
return isReactServerConditions(exportConditions) ? REACT_SERVER_MODULE_CACHE_GLOBAL_KEY : MODULE_CACHE_GLOBAL_KEY;
|
|
1136
|
+
}
|
|
1560
1137
|
function getRuntimeInitOwnerId(options) {
|
|
1561
1138
|
let ownerId = runtimeInitOwnerIds.get(options);
|
|
1562
1139
|
if (!ownerId) {
|
|
@@ -1640,10 +1217,10 @@ if (!${options.stateVar}) {
|
|
|
1640
1217
|
const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
|
|
1641
1218
|
`;
|
|
1642
1219
|
}
|
|
1643
|
-
function getRuntimeInitBootstrapCode(enableSsrInit = false, ownerImportId, ssrRemotes, hostInitImportId = ownerImportId) {
|
|
1220
|
+
function getRuntimeInitBootstrapCode(enableSsrInit = false, ownerImportId, ssrRemotes, hostInitImportId = ownerImportId, exportConditions) {
|
|
1644
1221
|
return `
|
|
1645
1222
|
const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey(ownerImportId))};
|
|
1646
|
-
const moduleCacheGlobalKey = ${JSON.stringify(
|
|
1223
|
+
const moduleCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
|
|
1647
1224
|
globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
1648
1225
|
globalThis[moduleCacheGlobalKey].share ||= {};
|
|
1649
1226
|
globalThis[moduleCacheGlobalKey].remote ||= {};
|
|
@@ -1661,14 +1238,14 @@ if (${SERVER_ENV_GUARD} && !globalThis[globalKey].ssrInitStarted) {
|
|
|
1661
1238
|
globalThis[globalKey].ssrInitStarted = true;
|
|
1662
1239
|
${getSsrNoopResolveCode(enableSsrInit, hostInitImportId, "globalThis[globalKey].initResolve", ssrRemotes)}
|
|
1663
1240
|
}` : ""}
|
|
1664
|
-
globalThis[globalKey].moduleCache
|
|
1241
|
+
globalThis[globalKey].moduleCache = globalThis[moduleCacheGlobalKey];
|
|
1665
1242
|
globalThis[globalKey].moduleCache.share ||= {};
|
|
1666
1243
|
globalThis[globalKey].moduleCache.remote ||= {};
|
|
1667
1244
|
`;
|
|
1668
1245
|
}
|
|
1669
|
-
function getRuntimeModuleCacheBootstrapCode() {
|
|
1246
|
+
function getRuntimeModuleCacheBootstrapCode(exportConditions) {
|
|
1670
1247
|
return `
|
|
1671
|
-
const __mfCacheGlobalKey = ${JSON.stringify(
|
|
1248
|
+
const __mfCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
|
|
1672
1249
|
globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
|
|
1673
1250
|
globalThis[__mfCacheGlobalKey].share ||= {};
|
|
1674
1251
|
globalThis[__mfCacheGlobalKey].remote ||= {};
|
|
@@ -2133,6 +1710,7 @@ function getPackageEsmEntryPath(pkg) {
|
|
|
2133
1710
|
resolveSubpathWithRequire: false
|
|
2134
1711
|
}) || resolvePackageEntryFromProjectRoot(pkg);
|
|
2135
1712
|
}
|
|
1713
|
+
const packageNamedExportsCache = /* @__PURE__ */ new Map();
|
|
2136
1714
|
const DEFAULT_SHARED_EXPORT_CONDITIONS = [
|
|
2137
1715
|
"browser",
|
|
2138
1716
|
"import",
|
|
@@ -2575,10 +2153,12 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
|
|
|
2575
2153
|
const exportKeywordRegex = /\bexport\b/g;
|
|
2576
2154
|
while ((match = exportKeywordRegex.exec(source)) !== null) {
|
|
2577
2155
|
if (!codePositions[match.index]) continue;
|
|
2578
|
-
if (
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2156
|
+
if (recognizedExportStarts.has(match.index)) continue;
|
|
2157
|
+
let previousCodeIndex = match.index - 1;
|
|
2158
|
+
while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
|
|
2159
|
+
if (source[previousCodeIndex] === ".") continue;
|
|
2160
|
+
scanState.complete = false;
|
|
2161
|
+
break;
|
|
2582
2162
|
}
|
|
2583
2163
|
return Array.from(names);
|
|
2584
2164
|
}
|
|
@@ -2619,10 +2199,13 @@ function getPackageNamedExports(pkg, exportConditions = DEFAULT_SHARED_EXPORT_CO
|
|
|
2619
2199
|
resolveSubpathWithRequire: false
|
|
2620
2200
|
});
|
|
2621
2201
|
if (esmEntryPath) {
|
|
2202
|
+
const cacheKey = !isWorkspaceFilePath(esmEntryPath) ? `${getPackageDetectionCwd()}\0${esmEntryPath}\0${exportConditions.join("\0")}` : void 0;
|
|
2203
|
+
const cached = cacheKey ? packageNamedExportsCache.get(cacheKey) : void 0;
|
|
2204
|
+
if (cached) return cached.value;
|
|
2622
2205
|
const inspection = inspectSharedExportsFromFile(esmEntryPath, exportConditions);
|
|
2623
|
-
|
|
2624
|
-
if (
|
|
2625
|
-
return;
|
|
2206
|
+
const value = !inspection || inspection.commonJs || path$1.extname(esmEntryPath) === ".cjs" ? getRequiredNamedExports(esmEntryPath) : inspection.namedExports;
|
|
2207
|
+
if (cacheKey) packageNamedExportsCache.set(cacheKey, { value });
|
|
2208
|
+
return value;
|
|
2626
2209
|
}
|
|
2627
2210
|
return getRequiredNamedExports(pkg);
|
|
2628
2211
|
}
|
|
@@ -2770,10 +2353,27 @@ function tryResolveImportFromPackageRoot(pkg, root) {
|
|
|
2770
2353
|
return;
|
|
2771
2354
|
}
|
|
2772
2355
|
}
|
|
2356
|
+
/**
|
|
2357
|
+
* Resolution walks from the project root up to the filesystem root, probing
|
|
2358
|
+
* every level, and the shared-module resolver asks for the same few packages
|
|
2359
|
+
* tens of thousands of times on a cold dev start. The detection cwd is part of
|
|
2360
|
+
* the key because `setPackageDetectionCwd` can move it between config hooks.
|
|
2361
|
+
*/
|
|
2362
|
+
const concreteSharedImportSourceCache = /* @__PURE__ */ new Map();
|
|
2363
|
+
function resetConcreteSharedImportSourceCache() {
|
|
2364
|
+
concreteSharedImportSourceCache.clear();
|
|
2365
|
+
}
|
|
2773
2366
|
function getConcreteSharedImportSource(pkg, shareItem) {
|
|
2774
2367
|
const configuredImport = shareItem?.shareConfig.import;
|
|
2775
2368
|
if (typeof configuredImport === "string") return configuredImport;
|
|
2776
2369
|
const projectRoot = getPackageDetectionCwd();
|
|
2370
|
+
const cacheKey = JSON.stringify([projectRoot, pkg]);
|
|
2371
|
+
if (concreteSharedImportSourceCache.has(cacheKey)) return concreteSharedImportSourceCache.get(cacheKey);
|
|
2372
|
+
const resolved = resolveConcreteSharedImportSource(pkg, projectRoot);
|
|
2373
|
+
concreteSharedImportSourceCache.set(cacheKey, resolved);
|
|
2374
|
+
return resolved;
|
|
2375
|
+
}
|
|
2376
|
+
function resolveConcreteSharedImportSource(pkg, projectRoot) {
|
|
2777
2377
|
if (tryResolveImportFromPackageRoot(pkg, projectRoot)) return;
|
|
2778
2378
|
let currentDir = path$1.dirname(projectRoot);
|
|
2779
2379
|
while (currentDir !== path$1.dirname(currentDir)) {
|
|
@@ -2927,7 +2527,7 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
|
|
|
2927
2527
|
});
|
|
2928
2528
|
preBuildCacheMap[pkg].writeSync(`
|
|
2929
2529
|
${sharedCacheHelperCode}
|
|
2930
|
-
const __mfCacheGlobalKey =
|
|
2530
|
+
const __mfCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
|
|
2931
2531
|
export const c = function(size) {
|
|
2932
2532
|
const cache = globalThis[__mfCacheGlobalKey]?.share;
|
|
2933
2533
|
const sharedReact = cache && __mfReadSharedCache(cache, ${reactCacheDescriptor});
|
|
@@ -2991,12 +2591,12 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
|
|
|
2991
2591
|
`, true);
|
|
2992
2592
|
}
|
|
2993
2593
|
/** Re-render already materialized wrappers after import analysis discovers exports. */
|
|
2994
|
-
function refreshTreeShakingModules(options) {
|
|
2594
|
+
function refreshTreeShakingModules(options, command = "build", isRolldown = false, exportConditions) {
|
|
2995
2595
|
const { preBuildShareItemMap } = getSharedVirtualModuleState(options);
|
|
2996
2596
|
for (const [pkg, shareItem] of Object.entries(preBuildShareItemMap)) {
|
|
2997
2597
|
if (!shareItem?.shareConfig.treeShaking) continue;
|
|
2998
|
-
writePreBuildLibPath(pkg, shareItem, options);
|
|
2999
|
-
writeLoadShareModule(pkg, shareItem,
|
|
2598
|
+
writePreBuildLibPath(pkg, shareItem, options, exportConditions);
|
|
2599
|
+
writeLoadShareModule(pkg, shareItem, command, isRolldown, options, exportConditions);
|
|
3000
2600
|
}
|
|
3001
2601
|
}
|
|
3002
2602
|
function getPreBuildLibImportId(pkg, options) {
|
|
@@ -3198,7 +2798,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
3198
2798
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
3199
2799
|
const { loadShareCacheMap } = getSharedVirtualModuleState(options);
|
|
3200
2800
|
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = createScopedSharedVirtualModule(pkg, LOAD_SHARE_TAG, options);
|
|
3201
|
-
let importLine = getRuntimeModuleCacheBootstrapCode();
|
|
2801
|
+
let importLine = getRuntimeModuleCacheBootstrapCode(exportConditions);
|
|
3202
2802
|
const cacheDescriptor = getSharedCacheDescriptorLiteral(pkg, shareItem);
|
|
3203
2803
|
const cacheOwner = JSON.stringify(resolvedOptions.name);
|
|
3204
2804
|
const runtimeInitOwnerImportId = options ? getRuntimeInitStatusImportId(options) : void 0;
|
|
@@ -3241,18 +2841,18 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
3241
2841
|
const servesRemoteSingletonFallback = command !== "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true;
|
|
3242
2842
|
const isConsumedByPeerSingleton = isSharedSingletonConsumedByPeer(pkg, resolvedOptions);
|
|
3243
2843
|
const usesEntryInjectedRemoteFallback = hasCompleteExportCoverage && command !== "build" && !isWorkspaceSingleton && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true && resolvedOptions.hostInitInjectLocation === "entry" && isConsumedByPeerSingleton;
|
|
3244
|
-
const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
|
|
2844
|
+
const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && !servesRemoteSingletonFallback && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
|
|
3245
2845
|
const usesDeferredTreeShakingFallback = hasCompleteExportCoverage && Boolean(treeShakingConsumer);
|
|
3246
2846
|
const reactMixedModeGuard = pkg === "react" ? createReactMixedModeRuntimeGuard() : "";
|
|
3247
2847
|
let exportLine;
|
|
3248
2848
|
let initBlock = "";
|
|
3249
2849
|
if (usesDeferredTreeShakingFallback) {
|
|
3250
2850
|
importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
|
|
3251
|
-
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage
|
|
2851
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
|
|
3252
2852
|
} else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
|
|
3253
2853
|
else if (usesDeferredSingletonFallback) {
|
|
3254
2854
|
importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
|
|
3255
|
-
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage
|
|
2855
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
|
|
3256
2856
|
} else if (detectedNamedExports === void 0) {
|
|
3257
2857
|
exportLine = `const __mfDefaultExport = (() => {
|
|
3258
2858
|
${generateShareModuleUnwrapCode({
|
|
@@ -3321,7 +2921,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
3321
2921
|
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
3322
2922
|
__mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
|
|
3323
2923
|
}
|
|
3324
|
-
const prebuildImportLine = usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? servesRemoteSingletonFallback
|
|
2924
|
+
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)};`;
|
|
3325
2925
|
const devDynamicImportLine = isWorkspacePackage ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
|
|
3326
2926
|
const moduleBody = usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? `
|
|
3327
2927
|
${prebuildImportLine}
|
|
@@ -3348,6 +2948,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
|
|
|
3348
2948
|
//#region src/virtualModules/virtualRemoteEntry.ts
|
|
3349
2949
|
let usedShares = /* @__PURE__ */ new Set();
|
|
3350
2950
|
const usedSharesByOptions = /* @__PURE__ */ new WeakMap();
|
|
2951
|
+
const materializedSharesByOptions = /* @__PURE__ */ new WeakMap();
|
|
3351
2952
|
function getScopedUsedShares(options) {
|
|
3352
2953
|
let scoped = usedSharesByOptions.get(options);
|
|
3353
2954
|
if (!scoped) {
|
|
@@ -3363,6 +2964,18 @@ function getUsedShares(options) {
|
|
|
3363
2964
|
function addUsedShares(pkg, options) {
|
|
3364
2965
|
usedShares.add(pkg);
|
|
3365
2966
|
if (options) getScopedUsedShares(options).add(pkg);
|
|
2967
|
+
if (options) {
|
|
2968
|
+
let scoped = materializedSharesByOptions.get(options);
|
|
2969
|
+
if (!scoped) {
|
|
2970
|
+
scoped = /* @__PURE__ */ new Set();
|
|
2971
|
+
materializedSharesByOptions.set(options, scoped);
|
|
2972
|
+
}
|
|
2973
|
+
scoped.add(pkg);
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
function addConfiguredShare(pkg, options) {
|
|
2977
|
+
usedShares.add(pkg);
|
|
2978
|
+
if (options) getScopedUsedShares(options).add(pkg);
|
|
3366
2979
|
}
|
|
3367
2980
|
const LOCAL_SHARED_IMPORT_MAP_ID = "virtual:mf-localSharedImportMap";
|
|
3368
2981
|
const localOwnerIds = /* @__PURE__ */ new WeakMap();
|
|
@@ -3409,6 +3022,7 @@ function generateLocalSharedImportMap(options) {
|
|
|
3409
3022
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
3410
3023
|
const useDirectReactImport = shouldUseDirectReactImport();
|
|
3411
3024
|
const orderedShares = getOrderedUsedShares(options);
|
|
3025
|
+
const sharesToMaterialize = new Set(getMaterializedShares(options));
|
|
3412
3026
|
return `
|
|
3413
3027
|
import {loadShare} from "@module-federation/runtime";
|
|
3414
3028
|
${orderedShares.map((pkg, index) => {
|
|
@@ -3429,7 +3043,7 @@ function generateLocalSharedImportMap(options) {
|
|
|
3429
3043
|
}).join(",")}
|
|
3430
3044
|
}
|
|
3431
3045
|
const usedShared = {
|
|
3432
|
-
${
|
|
3046
|
+
${orderedShares.map((key) => {
|
|
3433
3047
|
const shareItem = getNormalizeShareItem(key, resolvedOptions);
|
|
3434
3048
|
if (!shareItem) return null;
|
|
3435
3049
|
const detectedNamedExports = getSharedNamedExports(key, shareItem);
|
|
@@ -3447,6 +3061,7 @@ function generateLocalSharedImportMap(options) {
|
|
|
3447
3061
|
version: ${JSON.stringify(shareItem.version)},
|
|
3448
3062
|
scope: [${JSON.stringify(shareItem.scope)}],
|
|
3449
3063
|
loaded: false,
|
|
3064
|
+
materialize: ${sharesToMaterialize.has(key)},
|
|
3450
3065
|
eager: ${Boolean(shareItem.shareConfig.eager)},
|
|
3451
3066
|
from: ${JSON.stringify(resolvedOptions.name)},
|
|
3452
3067
|
canLiveRebind: ${canLiveRebind},
|
|
@@ -3517,7 +3132,7 @@ function generateLocalSharedImportMap(options) {
|
|
|
3517
3132
|
function getOrderedUsedShares(options) {
|
|
3518
3133
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
3519
3134
|
const shares = new Set(getUsedShares(options));
|
|
3520
|
-
Object.keys(resolvedOptions.shared).forEach((pkg) => {
|
|
3135
|
+
Object.keys(resolvedOptions.shared ?? {}).forEach((pkg) => {
|
|
3521
3136
|
if (!pkg.endsWith("/")) shares.add(pkg);
|
|
3522
3137
|
});
|
|
3523
3138
|
return orderSharedDependenciesFirst(Array.from(shares).sort((a, b) => {
|
|
@@ -3525,6 +3140,68 @@ function getOrderedUsedShares(options) {
|
|
|
3525
3140
|
return priority(a) - priority(b) || a.localeCompare(b);
|
|
3526
3141
|
}));
|
|
3527
3142
|
}
|
|
3143
|
+
function getMaterializedShares(options) {
|
|
3144
|
+
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
3145
|
+
const scopedRegistrations = options ? usedSharesByOptions.get(options) : void 0;
|
|
3146
|
+
const shares = new Set(options && scopedRegistrations?.size ? materializedSharesByOptions.get(options) ?? [] : usedShares);
|
|
3147
|
+
for (const [pkg, share] of Object.entries(resolvedOptions.shared ?? {})) if (!pkg.endsWith("/") && share.shareConfig?.eager) shares.add(pkg);
|
|
3148
|
+
const configured = /* @__PURE__ */ new Map();
|
|
3149
|
+
for (const pkg of getOrderedUsedShares(options)) {
|
|
3150
|
+
const packageName = getPackageName(pkg);
|
|
3151
|
+
if (!configured.has(packageName) || pkg === packageName) configured.set(packageName, pkg);
|
|
3152
|
+
}
|
|
3153
|
+
const pending = [...shares];
|
|
3154
|
+
while (pending.length) {
|
|
3155
|
+
const pkg = pending.pop();
|
|
3156
|
+
const packageName = getPackageName(pkg);
|
|
3157
|
+
const packageJson = getInstalledPackageJson(pkg)?.packageJson ?? (pkg !== packageName ? getInstalledPackageJson(packageName)?.packageJson : void 0);
|
|
3158
|
+
const dependencies = {
|
|
3159
|
+
...packageJson?.dependencies || {},
|
|
3160
|
+
...packageJson?.peerDependencies || {},
|
|
3161
|
+
...packageJson?.optionalDependencies || {}
|
|
3162
|
+
};
|
|
3163
|
+
for (const dependency of Object.keys(dependencies)) {
|
|
3164
|
+
const sharedDependency = configured.get(dependency);
|
|
3165
|
+
if (sharedDependency && !shares.has(sharedDependency)) {
|
|
3166
|
+
shares.add(sharedDependency);
|
|
3167
|
+
pending.push(sharedDependency);
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
return orderSharedDependenciesFirst([...shares].sort((a, b) => {
|
|
3172
|
+
const priority = (pkg) => pkg === "react" ? 0 : pkg === "react-dom" ? 1 : pkg.startsWith("react/") ? 2 : 3;
|
|
3173
|
+
return priority(a) - priority(b) || a.localeCompare(b);
|
|
3174
|
+
}));
|
|
3175
|
+
}
|
|
3176
|
+
function getShareBatches(options, materializedOnly = true) {
|
|
3177
|
+
const ordered = materializedOnly ? getMaterializedShares(options) : getOrderedUsedShares(options);
|
|
3178
|
+
const levels = /* @__PURE__ */ new Map();
|
|
3179
|
+
const roots = /* @__PURE__ */ new Map();
|
|
3180
|
+
const subpaths = /* @__PURE__ */ new Map();
|
|
3181
|
+
for (const pkg of ordered) {
|
|
3182
|
+
const packageName = getPackageName(pkg);
|
|
3183
|
+
if (pkg === packageName) roots.set(packageName, pkg);
|
|
3184
|
+
else subpaths.set(packageName, [...subpaths.get(packageName) ?? [], pkg]);
|
|
3185
|
+
}
|
|
3186
|
+
for (const pkg of ordered) {
|
|
3187
|
+
const packageName = getPackageName(pkg);
|
|
3188
|
+
const packageJson = getInstalledPackageJson(pkg)?.packageJson ?? (pkg !== packageName ? getInstalledPackageJson(packageName)?.packageJson : void 0);
|
|
3189
|
+
const dependencies = {
|
|
3190
|
+
...packageJson?.dependencies || {},
|
|
3191
|
+
...packageJson?.peerDependencies || {},
|
|
3192
|
+
...packageJson?.optionalDependencies || {}
|
|
3193
|
+
};
|
|
3194
|
+
const prerequisites = Object.keys(dependencies).map((dependency) => roots.get(dependency)).filter((dependency) => Boolean(dependency));
|
|
3195
|
+
if (pkg !== packageName && (packageName === "react" || packageName === "react-dom")) {
|
|
3196
|
+
const root = roots.get(packageName);
|
|
3197
|
+
if (root) prerequisites.push(root);
|
|
3198
|
+
} else if (pkg === packageName && packageName !== "react" && packageName !== "react-dom") prerequisites.push(...subpaths.get(packageName) ?? []);
|
|
3199
|
+
levels.set(pkg, prerequisites.reduce((level, dependency) => Math.max(level, (levels.get(dependency) ?? 0) + 1), 0));
|
|
3200
|
+
}
|
|
3201
|
+
const batches = [];
|
|
3202
|
+
for (const pkg of ordered) (batches[levels.get(pkg) ?? 0] ??= []).push(pkg);
|
|
3203
|
+
return batches.filter(Boolean);
|
|
3204
|
+
}
|
|
3528
3205
|
function orderSharedDependenciesFirst(sharedPackages) {
|
|
3529
3206
|
const sharedKeyByPackageName = /* @__PURE__ */ new Map();
|
|
3530
3207
|
const subpathKeysByPackageName = /* @__PURE__ */ new Map();
|
|
@@ -3575,7 +3252,7 @@ function orderSharedDependenciesFirst(sharedPackages) {
|
|
|
3575
3252
|
}
|
|
3576
3253
|
function getShareItemForPreload(pkg, options = getNormalizeModuleFederationOptions()) {
|
|
3577
3254
|
const shared = options.shared;
|
|
3578
|
-
const wildcardKey = `${
|
|
3255
|
+
const wildcardKey = `${getPackageName(pkg)}/`;
|
|
3579
3256
|
if (isExplicitSharedKey(pkg, options)) return shared[pkg];
|
|
3580
3257
|
if (isExplicitSharedKey(wildcardKey, options)) return shared[wildcardKey];
|
|
3581
3258
|
}
|
|
@@ -3750,34 +3427,24 @@ const externalSharedProviderSelectionHelperCode = `const __mfSelectExternalShare
|
|
|
3750
3427
|
) return undefined;
|
|
3751
3428
|
return { provider, scopeRootProvider };
|
|
3752
3429
|
};`;
|
|
3753
|
-
function generateRuntimeSharedCacheSeedCode(shareStrategy) {
|
|
3754
|
-
const
|
|
3430
|
+
function generateRuntimeSharedCacheSeedCode(shareStrategy, options) {
|
|
3431
|
+
const seedBatches = getShareBatches(options, false);
|
|
3755
3432
|
return `
|
|
3756
|
-
const __mfSeedOrder = ${JSON.stringify(
|
|
3757
|
-
const
|
|
3758
|
-
const
|
|
3759
|
-
|
|
3760
|
-
|
|
3761
|
-
|
|
3762
|
-
if (
|
|
3763
|
-
const
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
}
|
|
3769
|
-
let insertIndex = rootIndex;
|
|
3770
|
-
while (
|
|
3771
|
-
insertIndex > 0 &&
|
|
3772
|
-
__mfSeedPackageName(__mfSeedKeys[insertIndex - 1]) === packageName &&
|
|
3773
|
-
__mfSeedKeys[insertIndex - 1] !== packageName
|
|
3774
|
-
) {
|
|
3775
|
-
insertIndex--;
|
|
3776
|
-
}
|
|
3777
|
-
__mfSeedKeys.splice(insertIndex, 0, pkg);
|
|
3778
|
-
}
|
|
3433
|
+
const __mfSeedOrder = ${JSON.stringify(seedBatches.flat())};
|
|
3434
|
+
const __mfSeedBatches = ${JSON.stringify(seedBatches)};
|
|
3435
|
+
const __mfSeedKeys = __mfSeedOrder.filter((pkg) => usedShared[pkg] && usedShared[pkg].materialize !== false);
|
|
3436
|
+
__mfModuleCache.providerInit ||= new Map();
|
|
3437
|
+
const __mfInitializeProviderOnce = (key, initialize) => {
|
|
3438
|
+
const existing = __mfModuleCache.providerInit.get(key);
|
|
3439
|
+
if (existing) return existing;
|
|
3440
|
+
const pending = Promise.resolve().then(initialize);
|
|
3441
|
+
__mfModuleCache.providerInit.set(key, pending);
|
|
3442
|
+
pending.catch(() => __mfModuleCache.providerInit.delete(key));
|
|
3443
|
+
return pending;
|
|
3444
|
+
};
|
|
3779
3445
|
var __mfSeedLocalShared = async (seedKeys) => {
|
|
3780
|
-
|
|
3446
|
+
const requested = new Set(seedKeys);
|
|
3447
|
+
for (const batch of __mfSeedBatches) await Promise.all(batch.filter((pkg) => requested.has(pkg)).map(async (pkg) => {
|
|
3781
3448
|
const share = usedShared[pkg];
|
|
3782
3449
|
const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
|
|
3783
3450
|
if (
|
|
@@ -3785,7 +3452,7 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy) {
|
|
|
3785
3452
|
Boolean(share.treeShaking) ||
|
|
3786
3453
|
__mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined
|
|
3787
3454
|
) {
|
|
3788
|
-
|
|
3455
|
+
return;
|
|
3789
3456
|
}
|
|
3790
3457
|
const singletonCacheDescriptor = __mfGetSharedCacheDescriptor(pkg, true, share.version, share.scope);
|
|
3791
3458
|
const singletonModule = __mfReadSharedCache(__mfModuleCache.share, singletonCacheDescriptor);
|
|
@@ -3796,11 +3463,20 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy) {
|
|
|
3796
3463
|
singletonModule,
|
|
3797
3464
|
__mfReadSharedCacheOwner(__mfModuleCache.share, singletonCacheDescriptor)
|
|
3798
3465
|
);
|
|
3799
|
-
|
|
3466
|
+
return;
|
|
3800
3467
|
}
|
|
3801
|
-
const
|
|
3802
|
-
|
|
3803
|
-
|
|
3468
|
+
const pendingExternalProvider = typeof __mfGetPendingExternalSharedProvider === 'function'
|
|
3469
|
+
? __mfGetPendingExternalSharedProvider(pkg, share)
|
|
3470
|
+
: undefined;
|
|
3471
|
+
if (pendingExternalProvider && !pendingExternalProvider.lib && !pendingExternalProvider.loaded) {
|
|
3472
|
+
return;
|
|
3473
|
+
}
|
|
3474
|
+
const providerKey = cacheDescriptor.canonical;
|
|
3475
|
+
const resolved = await __mfInitializeProviderOnce(providerKey, async () => {
|
|
3476
|
+
const factory = await share.get();
|
|
3477
|
+
const mod = typeof factory === "function" ? factory() : factory;
|
|
3478
|
+
return Promise.resolve(mod);
|
|
3479
|
+
});
|
|
3804
3480
|
${normalizeRuntimeShareCode}
|
|
3805
3481
|
const normalizedModule = __mfNormalizeRuntimeShare(resolved);
|
|
3806
3482
|
const exportModule = normalizedModule === resolved ? {...resolved} : normalizedModule;
|
|
@@ -3809,7 +3485,7 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy) {
|
|
|
3809
3485
|
enumerable: false
|
|
3810
3486
|
});
|
|
3811
3487
|
__mfWriteSharedCache(__mfModuleCache.share, cacheDescriptor, exportModule, mfName);
|
|
3812
|
-
}
|
|
3488
|
+
}));
|
|
3813
3489
|
};
|
|
3814
3490
|
const __mfIsRuntimeOnlySharePending = (pkg) => {
|
|
3815
3491
|
const share = usedShared[pkg];
|
|
@@ -3875,7 +3551,7 @@ function getBrowserImportPath(importPath) {
|
|
|
3875
3551
|
}
|
|
3876
3552
|
function getHostAutoInitSharedSeedItems(options) {
|
|
3877
3553
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
3878
|
-
return
|
|
3554
|
+
return getMaterializedShares(options).map((pkg) => ({
|
|
3879
3555
|
pkg,
|
|
3880
3556
|
shareItem: getShareItemForPreload(pkg, resolvedOptions)
|
|
3881
3557
|
})).filter(({ shareItem }) => shareItem?.shareConfig?.import === false).sort((a, b) => {
|
|
@@ -3895,12 +3571,10 @@ function generateHostAutoInitSharedCacheSeedCode(command = "build", options) {
|
|
|
3895
3571
|
}
|
|
3896
3572
|
const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
|
|
3897
3573
|
function getRemoteEntryId(options) {
|
|
3898
|
-
|
|
3899
|
-
return `${REMOTE_ENTRY_ID}:${scopedKey}`;
|
|
3574
|
+
return `${REMOTE_ENTRY_ID}:${getVirtualModuleScopeKey(options)}`;
|
|
3900
3575
|
}
|
|
3901
|
-
const
|
|
3902
|
-
const
|
|
3903
|
-
const getSsrOnlyPluginSpecifier = (importStatement) => [...SSR_ONLY_PLUGIN_SPECIFIERS].find((s) => importStatement.includes(s));
|
|
3576
|
+
const isSsrOnlyPlugin = (importStatement) => [...SSR_ONLY_RUNTIME_PLUGINS].some((s) => importStatement.includes(s));
|
|
3577
|
+
const getSsrOnlyPluginSpecifier = (importStatement) => [...SSR_ONLY_RUNTIME_PLUGINS].find((s) => importStatement.includes(s));
|
|
3904
3578
|
function generateTreeShakingSharedResolutionCode(enabled) {
|
|
3905
3579
|
if (!enabled) return "const __mfResolveTreeShakingShared = async () => {};";
|
|
3906
3580
|
return `
|
|
@@ -4060,10 +3734,11 @@ function generateTreeShakingSnapshotPluginCode(enabled) {
|
|
|
4060
3734
|
},
|
|
4061
3735
|
});`;
|
|
4062
3736
|
}
|
|
4063
|
-
function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options), command = "build") {
|
|
3737
|
+
function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options), command = "build", exportConditions) {
|
|
4064
3738
|
const needsSharedProviderSelectionHelper = Object.keys(options.shared ?? {}).length > 0;
|
|
4065
3739
|
const hasTreeShakingShared = Object.values(options.shared ?? {}).some((share) => !!share?.shareConfig.treeShaking);
|
|
4066
3740
|
const hasMultipleShareScopes = Array.isArray(options.shareScope);
|
|
3741
|
+
const materializedShareBatches = JSON.stringify(getShareBatches(options, false));
|
|
4067
3742
|
const runtimeImports = [
|
|
4068
3743
|
"init as runtimeInit",
|
|
4069
3744
|
"loadRemote",
|
|
@@ -4117,14 +3792,16 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4117
3792
|
import {${runtimeImports}} from "@module-federation/runtime";
|
|
4118
3793
|
${runtimeHelperImports.length ? `import {${runtimeHelperImports.join(", ")}} from "@module-federation/runtime/helpers";` : ""}
|
|
4119
3794
|
${pluginImportNames.filter((item) => !isSsrOnlyPlugin(item[1])).map((item) => item[1]).join("\n")}
|
|
4120
|
-
${command === "build" ? getRuntimeInitResolveBootstrapCode(false,
|
|
4121
|
-
${getRuntimeModuleCacheBootstrapCode()}
|
|
3795
|
+
${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options), void 0, void 0, exportConditions) + "\n const { initResolve } = globalThis[globalKey];"}
|
|
3796
|
+
${getRuntimeModuleCacheBootstrapCode(exportConditions)}
|
|
4122
3797
|
const initTokens = {}
|
|
4123
3798
|
const shareScopeNames = Array.isArray(${JSON.stringify(options.shareScope)}) ? ${JSON.stringify(options.shareScope)} : [${JSON.stringify(options.shareScope)}]
|
|
4124
3799
|
const shareScopeName = ${JSON.stringify(hasMultipleShareScopes ? options.shareScope[0] : options.shareScope)}
|
|
4125
3800
|
const mfName = ${JSON.stringify(options.name)}
|
|
3801
|
+
const __mfMaterializedShareBatches = ${materializedShareBatches}
|
|
4126
3802
|
let localSharedImportMapPromise
|
|
4127
3803
|
let exposesMapPromise
|
|
3804
|
+
let __mfLateBridgeShared
|
|
4128
3805
|
const shouldRetrySharedInitError = ${command !== "build"} && ((error) => {
|
|
4129
3806
|
const message = String((error && error.message) || error || '');
|
|
4130
3807
|
return message.includes('Importing a module script failed') ||
|
|
@@ -4195,6 +3872,40 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4195
3872
|
instance?.options?.name !== mfName &&
|
|
4196
3873
|
${hasMultipleShareScopes ? "shareScopeNames.some((scopeName) => instance?.shareScopeMap?.[scopeName] === getShareScope(scopeName))" : `instance?.shareScopeMap?.['${options.shareScope}'] === shared`}
|
|
4197
3874
|
);
|
|
3875
|
+
const __mfRuntimeShareScopes = Object.create(null);
|
|
3876
|
+
const __mfCloneShareScope = (hostScope) => {
|
|
3877
|
+
const runtimeScope = Object.create(null);
|
|
3878
|
+
for (const [pkg, versions] of Object.entries(hostScope || {})) {
|
|
3879
|
+
runtimeScope[pkg] = Object.assign(Object.create(null), versions);
|
|
3880
|
+
}
|
|
3881
|
+
return runtimeScope;
|
|
3882
|
+
};
|
|
3883
|
+
const __mfGetRuntimeShareScope = (scopeName, hostScope) => {
|
|
3884
|
+
const isWebpackScope = !scopeRoot && Object.values(hostScope || {}).some((versions) =>
|
|
3885
|
+
Object.values(versions || {}).some(isWebpackProvider)
|
|
3886
|
+
);
|
|
3887
|
+
const runtimeScope = isWebpackScope ? __mfCloneShareScope(hostScope) : hostScope;
|
|
3888
|
+
__mfRuntimeShareScopes[scopeName] = {
|
|
3889
|
+
host: hostScope,
|
|
3890
|
+
runtime: runtimeScope,
|
|
3891
|
+
isWebpackScope
|
|
3892
|
+
};
|
|
3893
|
+
return runtimeScope;
|
|
3894
|
+
};
|
|
3895
|
+
const __mfRestoreForeignSharedProviders = () => {
|
|
3896
|
+
const webpackScopes = Object.values(__mfRuntimeShareScopes).filter(
|
|
3897
|
+
({ isWebpackScope }) => isWebpackScope
|
|
3898
|
+
);
|
|
3899
|
+
if (webpackScopes.length === 0) return;
|
|
3900
|
+
for (const { host, runtime } of webpackScopes) {
|
|
3901
|
+
for (const [pkg, versions] of Object.entries(host || {})) {
|
|
3902
|
+
const runtimeVersions = runtime[pkg] ||= Object.create(null);
|
|
3903
|
+
for (const [version, provider] of Object.entries(versions || {})) {
|
|
3904
|
+
runtimeVersions[version] = provider;
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
}
|
|
3908
|
+
};
|
|
4198
3909
|
const initialShared = Object.create(null);
|
|
4199
3910
|
${hasMultipleShareScopes ? `for (const scopeName of shareScopeNames) {
|
|
4200
3911
|
for (const [pkg, versions] of Object.entries(getShareScope(scopeName))) {
|
|
@@ -4213,6 +3924,41 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4213
3924
|
}
|
|
4214
3925
|
}`}
|
|
4215
3926
|
const {usedShared, usedRemotes} = await getLocalSharedImportMap()
|
|
3927
|
+
function isWebpackProvider(provider) {
|
|
3928
|
+
if (typeof provider?.get !== 'function') return false;
|
|
3929
|
+
const source = Function.prototype.toString.call(provider.get);
|
|
3930
|
+
return source.includes('__webpack_require__');
|
|
3931
|
+
}
|
|
3932
|
+
const __mfUsesWebpackShareScope = Object.values(initialShared).some((versions) =>
|
|
3933
|
+
Object.values(versions || {}).some(isWebpackProvider)
|
|
3934
|
+
);
|
|
3935
|
+
const __mfGetSharePackageName = (pkg) => {
|
|
3936
|
+
const parts = pkg.split('/');
|
|
3937
|
+
return pkg.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
3938
|
+
};
|
|
3939
|
+
const __mfGetPendingExternalSharedProvider = (pkg, share, versionMap) => {
|
|
3940
|
+
if (typeof __mfSelectExternalSharedProvider !== 'function') return undefined;
|
|
3941
|
+
const packageName = __mfGetSharePackageName(pkg);
|
|
3942
|
+
const candidates = packageName === pkg
|
|
3943
|
+
? [[pkg, share]]
|
|
3944
|
+
: [[pkg, share], [packageName, usedShared[packageName]]];
|
|
3945
|
+
for (const [candidatePkg, candidateShare] of candidates) {
|
|
3946
|
+
if (!candidateShare) continue;
|
|
3947
|
+
const candidateVersionMap = versionMap
|
|
3948
|
+
? (candidatePkg === pkg ? versionMap : initialShared[candidatePkg])
|
|
3949
|
+
: ${hasMultipleShareScopes ? "getShareVersions(candidatePkg, candidateShare)" : "shared[candidatePkg]"};
|
|
3950
|
+
const provider = __mfSelectExternalSharedProvider(
|
|
3951
|
+
candidateVersionMap,
|
|
3952
|
+
candidatePkg,
|
|
3953
|
+
candidateShare,
|
|
3954
|
+
'${options.shareStrategy}'
|
|
3955
|
+
);
|
|
3956
|
+
if (provider && isWebpackProvider(provider) && !provider.lib && !provider.loaded) {
|
|
3957
|
+
return provider;
|
|
3958
|
+
}
|
|
3959
|
+
}
|
|
3960
|
+
return undefined;
|
|
3961
|
+
};
|
|
4216
3962
|
// handling circular init calls before an external provider can re-enter this container
|
|
4217
3963
|
${hasMultipleShareScopes ? `const shareScopeNamesToInitialize = [];
|
|
4218
3964
|
for (const shareScopeName of shareScopeNames) {
|
|
@@ -4249,8 +3995,14 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4249
3995
|
});
|
|
4250
3996
|
${hasMultipleShareScopes ? `for (const shareScopeName of shareScopeNamesToInitialize) {
|
|
4251
3997
|
const scopeShare = getShareScope(shareScopeName);
|
|
4252
|
-
initRes.initShareScopeMap(
|
|
4253
|
-
|
|
3998
|
+
initRes.initShareScopeMap(
|
|
3999
|
+
shareScopeName,
|
|
4000
|
+
__mfGetRuntimeShareScope(shareScopeName, scopeShare)
|
|
4001
|
+
);
|
|
4002
|
+
}` : `initRes.initShareScopeMap(
|
|
4003
|
+
'${options.shareScope}',
|
|
4004
|
+
__mfGetRuntimeShareScope('${options.shareScope}', shared)
|
|
4005
|
+
);`}
|
|
4254
4006
|
function __mfSharePinLifecyclePlugin() {
|
|
4255
4007
|
return {
|
|
4256
4008
|
name: "vite-share-pin-lifecycle-plugin",
|
|
@@ -4522,6 +4274,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4522
4274
|
// this container's outer initScope. Materialized providers are already active,
|
|
4523
4275
|
// so resolve them directly and keep remote initialization on the guarded path.
|
|
4524
4276
|
let directFactory = provider.lib;
|
|
4277
|
+
if (!directFactory && isWebpackProvider(provider)) return;
|
|
4525
4278
|
if (!directFactory && provider.loading) directFactory = await provider.loading;
|
|
4526
4279
|
if (!directFactory && provider.loaded && typeof provider.get === 'function') {
|
|
4527
4280
|
directFactory = await provider.get();
|
|
@@ -4546,13 +4299,10 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4546
4299
|
const resolved = loadedShare?.resolved;
|
|
4547
4300
|
if (resolved === undefined) return;
|
|
4548
4301
|
if (__mfReadSharedCache(__mfModuleCache.share, usedCacheDescriptor) !== undefined) return;
|
|
4549
|
-
|
|
4550
|
-
actualSelection.registered &&
|
|
4551
|
-
liveVersionMap?.[actualSelection.version] !== actualProvider
|
|
4552
|
-
) return;` : `if (
|
|
4302
|
+
if (
|
|
4553
4303
|
actualSelection.registered &&
|
|
4554
4304
|
liveVersionMap?.[actualSelection.version] !== actualProvider
|
|
4555
|
-
) return
|
|
4305
|
+
) return;
|
|
4556
4306
|
__mfWriteSharedCache(
|
|
4557
4307
|
__mfModuleCache.share,
|
|
4558
4308
|
usedCacheDescriptor,
|
|
@@ -4572,6 +4322,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4572
4322
|
expectedSelection
|
|
4573
4323
|
) => {
|
|
4574
4324
|
try {
|
|
4325
|
+
if (__mfGetPendingExternalSharedProvider(pkg, usedShare)) return;
|
|
4575
4326
|
const usedCacheDescriptor = __mfGetSharedCacheDescriptor(pkg, usedShare.shareConfig?.singleton, usedShare.version, usedShare.scope);
|
|
4576
4327
|
const cachedShare = __mfReadSharedCache(__mfModuleCache.share, usedCacheDescriptor);
|
|
4577
4328
|
const cachedShareOwner = __mfReadSharedCacheOwner(__mfModuleCache.share, usedCacheDescriptor);
|
|
@@ -4619,6 +4370,12 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4619
4370
|
!scopeRootProvider &&
|
|
4620
4371
|
!__mfMatchesSharedProvider(liveProvider, provider)
|
|
4621
4372
|
) return;
|
|
4373
|
+
if (
|
|
4374
|
+
!selectedLocalProvider &&
|
|
4375
|
+
isWebpackProvider(provider) &&
|
|
4376
|
+
!provider.lib &&
|
|
4377
|
+
!provider.loaded
|
|
4378
|
+
) return;
|
|
4622
4379
|
const loadedShare = await __mfLoadPinnedRuntimeShare(
|
|
4623
4380
|
pkg,
|
|
4624
4381
|
usedShare.shareConfig,
|
|
@@ -4666,10 +4423,11 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4666
4423
|
console.error('[Module Federation] Failed to bridge external shared module "' + pkg + '"', e)
|
|
4667
4424
|
}
|
|
4668
4425
|
};
|
|
4669
|
-
for (const
|
|
4670
|
-
|
|
4426
|
+
for (const batch of __mfMaterializedShareBatches) await Promise.all(batch.map(async (pkg) => {
|
|
4427
|
+
const usedShare = usedShared[pkg];
|
|
4428
|
+
if (!usedShare || usedShare.materialize === false || usedShare.treeShaking) return;
|
|
4671
4429
|
await __mfBridgeMaterializedProvider(pkg, usedShare, initialShared[pkg]);
|
|
4672
|
-
}
|
|
4430
|
+
}));
|
|
4673
4431
|
for (const [pkg, share] of Object.entries(usedShared)) {
|
|
4674
4432
|
if (share.treeShaking) continue;
|
|
4675
4433
|
const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
|
|
@@ -4685,19 +4443,27 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4685
4443
|
);
|
|
4686
4444
|
}
|
|
4687
4445
|
}
|
|
4688
|
-
${generateRuntimeSharedCacheSeedCode(options.shareStrategy)}
|
|
4446
|
+
${generateRuntimeSharedCacheSeedCode(options.shareStrategy, options)}
|
|
4689
4447
|
${initializeSharingCode}
|
|
4448
|
+
__mfRestoreForeignSharedProviders();
|
|
4690
4449
|
// Calling provider.get() marks a provider as loaded. Wait until the Runtime has
|
|
4691
4450
|
// finalized normal same-version precedence before materializing an external share.
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
|
|
4695
|
-
|
|
4696
|
-
|
|
4697
|
-
|
|
4698
|
-
|
|
4699
|
-
|
|
4700
|
-
|
|
4451
|
+
const __mfBridgeSharedProviders = async () => {
|
|
4452
|
+
for (const batch of __mfMaterializedShareBatches) await Promise.all(batch.map(async (pkg) => {
|
|
4453
|
+
const usedShare = usedShared[pkg];
|
|
4454
|
+
if (!usedShare || usedShare.materialize === false || usedShare.treeShaking) return;
|
|
4455
|
+
await __mfBridgeExternalSharedProvider(
|
|
4456
|
+
pkg,
|
|
4457
|
+
usedShare,
|
|
4458
|
+
${hasMultipleShareScopes ? "getShareVersions(pkg, usedShare)" : "shared[pkg]"},
|
|
4459
|
+
initialShared[pkg],
|
|
4460
|
+
undefined
|
|
4461
|
+
);
|
|
4462
|
+
}));
|
|
4463
|
+
};
|
|
4464
|
+
await __mfBridgeSharedProviders();
|
|
4465
|
+
if (__mfUsesWebpackShareScope) {
|
|
4466
|
+
__mfLateBridgeShared = __mfBridgeSharedProviders;
|
|
4701
4467
|
}
|
|
4702
4468
|
try {
|
|
4703
4469
|
const allInstances = globalThis.__FEDERATION__?.__SHARE__;
|
|
@@ -4732,7 +4498,9 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4732
4498
|
}
|
|
4733
4499
|
}
|
|
4734
4500
|
}
|
|
4735
|
-
for (const
|
|
4501
|
+
for (const batch of __mfMaterializedShareBatches) await Promise.all(batch.map(async (pkg) => {
|
|
4502
|
+
const versionMap = globalVersionsByPackage[pkg];
|
|
4503
|
+
if (!versionMap) return;
|
|
4736
4504
|
await __mfBridgeExternalSharedProvider(
|
|
4737
4505
|
pkg,
|
|
4738
4506
|
usedShared[pkg],
|
|
@@ -4740,7 +4508,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4740
4508
|
initialShared[pkg],
|
|
4741
4509
|
bridgeSelections.get(pkg)
|
|
4742
4510
|
);
|
|
4743
|
-
}
|
|
4511
|
+
}));
|
|
4744
4512
|
} catch (e) {
|
|
4745
4513
|
console.error('[Module Federation] Failed to bridge external shared modules', e)
|
|
4746
4514
|
}
|
|
@@ -4751,6 +4519,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4751
4519
|
? __mfReadTreeShakingSharedSelection(__mfModuleCache.share, cacheDescriptor, mfName)
|
|
4752
4520
|
: __mfReadSharedCache(__mfModuleCache.share, cacheDescriptor);
|
|
4753
4521
|
if (share.shareConfig?.import !== false || cachedShare !== undefined) return;
|
|
4522
|
+
if (__mfGetPendingExternalSharedProvider(pkg, share, initialShared[pkg])) return;
|
|
4754
4523
|
${normalizeRuntimeShareCode}
|
|
4755
4524
|
const versionMap = ${hasMultipleShareScopes ? "getShareVersions(pkg, share)" : "shared?.[pkg]"};
|
|
4756
4525
|
const provider = __mfSelectSharedProvider(
|
|
@@ -4813,18 +4582,30 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4813
4582
|
// Resolve runtime-only dependencies and seed local fallbacks in dependency
|
|
4814
4583
|
// order. Stop at an unresolved provider so its consumers cannot capture an
|
|
4815
4584
|
// undefined or provisional singleton.
|
|
4585
|
+
const __mfReadyDeferredSeedKeys = [];
|
|
4816
4586
|
for (const pkg of __mfDeferredSeedKeys) {
|
|
4817
4587
|
const share = usedShared[pkg];
|
|
4818
4588
|
if (__mfIsRuntimeOnlySharePending(pkg)) {
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4589
|
+
try {
|
|
4590
|
+
if (share.treeShaking) {
|
|
4591
|
+
await __mfResolveTreeShakingShared(pkg, share);
|
|
4592
|
+
} else if (share.shareConfig?.import === false) {
|
|
4593
|
+
await __mfResolveImportFalseShared(pkg, share);
|
|
4594
|
+
}
|
|
4595
|
+
} catch (err) {
|
|
4596
|
+
// A rejected provider is an unresolved provider: stop here as the comment above
|
|
4597
|
+
// prescribes, instead of escalating to a container-wide init() failure.
|
|
4598
|
+
console.error(
|
|
4599
|
+
\`[Module Federation] Failed to resolve runtime-only shared module "\${pkg}"\`,
|
|
4600
|
+
err
|
|
4601
|
+
);
|
|
4602
|
+
break;
|
|
4823
4603
|
}
|
|
4824
4604
|
}
|
|
4825
4605
|
if (__mfIsRuntimeOnlySharePending(pkg)) break;
|
|
4826
|
-
|
|
4606
|
+
__mfReadyDeferredSeedKeys.push(pkg);
|
|
4827
4607
|
}
|
|
4608
|
+
await __mfSeedLocalShared(__mfReadyDeferredSeedKeys);
|
|
4828
4609
|
initResolve(initRes)
|
|
4829
4610
|
return initRes
|
|
4830
4611
|
}
|
|
@@ -4832,6 +4613,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
|
|
|
4832
4613
|
async function getExposes(moduleName) {
|
|
4833
4614
|
const exposesMap = await getExposesMap()
|
|
4834
4615
|
if (!(moduleName in exposesMap)) throw new Error(\`[Module Federation] Module \${moduleName} does not exist in container.\`)
|
|
4616
|
+
if (__mfLateBridgeShared) await __mfLateBridgeShared()
|
|
4835
4617
|
if (__mfModuleCache.pendingShareLoads) {
|
|
4836
4618
|
await Promise.all(__mfModuleCache.pendingShareLoads)
|
|
4837
4619
|
}
|
|
@@ -4868,13 +4650,14 @@ function getHostAutoInitState(options) {
|
|
|
4868
4650
|
}
|
|
4869
4651
|
return state;
|
|
4870
4652
|
}
|
|
4871
|
-
function generateHostAutoInitCode(remoteEntryImport, _command = "build", options) {
|
|
4653
|
+
function generateHostAutoInitCode(remoteEntryImport, _command = "build", options, exportConditions) {
|
|
4872
4654
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
4873
4655
|
const shouldPreloadShares = resolvedOptions.shareStrategy !== "loaded-first";
|
|
4874
4656
|
const hostInitShareOrder = JSON.stringify(getOrderedUsedShares(options));
|
|
4875
4657
|
const cacheOwner = JSON.stringify(resolvedOptions.name);
|
|
4658
|
+
const preferLocalVinextReact = hasPackageDependency("vinext") && (!exportConditions?.includes("browser") || exportConditions.includes("worker"));
|
|
4876
4659
|
return `
|
|
4877
|
-
${getRuntimeModuleCacheBootstrapCode()}
|
|
4660
|
+
${getRuntimeModuleCacheBootstrapCode(exportConditions)}
|
|
4878
4661
|
let hostInitPromise;
|
|
4879
4662
|
async function initHost() {
|
|
4880
4663
|
if (!hostInitPromise) {
|
|
@@ -4886,36 +4669,46 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
|
|
|
4886
4669
|
const {usedShared} = await import("${getLocalSharedImportMapPath(options)}");
|
|
4887
4670
|
${normalizeRuntimeShareCode}
|
|
4888
4671
|
${shouldPreloadShares ? `
|
|
4889
|
-
const __mfHostInitShareOrder = ${hostInitShareOrder}
|
|
4890
|
-
.concat(Object.keys(usedShared).filter((pkg) => !${hostInitShareOrder}.includes(pkg)));
|
|
4672
|
+
const __mfHostInitShareOrder = ${hostInitShareOrder};
|
|
4891
4673
|
for (const pkg of __mfHostInitShareOrder) {
|
|
4892
4674
|
const share = usedShared[pkg];
|
|
4893
|
-
if (!share) continue;
|
|
4675
|
+
if (!share || share.materialize === false) continue;
|
|
4894
4676
|
// remoteEntry.init resolves tree-enabled shares into the
|
|
4895
4677
|
// coverage-aware cache. Never republish that selected partial under
|
|
4896
4678
|
// a generic full-module key here.
|
|
4897
4679
|
if (share.treeShaking) continue;
|
|
4898
4680
|
const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
|
|
4899
|
-
if (
|
|
4681
|
+
if (
|
|
4682
|
+
__mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined &&
|
|
4683
|
+
__mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) !== undefined
|
|
4684
|
+
) {
|
|
4900
4685
|
continue;
|
|
4901
4686
|
}
|
|
4902
4687
|
await runtime.loadShare(pkg, {
|
|
4903
4688
|
customShareInfo: { shareConfig: share.shareConfig }
|
|
4904
|
-
}).then((factory) => {
|
|
4689
|
+
}).then(async (factory) => {
|
|
4905
4690
|
const mod = typeof factory === "function" ? factory() : factory;
|
|
4906
|
-
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4691
|
+
let resolved = __mfNormalizeRuntimeShare(await Promise.resolve(mod));
|
|
4692
|
+
${preferLocalVinextReact ? `if (
|
|
4693
|
+
(pkg === "react" || pkg === "react-dom") &&
|
|
4694
|
+
typeof share.get === "function" &&
|
|
4695
|
+
share.shareConfig?.import !== false
|
|
4696
|
+
) {
|
|
4697
|
+
try {
|
|
4698
|
+
const localFactory = await share.get();
|
|
4699
|
+
const localModule = typeof localFactory === "function" ? localFactory() : localFactory;
|
|
4700
|
+
resolved = __mfNormalizeRuntimeShare(await Promise.resolve(localModule));
|
|
4701
|
+
} catch {}
|
|
4702
|
+
}` : ""}
|
|
4703
|
+
__mfWriteSharedCache(
|
|
4704
|
+
__mfModuleCache.share,
|
|
4705
|
+
cacheDescriptor,
|
|
4706
|
+
resolved,
|
|
4707
|
+
${cacheOwner}
|
|
4708
|
+
);
|
|
4914
4709
|
});
|
|
4915
4710
|
}
|
|
4916
4711
|
` : ""}
|
|
4917
|
-
const __mfRemotePreloads = [];
|
|
4918
|
-
await Promise.all(__mfRemotePreloads);
|
|
4919
4712
|
return runtime;
|
|
4920
4713
|
})();
|
|
4921
4714
|
}
|
|
@@ -4925,27 +4718,29 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
|
|
|
4925
4718
|
export { initHost, hostInitPromise };
|
|
4926
4719
|
`;
|
|
4927
4720
|
}
|
|
4928
|
-
function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID, command = "build", options) {
|
|
4721
|
+
function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID, command = "build", options, exportConditions) {
|
|
4929
4722
|
const state = getHostAutoInitState(options);
|
|
4930
4723
|
state.remoteEntryId = remoteEntryId;
|
|
4931
4724
|
state.command = command;
|
|
4932
|
-
|
|
4725
|
+
if (exportConditions !== void 0) state.exportConditions = exportConditions;
|
|
4726
|
+
state.module.writeSync(generateHostAutoInitCode(JSON.stringify(remoteEntryId), command, options, state.exportConditions), true);
|
|
4933
4727
|
}
|
|
4934
|
-
function refreshHostAutoInit(options) {
|
|
4728
|
+
function refreshHostAutoInit(options, exportConditions) {
|
|
4935
4729
|
try {
|
|
4936
4730
|
const state = getHostAutoInitState(options);
|
|
4937
|
-
writeHostAutoInit(state.remoteEntryId, state.command, options);
|
|
4731
|
+
writeHostAutoInit(state.remoteEntryId, state.command, options, exportConditions);
|
|
4938
4732
|
} catch {}
|
|
4939
4733
|
}
|
|
4940
|
-
function getHostAutoInitImportId(options) {
|
|
4941
|
-
return getHostAutoInitState(options).module.getImportId();
|
|
4942
|
-
}
|
|
4943
4734
|
function getHostAutoInitPath(options) {
|
|
4944
4735
|
return getHostAutoInitState(options).module.getImportId();
|
|
4945
4736
|
}
|
|
4737
|
+
function isOwnedHostAutoInitId(id, options) {
|
|
4738
|
+
return VirtualModule.findById(id) === getHostAutoInitState(options).module;
|
|
4739
|
+
}
|
|
4946
4740
|
//#endregion
|
|
4947
4741
|
//#region src/virtualModules/virtualRemotes.ts
|
|
4948
4742
|
const cacheRemoteMap = /* @__PURE__ */ new WeakMap();
|
|
4743
|
+
const remoteModuleMetadata = /* @__PURE__ */ new WeakMap();
|
|
4949
4744
|
const remoteOptionsIds = /* @__PURE__ */ new WeakMap();
|
|
4950
4745
|
let nextRemoteOptionsId = 1;
|
|
4951
4746
|
function getRemoteOptionsId(options) {
|
|
@@ -4967,10 +4762,24 @@ function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer
|
|
|
4967
4762
|
if (!instanceCache.has(cacheKey)) {
|
|
4968
4763
|
const virtual = new VirtualModule(`${consumer === "unified" ? remote : `${remote}__mf_consumer__${consumer}`}${MF_OWNER_INFIX}${getRemoteOptionsId(options)}`, LOAD_REMOTE_TAG, ".js", options.internalName);
|
|
4969
4764
|
virtual.writeSync(generateRemotes(remote, command, enableSsrInit, consumer, options));
|
|
4765
|
+
remoteModuleMetadata.set(virtual, {
|
|
4766
|
+
remote,
|
|
4767
|
+
command,
|
|
4768
|
+
enableSsrInit,
|
|
4769
|
+
consumer,
|
|
4770
|
+
options
|
|
4771
|
+
});
|
|
4970
4772
|
instanceCache.set(cacheKey, virtual);
|
|
4971
4773
|
}
|
|
4972
4774
|
return instanceCache.get(cacheKey);
|
|
4973
4775
|
}
|
|
4776
|
+
function refreshRemoteModuleForEnvironment(id, options, exportConditions) {
|
|
4777
|
+
const virtual = VirtualModule.findById(id);
|
|
4778
|
+
const metadata = virtual && remoteModuleMetadata.get(virtual);
|
|
4779
|
+
if (!virtual || !metadata || metadata.options !== options) return false;
|
|
4780
|
+
virtual.write(generateRemotes(metadata.remote, metadata.command, metadata.enableSsrInit, metadata.consumer, options, exportConditions));
|
|
4781
|
+
return true;
|
|
4782
|
+
}
|
|
4974
4783
|
const usedRemotesMap = {};
|
|
4975
4784
|
const usedRemotesByOptions = /* @__PURE__ */ new WeakMap();
|
|
4976
4785
|
const dynamicRemotesByOptions = /* @__PURE__ */ new WeakMap();
|
|
@@ -5186,7 +4995,7 @@ ${deferRemoteLoad ? getLazyRemotePendingExport() : getEagerRemotePendingExport()
|
|
|
5186
4995
|
${command === "serve" && consumer === "server" ? getServerThenExport() : ""}
|
|
5187
4996
|
export { __mfDefaultExport as default };`;
|
|
5188
4997
|
}
|
|
5189
|
-
function generateRemotes(id, command, enableSsrInit = false, consumer = "unified", options) {
|
|
4998
|
+
function generateRemotes(id, command, enableSsrInit = false, consumer = "unified", options, exportConditions) {
|
|
5190
4999
|
const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
|
|
5191
5000
|
const isLoadedFirst = resolvedOptions.shareStrategy === "loaded-first";
|
|
5192
5001
|
const initMode = resolveRemoteInitMode(resolvedOptions.shareStrategy, consumer);
|
|
@@ -5212,9 +5021,9 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
|
|
|
5212
5021
|
const browserHostInitCode = `import(${JSON.stringify(hostAutoInitPath)})
|
|
5213
5022
|
.then((mod) => mod.hostInitPromise)
|
|
5214
5023
|
.then(initResolve, initReject);`;
|
|
5215
|
-
const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getRuntimeInitStatusImportId(options), ssrRemotes, hostAutoInitPath)}
|
|
5024
|
+
const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getRuntimeInitStatusImportId(options), ssrRemotes, hostAutoInitPath, exportConditions)}
|
|
5216
5025
|
const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];`;
|
|
5217
|
-
const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
|
|
5026
|
+
const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode(exportConditions)}
|
|
5218
5027
|
import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(hostAutoInitPath)};` : `${devRuntimeBootstrap}
|
|
5219
5028
|
${command === "serve" && consumer !== "server" ? browserHostInitCode : ""}`;
|
|
5220
5029
|
const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
|
|
@@ -5235,6 +5044,12 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
|
|
|
5235
5044
|
__mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
|
|
5236
5045
|
.then((runtime) => {
|
|
5237
5046
|
${registerRemoteCode}
|
|
5047
|
+
const moduleCacheKey = Symbol.for(${JSON.stringify(MODULE_CACHE_SHARE_SCOPE_KEY)});
|
|
5048
|
+
const shareScopes = runtime.shareScopeMap || {};
|
|
5049
|
+
for (const scope of Object.values(shareScopes)) {
|
|
5050
|
+
if (scope && typeof scope === "object") scope[moduleCacheKey] = __mfModuleCache;
|
|
5051
|
+
}
|
|
5052
|
+
shareScopes[moduleCacheKey] = __mfModuleCache;
|
|
5238
5053
|
return runtime.loadRemote(${JSON.stringify(runtimeRemoteId)});
|
|
5239
5054
|
})
|
|
5240
5055
|
.then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
|
|
@@ -5459,15 +5274,20 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5459
5274
|
};
|
|
5460
5275
|
const __mfRemotePreloads = [${remotePreloads}];
|
|
5461
5276
|
await Promise.allSettled(__mfRemotePreloads);` : `await initHost();`;
|
|
5277
|
+
const pendingShareLoadsAwait = `
|
|
5278
|
+
if (__mfModuleCache.pendingShareLoads) {
|
|
5279
|
+
await Promise.all(__mfModuleCache.pendingShareLoads);
|
|
5280
|
+
}
|
|
5281
|
+
const __mfReactServerModuleCache = globalThis[${JSON.stringify(getModuleCacheGlobalKey(["react-server"]))}];
|
|
5282
|
+
if (__mfReactServerModuleCache?.pendingShareLoads) {
|
|
5283
|
+
await Promise.all(__mfReactServerModuleCache.pendingShareLoads);
|
|
5284
|
+
}`;
|
|
5462
5285
|
const importCode = `
|
|
5463
5286
|
(async () => {
|
|
5464
5287
|
const __mfHostInit = await ${importExpression(initSrc)};
|
|
5465
5288
|
await __mfHostInit.__tla;
|
|
5466
5289
|
const { initHost } = __mfHostInit;
|
|
5467
|
-
${preloadBlock}
|
|
5468
|
-
if (__mfModuleCache.pendingShareLoads) {
|
|
5469
|
-
await Promise.all(__mfModuleCache.pendingShareLoads);
|
|
5470
|
-
}
|
|
5290
|
+
${preloadBlock}${pendingShareLoadsAwait}
|
|
5471
5291
|
})().then(() => ${entryImportExpression});
|
|
5472
5292
|
`;
|
|
5473
5293
|
return [
|
|
@@ -5493,6 +5313,10 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5493
5313
|
function normalizeModuleId(id) {
|
|
5494
5314
|
return normalizePathForImport(id.split("?")[0]);
|
|
5495
5315
|
}
|
|
5316
|
+
function isReactRouterClientEntry(id) {
|
|
5317
|
+
const normalized = normalizeModuleId(decodeViteId(id).replace(/^\0+/, ""));
|
|
5318
|
+
return /(?:^|\/)entry\.client\.(?:[cm]?[jt]sx?)$/.test(normalized);
|
|
5319
|
+
}
|
|
5496
5320
|
function resolveProjectId(id) {
|
|
5497
5321
|
if (id.startsWith("\0") || id.startsWith("virtual:")) return normalizeModuleId(id);
|
|
5498
5322
|
return normalizeModuleId(path$1.isAbsolute(id) ? id : path$1.resolve(viteConfig.root, id));
|
|
@@ -5753,10 +5577,11 @@ const __mfCurrentScript = document.currentScript;
|
|
|
5753
5577
|
const injection = `await import(${JSON.stringify(getEntryPath())}).then(({ initHost }) => initHost());\n `;
|
|
5754
5578
|
return mapCodeToCodeWithSourcemap(code.replace("vueApp.mount(vueAppRootContainer);", `${injection}vueApp.mount(vueAppRootContainer);`));
|
|
5755
5579
|
}
|
|
5756
|
-
const
|
|
5580
|
+
const isReactRouterEntry = isReactRouterClientEntry(id);
|
|
5581
|
+
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));
|
|
5757
5582
|
const isNuxtEntryAsyncModule = /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
|
|
5758
5583
|
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);
|
|
5759
|
-
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 || isNuxtClientEntryFallback)) {
|
|
5584
|
+
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)) {
|
|
5760
5585
|
clientInjected = true;
|
|
5761
5586
|
injectedTransformIds.add(projectId);
|
|
5762
5587
|
if (!waitsForInit) return mapCodeToCodeWithSourcemap(`import ${JSON.stringify(getEntryPath())};\n` + code);
|
|
@@ -5892,10 +5717,12 @@ const reactAdapter = {
|
|
|
5892
5717
|
* host components lives in the orphaned first runtime, but `reload(hmrId, ...)`
|
|
5893
5718
|
* goes through the second runtime — the lookup misses and HMR stops working.
|
|
5894
5719
|
*
|
|
5895
|
-
* This guard pins `__VUE_HMR_RUNTIME__` to the first
|
|
5720
|
+
* This guard pins `__VUE_HMR_RUNTIME__` to the first application Vue runtime
|
|
5896
5721
|
* via a property trap on `globalThis`. Subsequent writes from remote-side Vue
|
|
5897
|
-
* copies are silently dropped.
|
|
5898
|
-
*
|
|
5722
|
+
* copies are silently dropped. vite-plugin-checker bundles its own Vue runtime
|
|
5723
|
+
* and evaluates it before the application, so writes from its virtual runtime
|
|
5724
|
+
* are ignored explicitly. Must execute before any Vue module loads — injected
|
|
5725
|
+
* as a plain (non-module) script at `head-prepend`.
|
|
5899
5726
|
*
|
|
5900
5727
|
* `singleton: true` in `shared` is not sufficient: in dev mode MF's share-scope
|
|
5901
5728
|
* does not actually dedupe Vue across dev servers, so without this guard the
|
|
@@ -5906,7 +5733,11 @@ const VUE_HMR_RUNTIME_GUARD_SCRIPT = `
|
|
|
5906
5733
|
var h = null;
|
|
5907
5734
|
Object.defineProperty(globalThis, '__VUE_HMR_RUNTIME__', {
|
|
5908
5735
|
get: function () { return h; },
|
|
5909
|
-
set: function (v) {
|
|
5736
|
+
set: function (v) {
|
|
5737
|
+
var stack = new Error().stack || '';
|
|
5738
|
+
if (stack.indexOf('@vite-plugin-checker-runtime') !== -1) return;
|
|
5739
|
+
if (h === null) h = v;
|
|
5740
|
+
},
|
|
5910
5741
|
configurable: true,
|
|
5911
5742
|
enumerable: true,
|
|
5912
5743
|
});
|
|
@@ -5973,7 +5804,7 @@ const REMOTE_HMR_ENDPOINT = "__mf_hmr";
|
|
|
5973
5804
|
const REMOTE_HMR_EVENT = "mf:remote-update";
|
|
5974
5805
|
const REMOTE_HMR_CONNECT_RETRY_DELAY_MS = 1e3;
|
|
5975
5806
|
const REMOTE_HMR_CONNECT_MAX_RETRIES = 10;
|
|
5976
|
-
function getBasePath
|
|
5807
|
+
function getBasePath(base) {
|
|
5977
5808
|
if (!base) return "/";
|
|
5978
5809
|
if (base.startsWith("http://") || base.startsWith("https://")) try {
|
|
5979
5810
|
return new URL(base).pathname || "/";
|
|
@@ -5983,11 +5814,11 @@ function getBasePath$1(base) {
|
|
|
5983
5814
|
return base;
|
|
5984
5815
|
}
|
|
5985
5816
|
function getRemoteHmrPath(base) {
|
|
5986
|
-
return `${getBasePath
|
|
5817
|
+
return `${getBasePath(base).replace(/\/?$/, "/")}${REMOTE_HMR_ENDPOINT}`.replace(/\/{2,}/g, "/");
|
|
5987
5818
|
}
|
|
5988
5819
|
function getHmrWsPath(base, hmrPath) {
|
|
5989
|
-
const normalizedBase = getBasePath
|
|
5990
|
-
const normalizedPath = getBasePath
|
|
5820
|
+
const normalizedBase = getBasePath(base);
|
|
5821
|
+
const normalizedPath = getBasePath(hmrPath || "");
|
|
5991
5822
|
if (!normalizedPath || normalizedPath === "/") return normalizedBase;
|
|
5992
5823
|
return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
|
|
5993
5824
|
}
|
|
@@ -6872,7 +6703,7 @@ const buildFileToShareKeyMap = async (shareKeys, resolveFn, options) => {
|
|
|
6872
6703
|
* and shared packages are imported as bare specifiers (externals in the SSR build).
|
|
6873
6704
|
*/
|
|
6874
6705
|
function getVirtualExposesSSRId(options) {
|
|
6875
|
-
return `virtual:mf-exposes-ssr:${
|
|
6706
|
+
return `virtual:mf-exposes-ssr:${getVirtualModuleScopeKey(options)}`;
|
|
6876
6707
|
}
|
|
6877
6708
|
/**
|
|
6878
6709
|
* Generates the SSR exposes map module.
|
|
@@ -6908,8 +6739,7 @@ function generateExposesSSR(options, reactIslandExposes = /* @__PURE__ */ new Se
|
|
|
6908
6739
|
//#region src/virtualModules/virtualRemoteEntrySSR.ts
|
|
6909
6740
|
const REMOTE_ENTRY_SSR_ID = "virtual:mf-REMOTE_ENTRY_SSR_ID";
|
|
6910
6741
|
function getRemoteEntrySSRId(options) {
|
|
6911
|
-
|
|
6912
|
-
return `${REMOTE_ENTRY_SSR_ID}:${scopedKey}`;
|
|
6742
|
+
return `${REMOTE_ENTRY_SSR_ID}:${getVirtualModuleScopeKey(options)}`;
|
|
6913
6743
|
}
|
|
6914
6744
|
function getSsrRemoteEntryFileName(browserFilename) {
|
|
6915
6745
|
const ext = browserFilename.match(/\.[^.]+$/)?.[0] || ".js";
|
|
@@ -6927,11 +6757,25 @@ function getSsrRemoteEntryFileName(browserFilename) {
|
|
|
6927
6757
|
*/
|
|
6928
6758
|
function generateRemoteEntrySSR(options) {
|
|
6929
6759
|
const virtualExposesSSRId = getVirtualExposesSSRId(options);
|
|
6760
|
+
const sharedSingletons = Object.fromEntries(Object.entries(options.shared).filter(([, share]) => share.shareConfig.singleton));
|
|
6930
6761
|
return `
|
|
6931
6762
|
import { init as runtimeInit } from "@module-federation/runtime";
|
|
6932
6763
|
|
|
6764
|
+
const sharedSingletons = ${JSON.stringify(sharedSingletons)};
|
|
6765
|
+
const moduleCacheKey = Symbol.for(${JSON.stringify(MODULE_CACHE_SHARE_SCOPE_KEY)});
|
|
6933
6766
|
let exposesMapPromise;
|
|
6934
6767
|
|
|
6768
|
+
function createShareInitError(errors) {
|
|
6769
|
+
const details = errors.map(({ scopeName, pkg, error }) => {
|
|
6770
|
+
const target = pkg
|
|
6771
|
+
? \`scope "\${scopeName}" package "\${pkg}"\`
|
|
6772
|
+
: \`scope "\${scopeName}"\`;
|
|
6773
|
+
return \`\${target}: \${error instanceof Error ? error.message : String(error)}\`;
|
|
6774
|
+
});
|
|
6775
|
+
const message = \`[Module Federation SSR] Shared initialization failed: \${details.join('; ')}\`;
|
|
6776
|
+
return new AggregateError(errors.map(({ error }) => error), message);
|
|
6777
|
+
}
|
|
6778
|
+
|
|
6935
6779
|
async function getExposesMap() {
|
|
6936
6780
|
exposesMapPromise ??= import(${JSON.stringify(virtualExposesSSRId)}).then((mod) => mod.default ?? mod);
|
|
6937
6781
|
return exposesMapPromise;
|
|
@@ -6954,24 +6798,55 @@ function generateRemoteEntrySSR(options) {
|
|
|
6954
6798
|
const shareScopeNames = Array.isArray(${JSON.stringify(options.shareScope)})
|
|
6955
6799
|
? ${JSON.stringify(options.shareScope)}
|
|
6956
6800
|
: [${JSON.stringify(options.shareScope)}];
|
|
6957
|
-
|
|
6958
|
-
|
|
6801
|
+
const shareInitErrors = [];
|
|
6802
|
+
const cacheEntries = [];
|
|
6803
|
+
for (const scopeName of shareScopeNames) {
|
|
6804
|
+
let scopeShare;
|
|
6805
|
+
try {
|
|
6806
|
+
scopeShare = Array.isArray(${JSON.stringify(options.shareScope)})
|
|
6807
|
+
? shared?.[scopeName] || {}
|
|
6808
|
+
: shared || {};
|
|
6809
|
+
initRes.initShareScopeMap(scopeName, scopeShare);
|
|
6810
|
+
await Promise.all(
|
|
6811
|
+
await initRes.initializeSharing(scopeName, {
|
|
6812
|
+
strategy: ${JSON.stringify(options.shareStrategy ?? "version-first")},
|
|
6813
|
+
from: 'build',
|
|
6814
|
+
initScope,
|
|
6815
|
+
})
|
|
6816
|
+
);
|
|
6817
|
+
} catch (e) {
|
|
6818
|
+
shareInitErrors.push({ scopeName, pkg: undefined, error: e });
|
|
6819
|
+
continue;
|
|
6820
|
+
}
|
|
6821
|
+
|
|
6822
|
+
for (const [pkg, shareInfo] of Object.entries(sharedSingletons)) {
|
|
6959
6823
|
try {
|
|
6960
|
-
|
|
6961
|
-
|
|
6962
|
-
await
|
|
6963
|
-
|
|
6964
|
-
|
|
6965
|
-
|
|
6966
|
-
|
|
6967
|
-
|
|
6968
|
-
);
|
|
6824
|
+
if (shareInfo.scope !== scopeName) continue;
|
|
6825
|
+
if (!scopeShare[pkg]) continue;
|
|
6826
|
+
const factory = await initRes.loadShare(pkg, {
|
|
6827
|
+
customShareInfo: { ...shareInfo, scope: [scopeName] },
|
|
6828
|
+
});
|
|
6829
|
+
if (typeof factory !== 'function') {
|
|
6830
|
+
throw new Error('No compatible host provider was selected');
|
|
6831
|
+
}
|
|
6832
|
+
const module = await factory();
|
|
6833
|
+
cacheEntries.push({ scopeName, pkg, module });
|
|
6969
6834
|
} catch (e) {
|
|
6970
|
-
|
|
6835
|
+
shareInitErrors.push({ scopeName, pkg, error: e });
|
|
6971
6836
|
}
|
|
6972
6837
|
}
|
|
6973
|
-
}
|
|
6974
|
-
|
|
6838
|
+
}
|
|
6839
|
+
if (shareInitErrors.length > 0) {
|
|
6840
|
+
throw createShareInitError(shareInitErrors);
|
|
6841
|
+
}
|
|
6842
|
+
if (cacheEntries.length > 0) {
|
|
6843
|
+
const moduleCache = shared?.[moduleCacheKey] ||
|
|
6844
|
+
(globalThis.__mf_module_cache__ ||= { share: {}, remote: {} });
|
|
6845
|
+
const cache = (moduleCache.share ||= {});
|
|
6846
|
+
for (const { scopeName, pkg, module } of cacheEntries) {
|
|
6847
|
+
cache[scopeName + ':' + pkg] ??= module;
|
|
6848
|
+
if (scopeName === 'default') cache[pkg] ??= module;
|
|
6849
|
+
}
|
|
6975
6850
|
}
|
|
6976
6851
|
return initRes;
|
|
6977
6852
|
}
|
|
@@ -6987,318 +6862,6 @@ function generateRemoteEntrySSR(options) {
|
|
|
6987
6862
|
`;
|
|
6988
6863
|
}
|
|
6989
6864
|
//#endregion
|
|
6990
|
-
//#region src/plugins/pluginDts.ts
|
|
6991
|
-
var pluginDts_exports = /* @__PURE__ */ __exportAll({
|
|
6992
|
-
DEFAULT_PUBLIC_TYPES_FOLDER: () => DEFAULT_PUBLIC_TYPES_FOLDER,
|
|
6993
|
-
createDevDtsAssetMiddleware: () => createDevDtsAssetMiddleware,
|
|
6994
|
-
default: () => pluginDts,
|
|
6995
|
-
getDevDtsAssetPaths: () => getDevDtsAssetPaths,
|
|
6996
|
-
resolveDtsPluginOptions: () => resolveDtsPluginOptions
|
|
6997
|
-
});
|
|
6998
|
-
const DEFAULT_DEV_OPTIONS = {
|
|
6999
|
-
disableLiveReload: true,
|
|
7000
|
-
disableHotTypesReload: false,
|
|
7001
|
-
disableDynamicRemoteTypeHints: false
|
|
7002
|
-
};
|
|
7003
|
-
const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
|
|
7004
|
-
const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
|
|
7005
|
-
const DEV_TYPES_FOLDER = ".dev-server";
|
|
7006
|
-
const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
|
|
7007
|
-
const forkDevWorkerPath = (() => {
|
|
7008
|
-
return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
|
|
7009
|
-
})();
|
|
7010
|
-
var DevWorker = class {
|
|
7011
|
-
worker = rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
|
|
7012
|
-
constructor(options) {
|
|
7013
|
-
this.worker.connect(options);
|
|
7014
|
-
}
|
|
7015
|
-
update() {
|
|
7016
|
-
this.worker.process?.send?.({
|
|
7017
|
-
type: rpc.RpcGMCallTypes.CALL,
|
|
7018
|
-
id: this.worker.id,
|
|
7019
|
-
args: [void 0, "update"]
|
|
7020
|
-
});
|
|
7021
|
-
}
|
|
7022
|
-
exit() {
|
|
7023
|
-
this.worker.terminate();
|
|
7024
|
-
}
|
|
7025
|
-
};
|
|
7026
|
-
const normalizeDevOptions = (dev) => {
|
|
7027
|
-
if (dev === false) return false;
|
|
7028
|
-
if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
|
|
7029
|
-
return {
|
|
7030
|
-
...DEFAULT_DEV_OPTIONS,
|
|
7031
|
-
...dev
|
|
7032
|
-
};
|
|
7033
|
-
};
|
|
7034
|
-
const buildDtsModuleFederationConfig = (options) => {
|
|
7035
|
-
const exposes = {};
|
|
7036
|
-
Object.entries(options.exposes).forEach(([key, value]) => {
|
|
7037
|
-
if (value.import) exposes[key] = value.import;
|
|
7038
|
-
});
|
|
7039
|
-
const remotes = {};
|
|
7040
|
-
Object.entries(options.remotes).forEach(([key, remote]) => {
|
|
7041
|
-
if (!remote.entry) return;
|
|
7042
|
-
const entryGlobalName = remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key;
|
|
7043
|
-
remotes[key] = `${entryGlobalName}@${remote.entry}`;
|
|
7044
|
-
});
|
|
7045
|
-
return {
|
|
7046
|
-
...options,
|
|
7047
|
-
exposes,
|
|
7048
|
-
remotes
|
|
7049
|
-
};
|
|
7050
|
-
};
|
|
7051
|
-
const resolveOutputDir = (config) => {
|
|
7052
|
-
const { outDir } = config.build;
|
|
7053
|
-
if (path$1.isAbsolute(outDir)) return normalizePathForImport(path$1.relative(config.root, outDir));
|
|
7054
|
-
return outDir;
|
|
7055
|
-
};
|
|
7056
|
-
const ensureRuntimePlugin = (options, pluginId) => {
|
|
7057
|
-
if (!options.runtimePlugins.some((plugin) => {
|
|
7058
|
-
if (typeof plugin === "string") return plugin === pluginId;
|
|
7059
|
-
return plugin[0] === pluginId;
|
|
7060
|
-
})) options.runtimePlugins.push(pluginId);
|
|
7061
|
-
};
|
|
7062
|
-
const getExposeImportPaths = (options) => {
|
|
7063
|
-
return Object.values(options.exposes).map((value) => {
|
|
7064
|
-
return value.import;
|
|
7065
|
-
}).filter((value) => Boolean(value));
|
|
7066
|
-
};
|
|
7067
|
-
const usesVueSfcExposes = (options) => {
|
|
7068
|
-
return getExposeImportPaths(options).some((value) => value.endsWith(".vue"));
|
|
7069
|
-
};
|
|
7070
|
-
const resolveDtsPluginOptions = (dts, options, context) => {
|
|
7071
|
-
if (dts === false) return false;
|
|
7072
|
-
const inferredGenerateTypesDefaults = { generateAPITypes: true };
|
|
7073
|
-
if (usesVueSfcExposes(options) && hasPackageDependency("vue-tsc", context)) inferredGenerateTypesDefaults.compilerInstance = "vue-tsc";
|
|
7074
|
-
if (dts === true || typeof dts === "undefined") return { generateTypes: inferredGenerateTypesDefaults };
|
|
7075
|
-
const generateTypes = dts.generateTypes;
|
|
7076
|
-
return {
|
|
7077
|
-
...dts,
|
|
7078
|
-
generateTypes: generateTypes === false ? false : {
|
|
7079
|
-
...inferredGenerateTypesDefaults,
|
|
7080
|
-
...generateTypes === true || typeof generateTypes === "undefined" ? {} : generateTypes
|
|
7081
|
-
}
|
|
7082
|
-
};
|
|
7083
|
-
};
|
|
7084
|
-
const getBasePath = (base) => {
|
|
7085
|
-
if (base.startsWith("http://") || base.startsWith("https://")) return new URL(base).pathname.replace(/\/$/, "") || "/";
|
|
7086
|
-
return base.replace(/\/$/, "") || "/";
|
|
7087
|
-
};
|
|
7088
|
-
const joinBaseAndAsset = (base, assetFileName) => {
|
|
7089
|
-
const basePath = getBasePath(base);
|
|
7090
|
-
return `${basePath === "/" ? "" : basePath}/${assetFileName}`.replace(/\/{2,}/g, "/");
|
|
7091
|
-
};
|
|
7092
|
-
const getDevDtsAssetPaths = (options) => {
|
|
7093
|
-
const { outputDir, publicTypesFolder, root, base } = options;
|
|
7094
|
-
return {
|
|
7095
|
-
apiFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.d.ts`),
|
|
7096
|
-
apiRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.d.ts`),
|
|
7097
|
-
zipFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.zip`),
|
|
7098
|
-
zipRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.zip`)
|
|
7099
|
-
};
|
|
7100
|
-
};
|
|
7101
|
-
const createDevDtsAssetMiddleware = (assetPaths) => {
|
|
7102
|
-
return (req, res, next) => {
|
|
7103
|
-
const requestPath = req.url?.split("?")[0];
|
|
7104
|
-
const isZipRequest = requestPath === assetPaths.zipRequestPath;
|
|
7105
|
-
const isApiRequest = requestPath === assetPaths.apiRequestPath;
|
|
7106
|
-
if (!isZipRequest && !isApiRequest) {
|
|
7107
|
-
next();
|
|
7108
|
-
return;
|
|
7109
|
-
}
|
|
7110
|
-
const filePath = isZipRequest ? assetPaths.zipFilePath : assetPaths.apiFilePath;
|
|
7111
|
-
if (!fs.existsSync(filePath)) {
|
|
7112
|
-
res.statusCode = 404;
|
|
7113
|
-
res.end();
|
|
7114
|
-
return;
|
|
7115
|
-
}
|
|
7116
|
-
res.statusCode = 200;
|
|
7117
|
-
res.setHeader("Content-Type", isZipRequest ? "application/x-gzip" : "application/typescript");
|
|
7118
|
-
if (req.method === "HEAD") {
|
|
7119
|
-
res.end();
|
|
7120
|
-
return;
|
|
7121
|
-
}
|
|
7122
|
-
const stream = fs.createReadStream(filePath);
|
|
7123
|
-
stream.on("error", () => {
|
|
7124
|
-
if (!res.headersSent) res.statusCode = 500;
|
|
7125
|
-
res.end();
|
|
7126
|
-
});
|
|
7127
|
-
res.on("close", () => {
|
|
7128
|
-
stream.destroy();
|
|
7129
|
-
});
|
|
7130
|
-
stream.pipe(res);
|
|
7131
|
-
};
|
|
7132
|
-
};
|
|
7133
|
-
const normalizeDevDtsOptions = (dts, context) => {
|
|
7134
|
-
return normalizeOptions(isTSProject(dts, context), {
|
|
7135
|
-
generateTypes: { compileInChildProcess: true },
|
|
7136
|
-
consumeTypes: { consumeAPITypes: true },
|
|
7137
|
-
extraOptions: {},
|
|
7138
|
-
displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
|
|
7139
|
-
}, "mfOptions.dts")(dts);
|
|
7140
|
-
};
|
|
7141
|
-
const logDtsError = (error, dtsOptions) => {
|
|
7142
|
-
if (dtsOptions === false) return;
|
|
7143
|
-
if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
|
|
7144
|
-
mfError(error);
|
|
7145
|
-
};
|
|
7146
|
-
function pluginDts(options) {
|
|
7147
|
-
if (options.dts === false) return [];
|
|
7148
|
-
const baseDtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
|
|
7149
|
-
const getDtsModuleFederationConfig = (context) => ({
|
|
7150
|
-
...baseDtsModuleFederationConfig,
|
|
7151
|
-
dts: resolveDtsPluginOptions(options.dts, options, context)
|
|
7152
|
-
});
|
|
7153
|
-
let resolvedConfig;
|
|
7154
|
-
let devWorker;
|
|
7155
|
-
let normalizedDevOptions;
|
|
7156
|
-
let hasGeneratedBundle = false;
|
|
7157
|
-
return [{
|
|
7158
|
-
name: "module-federation-dts-dev",
|
|
7159
|
-
apply: "serve",
|
|
7160
|
-
config(config) {
|
|
7161
|
-
normalizedDevOptions = normalizeDevOptions(options.dev);
|
|
7162
|
-
if (!normalizedDevOptions) return;
|
|
7163
|
-
if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
|
|
7164
|
-
ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
|
|
7165
|
-
const define = config.define ? { ...config.define } : {};
|
|
7166
|
-
if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
|
|
7167
|
-
config.define = define;
|
|
7168
|
-
},
|
|
7169
|
-
configResolved(config) {
|
|
7170
|
-
resolvedConfig = config;
|
|
7171
|
-
},
|
|
7172
|
-
configureServer(server) {
|
|
7173
|
-
if (!normalizedDevOptions || !resolvedConfig) return;
|
|
7174
|
-
const devOptions = normalizedDevOptions;
|
|
7175
|
-
if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
|
|
7176
|
-
if (!options.name) throw createModuleFederationError("name is required if you want to enable dev server!");
|
|
7177
|
-
const outputDir = resolveOutputDir(resolvedConfig);
|
|
7178
|
-
const dtsModuleFederationConfig = getDtsModuleFederationConfig(resolvedConfig.root);
|
|
7179
|
-
const normalizedDtsOptions = normalizeDevDtsOptions(dtsModuleFederationConfig.dts, resolvedConfig.root);
|
|
7180
|
-
if (typeof normalizedDtsOptions !== "object") return;
|
|
7181
|
-
const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
|
|
7182
|
-
const remote = normalizedGenerateTypes === false ? void 0 : {
|
|
7183
|
-
implementation: normalizedDtsOptions.implementation,
|
|
7184
|
-
context: resolvedConfig.root,
|
|
7185
|
-
outputDir,
|
|
7186
|
-
moduleFederationConfig: { ...dtsModuleFederationConfig },
|
|
7187
|
-
hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
|
|
7188
|
-
...normalizedGenerateTypes,
|
|
7189
|
-
typesFolder: DEV_TYPES_FOLDER
|
|
7190
|
-
};
|
|
7191
|
-
if (remote) server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({
|
|
7192
|
-
outputDir,
|
|
7193
|
-
publicTypesFolder: remote.hostRemoteTypesFolder || "@mf-types",
|
|
7194
|
-
root: resolvedConfig.root,
|
|
7195
|
-
base: resolvedConfig.base
|
|
7196
|
-
})));
|
|
7197
|
-
if (remote && !remote.tsConfigPath && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
|
|
7198
|
-
const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
|
|
7199
|
-
const host = normalizedConsumeTypes === false ? void 0 : {
|
|
7200
|
-
implementation: normalizedDtsOptions.implementation,
|
|
7201
|
-
context: resolvedConfig.root,
|
|
7202
|
-
moduleFederationConfig: dtsModuleFederationConfig,
|
|
7203
|
-
typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
|
|
7204
|
-
abortOnError: false,
|
|
7205
|
-
...normalizedConsumeTypes
|
|
7206
|
-
};
|
|
7207
|
-
const extraOptions = normalizedDtsOptions.extraOptions || {};
|
|
7208
|
-
if (!remote && !host && devOptions.disableLiveReload) return;
|
|
7209
|
-
const startDevWorker = async () => {
|
|
7210
|
-
let remoteTypeUrls;
|
|
7211
|
-
if (host) remoteTypeUrls = await new Promise((resolve) => {
|
|
7212
|
-
consumeTypesAPI({
|
|
7213
|
-
host,
|
|
7214
|
-
extraOptions,
|
|
7215
|
-
displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
|
|
7216
|
-
}, resolve);
|
|
7217
|
-
});
|
|
7218
|
-
devWorker = new DevWorker({
|
|
7219
|
-
name: options.name,
|
|
7220
|
-
remote,
|
|
7221
|
-
host: host ? {
|
|
7222
|
-
...host,
|
|
7223
|
-
remoteTypeUrls
|
|
7224
|
-
} : void 0,
|
|
7225
|
-
extraOptions,
|
|
7226
|
-
disableLiveReload: devOptions.disableLiveReload,
|
|
7227
|
-
disableHotTypesReload: devOptions.disableHotTypesReload
|
|
7228
|
-
});
|
|
7229
|
-
const update = () => devWorker?.update();
|
|
7230
|
-
server.watcher.on("change", update);
|
|
7231
|
-
server.watcher.on("add", update);
|
|
7232
|
-
server.watcher.on("unlink", update);
|
|
7233
|
-
server.httpServer?.once("close", () => {
|
|
7234
|
-
devWorker?.exit();
|
|
7235
|
-
server.watcher.off("change", update);
|
|
7236
|
-
server.watcher.off("add", update);
|
|
7237
|
-
server.watcher.off("unlink", update);
|
|
7238
|
-
});
|
|
7239
|
-
};
|
|
7240
|
-
startDevWorker().catch((error) => {
|
|
7241
|
-
logDtsError(error, normalizedDtsOptions);
|
|
7242
|
-
});
|
|
7243
|
-
}
|
|
7244
|
-
}, {
|
|
7245
|
-
name: "module-federation-dts-build",
|
|
7246
|
-
apply: "build",
|
|
7247
|
-
configResolved(config) {
|
|
7248
|
-
resolvedConfig = config;
|
|
7249
|
-
},
|
|
7250
|
-
async generateBundle() {
|
|
7251
|
-
if (hasGeneratedBundle) return;
|
|
7252
|
-
hasGeneratedBundle = true;
|
|
7253
|
-
if (!resolvedConfig) return;
|
|
7254
|
-
let normalizedDtsOptions;
|
|
7255
|
-
try {
|
|
7256
|
-
normalizedDtsOptions = normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root), resolvedConfig.root);
|
|
7257
|
-
} catch (error) {
|
|
7258
|
-
logDtsError(error, options.dts);
|
|
7259
|
-
return;
|
|
7260
|
-
}
|
|
7261
|
-
if (typeof normalizedDtsOptions !== "object") return;
|
|
7262
|
-
const context = resolvedConfig.root;
|
|
7263
|
-
const outputDir = resolveOutputDir(resolvedConfig);
|
|
7264
|
-
let consumeOptions;
|
|
7265
|
-
try {
|
|
7266
|
-
consumeOptions = normalizeConsumeTypesOptions({
|
|
7267
|
-
context,
|
|
7268
|
-
dtsOptions: normalizedDtsOptions,
|
|
7269
|
-
pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
|
|
7270
|
-
});
|
|
7271
|
-
} catch (error) {
|
|
7272
|
-
logDtsError(error, normalizedDtsOptions);
|
|
7273
|
-
return;
|
|
7274
|
-
}
|
|
7275
|
-
if (consumeOptions?.host?.typesOnBuild) try {
|
|
7276
|
-
await consumeTypesAPI(consumeOptions);
|
|
7277
|
-
} catch (error) {
|
|
7278
|
-
logDtsError(error, normalizedDtsOptions);
|
|
7279
|
-
}
|
|
7280
|
-
let generateOptions;
|
|
7281
|
-
try {
|
|
7282
|
-
generateOptions = normalizeGenerateTypesOptions({
|
|
7283
|
-
context,
|
|
7284
|
-
outputDir,
|
|
7285
|
-
dtsOptions: normalizedDtsOptions,
|
|
7286
|
-
pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
|
|
7287
|
-
});
|
|
7288
|
-
} catch (error) {
|
|
7289
|
-
logDtsError(error, normalizedDtsOptions);
|
|
7290
|
-
return;
|
|
7291
|
-
}
|
|
7292
|
-
if (!generateOptions) return;
|
|
7293
|
-
try {
|
|
7294
|
-
await generateTypesAPI({ dtsManagerOptions: generateOptions });
|
|
7295
|
-
} catch (error) {
|
|
7296
|
-
logDtsError(error, normalizedDtsOptions);
|
|
7297
|
-
}
|
|
7298
|
-
}
|
|
7299
|
-
}];
|
|
7300
|
-
}
|
|
7301
|
-
//#endregion
|
|
7302
6865
|
//#region src/plugins/pluginMFManifest.ts
|
|
7303
6866
|
/**
|
|
7304
6867
|
* Resolves the build version for the module federation manifest.
|
|
@@ -7884,6 +7447,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7884
7447
|
const cleanId = id.split("?")[0];
|
|
7885
7448
|
return cleanId.includes(getHostAutoInitPath(options)) || cleanId.includes(getHostAutoInitPath());
|
|
7886
7449
|
};
|
|
7450
|
+
const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
|
|
7887
7451
|
function isRemoteImport(source) {
|
|
7888
7452
|
return Object.keys(options.remotes).some((name) => source === name || source.startsWith(name + "/"));
|
|
7889
7453
|
}
|
|
@@ -7983,7 +7547,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7983
7547
|
}
|
|
7984
7548
|
},
|
|
7985
7549
|
async load(id) {
|
|
7986
|
-
if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
|
|
7550
|
+
if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(this)));
|
|
7987
7551
|
if (id === virtualExposesId) {
|
|
7988
7552
|
await refreshExposeRemoteDependencies(this);
|
|
7989
7553
|
return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
|
|
@@ -7993,7 +7557,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
7993
7557
|
async transform(code, id) {
|
|
7994
7558
|
return mapCodeToCodeWithSourcemap(await (async () => {
|
|
7995
7559
|
if (!filterId(id)) return;
|
|
7996
|
-
if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
|
|
7560
|
+
if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(this)));
|
|
7997
7561
|
if (id === virtualExposesId) {
|
|
7998
7562
|
await refreshExposeRemoteDependencies(this);
|
|
7999
7563
|
return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
|
|
@@ -8011,7 +7575,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
8011
7575
|
return `
|
|
8012
7576
|
const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
|
|
8013
7577
|
const remoteEntryImport = typeof window !== 'undefined' ? ${isAbsolutePublicPath ? remoteEntryUrl : `origin + ${remoteEntryUrl}`} : ${JSON.stringify(ssrRemoteEntry)};
|
|
8014
|
-
${generateHostAutoInitCode("remoteEntryImport", "serve", options)}
|
|
7578
|
+
${generateHostAutoInitCode("remoteEntryImport", "serve", options, getEnvironmentConditions(this))}
|
|
8015
7579
|
`;
|
|
8016
7580
|
}
|
|
8017
7581
|
return code;
|
|
@@ -8225,12 +7789,15 @@ function getSharedKeyMatcher(shared) {
|
|
|
8225
7789
|
let vueKey;
|
|
8226
7790
|
for (const key of keys) {
|
|
8227
7791
|
const keyBase = key.endsWith("/") ? key.slice(0, -1) : key;
|
|
7792
|
+
const shareItem = shared[key];
|
|
8228
7793
|
if (!vueKey && keyBase === "vue") vueKey = key;
|
|
8229
7794
|
if (key.endsWith("/")) wildcardKeys.push({
|
|
8230
7795
|
key,
|
|
8231
7796
|
base: keyBase
|
|
8232
7797
|
});
|
|
8233
|
-
|
|
7798
|
+
if (shareItem.shareConfig?.import !== false) {
|
|
7799
|
+
for (const subpath of getCommonSharedSubpaths(keyBase)) if (!commonSubpathKeys.has(subpath)) commonSubpathKeys.set(subpath, key);
|
|
7800
|
+
}
|
|
8234
7801
|
}
|
|
8235
7802
|
const sourceCache = /* @__PURE__ */ new Map();
|
|
8236
7803
|
const matcher = { find(source) {
|
|
@@ -8307,6 +7874,8 @@ function proxySharedModule(options) {
|
|
|
8307
7874
|
const materializedLoadShareSources = /* @__PURE__ */ new Set();
|
|
8308
7875
|
const emittedTreeShakingProviders = /* @__PURE__ */ new Set();
|
|
8309
7876
|
const hasAnalyzableShares = Object.values(shared).some((share) => shouldAnalyzeSharedExports(share));
|
|
7877
|
+
const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
|
|
7878
|
+
const refreshTreeShakingForEnvironment = (context) => refreshTreeShakingModules(federationOptions, _command, getIsRolldown(context), getEnvironmentConditions(context));
|
|
8310
7879
|
const normalizeTreeShakingOutputPath = (value) => {
|
|
8311
7880
|
const normalized = normalizePathForImport(value);
|
|
8312
7881
|
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.`);
|
|
@@ -8352,7 +7921,7 @@ function proxySharedModule(options) {
|
|
|
8352
7921
|
},
|
|
8353
7922
|
load(id) {
|
|
8354
7923
|
if (id === getResolvedLocalSharedImportMapId(federationOptions)) return getParsePromise().then((_) => {
|
|
8355
|
-
|
|
7924
|
+
refreshTreeShakingForEnvironment(this);
|
|
8356
7925
|
const providerPackages = /* @__PURE__ */ new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
|
|
8357
7926
|
for (const pkg of providerPackages) {
|
|
8358
7927
|
const sharedKey = findSharedKeyForSource(pkg, shared);
|
|
@@ -8386,15 +7955,16 @@ function proxySharedModule(options) {
|
|
|
8386
7955
|
configResolved(config) {
|
|
8387
7956
|
_config = config;
|
|
8388
7957
|
const isRolldown = getIsRolldown(this);
|
|
7958
|
+
const registerConfiguredShare = _command === "serve" ? addConfiguredShare : addUsedShares;
|
|
8389
7959
|
Object.keys(shared).forEach((key) => {
|
|
8390
7960
|
if (key.endsWith("/")) return;
|
|
8391
7961
|
if (useDirectReactImport && key === "react") {
|
|
8392
|
-
|
|
7962
|
+
registerConfiguredShare(key, federationOptions);
|
|
8393
7963
|
return;
|
|
8394
7964
|
}
|
|
8395
7965
|
writeLoadShareModule(key, shared[key], _command, isRolldown, federationOptions);
|
|
8396
7966
|
if (shared[key].shareConfig.import !== false) writePreBuildLibPath(key, shared[key], federationOptions);
|
|
8397
|
-
|
|
7967
|
+
registerConfiguredShare(key, federationOptions);
|
|
8398
7968
|
});
|
|
8399
7969
|
writeLocalSharedImportMap(federationOptions);
|
|
8400
7970
|
refreshHostAutoInit(federationOptions);
|
|
@@ -8403,7 +7973,7 @@ function proxySharedModule(options) {
|
|
|
8403
7973
|
if (_command !== "build") return;
|
|
8404
7974
|
resetTreeShakingExports(federationOptions);
|
|
8405
7975
|
emittedTreeShakingProviders.clear();
|
|
8406
|
-
|
|
7976
|
+
refreshTreeShakingForEnvironment(this);
|
|
8407
7977
|
},
|
|
8408
7978
|
shouldTransformCachedModule() {
|
|
8409
7979
|
return _command === "build" && hasAnalyzableShares;
|
|
@@ -8411,7 +7981,7 @@ function proxySharedModule(options) {
|
|
|
8411
7981
|
transform(code, id) {
|
|
8412
7982
|
if (_command !== "build" || !hasAnalyzableShares) return;
|
|
8413
7983
|
collectTreeShakingImports(code, id, shared, findSharedKeyForSource, (sharedKey, exports, request) => recordTreeShakingExports(sharedKey, exports, request, federationOptions), (sharedKey, request) => markTreeShakingPackageUnsafe(sharedKey, request, federationOptions));
|
|
8414
|
-
|
|
7984
|
+
refreshTreeShakingForEnvironment(this);
|
|
8415
7985
|
}
|
|
8416
7986
|
},
|
|
8417
7987
|
{
|
|
@@ -8841,7 +8411,7 @@ function getRealPathIfExists(filePath) {
|
|
|
8841
8411
|
return;
|
|
8842
8412
|
}
|
|
8843
8413
|
}
|
|
8844
|
-
function
|
|
8414
|
+
function isCanonicalPathWithinDirectory(filePath, directory) {
|
|
8845
8415
|
const realFilePath = getRealPathIfExists(filePath) ?? path$1.resolve(filePath);
|
|
8846
8416
|
const realDirectory = getRealPathIfExists(directory) ?? path$1.resolve(directory);
|
|
8847
8417
|
const relative = path$1.relative(realDirectory, realFilePath);
|
|
@@ -8851,7 +8421,7 @@ function getRunnerAllowedDirectories(config) {
|
|
|
8851
8421
|
return [config.root, ...config.server?.fs?.allow ?? []].map((directory) => path$1.resolve(directory));
|
|
8852
8422
|
}
|
|
8853
8423
|
function isPathWithinAllowedDirectories(filePath, allowedDirectories) {
|
|
8854
|
-
return allowedDirectories.some((directory) =>
|
|
8424
|
+
return allowedDirectories.some((directory) => isCanonicalPathWithinDirectory(filePath, directory));
|
|
8855
8425
|
}
|
|
8856
8426
|
function isSafeRunnerFetchModuleId(id, config) {
|
|
8857
8427
|
if (typeof id !== "string" || !id) return false;
|
|
@@ -9006,7 +8576,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
9006
8576
|
},
|
|
9007
8577
|
configureServer(server) {
|
|
9008
8578
|
const base = "/__mf_ssr__";
|
|
9009
|
-
const basePath = getBasePath$
|
|
8579
|
+
const basePath = getBasePath$1(viteConfig?.base);
|
|
9010
8580
|
const ssrEntryFileName = getSsrRemoteEntryFileName(options.filename);
|
|
9011
8581
|
if (isNuxtProject || isNuxtClientBase(basePath)) server.middlewares.use((req, _res, next) => {
|
|
9012
8582
|
if (req.url?.replace(/\?.*/, "") === `${basePath}/${ssrEntryFileName}`) req.url = `${basePath}/__mf_ssr__/${ssrEntryFileName}`;
|
|
@@ -9061,7 +8631,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
9061
8631
|
const ssrPath = `${base}/${ssrEntryFileName}`;
|
|
9062
8632
|
server.middlewares.use(ssrPath, (_req, res) => {
|
|
9063
8633
|
const exposesUrl = `${base}/${options.filename.replace(/\.[^.]+$/, "")}.exposes.js`;
|
|
9064
|
-
const code =
|
|
8634
|
+
const code = getSsrRemoteEntrySource().replace(JSON.stringify(virtualExposesSSRId), JSON.stringify(exposesUrl));
|
|
9065
8635
|
res.setHeader("Content-Type", "application/javascript");
|
|
9066
8636
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
9067
8637
|
res.end(code);
|
|
@@ -9080,7 +8650,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
9080
8650
|
if (id === `/__mf_ssr__/${options.filename.replace(/\.[^.]+$/, "")}.exposes.js`) return virtualExposesSSRId;
|
|
9081
8651
|
},
|
|
9082
8652
|
load(id) {
|
|
9083
|
-
if (id === remoteEntrySSRId || id.startsWith(remoteEntrySSRId)) return
|
|
8653
|
+
if (id === remoteEntrySSRId || id.startsWith(remoteEntrySSRId)) return getSsrRemoteEntrySource();
|
|
9084
8654
|
if (id === virtualExposesSSRId || id.startsWith(virtualExposesSSRId)) return generateExposesSSR(options, reactIslandExposes);
|
|
9085
8655
|
},
|
|
9086
8656
|
buildStart() {
|
|
@@ -9112,9 +8682,6 @@ function pluginSSRRemoteEntry(options) {
|
|
|
9112
8682
|
});
|
|
9113
8683
|
}
|
|
9114
8684
|
if (this.environment?.name === "ssr") ssrOutputFiles = collectEntryOutputFiles(bundle, ssrOutputFilename);
|
|
9115
|
-
if (!isRolldown) return;
|
|
9116
|
-
const chunk = bundle[ssrOutputFilename];
|
|
9117
|
-
if (!chunk || chunk.type !== "chunk") return;
|
|
9118
8685
|
}
|
|
9119
8686
|
},
|
|
9120
8687
|
writeBundle(outputOptions) {
|
|
@@ -9134,7 +8701,7 @@ function pluginSSRRemoteEntry(options) {
|
|
|
9134
8701
|
for (const fileName of ssrOutputFiles) {
|
|
9135
8702
|
const source = path$1.resolve(ssrDir, fileName);
|
|
9136
8703
|
const destination = path$1.resolve(clientDir, fileName);
|
|
9137
|
-
if (!
|
|
8704
|
+
if (!isResolvedPathWithinDirectory(source, ssrDir) || !isResolvedPathWithinDirectory(destination, clientDir)) continue;
|
|
9138
8705
|
if (!fs$1.existsSync(source) || fs$1.existsSync(destination)) continue;
|
|
9139
8706
|
fs$1.mkdirSync(path$1.dirname(destination), { recursive: true });
|
|
9140
8707
|
fs$1.copyFileSync(source, destination);
|
|
@@ -9165,7 +8732,7 @@ function collectEntryOutputFiles(bundle, entryFileName) {
|
|
|
9165
8732
|
visit(entryFileName);
|
|
9166
8733
|
return files;
|
|
9167
8734
|
}
|
|
9168
|
-
function
|
|
8735
|
+
function isResolvedPathWithinDirectory(filePath, directory) {
|
|
9169
8736
|
const relative = path$1.relative(directory, filePath);
|
|
9170
8737
|
return relative !== "" && !relative.startsWith(`..${path$1.sep}`) && relative !== "..";
|
|
9171
8738
|
}
|
|
@@ -9353,42 +8920,6 @@ function isTestEnv() {
|
|
|
9353
8920
|
return process.env.NODE_ENV === "test" || process.env.VITEST != null || process.env.JEST_WORKER_ID != null;
|
|
9354
8921
|
}
|
|
9355
8922
|
//#endregion
|
|
9356
|
-
//#region src/utils/sharedExportConditions.ts
|
|
9357
|
-
const DEFAULT_CLIENT_EXPORT_CONDITIONS = [
|
|
9358
|
-
"browser",
|
|
9359
|
-
"import",
|
|
9360
|
-
"module",
|
|
9361
|
-
"default"
|
|
9362
|
-
];
|
|
9363
|
-
const DEFAULT_NODE_SSR_EXPORT_CONDITIONS = [
|
|
9364
|
-
"node",
|
|
9365
|
-
"import",
|
|
9366
|
-
"module",
|
|
9367
|
-
"default"
|
|
9368
|
-
];
|
|
9369
|
-
const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
|
|
9370
|
-
"worker",
|
|
9371
|
-
"browser",
|
|
9372
|
-
"import",
|
|
9373
|
-
"module",
|
|
9374
|
-
"default"
|
|
9375
|
-
];
|
|
9376
|
-
const VITE_DEV_PROD_CONDITION = "development|production";
|
|
9377
|
-
function appendConditions(conditions, fallbackConditions) {
|
|
9378
|
-
return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
|
|
9379
|
-
}
|
|
9380
|
-
function resolveViteModeCondition(conditions, isProduction) {
|
|
9381
|
-
const modeCondition = isProduction ? "production" : "development";
|
|
9382
|
-
return [...new Set(conditions.map((condition) => condition === VITE_DEV_PROD_CONDITION ? modeCondition : condition))];
|
|
9383
|
-
}
|
|
9384
|
-
function getSharedExportConditions({ environmentConditions, isProduction, isSsr, rootConditions, ssrConditions, ssrTarget = "node" }) {
|
|
9385
|
-
if (environmentConditions !== void 0) return resolveViteModeCondition(appendConditions(environmentConditions, ["import", "default"]), isProduction);
|
|
9386
|
-
const defaultConditions = isSsr ? ssrTarget === "webworker" ? DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS : DEFAULT_NODE_SSR_EXPORT_CONDITIONS : DEFAULT_CLIENT_EXPORT_CONDITIONS;
|
|
9387
|
-
const configuredConditions = isSsr ? ssrConditions ?? rootConditions : rootConditions;
|
|
9388
|
-
if (configuredConditions !== void 0) return resolveViteModeCondition(appendConditions(configuredConditions, defaultConditions), isProduction);
|
|
9389
|
-
return [...defaultConditions];
|
|
9390
|
-
}
|
|
9391
|
-
//#endregion
|
|
9392
8923
|
//#region src/utils/normalizeOptimizeDeps.ts
|
|
9393
8924
|
var normalizeOptimizeDeps_default = {
|
|
9394
8925
|
name: "normalizeOptimizeDeps",
|
|
@@ -9625,6 +9156,74 @@ function includeLinkedSharedEntries(optimizeDeps, shared, projectRoot, exposes,
|
|
|
9625
9156
|
for (const entry of additions) entries.add(entry);
|
|
9626
9157
|
optimizeDeps.entries = [...entries];
|
|
9627
9158
|
}
|
|
9159
|
+
function stabilizeOptimizeDeps(optimizeDeps) {
|
|
9160
|
+
optimizeDeps.include = [...new Set(optimizeDeps.include ?? [])].sort();
|
|
9161
|
+
optimizeDeps.exclude = [...new Set(optimizeDeps.exclude ?? [])].sort();
|
|
9162
|
+
}
|
|
9163
|
+
function isFile(candidate) {
|
|
9164
|
+
try {
|
|
9165
|
+
return statSync(candidate).isFile();
|
|
9166
|
+
} catch {
|
|
9167
|
+
return false;
|
|
9168
|
+
}
|
|
9169
|
+
}
|
|
9170
|
+
function registerEntryImports(options, projectRoot) {
|
|
9171
|
+
const staticImport = /\b(?:import|export)\s+(?:type\s+)?(?:[^'";]*?\s+from\s*)?(['"])([^'"]+)\1/g;
|
|
9172
|
+
const dynamicImport = /\b(?:import|require)\s*\(\s*(['"])([^'"]+)\1/g;
|
|
9173
|
+
const sourceExtensions = [
|
|
9174
|
+
".mjs",
|
|
9175
|
+
".js",
|
|
9176
|
+
".mts",
|
|
9177
|
+
".ts",
|
|
9178
|
+
".jsx",
|
|
9179
|
+
".tsx",
|
|
9180
|
+
".vue",
|
|
9181
|
+
".svelte"
|
|
9182
|
+
];
|
|
9183
|
+
const root = path$1.resolve(projectRoot);
|
|
9184
|
+
const pending = [];
|
|
9185
|
+
const visited = /* @__PURE__ */ new Map();
|
|
9186
|
+
const enqueue = (request, importer = path$1.join(root, "index.html"), preloadRemotes = false) => {
|
|
9187
|
+
const cleanRequest = request.replace(/[?#].*$/, "");
|
|
9188
|
+
if (!cleanRequest.startsWith(".") && !cleanRequest.startsWith("/") && !path$1.isAbsolute(cleanRequest)) return;
|
|
9189
|
+
const base = cleanRequest.startsWith("/") ? path$1.resolve(root, `.${cleanRequest}`) : path$1.resolve(path$1.dirname(importer), cleanRequest);
|
|
9190
|
+
const relative = path$1.relative(root, base);
|
|
9191
|
+
if (relative.startsWith(`..${path$1.sep}`) || path$1.isAbsolute(relative)) return;
|
|
9192
|
+
const file = [
|
|
9193
|
+
base,
|
|
9194
|
+
...sourceExtensions.map((extension) => `${base}${extension}`),
|
|
9195
|
+
...sourceExtensions.map((extension) => path$1.join(base, `index${extension}`))
|
|
9196
|
+
].find(isFile);
|
|
9197
|
+
if (file && (!visited.has(file) || preloadRemotes && !visited.get(file))) pending.push({
|
|
9198
|
+
file,
|
|
9199
|
+
preloadRemotes
|
|
9200
|
+
});
|
|
9201
|
+
};
|
|
9202
|
+
const htmlEntry = path$1.join(root, "index.html");
|
|
9203
|
+
if (existsSync(htmlEntry)) {
|
|
9204
|
+
const html = readFileSync(htmlEntry, "utf8");
|
|
9205
|
+
for (const match of html.matchAll(/<script\b[^>]*\bsrc=(['"])([^'"]+)\1[^>]*>/gi)) enqueue(match[2], htmlEntry, true);
|
|
9206
|
+
}
|
|
9207
|
+
for (const expose of Object.values(options.exposes ?? {})) enqueue(expose.import);
|
|
9208
|
+
while (pending.length) {
|
|
9209
|
+
const { file, preloadRemotes } = pending.pop();
|
|
9210
|
+
if (visited.get(file) || visited.has(file) && !preloadRemotes) continue;
|
|
9211
|
+
visited.set(file, preloadRemotes);
|
|
9212
|
+
const code = readFileSync(file, "utf8");
|
|
9213
|
+
for (const pattern of [staticImport, dynamicImport]) {
|
|
9214
|
+
const isStatic = pattern === staticImport;
|
|
9215
|
+
pattern.lastIndex = 0;
|
|
9216
|
+
for (const match of code.matchAll(pattern)) {
|
|
9217
|
+
const request = match[2];
|
|
9218
|
+
const remoteKey = preloadRemotes && isStatic && request ? Object.keys(options.remotes).find((name) => request === name || request.startsWith(`${name}/`)) : void 0;
|
|
9219
|
+
const sharedKey = request && findSharedKey(request, options.shared);
|
|
9220
|
+
if (remoteKey) addUsedRemote(remoteKey, request, options);
|
|
9221
|
+
else if (sharedKey) addUsedShares(request, options);
|
|
9222
|
+
else if (request) enqueue(request, file, preloadRemotes && isStatic);
|
|
9223
|
+
}
|
|
9224
|
+
}
|
|
9225
|
+
}
|
|
9226
|
+
}
|
|
9628
9227
|
/**
|
|
9629
9228
|
* Plugin that runs FIRST to register generated virtual modules in the config hook.
|
|
9630
9229
|
* This prevents 504 "Outdated Optimize Dep" errors by ensuring ids are known
|
|
@@ -9639,6 +9238,7 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9639
9238
|
config(config, { command: _command }) {
|
|
9640
9239
|
if (_command === "serve") ignoreFederationGeneratedFiles(config, options);
|
|
9641
9240
|
const root = config.root || process.cwd();
|
|
9241
|
+
resetConcreteSharedImportSourceCache();
|
|
9642
9242
|
setPackageDetectionCwd(root);
|
|
9643
9243
|
const isVinext = hasPackageDependency("vinext");
|
|
9644
9244
|
initVirtualModules(_command, getRemoteEntryId(options), false, options);
|
|
@@ -9652,8 +9252,10 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9652
9252
|
config.optimizeDeps.exclude.push(...Object.keys(remotes || {}));
|
|
9653
9253
|
}
|
|
9654
9254
|
}
|
|
9255
|
+
if (_command === "serve" && (Object.keys(shared ?? {}).length > 0 || Object.keys(remotes ?? {}).length > 0)) registerEntryImports(options, root);
|
|
9655
9256
|
if (shared && Object.keys(shared).length > 0) {
|
|
9656
9257
|
if (_command === "serve") {
|
|
9258
|
+
excludeSharedSubDependencies(shared);
|
|
9657
9259
|
config.optimizeDeps = config.optimizeDeps || {};
|
|
9658
9260
|
config.optimizeDeps.include = config.optimizeDeps.include || [];
|
|
9659
9261
|
const optimizeDeps = config.optimizeDeps;
|
|
@@ -9685,16 +9287,15 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9685
9287
|
const isReactDomRequire = resolveOptions?.kind?.startsWith("require") && isReactDomSelfReference(source, importer);
|
|
9686
9288
|
if (resolveOptions?.kind?.startsWith("require") && !isReactRequire && !isReactDomRequire) return;
|
|
9687
9289
|
if (isCommonJsImporter(importer) && !isReactSingleton && !isReactDomRequire) return;
|
|
9290
|
+
if (resolveOptions?.kind !== "entry-point") addUsedShares(source, options);
|
|
9688
9291
|
if (isReactRequire || isReactDomRequire) {
|
|
9689
9292
|
writeLoadShareModule(source, shareItem, _command, isRolldown, options);
|
|
9690
9293
|
if (shareItem.shareConfig?.import !== false) writePreBuildLibPath(source, shareItem, options);
|
|
9691
|
-
addUsedShares(source, options);
|
|
9692
9294
|
return { id: `module-federation:optimized-require-${source}` };
|
|
9693
9295
|
}
|
|
9694
9296
|
const loadSharePath = getLoadShareModulePath(source, isRolldown, options);
|
|
9695
9297
|
writeLoadShareModule(source, shareItem, _command, isRolldown, options);
|
|
9696
9298
|
if (shareItem.shareConfig?.import !== false) writePreBuildLibPath(source, shareItem, options);
|
|
9697
|
-
addUsedShares(source, options);
|
|
9698
9299
|
return {
|
|
9699
9300
|
id: loadSharePath,
|
|
9700
9301
|
external: true
|
|
@@ -9717,6 +9318,7 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9717
9318
|
if (isSharedResolverInternalImporter(args.importer)) return;
|
|
9718
9319
|
if (!findSharedKey(args.path, shared) || isAssetLikeImport(args.path)) return;
|
|
9719
9320
|
if (getPackageNameFromNodeModulePath(args.importer) === getPackageName(args.path) && !isReactDomSelfReference(args.path, args.importer)) return;
|
|
9321
|
+
addUsedShares(args.path, options);
|
|
9720
9322
|
return {
|
|
9721
9323
|
path: args.path,
|
|
9722
9324
|
namespace: "mf-shared"
|
|
@@ -9732,7 +9334,6 @@ function createEarlyVirtualModulesPlugin(options) {
|
|
|
9732
9334
|
const loadSharePath = getLoadShareModulePath(args.path, isRolldown, options);
|
|
9733
9335
|
writeLoadShareModule(args.path, shareItem, _command, isRolldown, options);
|
|
9734
9336
|
if (shareItem.shareConfig?.import !== false) writePreBuildLibPath(args.path, shareItem, options);
|
|
9735
|
-
addUsedShares(args.path, options);
|
|
9736
9337
|
return {
|
|
9737
9338
|
loader: "js",
|
|
9738
9339
|
resolveDir: root,
|
|
@@ -9761,13 +9362,13 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
9761
9362
|
continue;
|
|
9762
9363
|
}
|
|
9763
9364
|
if (isVinext && key === "react") {
|
|
9764
|
-
|
|
9365
|
+
addConfiguredShare(key, options);
|
|
9765
9366
|
continue;
|
|
9766
9367
|
}
|
|
9767
9368
|
getLoadShareModulePath(key, isRolldown, options);
|
|
9768
9369
|
writeLoadShareModule(key, shareItem, _command, isRolldown, options);
|
|
9769
9370
|
if (shareItem.shareConfig?.import !== false) writePreBuildLibPath(key, shareItem, options);
|
|
9770
|
-
|
|
9371
|
+
addConfiguredShare(key, options);
|
|
9771
9372
|
if (_command === "serve" && shareItem.shareConfig?.import !== false) {
|
|
9772
9373
|
const optimizeDeps = config.optimizeDeps ??= {};
|
|
9773
9374
|
optimizeDeps.include ??= [];
|
|
@@ -9785,7 +9386,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
9785
9386
|
getLoadShareModulePath(subpath, isRolldown, options);
|
|
9786
9387
|
writeLoadShareModule(subpath, shareItem, _command, isRolldown, options);
|
|
9787
9388
|
writePreBuildLibPath(subpath, shareItem, options);
|
|
9788
|
-
|
|
9389
|
+
addConfiguredShare(subpath, options);
|
|
9789
9390
|
if (canResolveSubpath) {
|
|
9790
9391
|
optimizeDeps.include.push(subpath);
|
|
9791
9392
|
if (key === "react-dom") optimizeDeps.include.push(`${key} > ${subpath}`);
|
|
@@ -9798,6 +9399,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
9798
9399
|
if (_command === "serve") {
|
|
9799
9400
|
config.optimizeDeps ??= {};
|
|
9800
9401
|
includeLinkedSharedEntries(config.optimizeDeps, shared, root, options.exposes, config.build?.outDir ?? "dist");
|
|
9402
|
+
stabilizeOptimizeDeps(config.optimizeDeps);
|
|
9801
9403
|
}
|
|
9802
9404
|
},
|
|
9803
9405
|
configResolved(config) {
|
|
@@ -9827,7 +9429,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
9827
9429
|
resolvedShared[pkg] = resolveImportPath(pkg);
|
|
9828
9430
|
} catch {}
|
|
9829
9431
|
}
|
|
9830
|
-
const ssrEntryLoaderSpecifier =
|
|
9432
|
+
const ssrEntryLoaderSpecifier = SSR_ENTRY_LOADER_SPECIFIER;
|
|
9831
9433
|
try {
|
|
9832
9434
|
resolveImportPath(ssrEntryLoaderSpecifier);
|
|
9833
9435
|
options.runtimePlugins.push([ssrEntryLoaderSpecifier, { resolvedShared }]);
|
|
@@ -9835,7 +9437,6 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
9835
9437
|
}
|
|
9836
9438
|
};
|
|
9837
9439
|
}
|
|
9838
|
-
const SSR_ONLY_PLUGINS = /* @__PURE__ */ new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
9839
9440
|
function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaultDisableSnapshot }) {
|
|
9840
9441
|
const envTargetDefineValue = !options.target && isAstro ? "undefined" : JSON.stringify(target);
|
|
9841
9442
|
if (!("ENV_TARGET" in define)) define.ENV_TARGET = envTargetDefineValue;
|
|
@@ -9847,7 +9448,7 @@ function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaul
|
|
|
9847
9448
|
}
|
|
9848
9449
|
function loadPluginDts(options) {
|
|
9849
9450
|
if (options.dts === false) return [];
|
|
9850
|
-
return [
|
|
9451
|
+
return [import("./pluginDts-BNCg4Gri.js").then(({ default: pluginDts }) => pluginDts(options))];
|
|
9851
9452
|
}
|
|
9852
9453
|
const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
|
|
9853
9454
|
function isInjectExternalRuntimeCorePlugin(specifier) {
|
|
@@ -9888,7 +9489,7 @@ function federation(mfUserOptions) {
|
|
|
9888
9489
|
const virtualExposesId = getVirtualExposesId(options);
|
|
9889
9490
|
const moduleParseController = createModuleParseController();
|
|
9890
9491
|
const moduleParsePlugins = pluginModuleParseEnd_default((id) => {
|
|
9891
|
-
return id.includes(
|
|
9492
|
+
return id.includes(getHostAutoInitPath(options)) || id.includes(remoteEntryId) || id.includes(virtualExposesId) || id.includes("virtual:mf-localSharedImportMap") || id.includes("__loadShare__") || id.includes("__prebuild__") || id.includes("__treeShakingProvider__") || id.includes("__mf_tree_shaking_graph__");
|
|
9892
9493
|
}, {
|
|
9893
9494
|
moduleParseTimeout: options.moduleParseTimeout,
|
|
9894
9495
|
moduleParseIdleTimeout: options.moduleParseIdleTimeout,
|
|
@@ -9914,6 +9515,7 @@ function federation(mfUserOptions) {
|
|
|
9914
9515
|
ssrTarget
|
|
9915
9516
|
});
|
|
9916
9517
|
};
|
|
9518
|
+
const refreshLoadRemoteModuleForEnvironment = (id, context, loadOptions) => refreshRemoteModuleForEnvironment(id, options, getLoadHookExportConditions(context, loadOptions));
|
|
9917
9519
|
const refreshPreBuildModuleForEnvironment = (id, context, loadOptions) => {
|
|
9918
9520
|
const pkg = getCachedPreBuildPkg(id);
|
|
9919
9521
|
if (!pkg) return "not-applicable";
|
|
@@ -9977,8 +9579,10 @@ function federation(mfUserOptions) {
|
|
|
9977
9579
|
return virtualModule.getResolvedId();
|
|
9978
9580
|
},
|
|
9979
9581
|
load(id, loadOptions) {
|
|
9582
|
+
if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
|
|
9980
9583
|
if (command !== "build" && id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
|
|
9981
9584
|
if (id.includes("__prebuild__") && refreshPreBuildModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
|
|
9585
|
+
if (id.includes("__H_A_I__") && isOwnedHostAutoInitId(id, options)) refreshHostAutoInit(options, getLoadHookExportConditions(this, loadOptions));
|
|
9982
9586
|
const virtualModule = VirtualModule.findById(id);
|
|
9983
9587
|
if (!virtualModule) return;
|
|
9984
9588
|
if (command === "build" && (id.includes("__loadShare__") || id.includes("__loadRemote__"))) return;
|
|
@@ -10199,6 +9803,7 @@ function federation(mfUserOptions) {
|
|
|
10199
9803
|
load(id, loadOptions) {
|
|
10200
9804
|
const loadVirtualModule = (importFalseExportUsage) => {
|
|
10201
9805
|
if (!id.includes("__loadShare__") && !id.includes("__loadRemote__")) return;
|
|
9806
|
+
if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
|
|
10202
9807
|
if (id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions, importFalseExportUsage) === "not-owned") return;
|
|
10203
9808
|
const virtualModule = VirtualModule.findById(id);
|
|
10204
9809
|
if (!virtualModule?.code) return null;
|
|
@@ -10288,7 +9893,7 @@ function federation(mfUserOptions) {
|
|
|
10288
9893
|
if (needsRuntimeHelpers) config.optimizeDeps.include.push("@module-federation/runtime/helpers");
|
|
10289
9894
|
options.runtimePlugins.forEach((p) => {
|
|
10290
9895
|
const pluginPath = typeof p === "string" ? p : p[0];
|
|
10291
|
-
if (
|
|
9896
|
+
if (SSR_ONLY_RUNTIME_PLUGINS.has(pluginPath)) return;
|
|
10292
9897
|
if (pluginPath && !pluginPath.startsWith(".") && !pluginPath.startsWith("/") && !pluginPath.startsWith("\0") && !pluginPath.startsWith("virtual:")) {
|
|
10293
9898
|
let optimizeDep = pluginPath;
|
|
10294
9899
|
if (pluginPath === "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin") try {
|